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		$pageAsString = (string) $page;
12388		if ($pageAsString && $pageAsString[0] == '*') {
12389			$page = intval(substr($page, 1));
12390			// this page number will not be changed when moving/add/deleting pages
12391			$fixed = true;
12392		}
12393		if (empty($page)) {
12394			$page = $this->PageNo();
12395			if (empty($page)) {
12396				return;
12397			}
12398		}
12399		$this->outlines[] = array('t' => $txt, 'l' => $level, 'x' => $x, 'y' => $y, 'p' => $page, 'f' => $fixed, 's' => strtoupper($style), 'c' => $color, 'u' => $link);
12400	}
12401
12402	/**
12403	 * Sort bookmarks for page and key.
12404	 * @protected
12405	 * @since 5.9.119 (2011-09-19)
12406	 */
12407	protected function sortBookmarks() {
12408		// get sorting columns
12409		$outline_p = array();
12410		$outline_y = array();
12411		foreach ($this->outlines as $key => $row) {
12412			$outline_p[$key] = $row['p'];
12413			$outline_k[$key] = $key;
12414		}
12415		// sort outlines by page and original position
12416		array_multisort($outline_p, SORT_NUMERIC, SORT_ASC, $outline_k, SORT_NUMERIC, SORT_ASC, $this->outlines);
12417	}
12418
12419	/**
12420	 * Create a bookmark PDF string.
12421	 * @protected
12422	 * @author Olivier Plathey, Nicola Asuni
12423	 * @since 2.1.002 (2008-02-12)
12424	 */
12425	protected function _putbookmarks() {
12426		$nb = count($this->outlines);
12427		if ($nb == 0) {
12428			return;
12429		}
12430		// sort bookmarks
12431		$this->sortBookmarks();
12432		$lru = array();
12433		$level = 0;
12434		foreach ($this->outlines as $i => $o) {
12435			if ($o['l'] > 0) {
12436				$parent = $lru[($o['l'] - 1)];
12437				//Set parent and last pointers
12438				$this->outlines[$i]['parent'] = $parent;
12439				$this->outlines[$parent]['last'] = $i;
12440				if ($o['l'] > $level) {
12441					//Level increasing: set first pointer
12442					$this->outlines[$parent]['first'] = $i;
12443				}
12444			} else {
12445				$this->outlines[$i]['parent'] = $nb;
12446			}
12447			if (($o['l'] <= $level) AND ($i > 0)) {
12448				//Set prev and next pointers
12449				$prev = $lru[$o['l']];
12450				$this->outlines[$prev]['next'] = $i;
12451				$this->outlines[$i]['prev'] = $prev;
12452			}
12453			$lru[$o['l']] = $i;
12454			$level = $o['l'];
12455		}
12456		//Outline items
12457		$n = $this->n + 1;
12458		$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';
12459		foreach ($this->outlines as $i => $o) {
12460			$oid = $this->_newobj();
12461			// covert HTML title to string
12462			$title = preg_replace($nltags, "\n", $o['t']);
12463			$title = preg_replace("/[\r]+/si", '', $title);
12464			$title = preg_replace("/[\n]+/si", "\n", $title);
12465			$title = strip_tags($title);
12466			$title = $this->stringTrim($title);
12467			$out = '<</Title '.$this->_textstring($title, $oid);
12468			$out .= ' /Parent '.($n + $o['parent']).' 0 R';
12469			if (isset($o['prev'])) {
12470				$out .= ' /Prev '.($n + $o['prev']).' 0 R';
12471			}
12472			if (isset($o['next'])) {
12473				$out .= ' /Next '.($n + $o['next']).' 0 R';
12474			}
12475			if (isset($o['first'])) {
12476				$out .= ' /First '.($n + $o['first']).' 0 R';
12477			}
12478			if (isset($o['last'])) {
12479				$out .= ' /Last '.($n + $o['last']).' 0 R';
12480			}
12481			if (isset($o['u']) AND !empty($o['u'])) {
12482				// link
12483				if (is_string($o['u'])) {
12484					if ($o['u'][0] == '#') {
12485						// internal destination
12486						$out .= ' /Dest /'.TCPDF_STATIC::encodeNameObject(substr($o['u'], 1));
12487					} elseif ($o['u'][0] == '%') {
12488						// embedded PDF file
12489						$filename = basename(substr($o['u'], 1));
12490						$out .= ' /A <</S /GoToE /D [0 /Fit] /NewWindow true /T << /R /C /P '.($o['p'] - 1).' /A '.$this->embeddedfiles[$filename]['a'].' >> >>';
12491					} elseif ($o['u'][0] == '*') {
12492						// embedded generic file
12493						$filename = basename(substr($o['u'], 1));
12494						$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});';
12495						$out .= ' /A <</S /JavaScript /JS '.$this->_textstring($jsa, $oid).'>>';
12496					} else {
12497						// external URI link
12498						$out .= ' /A <</S /URI /URI '.$this->_datastring($this->unhtmlentities($o['u']), $oid).'>>';
12499					}
12500				} elseif (isset($this->links[$o['u']])) {
12501					// internal link ID
12502					$l = $this->links[$o['u']];
12503					if (isset($this->page_obj_id[($l['p'])])) {
12504						$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)));
12505					}
12506				}
12507			} elseif (isset($this->page_obj_id[($o['p'])])) {
12508				// link to a page
12509				$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)));
12510			}
12511			// set font style
12512			$style = 0;
12513			if (!empty($o['s'])) {
12514				// bold
12515				if (strpos($o['s'], 'B') !== false) {
12516					$style |= 2;
12517				}
12518				// oblique
12519				if (strpos($o['s'], 'I') !== false) {
12520					$style |= 1;
12521				}
12522			}
12523			$out .= sprintf(' /F %d', $style);
12524			// set bookmark color
12525			if (isset($o['c']) AND is_array($o['c']) AND (count($o['c']) == 3)) {
12526				$color = array_values($o['c']);
12527				$out .= sprintf(' /C [%F %F %F]', ($color[0] / 255), ($color[1] / 255), ($color[2] / 255));
12528			} else {
12529				// black
12530				$out .= ' /C [0.0 0.0 0.0]';
12531			}
12532			$out .= ' /Count 0'; // normally closed item
12533			$out .= ' >>';
12534			$out .= "\n".'endobj';
12535			$this->_out($out);
12536		}
12537		//Outline root
12538		$this->OutlineRoot = $this->_newobj();
12539		$this->_out('<< /Type /Outlines /First '.$n.' 0 R /Last '.($n + $lru[0]).' 0 R >>'."\n".'endobj');
12540	}
12541
12542	// --- JAVASCRIPT ------------------------------------------------------
12543
12544	/**
12545	 * Adds a javascript
12546	 * @param $script (string) Javascript code
12547	 * @public
12548	 * @author Johannes G\FCntert, Nicola Asuni
12549	 * @since 2.1.002 (2008-02-12)
12550	 */
12551	public function IncludeJS($script) {
12552		$this->javascript .= $script;
12553	}
12554
12555	/**
12556	 * Adds a javascript object and return object ID
12557	 * @param $script (string) Javascript code
12558	 * @param $onload (boolean) if true executes this object when opening the document
12559	 * @return int internal object ID
12560	 * @public
12561	 * @author Nicola Asuni
12562	 * @since 4.8.000 (2009-09-07)
12563	 */
12564	public function addJavascriptObject($script, $onload=false) {
12565		if ($this->pdfa_mode) {
12566			// javascript is not allowed in PDF/A mode
12567			return false;
12568		}
12569		++$this->n;
12570		$this->js_objects[$this->n] = array('n' => $this->n, 'js' => $script, 'onload' => $onload);
12571		return $this->n;
12572	}
12573
12574	/**
12575	 * Create a javascript PDF string.
12576	 * @protected
12577	 * @author Johannes G\FCntert, Nicola Asuni
12578	 * @since 2.1.002 (2008-02-12)
12579	 */
12580	protected function _putjavascript() {
12581		if ($this->pdfa_mode OR (empty($this->javascript) AND empty($this->js_objects))) {
12582			return;
12583		}
12584		if (strpos($this->javascript, 'this.addField') > 0) {
12585			if (!$this->ur['enabled']) {
12586				//$this->setUserRights();
12587			}
12588			// the following two lines are used to avoid form fields duplication after saving
12589			// The addField method only works when releasing user rights (UR3)
12590			$jsa = sprintf("ftcpdfdocsaved=this.addField('%s','%s',%d,[%F,%F,%F,%F]);", 'tcpdfdocsaved', 'text', 0, 0, 1, 0, 1);
12591			$jsb = "getField('tcpdfdocsaved').value='saved';";
12592			$this->javascript = $jsa."\n".$this->javascript."\n".$jsb;
12593		}
12594		// name tree for javascript
12595		$this->n_js = '<< /Names [';
12596		if (!empty($this->javascript)) {
12597			$this->n_js .= ' (EmbeddedJS) '.($this->n + 1).' 0 R';
12598		}
12599		if (!empty($this->js_objects)) {
12600			foreach ($this->js_objects as $key => $val) {
12601				if ($val['onload']) {
12602					$this->n_js .= ' (JS'.$key.') '.$key.' 0 R';
12603				}
12604			}
12605		}
12606		$this->n_js .= ' ] >>';
12607		// default Javascript object
12608		if (!empty($this->javascript)) {
12609			$obj_id = $this->_newobj();
12610			$out = '<< /S /JavaScript';
12611			$out .= ' /JS '.$this->_textstring($this->javascript, $obj_id);
12612			$out .= ' >>';
12613			$out .= "\n".'endobj';
12614			$this->_out($out);
12615		}
12616		// additional Javascript objects
12617		if (!empty($this->js_objects)) {
12618			foreach ($this->js_objects as $key => $val) {
12619				$out = $this->_getobj($key)."\n".' << /S /JavaScript /JS '.$this->_textstring($val['js'], $key).' >>'."\n".'endobj';
12620				$this->_out($out);
12621			}
12622		}
12623	}
12624
12625	/**
12626	 * Adds a javascript form field.
12627	 * @param $type (string) field type
12628	 * @param $name (string) field name
12629	 * @param $x (int) horizontal position
12630	 * @param $y (int) vertical position
12631	 * @param $w (int) width
12632	 * @param $h (int) height
12633	 * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
12634	 * @protected
12635	 * @author Denis Van Nuffelen, Nicola Asuni
12636	 * @since 2.1.002 (2008-02-12)
12637	 */
12638	protected function _addfield($type, $name, $x, $y, $w, $h, $prop) {
12639		if ($this->rtl) {
12640			$x = $x - $w;
12641		}
12642		// the followind avoid fields duplication after saving the document
12643		$this->javascript .= "if (getField('tcpdfdocsaved').value != 'saved') {";
12644		$k = $this->k;
12645		$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";
12646		$this->javascript .= 'f'.$name.'.textSize='.$this->FontSizePt.";\n";
12647		foreach($prop as $key => $val) {
12648			if (strcmp(substr($key, -5), 'Color') == 0) {
12649				$val = TCPDF_COLORS::_JScolor($val);
12650			} else {
12651				$val = "'".$val."'";
12652			}
12653			$this->javascript .= 'f'.$name.'.'.$key.'='.$val.";\n";
12654		}
12655		if ($this->rtl) {
12656			$this->x -= $w;
12657		} else {
12658			$this->x += $w;
12659		}
12660		$this->javascript .= '}';
12661	}
12662
12663	// --- FORM FIELDS -----------------------------------------------------
12664
12665
12666
12667	/**
12668	 * Set default properties for form fields.
12669	 * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
12670	 * @public
12671	 * @author Nicola Asuni
12672	 * @since 4.8.000 (2009-09-06)
12673	 */
12674	public function setFormDefaultProp($prop=array()) {
12675		$this->default_form_prop = $prop;
12676	}
12677
12678	/**
12679	 * Return the default properties for form fields.
12680	 * @return array $prop javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
12681	 * @public
12682	 * @author Nicola Asuni
12683	 * @since 4.8.000 (2009-09-06)
12684	 */
12685	public function getFormDefaultProp() {
12686		return $this->default_form_prop;
12687	}
12688
12689	/**
12690	 * Creates a text field
12691	 * @param $name (string) field name
12692	 * @param $w (float) Width of the rectangle
12693	 * @param $h (float) Height of the rectangle
12694	 * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
12695	 * @param $opt (array) annotation parameters. Possible values are described on official PDF32000_2008 reference.
12696	 * @param $x (float) Abscissa of the upper-left corner of the rectangle
12697	 * @param $y (float) Ordinate of the upper-left corner of the rectangle
12698	 * @param $js (boolean) if true put the field using JavaScript (requires Acrobat Writer to be rendered).
12699	 * @public
12700	 * @author Nicola Asuni
12701	 * @since 4.8.000 (2009-09-07)
12702	 */
12703	public function TextField($name, $w, $h, $prop=array(), $opt=array(), $x='', $y='', $js=false) {
12704		if ($x === '') {
12705			$x = $this->x;
12706		}
12707		if ($y === '') {
12708			$y = $this->y;
12709		}
12710		// check page for no-write regions and adapt page margins if necessary
12711		list($x, $y) = $this->checkPageRegions($h, $x, $y);
12712		if ($js) {
12713			$this->_addfield('text', $name, $x, $y, $w, $h, $prop);
12714			return;
12715		}
12716		// get default style
12717		$prop = array_merge($this->getFormDefaultProp(), $prop);
12718		// get annotation data
12719		$popt = TCPDF_STATIC::getAnnotOptFromJSProp($prop, $this->spot_colors, $this->rtl);
12720		// set default appearance stream
12721		$this->annotation_fonts[$this->CurrentFont['fontkey']] = $this->CurrentFont['i'];
12722		$fontstyle = sprintf('/F%d %F Tf %s', $this->CurrentFont['i'], $this->FontSizePt, $this->TextColor);
12723		$popt['da'] = $fontstyle;
12724		// build appearance stream
12725		$popt['ap'] = array();
12726		$popt['ap']['n'] = '/Tx BMC q '.$fontstyle.' ';
12727		$text = '';
12728		if (isset($prop['value']) AND !empty($prop['value'])) {
12729			$text = $prop['value'];
12730		} elseif (isset($opt['v']) AND !empty($opt['v'])) {
12731			$text = $opt['v'];
12732		}
12733		$tmpid = $this->startTemplate($w, $h, false);
12734		$align = '';
12735		if (isset($popt['q'])) {
12736			switch ($popt['q']) {
12737				case 0: {
12738					$align = 'L';
12739					break;
12740				}
12741				case 1: {
12742					$align = 'C';
12743					break;
12744				}
12745				case 2: {
12746					$align = 'R';
12747					break;
12748				}
12749				default: {
12750					$align = '';
12751					break;
12752				}
12753			}
12754		}
12755		$this->MultiCell($w, $h, $text, 0, $align, false, 0, 0, 0, true, 0, false, true, 0, 'T', false);
12756		$this->endTemplate();
12757		--$this->n;
12758		$popt['ap']['n'] .= $this->xobjects[$tmpid]['outdata'];
12759		unset($this->xobjects[$tmpid]);
12760		$popt['ap']['n'] .= 'Q EMC';
12761		// merge options
12762		$opt = array_merge($popt, $opt);
12763		// remove some conflicting options
12764		unset($opt['bs']);
12765		// set remaining annotation data
12766		$opt['Subtype'] = 'Widget';
12767		$opt['ft'] = 'Tx';
12768		$opt['t'] = $name;
12769		// Additional annotation's parameters (check _putannotsobj() method):
12770		//$opt['f']
12771		//$opt['as']
12772		//$opt['bs']
12773		//$opt['be']
12774		//$opt['c']
12775		//$opt['border']
12776		//$opt['h']
12777		//$opt['mk'];
12778		//$opt['mk']['r']
12779		//$opt['mk']['bc'];
12780		//$opt['mk']['bg'];
12781		unset($opt['mk']['ca']);
12782		unset($opt['mk']['rc']);
12783		unset($opt['mk']['ac']);
12784		unset($opt['mk']['i']);
12785		unset($opt['mk']['ri']);
12786		unset($opt['mk']['ix']);
12787		unset($opt['mk']['if']);
12788		//$opt['mk']['if']['sw'];
12789		//$opt['mk']['if']['s'];
12790		//$opt['mk']['if']['a'];
12791		//$opt['mk']['if']['fb'];
12792		unset($opt['mk']['tp']);
12793		//$opt['tu']
12794		//$opt['tm']
12795		//$opt['ff']
12796		//$opt['v']
12797		//$opt['dv']
12798		//$opt['a']
12799		//$opt['aa']
12800		//$opt['q']
12801		$this->Annotation($x, $y, $w, $h, $name, $opt, 0);
12802		if ($this->rtl) {
12803			$this->x -= $w;
12804		} else {
12805			$this->x += $w;
12806		}
12807	}
12808
12809	/**
12810	 * Creates a RadioButton field.
12811	 * @param $name (string) Field name.
12812	 * @param $w (int) Width of the radio button.
12813	 * @param $prop (array) Javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
12814	 * @param $opt (array) Annotation parameters. Possible values are described on official PDF32000_2008 reference.
12815	 * @param $onvalue (string) Value to be returned if selected.
12816	 * @param $checked (boolean) Define the initial state.
12817	 * @param $x (float) Abscissa of the upper-left corner of the rectangle
12818	 * @param $y (float) Ordinate of the upper-left corner of the rectangle
12819	 * @param $js (boolean) If true put the field using JavaScript (requires Acrobat Writer to be rendered).
12820	 * @public
12821	 * @author Nicola Asuni
12822	 * @since 4.8.000 (2009-09-07)
12823	 */
12824	public function RadioButton($name, $w, $prop=array(), $opt=array(), $onvalue='On', $checked=false, $x='', $y='', $js=false) {
12825		if ($x === '') {
12826			$x = $this->x;
12827		}
12828		if ($y === '') {
12829			$y = $this->y;
12830		}
12831		// check page for no-write regions and adapt page margins if necessary
12832		list($x, $y) = $this->checkPageRegions($w, $x, $y);
12833		if ($js) {
12834			$this->_addfield('radiobutton', $name, $x, $y, $w, $w, $prop);
12835			return;
12836		}
12837		if (TCPDF_STATIC::empty_string($onvalue)) {
12838			$onvalue = 'On';
12839		}
12840		if ($checked) {
12841			$defval = $onvalue;
12842		} else {
12843			$defval = 'Off';
12844		}
12845		// set font
12846		$font = 'zapfdingbats';
12847		if ($this->pdfa_mode) {
12848			// all fonts must be embedded
12849			$font = 'pdfa'.$font;
12850		}
12851		$this->AddFont($font);
12852		$tmpfont = $this->getFontBuffer($font);
12853		// set data for parent group
12854		if (!isset($this->radiobutton_groups[$this->page])) {
12855			$this->radiobutton_groups[$this->page] = array();
12856		}
12857		if (!isset($this->radiobutton_groups[$this->page][$name])) {
12858			$this->radiobutton_groups[$this->page][$name] = array();
12859			++$this->n;
12860			$this->radiobutton_groups[$this->page][$name]['n'] = $this->n;
12861			$this->radio_groups[] = $this->n;
12862		}
12863		$kid = ($this->n + 1);
12864		// save object ID to be added on Kids entry on parent object
12865		$this->radiobutton_groups[$this->page][$name][] = array('kid' => $kid, 'def' => $defval);
12866		// get default style
12867		$prop = array_merge($this->getFormDefaultProp(), $prop);
12868		$prop['NoToggleToOff'] = 'true';
12869		$prop['Radio'] = 'true';
12870		$prop['borderStyle'] = 'inset';
12871		// get annotation data
12872		$popt = TCPDF_STATIC::getAnnotOptFromJSProp($prop, $this->spot_colors, $this->rtl);
12873		// set additional default options
12874		$this->annotation_fonts[$tmpfont['fontkey']] = $tmpfont['i'];
12875		$fontstyle = sprintf('/F%d %F Tf %s', $tmpfont['i'], $this->FontSizePt, $this->TextColor);
12876		$popt['da'] = $fontstyle;
12877		// build appearance stream
12878		$popt['ap'] = array();
12879		$popt['ap']['n'] = array();
12880		$fx = ((($w - $this->getAbsFontMeasure($tmpfont['cw'][108])) / 2) * $this->k);
12881		$fy = (($w - ((($tmpfont['desc']['Ascent'] - $tmpfont['desc']['Descent']) * $this->FontSizePt / 1000) / $this->k)) * $this->k);
12882		$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);
12883		$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);
12884		if (!isset($popt['mk'])) {
12885			$popt['mk'] = array();
12886		}
12887		$popt['mk']['ca'] = '(l)';
12888		// merge options
12889		$opt = array_merge($popt, $opt);
12890		// set remaining annotation data
12891		$opt['Subtype'] = 'Widget';
12892		$opt['ft'] = 'Btn';
12893		if ($checked) {
12894			$opt['v'] = array('/'.$onvalue);
12895			$opt['as'] = $onvalue;
12896		} else {
12897			$opt['as'] = 'Off';
12898		}
12899		// store readonly flag
12900		if (!isset($this->radiobutton_groups[$this->page][$name]['#readonly#'])) {
12901			$this->radiobutton_groups[$this->page][$name]['#readonly#'] = false;
12902		}
12903		$this->radiobutton_groups[$this->page][$name]['#readonly#'] |= ($opt['f'] & 64);
12904		$this->Annotation($x, $y, $w, $w, $name, $opt, 0);
12905		if ($this->rtl) {
12906			$this->x -= $w;
12907		} else {
12908			$this->x += $w;
12909		}
12910	}
12911
12912	/**
12913	 * Creates a List-box field
12914	 * @param $name (string) field name
12915	 * @param $w (int) width
12916	 * @param $h (int) height
12917	 * @param $values (array) array containing the list of values.
12918	 * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
12919	 * @param $opt (array) annotation parameters. Possible values are described on official PDF32000_2008 reference.
12920	 * @param $x (float) Abscissa of the upper-left corner of the rectangle
12921	 * @param $y (float) Ordinate of the upper-left corner of the rectangle
12922	 * @param $js (boolean) if true put the field using JavaScript (requires Acrobat Writer to be rendered).
12923	 * @public
12924	 * @author Nicola Asuni
12925	 * @since 4.8.000 (2009-09-07)
12926	 */
12927	public function ListBox($name, $w, $h, $values, $prop=array(), $opt=array(), $x='', $y='', $js=false) {
12928		if ($x === '') {
12929			$x = $this->x;
12930		}
12931		if ($y === '') {
12932			$y = $this->y;
12933		}
12934		// check page for no-write regions and adapt page margins if necessary
12935		list($x, $y) = $this->checkPageRegions($h, $x, $y);
12936		if ($js) {
12937			$this->_addfield('listbox', $name, $x, $y, $w, $h, $prop);
12938			$s = '';
12939			foreach ($values as $value) {
12940				if (is_array($value)) {
12941					$s .= ',[\''.addslashes($value[1]).'\',\''.addslashes($value[0]).'\']';
12942				} else {
12943					$s .= ',[\''.addslashes($value).'\',\''.addslashes($value).'\']';
12944				}
12945			}
12946			$this->javascript .= 'f'.$name.'.setItems('.substr($s, 1).');'."\n";
12947			return;
12948		}
12949		// get default style
12950		$prop = array_merge($this->getFormDefaultProp(), $prop);
12951		// get annotation data
12952		$popt = TCPDF_STATIC::getAnnotOptFromJSProp($prop, $this->spot_colors, $this->rtl);
12953		// set additional default values
12954		$this->annotation_fonts[$this->CurrentFont['fontkey']] = $this->CurrentFont['i'];
12955		$fontstyle = sprintf('/F%d %F Tf %s', $this->CurrentFont['i'], $this->FontSizePt, $this->TextColor);
12956		$popt['da'] = $fontstyle;
12957		// build appearance stream
12958		$popt['ap'] = array();
12959		$popt['ap']['n'] = '/Tx BMC q '.$fontstyle.' ';
12960		$text = '';
12961		foreach($values as $item) {
12962			if (is_array($item)) {
12963				$text .= $item[1]."\n";
12964			} else {
12965				$text .= $item."\n";
12966			}
12967		}
12968		$tmpid = $this->startTemplate($w, $h, false);
12969		$this->MultiCell($w, $h, $text, 0, '', false, 0, 0, 0, true, 0, false, true, 0, 'T', false);
12970		$this->endTemplate();
12971		--$this->n;
12972		$popt['ap']['n'] .= $this->xobjects[$tmpid]['outdata'];
12973		unset($this->xobjects[$tmpid]);
12974		$popt['ap']['n'] .= 'Q EMC';
12975		// merge options
12976		$opt = array_merge($popt, $opt);
12977		// set remaining annotation data
12978		$opt['Subtype'] = 'Widget';
12979		$opt['ft'] = 'Ch';
12980		$opt['t'] = $name;
12981		$opt['opt'] = $values;
12982		unset($opt['mk']['ca']);
12983		unset($opt['mk']['rc']);
12984		unset($opt['mk']['ac']);
12985		unset($opt['mk']['i']);
12986		unset($opt['mk']['ri']);
12987		unset($opt['mk']['ix']);
12988		unset($opt['mk']['if']);
12989		unset($opt['mk']['tp']);
12990		$this->Annotation($x, $y, $w, $h, $name, $opt, 0);
12991		if ($this->rtl) {
12992			$this->x -= $w;
12993		} else {
12994			$this->x += $w;
12995		}
12996	}
12997
12998	/**
12999	 * Creates a Combo-box field
13000	 * @param $name (string) field name
13001	 * @param $w (int) width
13002	 * @param $h (int) height
13003	 * @param $values (array) array containing the list of values.
13004	 * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
13005	 * @param $opt (array) annotation parameters. Possible values are described on official PDF32000_2008 reference.
13006	 * @param $x (float) Abscissa of the upper-left corner of the rectangle
13007	 * @param $y (float) Ordinate of the upper-left corner of the rectangle
13008	 * @param $js (boolean) if true put the field using JavaScript (requires Acrobat Writer to be rendered).
13009	 * @public
13010	 * @author Nicola Asuni
13011	 * @since 4.8.000 (2009-09-07)
13012	 */
13013	public function ComboBox($name, $w, $h, $values, $prop=array(), $opt=array(), $x='', $y='', $js=false) {
13014		if ($x === '') {
13015			$x = $this->x;
13016		}
13017		if ($y === '') {
13018			$y = $this->y;
13019		}
13020		// check page for no-write regions and adapt page margins if necessary
13021		list($x, $y) = $this->checkPageRegions($h, $x, $y);
13022		if ($js) {
13023			$this->_addfield('combobox', $name, $x, $y, $w, $h, $prop);
13024			$s = '';
13025			foreach ($values as $value) {
13026				if (is_array($value)) {
13027					$s .= ',[\''.addslashes($value[1]).'\',\''.addslashes($value[0]).'\']';
13028				} else {
13029					$s .= ',[\''.addslashes($value).'\',\''.addslashes($value).'\']';
13030				}
13031			}
13032			$this->javascript .= 'f'.$name.'.setItems('.substr($s, 1).');'."\n";
13033			return;
13034		}
13035		// get default style
13036		$prop = array_merge($this->getFormDefaultProp(), $prop);
13037		$prop['Combo'] = true;
13038		// get annotation data
13039		$popt = TCPDF_STATIC::getAnnotOptFromJSProp($prop, $this->spot_colors, $this->rtl);
13040		// set additional default options
13041		$this->annotation_fonts[$this->CurrentFont['fontkey']] = $this->CurrentFont['i'];
13042		$fontstyle = sprintf('/F%d %F Tf %s', $this->CurrentFont['i'], $this->FontSizePt, $this->TextColor);
13043		$popt['da'] = $fontstyle;
13044		// build appearance stream
13045		$popt['ap'] = array();
13046		$popt['ap']['n'] = '/Tx BMC q '.$fontstyle.' ';
13047		$text = '';
13048		foreach($values as $item) {
13049			if (is_array($item)) {
13050				$text .= $item[1]."\n";
13051			} else {
13052				$text .= $item."\n";
13053			}
13054		}
13055		$tmpid = $this->startTemplate($w, $h, false);
13056		$this->MultiCell($w, $h, $text, 0, '', false, 0, 0, 0, true, 0, false, true, 0, 'T', false);
13057		$this->endTemplate();
13058		--$this->n;
13059		$popt['ap']['n'] .= $this->xobjects[$tmpid]['outdata'];
13060		unset($this->xobjects[$tmpid]);
13061		$popt['ap']['n'] .= 'Q EMC';
13062		// merge options
13063		$opt = array_merge($popt, $opt);
13064		// set remaining annotation data
13065		$opt['Subtype'] = 'Widget';
13066		$opt['ft'] = 'Ch';
13067		$opt['t'] = $name;
13068		$opt['opt'] = $values;
13069		unset($opt['mk']['ca']);
13070		unset($opt['mk']['rc']);
13071		unset($opt['mk']['ac']);
13072		unset($opt['mk']['i']);
13073		unset($opt['mk']['ri']);
13074		unset($opt['mk']['ix']);
13075		unset($opt['mk']['if']);
13076		unset($opt['mk']['tp']);
13077		$this->Annotation($x, $y, $w, $h, $name, $opt, 0);
13078		if ($this->rtl) {
13079			$this->x -= $w;
13080		} else {
13081			$this->x += $w;
13082		}
13083	}
13084
13085	/**
13086	 * Creates a CheckBox field
13087	 * @param $name (string) field name
13088	 * @param $w (int) width
13089	 * @param $checked (boolean) define the initial state.
13090	 * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
13091	 * @param $opt (array) annotation parameters. Possible values are described on official PDF32000_2008 reference.
13092	 * @param $onvalue (string) value to be returned if selected.
13093	 * @param $x (float) Abscissa of the upper-left corner of the rectangle
13094	 * @param $y (float) Ordinate of the upper-left corner of the rectangle
13095	 * @param $js (boolean) if true put the field using JavaScript (requires Acrobat Writer to be rendered).
13096	 * @public
13097	 * @author Nicola Asuni
13098	 * @since 4.8.000 (2009-09-07)
13099	 */
13100	public function CheckBox($name, $w, $checked=false, $prop=array(), $opt=array(), $onvalue='Yes', $x='', $y='', $js=false) {
13101		if ($x === '') {
13102			$x = $this->x;
13103		}
13104		if ($y === '') {
13105			$y = $this->y;
13106		}
13107		// check page for no-write regions and adapt page margins if necessary
13108		list($x, $y) = $this->checkPageRegions($w, $x, $y);
13109		if ($js) {
13110			$this->_addfield('checkbox', $name, $x, $y, $w, $w, $prop);
13111			return;
13112		}
13113		if (!isset($prop['value'])) {
13114			$prop['value'] = array('Yes');
13115		}
13116		// get default style
13117		$prop = array_merge($this->getFormDefaultProp(), $prop);
13118		$prop['borderStyle'] = 'inset';
13119		// get annotation data
13120		$popt = TCPDF_STATIC::getAnnotOptFromJSProp($prop, $this->spot_colors, $this->rtl);
13121		// set additional default options
13122		$font = 'zapfdingbats';
13123		if ($this->pdfa_mode) {
13124			// all fonts must be embedded
13125			$font = 'pdfa'.$font;
13126		}
13127		$this->AddFont($font);
13128		$tmpfont = $this->getFontBuffer($font);
13129		$this->annotation_fonts[$tmpfont['fontkey']] = $tmpfont['i'];
13130		$fontstyle = sprintf('/F%d %F Tf %s', $tmpfont['i'], $this->FontSizePt, $this->TextColor);
13131		$popt['da'] = $fontstyle;
13132		// build appearance stream
13133		$popt['ap'] = array();
13134		$popt['ap']['n'] = array();
13135		$fx = ((($w - $this->getAbsFontMeasure($tmpfont['cw'][110])) / 2) * $this->k);
13136		$fy = (($w - ((($tmpfont['desc']['Ascent'] - $tmpfont['desc']['Descent']) * $this->FontSizePt / 1000) / $this->k)) * $this->k);
13137		$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);
13138		$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);
13139		// merge options
13140		$opt = array_merge($popt, $opt);
13141		// set remaining annotation data
13142		$opt['Subtype'] = 'Widget';
13143		$opt['ft'] = 'Btn';
13144		$opt['t'] = $name;
13145		if (TCPDF_STATIC::empty_string($onvalue)) {
13146			$onvalue = 'Yes';
13147		}
13148		$opt['opt'] = array($onvalue);
13149		if ($checked) {
13150			$opt['v'] = array('/Yes');
13151			$opt['as'] = 'Yes';
13152		} else {
13153			$opt['v'] = array('/Off');
13154			$opt['as'] = 'Off';
13155		}
13156		$this->Annotation($x, $y, $w, $w, $name, $opt, 0);
13157		if ($this->rtl) {
13158			$this->x -= $w;
13159		} else {
13160			$this->x += $w;
13161		}
13162	}
13163
13164	/**
13165	 * Creates a button field
13166	 * @param $name (string) field name
13167	 * @param $w (int) width
13168	 * @param $h (int) height
13169	 * @param $caption (string) caption.
13170	 * @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.
13171	 * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
13172	 * @param $opt (array) annotation parameters. Possible values are described on official PDF32000_2008 reference.
13173	 * @param $x (float) Abscissa of the upper-left corner of the rectangle
13174	 * @param $y (float) Ordinate of the upper-left corner of the rectangle
13175	 * @param $js (boolean) if true put the field using JavaScript (requires Acrobat Writer to be rendered).
13176	 * @public
13177	 * @author Nicola Asuni
13178	 * @since 4.8.000 (2009-09-07)
13179	 */
13180	public function Button($name, $w, $h, $caption, $action, $prop=array(), $opt=array(), $x='', $y='', $js=false) {
13181		if ($x === '') {
13182			$x = $this->x;
13183		}
13184		if ($y === '') {
13185			$y = $this->y;
13186		}
13187		// check page for no-write regions and adapt page margins if necessary
13188		list($x, $y) = $this->checkPageRegions($h, $x, $y);
13189		if ($js) {
13190			$this->_addfield('button', $name, $this->x, $this->y, $w, $h, $prop);
13191			$this->javascript .= 'f'.$name.".buttonSetCaption('".addslashes($caption)."');\n";
13192			$this->javascript .= 'f'.$name.".setAction('MouseUp','".addslashes($action)."');\n";
13193			$this->javascript .= 'f'.$name.".highlight='push';\n";
13194			$this->javascript .= 'f'.$name.".print=false;\n";
13195			return;
13196		}
13197		// get default style
13198		$prop = array_merge($this->getFormDefaultProp(), $prop);
13199		$prop['Pushbutton'] = 'true';
13200		$prop['highlight'] = 'push';
13201		$prop['display'] = 'display.noPrint';
13202		// get annotation data
13203		$popt = TCPDF_STATIC::getAnnotOptFromJSProp($prop, $this->spot_colors, $this->rtl);
13204		$this->annotation_fonts[$this->CurrentFont['fontkey']] = $this->CurrentFont['i'];
13205		$fontstyle = sprintf('/F%d %F Tf %s', $this->CurrentFont['i'], $this->FontSizePt, $this->TextColor);
13206		$popt['da'] = $fontstyle;
13207		// build appearance stream
13208		$popt['ap'] = array();
13209		$popt['ap']['n'] = '/Tx BMC q '.$fontstyle.' ';
13210		$tmpid = $this->startTemplate($w, $h, false);
13211		$bw = (2 / $this->k); // border width
13212		$border = array(
13213			'L' => array('width' => $bw, 'cap' => 'square', 'join' => 'miter', 'dash' => 0, 'color' => array(231)),
13214			'R' => array('width' => $bw, 'cap' => 'square', 'join' => 'miter', 'dash' => 0, 'color' => array(51)),
13215			'T' => array('width' => $bw, 'cap' => 'square', 'join' => 'miter', 'dash' => 0, 'color' => array(231)),
13216			'B' => array('width' => $bw, 'cap' => 'square', 'join' => 'miter', 'dash' => 0, 'color' => array(51)));
13217		$this->SetFillColor(204);
13218		$this->Cell($w, $h, $caption, $border, 0, 'C', true, '', 1, false, 'T', 'M');
13219		$this->endTemplate();
13220		--$this->n;
13221		$popt['ap']['n'] .= $this->xobjects[$tmpid]['outdata'];
13222		unset($this->xobjects[$tmpid]);
13223		$popt['ap']['n'] .= 'Q EMC';
13224		// set additional default options
13225		if (!isset($popt['mk'])) {
13226			$popt['mk'] = array();
13227		}
13228		$ann_obj_id = ($this->n + 1);
13229		if (!empty($action) AND !is_array($action)) {
13230			$ann_obj_id = ($this->n + 2);
13231		}
13232		$popt['mk']['ca'] = $this->_textstring($caption, $ann_obj_id);
13233		$popt['mk']['rc'] = $this->_textstring($caption, $ann_obj_id);
13234		$popt['mk']['ac'] = $this->_textstring($caption, $ann_obj_id);
13235		// merge options
13236		$opt = array_merge($popt, $opt);
13237		// set remaining annotation data
13238		$opt['Subtype'] = 'Widget';
13239		$opt['ft'] = 'Btn';
13240		$opt['t'] = $caption;
13241		$opt['v'] = $name;
13242		if (!empty($action)) {
13243			if (is_array($action)) {
13244				// form action options as on section 12.7.5 of PDF32000_2008.
13245				$opt['aa'] = '/D <<';
13246				$bmode = array('SubmitForm', 'ResetForm', 'ImportData');
13247				foreach ($action AS $key => $val) {
13248					if (($key == 'S') AND in_array($val, $bmode)) {
13249						$opt['aa'] .= ' /S /'.$val;
13250					} elseif (($key == 'F') AND (!empty($val))) {
13251						$opt['aa'] .= ' /F '.$this->_datastring($val, $ann_obj_id);
13252					} elseif (($key == 'Fields') AND is_array($val) AND !empty($val)) {
13253						$opt['aa'] .= ' /Fields [';
13254						foreach ($val AS $field) {
13255							$opt['aa'] .= ' '.$this->_textstring($field, $ann_obj_id);
13256						}
13257						$opt['aa'] .= ']';
13258					} elseif (($key == 'Flags')) {
13259						$ff = 0;
13260						if (is_array($val)) {
13261							foreach ($val AS $flag) {
13262								switch ($flag) {
13263									case 'Include/Exclude': {
13264										$ff += 1 << 0;
13265										break;
13266									}
13267									case 'IncludeNoValueFields': {
13268										$ff += 1 << 1;
13269										break;
13270									}
13271									case 'ExportFormat': {
13272										$ff += 1 << 2;
13273										break;
13274									}
13275									case 'GetMethod': {
13276										$ff += 1 << 3;
13277										break;
13278									}
13279									case 'SubmitCoordinates': {
13280										$ff += 1 << 4;
13281										break;
13282									}
13283									case 'XFDF': {
13284										$ff += 1 << 5;
13285										break;
13286									}
13287									case 'IncludeAppendSaves': {
13288										$ff += 1 << 6;
13289										break;
13290									}
13291									case 'IncludeAnnotations': {
13292										$ff += 1 << 7;
13293										break;
13294									}
13295									case 'SubmitPDF': {
13296										$ff += 1 << 8;
13297										break;
13298									}
13299									case 'CanonicalFormat': {
13300										$ff += 1 << 9;
13301										break;
13302									}
13303									case 'ExclNonUserAnnots': {
13304										$ff += 1 << 10;
13305										break;
13306									}
13307									case 'ExclFKey': {
13308										$ff += 1 << 11;
13309										break;
13310									}
13311									case 'EmbedForm': {
13312										$ff += 1 << 13;
13313										break;
13314									}
13315								}
13316							}
13317						} else {
13318							$ff = intval($val);
13319						}
13320						$opt['aa'] .= ' /Flags '.$ff;
13321					}
13322				}
13323				$opt['aa'] .= ' >>';
13324			} else {
13325				// Javascript action or raw action command
13326				$js_obj_id = $this->addJavascriptObject($action);
13327				$opt['aa'] = '/D '.$js_obj_id.' 0 R';
13328			}
13329		}
13330		$this->Annotation($x, $y, $w, $h, $name, $opt, 0);
13331		if ($this->rtl) {
13332			$this->x -= $w;
13333		} else {
13334			$this->x += $w;
13335		}
13336	}
13337
13338	// --- END FORMS FIELDS ------------------------------------------------
13339
13340	/**
13341	 * Add certification signature (DocMDP or UR3)
13342	 * You can set only one signature type
13343	 * @protected
13344	 * @author Nicola Asuni
13345	 * @since 4.6.008 (2009-05-07)
13346	 */
13347	protected function _putsignature() {
13348		if ((!$this->sign) OR (!isset($this->signature_data['cert_type']))) {
13349			return;
13350		}
13351		$sigobjid = ($this->sig_obj_id + 1);
13352		$out = $this->_getobj($sigobjid)."\n";
13353		$out .= '<< /Type /Sig';
13354		$out .= ' /Filter /Adobe.PPKLite';
13355		$out .= ' /SubFilter /adbe.pkcs7.detached';
13356		$out .= ' '.TCPDF_STATIC::$byterange_string;
13357		$out .= ' /Contents<'.str_repeat('0', $this->signature_max_length).'>';
13358		if (empty($this->signature_data['approval']) OR ($this->signature_data['approval'] != 'A')) {
13359			$out .= ' /Reference ['; // array of signature reference dictionaries
13360			$out .= ' << /Type /SigRef';
13361			if ($this->signature_data['cert_type'] > 0) {
13362				$out .= ' /TransformMethod /DocMDP';
13363				$out .= ' /TransformParams <<';
13364				$out .= ' /Type /TransformParams';
13365				$out .= ' /P '.$this->signature_data['cert_type'];
13366				$out .= ' /V /1.2';
13367			} else {
13368				$out .= ' /TransformMethod /UR3';
13369				$out .= ' /TransformParams <<';
13370				$out .= ' /Type /TransformParams';
13371				$out .= ' /V /2.2';
13372				if (!TCPDF_STATIC::empty_string($this->ur['document'])) {
13373					$out .= ' /Document['.$this->ur['document'].']';
13374				}
13375				if (!TCPDF_STATIC::empty_string($this->ur['form'])) {
13376					$out .= ' /Form['.$this->ur['form'].']';
13377				}
13378				if (!TCPDF_STATIC::empty_string($this->ur['signature'])) {
13379					$out .= ' /Signature['.$this->ur['signature'].']';
13380				}
13381				if (!TCPDF_STATIC::empty_string($this->ur['annots'])) {
13382					$out .= ' /Annots['.$this->ur['annots'].']';
13383				}
13384				if (!TCPDF_STATIC::empty_string($this->ur['ef'])) {
13385					$out .= ' /EF['.$this->ur['ef'].']';
13386				}
13387				if (!TCPDF_STATIC::empty_string($this->ur['formex'])) {
13388					$out .= ' /FormEX['.$this->ur['formex'].']';
13389				}
13390			}
13391			$out .= ' >>'; // close TransformParams
13392			// optional digest data (values must be calculated and replaced later)
13393			//$out .= ' /Data ********** 0 R';
13394			//$out .= ' /DigestMethod/MD5';
13395			//$out .= ' /DigestLocation[********** 34]';
13396			//$out .= ' /DigestValue<********************************>';
13397			$out .= ' >>';
13398			$out .= ' ]'; // end of reference
13399		}
13400		if (isset($this->signature_data['info']['Name']) AND !TCPDF_STATIC::empty_string($this->signature_data['info']['Name'])) {
13401			$out .= ' /Name '.$this->_textstring($this->signature_data['info']['Name'], $sigobjid);
13402		}
13403		if (isset($this->signature_data['info']['Location']) AND !TCPDF_STATIC::empty_string($this->signature_data['info']['Location'])) {
13404			$out .= ' /Location '.$this->_textstring($this->signature_data['info']['Location'], $sigobjid);
13405		}
13406		if (isset($this->signature_data['info']['Reason']) AND !TCPDF_STATIC::empty_string($this->signature_data['info']['Reason'])) {
13407			$out .= ' /Reason '.$this->_textstring($this->signature_data['info']['Reason'], $sigobjid);
13408		}
13409		if (isset($this->signature_data['info']['ContactInfo']) AND !TCPDF_STATIC::empty_string($this->signature_data['info']['ContactInfo'])) {
13410			$out .= ' /ContactInfo '.$this->_textstring($this->signature_data['info']['ContactInfo'], $sigobjid);
13411		}
13412		$out .= ' /M '.$this->_datestring($sigobjid, $this->doc_modification_timestamp);
13413		$out .= ' >>';
13414		$out .= "\n".'endobj';
13415		$this->_out($out);
13416	}
13417
13418	/**
13419	 * Set User's Rights for PDF Reader
13420	 * WARNING: This is experimental and currently do not work.
13421	 * Check the PDF Reference 8.7.1 Transform Methods,
13422	 * Table 8.105 Entries in the UR transform parameters dictionary
13423	 * @param $enable (boolean) if true enable user's rights on PDF reader
13424	 * @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.
13425	 * @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.
13426	 * @param $form (string) Names specifying additional form-field-related usage rights for the document. Valid names are: /Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate
13427	 * @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.
13428	 * @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
13429	 Names specifying additional embedded-files-related usage rights for the document.
13430	 * @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.
13431	 * @public
13432	 * @author Nicola Asuni
13433	 * @since 2.9.000 (2008-03-26)
13434	 */
13435	public function setUserRights(
13436			$enable=true,
13437			$document='/FullSave',
13438			$annots='/Create/Delete/Modify/Copy/Import/Export',
13439			$form='/Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate',
13440			$signature='/Modify',
13441			$ef='/Create/Delete/Modify/Import',
13442			$formex='') {
13443		$this->ur['enabled'] = $enable;
13444		$this->ur['document'] = $document;
13445		$this->ur['annots'] = $annots;
13446		$this->ur['form'] = $form;
13447		$this->ur['signature'] = $signature;
13448		$this->ur['ef'] = $ef;
13449		$this->ur['formex'] = $formex;
13450		if (!$this->sign) {
13451			$this->setSignature('', '', '', '', 0, array());
13452		}
13453	}
13454
13455	/**
13456	 * Enable document signature (requires the OpenSSL Library).
13457	 * The digital signature improve document authenticity and integrity and allows o enable extra features on Acrobat Reader.
13458	 * To create self-signed signature: openssl req -x509 -nodes -days 365000 -newkey rsa:1024 -keyout tcpdf.crt -out tcpdf.crt
13459	 * To export crt to p12: openssl pkcs12 -export -in tcpdf.crt -out tcpdf.p12
13460	 * To convert pfx certificate to pem: openssl pkcs12 -in tcpdf.pfx -out tcpdf.crt -nodes
13461	 * @param $signing_cert (mixed) signing certificate (string or filename prefixed with 'file://')
13462	 * @param $private_key (mixed) private key (string or filename prefixed with 'file://')
13463	 * @param $private_key_password (string) password
13464	 * @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.
13465	 * @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.
13466	 * @param $info (array) array of option information: Name, Location, Reason, ContactInfo.
13467	 * @param $approval (string) Enable approval signature eg. for PDF incremental update
13468	 * @public
13469	 * @author Nicola Asuni
13470	 * @since 4.6.005 (2009-04-24)
13471	 */
13472	public function setSignature($signing_cert='', $private_key='', $private_key_password='', $extracerts='', $cert_type=2, $info=array(), $approval='') {
13473		// to create self-signed signature: openssl req -x509 -nodes -days 365000 -newkey rsa:1024 -keyout tcpdf.crt -out tcpdf.crt
13474		// to export crt to p12: openssl pkcs12 -export -in tcpdf.crt -out tcpdf.p12
13475		// to convert pfx certificate to pem: openssl
13476		//     OpenSSL> pkcs12 -in <cert.pfx> -out <cert.crt> -nodes
13477		$this->sign = true;
13478		++$this->n;
13479		$this->sig_obj_id = $this->n; // signature widget
13480		++$this->n; // signature object ($this->sig_obj_id + 1)
13481		$this->signature_data = array();
13482		if (strlen($signing_cert) == 0) {
13483			$this->Error('Please provide a certificate file and password!');
13484		}
13485		if (strlen($private_key) == 0) {
13486			$private_key = $signing_cert;
13487		}
13488		$this->signature_data['signcert'] = $signing_cert;
13489		$this->signature_data['privkey'] = $private_key;
13490		$this->signature_data['password'] = $private_key_password;
13491		$this->signature_data['extracerts'] = $extracerts;
13492		$this->signature_data['cert_type'] = $cert_type;
13493		$this->signature_data['info'] = $info;
13494		$this->signature_data['approval'] = $approval;
13495	}
13496
13497	/**
13498	 * Set the digital signature appearance (a cliccable rectangle area to get signature properties)
13499	 * @param $x (float) Abscissa of the upper-left corner.
13500	 * @param $y (float) Ordinate of the upper-left corner.
13501	 * @param $w (float) Width of the signature area.
13502	 * @param $h (float) Height of the signature area.
13503	 * @param $page (int) option page number (if < 0 the current page is used).
13504	 * @param $name (string) Name of the signature.
13505	 * @public
13506	 * @author Nicola Asuni
13507	 * @since 5.3.011 (2010-06-17)
13508	 */
13509	public function setSignatureAppearance($x=0, $y=0, $w=0, $h=0, $page=-1, $name='') {
13510		$this->signature_appearance = $this->getSignatureAppearanceArray($x, $y, $w, $h, $page, $name);
13511	}
13512
13513	/**
13514	 * Add an empty digital signature appearance (a cliccable rectangle area to get signature properties)
13515	 * @param $x (float) Abscissa of the upper-left corner.
13516	 * @param $y (float) Ordinate of the upper-left corner.
13517	 * @param $w (float) Width of the signature area.
13518	 * @param $h (float) Height of the signature area.
13519	 * @param $page (int) option page number (if < 0 the current page is used).
13520	 * @param $name (string) Name of the signature.
13521	 * @public
13522	 * @author Nicola Asuni
13523	 * @since 5.9.101 (2011-07-06)
13524	 */
13525	public function addEmptySignatureAppearance($x=0, $y=0, $w=0, $h=0, $page=-1, $name='') {
13526		++$this->n;
13527		$this->empty_signature_appearance[] = array('objid' => $this->n) + $this->getSignatureAppearanceArray($x, $y, $w, $h, $page, $name);
13528	}
13529
13530	/**
13531	 * Get the array that defines the signature appearance (page and rectangle coordinates).
13532	 * @param $x (float) Abscissa of the upper-left corner.
13533	 * @param $y (float) Ordinate of the upper-left corner.
13534	 * @param $w (float) Width of the signature area.
13535	 * @param $h (float) Height of the signature area.
13536	 * @param $page (int) option page number (if < 0 the current page is used).
13537	 * @param $name (string) Name of the signature.
13538	 * @return (array) Array defining page and rectangle coordinates of signature appearance.
13539	 * @protected
13540	 * @author Nicola Asuni
13541	 * @since 5.9.101 (2011-07-06)
13542	 */
13543	protected function getSignatureAppearanceArray($x=0, $y=0, $w=0, $h=0, $page=-1, $name='') {
13544		$sigapp = array();
13545		if (($page < 1) OR ($page > $this->numpages)) {
13546			$sigapp['page'] = $this->page;
13547		} else {
13548			$sigapp['page'] = intval($page);
13549		}
13550		if (empty($name)) {
13551			$sigapp['name'] = 'Signature';
13552		} else {
13553			$sigapp['name'] = $name;
13554		}
13555		$a = $x * $this->k;
13556		$b = $this->pagedim[($sigapp['page'])]['h'] - (($y + $h) * $this->k);
13557		$c = $w * $this->k;
13558		$d = $h * $this->k;
13559		$sigapp['rect'] = sprintf('%F %F %F %F', $a, $b, ($a + $c), ($b + $d));
13560		return $sigapp;
13561	}
13562
13563	/**
13564	 * Enable document timestamping (requires the OpenSSL Library).
13565	 * The trusted timestamping improve document security that means that no one should be able to change the document once it has been recorded.
13566	 * Use with digital signature only!
13567	 * @param $tsa_host (string) Time Stamping Authority (TSA) server (prefixed with 'https://')
13568	 * @param $tsa_username (string) Specifies the username for TSA authorization (optional) OR specifies the TSA authorization PEM file (see: example_66.php, optional)
13569	 * @param $tsa_password (string) Specifies the password for TSA authorization (optional)
13570	 * @param $tsa_cert (string) Specifies the location of TSA certificate for authorization (optional for cURL)
13571	 * @public
13572	 * @author Richard Stockinger
13573	 * @since 6.0.090 (2014-06-16)
13574	 */
13575	public function setTimeStamp($tsa_host='', $tsa_username='', $tsa_password='', $tsa_cert='') {
13576		$this->tsa_data = array();
13577		if (!function_exists('curl_init')) {
13578			$this->Error('Please enable cURL PHP extension!');
13579		}
13580		if (strlen($tsa_host) == 0) {
13581			$this->Error('Please specify the host of Time Stamping Authority (TSA)!');
13582		}
13583		$this->tsa_data['tsa_host'] = $tsa_host;
13584		if (is_file($tsa_username)) {
13585			$this->tsa_data['tsa_auth'] = $tsa_username;
13586		} else {
13587			$this->tsa_data['tsa_username'] = $tsa_username;
13588		}
13589		$this->tsa_data['tsa_password'] = $tsa_password;
13590		$this->tsa_data['tsa_cert'] = $tsa_cert;
13591		$this->tsa_timestamp = true;
13592	}
13593
13594	/**
13595	 * NOT YET IMPLEMENTED
13596	 * Request TSA for a timestamp
13597	 * @param $signature (string) Digital signature as binary string
13598	 * @return (string) Timestamped digital signature
13599	 * @protected
13600	 * @author Richard Stockinger
13601	 * @since 6.0.090 (2014-06-16)
13602	 */
13603	protected function applyTSA($signature) {
13604		if (!$this->tsa_timestamp) {
13605			return $signature;
13606		}
13607		//@TODO: implement this feature
13608		return $signature;
13609	}
13610
13611	/**
13612	 * Create a new page group.
13613	 * NOTE: call this function before calling AddPage()
13614	 * @param $page (int) starting group page (leave empty for next page).
13615	 * @public
13616	 * @since 3.0.000 (2008-03-27)
13617	 */
13618	public function startPageGroup($page='') {
13619		if (empty($page)) {
13620			$page = $this->page + 1;
13621		}
13622		$this->newpagegroup[$page] = sizeof($this->newpagegroup) + 1;
13623	}
13624
13625	/**
13626	 * Set the starting page number.
13627	 * @param $num (int) Starting page number.
13628	 * @since 5.9.093 (2011-06-16)
13629	 * @public
13630	 */
13631	public function setStartingPageNumber($num=1) {
13632		$this->starting_page_number = max(0, intval($num));
13633	}
13634
13635	/**
13636	 * Returns the string alias used right align page numbers.
13637	 * If the current font is unicode type, the returned string wil contain an additional open curly brace.
13638	 * @return string
13639	 * @since 5.9.099 (2011-06-27)
13640	 * @public
13641	 */
13642	public function getAliasRightShift() {
13643		// calculate aproximatively the ratio between widths of aliases and replacements.
13644		$ref = '{'.TCPDF_STATIC::$alias_right_shift.'}{'.TCPDF_STATIC::$alias_tot_pages.'}{'.TCPDF_STATIC::$alias_num_page.'}';
13645		$rep = str_repeat(' ', $this->GetNumChars($ref));
13646		$wrep = $this->GetStringWidth($rep);
13647		if ($wrep > 0) {
13648			$wdiff = max(1, ($this->GetStringWidth($ref) / $wrep));
13649		} else {
13650			$wdiff = 1;
13651		}
13652		$sdiff = sprintf('%F', $wdiff);
13653		$alias = TCPDF_STATIC::$alias_right_shift.$sdiff.'}';
13654		if ($this->isUnicodeFont()) {
13655			$alias = '{'.$alias;
13656		}
13657		return $alias;
13658	}
13659
13660	/**
13661	 * Returns the string alias used for the total number of pages.
13662	 * If the current font is unicode type, the returned string is surrounded by additional curly braces.
13663	 * This alias will be replaced by the total number of pages in the document.
13664	 * @return string
13665	 * @since 4.0.018 (2008-08-08)
13666	 * @public
13667	 */
13668	public function getAliasNbPages() {
13669		if ($this->isUnicodeFont()) {
13670			return '{'.TCPDF_STATIC::$alias_tot_pages.'}';
13671		}
13672		return TCPDF_STATIC::$alias_tot_pages;
13673	}
13674
13675	/**
13676	 * Returns the string alias used for the page number.
13677	 * If the current font is unicode type, the returned string is surrounded by additional curly braces.
13678	 * This alias will be replaced by the page number.
13679	 * @return string
13680	 * @since 4.5.000 (2009-01-02)
13681	 * @public
13682	 */
13683	public function getAliasNumPage() {
13684		if ($this->isUnicodeFont()) {
13685			return '{'.TCPDF_STATIC::$alias_num_page.'}';
13686		}
13687		return TCPDF_STATIC::$alias_num_page;
13688	}
13689
13690	/**
13691	 * Return the alias for the total number of pages in the current page group.
13692	 * If the current font is unicode type, the returned string is surrounded by additional curly braces.
13693	 * This alias will be replaced by the total number of pages in this group.
13694	 * @return alias of the current page group
13695	 * @public
13696	 * @since 3.0.000 (2008-03-27)
13697	 */
13698	public function getPageGroupAlias() {
13699		if ($this->isUnicodeFont()) {
13700			return '{'.TCPDF_STATIC::$alias_group_tot_pages.'}';
13701		}
13702		return TCPDF_STATIC::$alias_group_tot_pages;
13703	}
13704
13705	/**
13706	 * Return the alias for the page number on the current page group.
13707	 * If the current font is unicode type, the returned string is surrounded by additional curly braces.
13708	 * This alias will be replaced by the page number (relative to the belonging group).
13709	 * @return alias of the current page group
13710	 * @public
13711	 * @since 4.5.000 (2009-01-02)
13712	 */
13713	public function getPageNumGroupAlias() {
13714		if ($this->isUnicodeFont()) {
13715			return '{'.TCPDF_STATIC::$alias_group_num_page.'}';
13716		}
13717		return TCPDF_STATIC::$alias_group_num_page;
13718	}
13719
13720	/**
13721	 * Return the current page in the group.
13722	 * @return current page in the group
13723	 * @public
13724	 * @since 3.0.000 (2008-03-27)
13725	 */
13726	public function getGroupPageNo() {
13727		return $this->pagegroups[$this->currpagegroup];
13728	}
13729
13730	/**
13731	 * Returns the current group page number formatted as a string.
13732	 * @public
13733	 * @since 4.3.003 (2008-11-18)
13734	 * @see PaneNo(), formatPageNumber()
13735	 */
13736	public function getGroupPageNoFormatted() {
13737		return TCPDF_STATIC::formatPageNumber($this->getGroupPageNo());
13738	}
13739
13740	/**
13741	 * Returns the current page number formatted as a string.
13742	 * @public
13743	 * @since 4.2.005 (2008-11-06)
13744	 * @see PaneNo(), formatPageNumber()
13745	 */
13746	public function PageNoFormatted() {
13747		return TCPDF_STATIC::formatPageNumber($this->PageNo());
13748	}
13749
13750	/**
13751	 * Put pdf layers.
13752	 * @protected
13753	 * @since 3.0.000 (2008-03-27)
13754	 */
13755	protected function _putocg() {
13756		if (empty($this->pdflayers)) {
13757			return;
13758		}
13759		foreach ($this->pdflayers as $key => $layer) {
13760			 $this->pdflayers[$key]['objid'] = $this->_newobj();
13761			 $out = '<< /Type /OCG';
13762			 $out .= ' /Name '.$this->_textstring($layer['name'], $this->pdflayers[$key]['objid']);
13763			 $out .= ' /Usage <<';
13764			 if (isset($layer['print']) AND ($layer['print'] !== NULL)) {
13765				$out .= ' /Print <</PrintState /'.($layer['print']?'ON':'OFF').'>>';
13766			 }
13767			 $out .= ' /View <</ViewState /'.($layer['view']?'ON':'OFF').'>>';
13768			 $out .= ' >> >>';
13769			 $out .= "\n".'endobj';
13770			 $this->_out($out);
13771		}
13772	}
13773
13774	/**
13775	 * Start a new pdf layer.
13776	 * @param $name (string) Layer name (only a-z letters and numbers). Leave empty for automatic name.
13777	 * @param $print (boolean|null) Set to TRUE to print this layer, FALSE to not print and NULL to not set this option
13778	 * @param $view (boolean) Set to true to view this layer.
13779	 * @param $lock (boolean) If true lock the layer
13780	 * @public
13781	 * @since 5.9.102 (2011-07-13)
13782	 */
13783	public function startLayer($name='', $print=true, $view=true, $lock=true) {
13784		if ($this->state != 2) {
13785			return;
13786		}
13787		$layer = sprintf('LYR%03d', (count($this->pdflayers) + 1));
13788		if (empty($name)) {
13789			$name = $layer;
13790		} else {
13791			$name = preg_replace('/[^a-zA-Z0-9_\-]/', '', $name);
13792		}
13793		$this->pdflayers[] = array('layer' => $layer, 'name' => $name, 'print' => $print, 'view' => $view, 'lock' => $lock);
13794		$this->openMarkedContent = true;
13795		$this->_out('/OC /'.$layer.' BDC');
13796	}
13797
13798	/**
13799	 * End the current PDF layer.
13800	 * @public
13801	 * @since 5.9.102 (2011-07-13)
13802	 */
13803	public function endLayer() {
13804		if ($this->state != 2) {
13805			return;
13806		}
13807		if ($this->openMarkedContent) {
13808			// close existing open marked-content layer
13809			$this->_out('EMC');
13810			$this->openMarkedContent = false;
13811		}
13812	}
13813
13814	/**
13815	 * Set the visibility of the successive elements.
13816	 * This can be useful, for instance, to put a background
13817	 * image or color that will show on screen but won't print.
13818	 * @param $v (string) visibility mode. Legal values are: all, print, screen or view.
13819	 * @public
13820	 * @since 3.0.000 (2008-03-27)
13821	 */
13822	public function setVisibility($v) {
13823		if ($this->state != 2) {
13824			return;
13825		}
13826		$this->endLayer();
13827		switch($v) {
13828			case 'print': {
13829				$this->startLayer('Print', true, false);
13830				break;
13831			}
13832			case 'view':
13833			case 'screen': {
13834				$this->startLayer('View', false, true);
13835				break;
13836			}
13837			case 'all': {
13838				$this->_out('');
13839				break;
13840			}
13841			default: {
13842				$this->Error('Incorrect visibility: '.$v);
13843				break;
13844			}
13845		}
13846	}
13847
13848	/**
13849	 * Add transparency parameters to the current extgstate
13850	 * @param $parms (array) parameters
13851	 * @return the number of extgstates
13852	 * @protected
13853	 * @since 3.0.000 (2008-03-27)
13854	 */
13855	protected function addExtGState($parms) {
13856		if ($this->pdfa_mode) {
13857			// transparencies are not allowed in PDF/A mode
13858			return;
13859		}
13860		// check if this ExtGState already exist
13861		foreach ($this->extgstates as $i => $ext) {
13862			if ($ext['parms'] == $parms) {
13863				if ($this->inxobj) {
13864					// we are inside an XObject template
13865					$this->xobjects[$this->xobjid]['extgstates'][$i] = $ext;
13866				}
13867				// return reference to existing ExtGState
13868				return $i;
13869			}
13870		}
13871		$n = (count($this->extgstates) + 1);
13872		$this->extgstates[$n] = array('parms' => $parms);
13873		if ($this->inxobj) {
13874			// we are inside an XObject template
13875			$this->xobjects[$this->xobjid]['extgstates'][$n] = $this->extgstates[$n];
13876		}
13877		return $n;
13878	}
13879
13880	/**
13881	 * Add an extgstate
13882	 * @param $gs (array) extgstate
13883	 * @protected
13884	 * @since 3.0.000 (2008-03-27)
13885	 */
13886	protected function setExtGState($gs) {
13887		if ($this->pdfa_mode OR ($this->state != 2)) {
13888			// transparency is not allowed in PDF/A mode
13889			return;
13890		}
13891		$this->_out(sprintf('/GS%d gs', $gs));
13892	}
13893
13894	/**
13895	 * Put extgstates for object transparency
13896	 * @protected
13897	 * @since 3.0.000 (2008-03-27)
13898	 */
13899	protected function _putextgstates() {
13900		foreach ($this->extgstates as $i => $ext) {
13901			$this->extgstates[$i]['n'] = $this->_newobj();
13902			$out = '<< /Type /ExtGState';
13903			foreach ($ext['parms'] as $k => $v) {
13904				if (is_float($v)) {
13905					$v = sprintf('%F', $v);
13906				} elseif ($v === true) {
13907					$v = 'true';
13908				} elseif ($v === false) {
13909					$v = 'false';
13910				}
13911				$out .= ' /'.$k.' '.$v;
13912			}
13913			$out .= ' >>';
13914			$out .= "\n".'endobj';
13915			$this->_out($out);
13916		}
13917	}
13918
13919	/**
13920	 * Set overprint mode for stroking (OP) and non-stroking (op) painting operations.
13921	 * (Check the "Entries in a Graphics State Parameter Dictionary" on PDF 32000-1:2008).
13922	 * @param $stroking (boolean) If true apply overprint for stroking operations.
13923	 * @param $nonstroking (boolean) If true apply overprint for painting operations other than stroking.
13924	 * @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).
13925	 * @public
13926	 * @since 5.9.152 (2012-03-23)
13927	 */
13928	public function setOverprint($stroking=true, $nonstroking='', $mode=0) {
13929		if ($this->state != 2) {
13930			return;
13931		}
13932		$stroking = $stroking ? true : false;
13933		if (TCPDF_STATIC::empty_string($nonstroking)) {
13934			// default value if not set
13935			$nonstroking = $stroking;
13936		} else {
13937			$nonstroking = $nonstroking ? true : false;
13938		}
13939		if (($mode != 0) AND ($mode != 1)) {
13940			$mode = 0;
13941		}
13942		$this->overprint = array('OP' => $stroking, 'op' => $nonstroking, 'OPM' => $mode);
13943		$gs = $this->addExtGState($this->overprint);
13944		$this->setExtGState($gs);
13945	}
13946
13947	/**
13948	 * Get the overprint mode array (OP, op, OPM).
13949	 * (Check the "Entries in a Graphics State Parameter Dictionary" on PDF 32000-1:2008).
13950	 * @return array.
13951	 * @public
13952	 * @since 5.9.152 (2012-03-23)
13953	 */
13954	public function getOverprint() {
13955		return $this->overprint;
13956	}
13957
13958	/**
13959	 * Set alpha for stroking (CA) and non-stroking (ca) operations.
13960	 * @param $stroking (float) Alpha value for stroking operations: real value from 0 (transparent) to 1 (opaque).
13961	 * @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
13962	 * @param $nonstroking (float) Alpha value for non-stroking operations: real value from 0 (transparent) to 1 (opaque).
13963	 * @param $ais (boolean)
13964	 * @public
13965	 * @since 3.0.000 (2008-03-27)
13966	 */
13967	public function setAlpha($stroking=1, $bm='Normal', $nonstroking='', $ais=false) {
13968		if ($this->pdfa_mode) {
13969			// transparency is not allowed in PDF/A mode
13970			return;
13971		}
13972		$stroking = floatval($stroking);
13973		if (TCPDF_STATIC::empty_string($nonstroking)) {
13974			// default value if not set
13975			$nonstroking = $stroking;
13976		} else {
13977			$nonstroking = floatval($nonstroking);
13978		}
13979		if ($bm[0] == '/') {
13980			// remove trailing slash
13981			$bm = substr($bm, 1);
13982		}
13983		if (!in_array($bm, array('Normal', 'Multiply', 'Screen', 'Overlay', 'Darken', 'Lighten', 'ColorDodge', 'ColorBurn', 'HardLight', 'SoftLight', 'Difference', 'Exclusion', 'Hue', 'Saturation', 'Color', 'Luminosity'))) {
13984			$bm = 'Normal';
13985		}
13986		$ais = $ais ? true : false;
13987		$this->alpha = array('CA' => $stroking, 'ca' => $nonstroking, 'BM' => '/'.$bm, 'AIS' => $ais);
13988		$gs = $this->addExtGState($this->alpha);
13989		$this->setExtGState($gs);
13990	}
13991
13992	/**
13993	 * Get the alpha mode array (CA, ca, BM, AIS).
13994	 * (Check the "Entries in a Graphics State Parameter Dictionary" on PDF 32000-1:2008).
13995	 * @return array.
13996	 * @public
13997	 * @since 5.9.152 (2012-03-23)
13998	 */
13999	public function getAlpha() {
14000		return $this->alpha;
14001	}
14002
14003	/**
14004	 * Set the default JPEG compression quality (1-100)
14005	 * @param $quality (int) JPEG quality, integer between 1 and 100
14006	 * @public
14007	 * @since 3.0.000 (2008-03-27)
14008	 */
14009	public function setJPEGQuality($quality) {
14010		if (($quality < 1) OR ($quality > 100)) {
14011			$quality = 75;
14012		}
14013		$this->jpeg_quality = intval($quality);
14014	}
14015
14016	/**
14017	 * Set the default number of columns in a row for HTML tables.
14018	 * @param $cols (int) number of columns
14019	 * @public
14020	 * @since 3.0.014 (2008-06-04)
14021	 */
14022	public function setDefaultTableColumns($cols=4) {
14023		$this->default_table_columns = intval($cols);
14024	}
14025
14026	/**
14027	 * Set the height of the cell (line height) respect the font height.
14028	 * @param $h (int) cell proportion respect font height (typical value = 1.25).
14029	 * @public
14030	 * @since 3.0.014 (2008-06-04)
14031	 */
14032	public function setCellHeightRatio($h) {
14033		$this->cell_height_ratio = $h;
14034	}
14035
14036	/**
14037	 * return the height of cell repect font height.
14038	 * @public
14039	 * @since 4.0.012 (2008-07-24)
14040	 */
14041	public function getCellHeightRatio() {
14042		return $this->cell_height_ratio;
14043	}
14044
14045	/**
14046	 * Set the PDF version (check PDF reference for valid values).
14047	 * @param $version (string) PDF document version.
14048	 * @public
14049	 * @since 3.1.000 (2008-06-09)
14050	 */
14051	public function setPDFVersion($version='1.7') {
14052		if ($this->pdfa_mode && $this->pdfa_version == 1 ) {
14053			// PDF/A mode
14054			$this->PDFVersion = '1.4';
14055		} else {
14056			$this->PDFVersion = $version;
14057		}
14058	}
14059
14060	/**
14061	 * Set the viewer preferences dictionary controlling the way the document is to be presented on the screen or in print.
14062	 * (see Section 8.1 of PDF reference, "Viewer Preferences").
14063	 * <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>
14064	 * @param $preferences (array) array of options.
14065	 * @author Nicola Asuni
14066	 * @public
14067	 * @since 3.1.000 (2008-06-09)
14068	 */
14069	public function setViewerPreferences($preferences) {
14070		$this->viewer_preferences = $preferences;
14071	}
14072
14073	/**
14074	 * Paints color transition registration bars
14075	 * @param $x (float) abscissa of the top left corner of the rectangle.
14076	 * @param $y (float) ordinate of the top left corner of the rectangle.
14077	 * @param $w (float) width of the rectangle.
14078	 * @param $h (float) height of the rectangle.
14079	 * @param $transition (boolean) if true prints tcolor transitions to white.
14080	 * @param $vertical (boolean) if true prints bar vertically.
14081	 * @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.
14082	 * @author Nicola Asuni
14083	 * @since 4.9.000 (2010-03-26)
14084	 * @public
14085	 */
14086	public function colorRegistrationBar($x, $y, $w, $h, $transition=true, $vertical=false, $colors='A,R,G,B,C,M,Y,K') {
14087		if (strpos($colors, 'ALLSPOT') !== false) {
14088			// expand spot colors
14089			$spot_colors = '';
14090			foreach ($this->spot_colors as $spot_color_name => $v) {
14091				$spot_colors .= ','.$spot_color_name;
14092			}
14093			if (!empty($spot_colors)) {
14094				$spot_colors = substr($spot_colors, 1);
14095				$colors = str_replace('ALLSPOT', $spot_colors, $colors);
14096			} else {
14097				$colors = str_replace('ALLSPOT', 'NONE', $colors);
14098			}
14099		}
14100		$bars = explode(',', $colors);
14101		$numbars = count($bars); // number of bars to print
14102		if ($numbars <= 0) {
14103			return;
14104		}
14105		// set bar measures
14106		if ($vertical) {
14107			$coords = array(0, 0, 0, 1);
14108			$wb = $w / $numbars; // bar width
14109			$hb = $h; // bar height
14110			$xd = $wb; // delta x
14111			$yd = 0; // delta y
14112		} else {
14113			$coords = array(1, 0, 0, 0);
14114			$wb = $w; // bar width
14115			$hb = $h / $numbars; // bar height
14116			$xd = 0; // delta x
14117			$yd = $hb; // delta y
14118		}
14119		$xb = $x;
14120		$yb = $y;
14121		foreach ($bars as $col) {
14122			switch ($col) {
14123				// set transition colors
14124				case 'A': { // BLACK (GRAYSCALE)
14125					$col_a = array(255);
14126					$col_b = array(0);
14127					break;
14128				}
14129				case 'W': { // WHITE (GRAYSCALE)
14130					$col_a = array(0);
14131					$col_b = array(255);
14132					break;
14133				}
14134				case 'R': { // RED (RGB)
14135					$col_a = array(255,255,255);
14136					$col_b = array(255,0,0);
14137					break;
14138				}
14139				case 'G': { // GREEN (RGB)
14140					$col_a = array(255,255,255);
14141					$col_b = array(0,255,0);
14142					break;
14143				}
14144				case 'B': { // BLUE (RGB)
14145					$col_a = array(255,255,255);
14146					$col_b = array(0,0,255);
14147					break;
14148				}
14149				case 'C': { // CYAN (CMYK)
14150					$col_a = array(0,0,0,0);
14151					$col_b = array(100,0,0,0);
14152					break;
14153				}
14154				case 'M': { // MAGENTA (CMYK)
14155					$col_a = array(0,0,0,0);
14156					$col_b = array(0,100,0,0);
14157					break;
14158				}
14159				case 'Y': { // YELLOW (CMYK)
14160					$col_a = array(0,0,0,0);
14161					$col_b = array(0,0,100,0);
14162					break;
14163				}
14164				case 'K': { // KEY - BLACK (CMYK)
14165					$col_a = array(0,0,0,0);
14166					$col_b = array(0,0,0,100);
14167					break;
14168				}
14169				case 'RGB': { // BLACK REGISTRATION (RGB)
14170					$col_a = array(255,255,255);
14171					$col_b = array(0,0,0);
14172					break;
14173				}
14174				case 'CMYK': { // BLACK REGISTRATION (CMYK)
14175					$col_a = array(0,0,0,0);
14176					$col_b = array(100,100,100,100);
14177					break;
14178				}
14179				case 'ALL': { // SPOT COLOR REGISTRATION
14180					$col_a = array(0,0,0,0,'None');
14181					$col_b = array(100,100,100,100,'All');
14182					break;
14183				}
14184				case 'NONE': { // SKIP THIS COLOR
14185					$col_a = array(0,0,0,0,'None');
14186					$col_b = array(0,0,0,0,'None');
14187					break;
14188				}
14189				default: { // SPECIFIC SPOT COLOR NAME
14190					$col_a = array(0,0,0,0,'None');
14191					$col_b = TCPDF_COLORS::getSpotColor($col, $this->spot_colors);
14192					if ($col_b === false) {
14193						// in case of error defaults to the registration color
14194						$col_b = array(100,100,100,100,'All');
14195					}
14196					break;
14197				}
14198			}
14199			if ($col != 'NONE') {
14200				if ($transition) {
14201					// color gradient
14202					$this->LinearGradient($xb, $yb, $wb, $hb, $col_a, $col_b, $coords);
14203				} else {
14204					$this->SetFillColorArray($col_b);
14205					// colored rectangle
14206					$this->Rect($xb, $yb, $wb, $hb, 'F', array());
14207				}
14208				$xb += $xd;
14209				$yb += $yd;
14210			}
14211		}
14212	}
14213
14214	/**
14215	 * Paints crop marks.
14216	 * @param $x (float) abscissa of the crop mark center.
14217	 * @param $y (float) ordinate of the crop mark center.
14218	 * @param $w (float) width of the crop mark.
14219	 * @param $h (float) height of the crop mark.
14220	 * @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.
14221	 * @param $color (array) crop mark color (default spot registration color).
14222	 * @author Nicola Asuni
14223	 * @since 4.9.000 (2010-03-26)
14224	 * @public
14225	 */
14226	public function cropMark($x, $y, $w, $h, $type='T,R,B,L', $color=array(100,100,100,100,'All')) {
14227		$this->SetLineStyle(array('width' => (0.5 / $this->k), 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => $color));
14228		$type = strtoupper($type);
14229		$type = preg_replace('/[^A-Z\-\,]*/', '', $type);
14230		// split type in single components
14231		$type = str_replace('-', ',', $type);
14232		$type = str_replace('TL', 'T,L', $type);
14233		$type = str_replace('TR', 'T,R', $type);
14234		$type = str_replace('BL', 'F,L', $type);
14235		$type = str_replace('BR', 'F,R', $type);
14236		$type = str_replace('A', 'T,L', $type);
14237		$type = str_replace('B', 'T,R', $type);
14238		$type = str_replace('T,RO', 'BO', $type);
14239		$type = str_replace('C', 'F,L', $type);
14240		$type = str_replace('D', 'F,R', $type);
14241		$crops = explode(',', strtoupper($type));
14242		// remove duplicates
14243		$crops = array_unique($crops);
14244		$dw = ($w / 4); // horizontal space to leave before the intersection point
14245		$dh = ($h / 4); // vertical space to leave before the intersection point
14246		foreach ($crops as $crop) {
14247			switch ($crop) {
14248				case 'T':
14249				case 'TOP': {
14250					$x1 = $x;
14251					$y1 = ($y - $h);
14252					$x2 = $x;
14253					$y2 = ($y - $dh);
14254					break;
14255				}
14256				case 'F':
14257				case 'BOTTOM': {
14258					$x1 = $x;
14259					$y1 = ($y + $dh);
14260					$x2 = $x;
14261					$y2 = ($y + $h);
14262					break;
14263				}
14264				case 'L':
14265				case 'LEFT': {
14266					$x1 = ($x - $w);
14267					$y1 = $y;
14268					$x2 = ($x - $dw);
14269					$y2 = $y;
14270					break;
14271				}
14272				case 'R':
14273				case 'RIGHT': {
14274					$x1 = ($x + $dw);
14275					$y1 = $y;
14276					$x2 = ($x + $w);
14277					$y2 = $y;
14278					break;
14279				}
14280			}
14281			$this->Line($x1, $y1, $x2, $y2);
14282		}
14283	}
14284
14285	/**
14286	 * Paints a registration mark
14287	 * @param $x (float) abscissa of the registration mark center.
14288	 * @param $y (float) ordinate of the registration mark center.
14289	 * @param $r (float) radius of the crop mark.
14290	 * @param $double (boolean) if true print two concentric crop marks.
14291	 * @param $cola (array) crop mark color (default spot registration color 'All').
14292	 * @param $colb (array) second crop mark color (default spot registration color 'None').
14293	 * @author Nicola Asuni
14294	 * @since 4.9.000 (2010-03-26)
14295	 * @public
14296	 */
14297	public function registrationMark($x, $y, $r, $double=false, $cola=array(100,100,100,100,'All'), $colb=array(0,0,0,0,'None')) {
14298		$line_style = array('width' => max((0.5 / $this->k),($r / 30)), 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => $cola);
14299		$this->SetFillColorArray($cola);
14300		$this->PieSector($x, $y, $r, 90, 180, 'F');
14301		$this->PieSector($x, $y, $r, 270, 360, 'F');
14302		$this->Circle($x, $y, $r, 0, 360, 'C', $line_style, array(), 8);
14303		if ($double) {
14304			$ri = $r * 0.5;
14305			$this->SetFillColorArray($colb);
14306			$this->PieSector($x, $y, $ri, 90, 180, 'F');
14307			$this->PieSector($x, $y, $ri, 270, 360, 'F');
14308			$this->SetFillColorArray($cola);
14309			$this->PieSector($x, $y, $ri, 0, 90, 'F');
14310			$this->PieSector($x, $y, $ri, 180, 270, 'F');
14311			$this->Circle($x, $y, $ri, 0, 360, 'C', $line_style, array(), 8);
14312		}
14313	}
14314
14315	/**
14316	 * Paints a CMYK registration mark
14317	 * @param $x (float) abscissa of the registration mark center.
14318	 * @param $y (float) ordinate of the registration mark center.
14319	 * @param $r (float) radius of the crop mark.
14320	 * @author Nicola Asuni
14321	 * @since 6.0.038 (2013-09-30)
14322	 * @public
14323	 */
14324	public function registrationMarkCMYK($x, $y, $r) {
14325		// line width
14326		$lw = max((0.5 / $this->k),($r / 8));
14327		// internal radius
14328		$ri = ($r * 0.6);
14329		// external radius
14330		$re = ($r * 1.3);
14331		// Cyan
14332		$this->SetFillColorArray(array(100,0,0,0));
14333		$this->PieSector($x, $y, $ri, 270, 360, 'F');
14334		// Magenta
14335		$this->SetFillColorArray(array(0,100,0,0));
14336		$this->PieSector($x, $y, $ri, 0, 90, 'F');
14337		// Yellow
14338		$this->SetFillColorArray(array(0,0,100,0));
14339		$this->PieSector($x, $y, $ri, 90, 180, 'F');
14340		// Key - black
14341		$this->SetFillColorArray(array(0,0,0,100));
14342		$this->PieSector($x, $y, $ri, 180, 270, 'F');
14343		// registration color
14344		$line_style = array('width' => $lw, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(100,100,100,100,'All'));
14345		$this->SetFillColorArray(array(100,100,100,100,'All'));
14346		// external circle
14347		$this->Circle($x, $y, $r, 0, 360, 'C', $line_style, array(), 8);
14348		// cross lines
14349		$this->Line($x, ($y - $re), $x, ($y - $ri));
14350		$this->Line($x, ($y + $ri), $x, ($y + $re));
14351		$this->Line(($x - $re), $y, ($x - $ri), $y);
14352		$this->Line(($x + $ri), $y, ($x + $re), $y);
14353	}
14354
14355	/**
14356	 * Paints a linear colour gradient.
14357	 * @param $x (float) abscissa of the top left corner of the rectangle.
14358	 * @param $y (float) ordinate of the top left corner of the rectangle.
14359	 * @param $w (float) width of the rectangle.
14360	 * @param $h (float) height of the rectangle.
14361	 * @param $col1 (array) first color (Grayscale, RGB or CMYK components).
14362	 * @param $col2 (array) second color (Grayscale, RGB or CMYK components).
14363	 * @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).
14364	 * @author Andreas W\FCrmser, Nicola Asuni
14365	 * @since 3.1.000 (2008-06-09)
14366	 * @public
14367	 */
14368	public function LinearGradient($x, $y, $w, $h, $col1=array(), $col2=array(), $coords=array(0,0,1,0)) {
14369		$this->Clip($x, $y, $w, $h);
14370		$this->Gradient(2, $coords, array(array('color' => $col1, 'offset' => 0, 'exponent' => 1), array('color' => $col2, 'offset' => 1, 'exponent' => 1)), array(), false);
14371	}
14372
14373	/**
14374	 * Paints a radial colour gradient.
14375	 * @param $x (float) abscissa of the top left corner of the rectangle.
14376	 * @param $y (float) ordinate of the top left corner of the rectangle.
14377	 * @param $w (float) width of the rectangle.
14378	 * @param $h (float) height of the rectangle.
14379	 * @param $col1 (array) first color (Grayscale, RGB or CMYK components).
14380	 * @param $col2 (array) second color (Grayscale, RGB or CMYK components).
14381	 * @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.
14382	 * @author Andreas W\FCrmser, Nicola Asuni
14383	 * @since 3.1.000 (2008-06-09)
14384	 * @public
14385	 */
14386	public function RadialGradient($x, $y, $w, $h, $col1=array(), $col2=array(), $coords=array(0.5,0.5,0.5,0.5,1)) {
14387		$this->Clip($x, $y, $w, $h);
14388		$this->Gradient(3, $coords, array(array('color' => $col1, 'offset' => 0, 'exponent' => 1), array('color' => $col2, 'offset' => 1, 'exponent' => 1)), array(), false);
14389	}
14390
14391	/**
14392	 * Paints a coons patch mesh.
14393	 * @param $x (float) abscissa of the top left corner of the rectangle.
14394	 * @param $y (float) ordinate of the top left corner of the rectangle.
14395	 * @param $w (float) width of the rectangle.
14396	 * @param $h (float) height of the rectangle.
14397	 * @param $col1 (array) first color (lower left corner) (RGB components).
14398	 * @param $col2 (array) second color (lower right corner) (RGB components).
14399	 * @param $col3 (array) third color (upper right corner) (RGB components).
14400	 * @param $col4 (array) fourth color (upper left corner) (RGB components).
14401	 * @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>
14402	 * @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
14403	 * @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
14404	 * @param $antialias (boolean) A flag indicating whether to filter the shading function to prevent aliasing artifacts.
14405	 * @author Andreas W\FCrmser, Nicola Asuni
14406	 * @since 3.1.000 (2008-06-09)
14407	 * @public
14408	 */
14409	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) {
14410		if ($this->pdfa_mode OR ($this->state != 2)) {
14411			return;
14412		}
14413		$this->Clip($x, $y, $w, $h);
14414		$n = count($this->gradients) + 1;
14415		$this->gradients[$n] = array();
14416		$this->gradients[$n]['type'] = 6; //coons patch mesh
14417		$this->gradients[$n]['coords'] = array();
14418		$this->gradients[$n]['antialias'] = $antialias;
14419		$this->gradients[$n]['colors'] = array();
14420		$this->gradients[$n]['transparency'] = false;
14421		//check the coords array if it is the simple array or the multi patch array
14422		if (!isset($coords[0]['f'])) {
14423			//simple array -> convert to multi patch array
14424			if (!isset($col1[1])) {
14425				$col1[1] = $col1[2] = $col1[0];
14426			}
14427			if (!isset($col2[1])) {
14428				$col2[1] = $col2[2] = $col2[0];
14429			}
14430			if (!isset($col3[1])) {
14431				$col3[1] = $col3[2] = $col3[0];
14432			}
14433			if (!isset($col4[1])) {
14434				$col4[1] = $col4[2] = $col4[0];
14435			}
14436			$patch_array[0]['f'] = 0;
14437			$patch_array[0]['points'] = $coords;
14438			$patch_array[0]['colors'][0]['r'] = $col1[0];
14439			$patch_array[0]['colors'][0]['g'] = $col1[1];
14440			$patch_array[0]['colors'][0]['b'] = $col1[2];
14441			$patch_array[0]['colors'][1]['r'] = $col2[0];
14442			$patch_array[0]['colors'][1]['g'] = $col2[1];
14443			$patch_array[0]['colors'][1]['b'] = $col2[2];
14444			$patch_array[0]['colors'][2]['r'] = $col3[0];
14445			$patch_array[0]['colors'][2]['g'] = $col3[1];
14446			$patch_array[0]['colors'][2]['b'] = $col3[2];
14447			$patch_array[0]['colors'][3]['r'] = $col4[0];
14448			$patch_array[0]['colors'][3]['g'] = $col4[1];
14449			$patch_array[0]['colors'][3]['b'] = $col4[2];
14450		} else {
14451			//multi patch array
14452			$patch_array = $coords;
14453		}
14454		$bpcd = 65535; //16 bits per coordinate
14455		//build the data stream
14456		$this->gradients[$n]['stream'] = '';
14457		$count_patch = count($patch_array);
14458		for ($i=0; $i < $count_patch; ++$i) {
14459			$this->gradients[$n]['stream'] .= chr($patch_array[$i]['f']); //start with the edge flag as 8 bit
14460			$count_points = count($patch_array[$i]['points']);
14461			for ($j=0; $j < $count_points; ++$j) {
14462				//each point as 16 bit
14463				$patch_array[$i]['points'][$j] = (($patch_array[$i]['points'][$j] - $coords_min) / ($coords_max - $coords_min)) * $bpcd;
14464				if ($patch_array[$i]['points'][$j] < 0) {
14465					$patch_array[$i]['points'][$j] = 0;
14466				}
14467				if ($patch_array[$i]['points'][$j] > $bpcd) {
14468					$patch_array[$i]['points'][$j] = $bpcd;
14469				}
14470				$this->gradients[$n]['stream'] .= chr(floor($patch_array[$i]['points'][$j] / 256));
14471				$this->gradients[$n]['stream'] .= chr(floor($patch_array[$i]['points'][$j] % 256));
14472			}
14473			$count_cols = count($patch_array[$i]['colors']);
14474			for ($j=0; $j < $count_cols; ++$j) {
14475				//each color component as 8 bit
14476				$this->gradients[$n]['stream'] .= chr($patch_array[$i]['colors'][$j]['r']);
14477				$this->gradients[$n]['stream'] .= chr($patch_array[$i]['colors'][$j]['g']);
14478				$this->gradients[$n]['stream'] .= chr($patch_array[$i]['colors'][$j]['b']);
14479			}
14480		}
14481		//paint the gradient
14482		$this->_out('/Sh'.$n.' sh');
14483		//restore previous Graphic State
14484		$this->_outRestoreGraphicsState();
14485		if ($this->inxobj) {
14486			// we are inside an XObject template
14487			$this->xobjects[$this->xobjid]['gradients'][$n] = $this->gradients[$n];
14488		}
14489	}
14490
14491	/**
14492	 * Set a rectangular clipping area.
14493	 * @param $x (float) abscissa of the top left corner of the rectangle (or top right corner for RTL mode).
14494	 * @param $y (float) ordinate of the top left corner of the rectangle.
14495	 * @param $w (float) width of the rectangle.
14496	 * @param $h (float) height of the rectangle.
14497	 * @author Andreas W\FCrmser, Nicola Asuni
14498	 * @since 3.1.000 (2008-06-09)
14499	 * @protected
14500	 */
14501	protected function Clip($x, $y, $w, $h) {
14502		if ($this->state != 2) {
14503			 return;
14504		}
14505		if ($this->rtl) {
14506			$x = $this->w - $x - $w;
14507		}
14508		//save current Graphic State
14509		$s = 'q';
14510		//set clipping area
14511		$s .= sprintf(' %F %F %F %F re W n', $x*$this->k, ($this->h-$y)*$this->k, $w*$this->k, -$h*$this->k);
14512		//set up transformation matrix for gradient
14513		$s .= sprintf(' %F 0 0 %F %F %F cm', $w*$this->k, $h*$this->k, $x*$this->k, ($this->h-($y+$h))*$this->k);
14514		$this->_out($s);
14515	}
14516
14517	/**
14518	 * Output gradient.
14519	 * @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)
14520	 * @param $coords (array) array of coordinates.
14521	 * @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).
14522	 * @param $background (array) An array of colour components appropriate to the colour space, specifying a single background colour value.
14523	 * @param $antialias (boolean) A flag indicating whether to filter the shading function to prevent aliasing artifacts.
14524	 * @author Nicola Asuni
14525	 * @since 3.1.000 (2008-06-09)
14526	 * @public
14527	 */
14528	public function Gradient($type, $coords, $stops, $background=array(), $antialias=false) {
14529		if ($this->pdfa_mode OR ($this->state != 2)) {
14530			return;
14531		}
14532		$n = count($this->gradients) + 1;
14533		$this->gradients[$n] = array();
14534		$this->gradients[$n]['type'] = $type;
14535		$this->gradients[$n]['coords'] = $coords;
14536		$this->gradients[$n]['antialias'] = $antialias;
14537		$this->gradients[$n]['colors'] = array();
14538		$this->gradients[$n]['transparency'] = false;
14539		// color space
14540		$numcolspace = count($stops[0]['color']);
14541		$bcolor = array_values($background);
14542		switch($numcolspace) {
14543			case 5:   // SPOT
14544			case 4: { // CMYK
14545				$this->gradients[$n]['colspace'] = 'DeviceCMYK';
14546				if (!empty($background)) {
14547					$this->gradients[$n]['background'] = sprintf('%F %F %F %F', $bcolor[0]/100, $bcolor[1]/100, $bcolor[2]/100, $bcolor[3]/100);
14548				}
14549				break;
14550			}
14551			case 3: { // RGB
14552				$this->gradients[$n]['colspace'] = 'DeviceRGB';
14553				if (!empty($background)) {
14554					$this->gradients[$n]['background'] = sprintf('%F %F %F', $bcolor[0]/255, $bcolor[1]/255, $bcolor[2]/255);
14555				}
14556				break;
14557			}
14558			case 1: { // GRAY SCALE
14559				$this->gradients[$n]['colspace'] = 'DeviceGray';
14560				if (!empty($background)) {
14561					$this->gradients[$n]['background'] = sprintf('%F', $bcolor[0]/255);
14562				}
14563				break;
14564			}
14565		}
14566		$num_stops = count($stops);
14567		$last_stop_id = $num_stops - 1;
14568		foreach ($stops as $key => $stop) {
14569			$this->gradients[$n]['colors'][$key] = array();
14570			// offset represents a location along the gradient vector
14571			if (isset($stop['offset'])) {
14572				$this->gradients[$n]['colors'][$key]['offset'] = $stop['offset'];
14573			} else {
14574				if ($key == 0) {
14575					$this->gradients[$n]['colors'][$key]['offset'] = 0;
14576				} elseif ($key == $last_stop_id) {
14577					$this->gradients[$n]['colors'][$key]['offset'] = 1;
14578				} else {
14579					$offsetstep = (1 - $this->gradients[$n]['colors'][($key - 1)]['offset']) / ($num_stops - $key);
14580					$this->gradients[$n]['colors'][$key]['offset'] = $this->gradients[$n]['colors'][($key - 1)]['offset'] + $offsetstep;
14581				}
14582			}
14583			if (isset($stop['opacity'])) {
14584				$this->gradients[$n]['colors'][$key]['opacity'] = $stop['opacity'];
14585				if ((!$this->pdfa_mode) AND ($stop['opacity'] < 1)) {
14586					$this->gradients[$n]['transparency'] = true;
14587				}
14588			} else {
14589				$this->gradients[$n]['colors'][$key]['opacity'] = 1;
14590			}
14591			// exponent for the exponential interpolation function
14592			if (isset($stop['exponent'])) {
14593				$this->gradients[$n]['colors'][$key]['exponent'] = $stop['exponent'];
14594			} else {
14595				$this->gradients[$n]['colors'][$key]['exponent'] = 1;
14596			}
14597			// set colors
14598			$color = array_values($stop['color']);
14599			switch($numcolspace) {
14600				case 5:   // SPOT
14601				case 4: { // CMYK
14602					$this->gradients[$n]['colors'][$key]['color'] = sprintf('%F %F %F %F', $color[0]/100, $color[1]/100, $color[2]/100, $color[3]/100);
14603					break;
14604				}
14605				case 3: { // RGB
14606					$this->gradients[$n]['colors'][$key]['color'] = sprintf('%F %F %F', $color[0]/255, $color[1]/255, $color[2]/255);
14607					break;
14608				}
14609				case 1: { // GRAY SCALE
14610					$this->gradients[$n]['colors'][$key]['color'] = sprintf('%F', $color[0]/255);
14611					break;
14612				}
14613			}
14614		}
14615		if ($this->gradients[$n]['transparency']) {
14616			// paint luminosity gradient
14617			$this->_out('/TGS'.$n.' gs');
14618		}
14619		//paint the gradient
14620		$this->_out('/Sh'.$n.' sh');
14621		//restore previous Graphic State
14622		$this->_outRestoreGraphicsState();
14623		if ($this->inxobj) {
14624			// we are inside an XObject template
14625			$this->xobjects[$this->xobjid]['gradients'][$n] = $this->gradients[$n];
14626		}
14627	}
14628
14629	/**
14630	 * Output gradient shaders.
14631	 * @author Nicola Asuni
14632	 * @since 3.1.000 (2008-06-09)
14633	 * @protected
14634	 */
14635	function _putshaders() {
14636		if ($this->pdfa_mode) {
14637			return;
14638		}
14639		$idt = count($this->gradients); //index for transparency gradients
14640		foreach ($this->gradients as $id => $grad) {
14641			if (($grad['type'] == 2) OR ($grad['type'] == 3)) {
14642				$fc = $this->_newobj();
14643				$out = '<<';
14644				$out .= ' /FunctionType 3';
14645				$out .= ' /Domain [0 1]';
14646				$functions = '';
14647				$bounds = '';
14648				$encode = '';
14649				$i = 1;
14650				$num_cols = count($grad['colors']);
14651				$lastcols = $num_cols - 1;
14652				for ($i = 1; $i < $num_cols; ++$i) {
14653					$functions .= ($fc + $i).' 0 R ';
14654					if ($i < $lastcols) {
14655						$bounds .= sprintf('%F ', $grad['colors'][$i]['offset']);
14656					}
14657					$encode .= '0 1 ';
14658				}
14659				$out .= ' /Functions ['.trim($functions).']';
14660				$out .= ' /Bounds ['.trim($bounds).']';
14661				$out .= ' /Encode ['.trim($encode).']';
14662				$out .= ' >>';
14663				$out .= "\n".'endobj';
14664				$this->_out($out);
14665				for ($i = 1; $i < $num_cols; ++$i) {
14666					$this->_newobj();
14667					$out = '<<';
14668					$out .= ' /FunctionType 2';
14669					$out .= ' /Domain [0 1]';
14670					$out .= ' /C0 ['.$grad['colors'][($i - 1)]['color'].']';
14671					$out .= ' /C1 ['.$grad['colors'][$i]['color'].']';
14672					$out .= ' /N '.$grad['colors'][$i]['exponent'];
14673					$out .= ' >>';
14674					$out .= "\n".'endobj';
14675					$this->_out($out);
14676				}
14677				// set transparency functions
14678				if ($grad['transparency']) {
14679					$ft = $this->_newobj();
14680					$out = '<<';
14681					$out .= ' /FunctionType 3';
14682					$out .= ' /Domain [0 1]';
14683					$functions = '';
14684					$i = 1;
14685					$num_cols = count($grad['colors']);
14686					for ($i = 1; $i < $num_cols; ++$i) {
14687						$functions .= ($ft + $i).' 0 R ';
14688					}
14689					$out .= ' /Functions ['.trim($functions).']';
14690					$out .= ' /Bounds ['.trim($bounds).']';
14691					$out .= ' /Encode ['.trim($encode).']';
14692					$out .= ' >>';
14693					$out .= "\n".'endobj';
14694					$this->_out($out);
14695					for ($i = 1; $i < $num_cols; ++$i) {
14696						$this->_newobj();
14697						$out = '<<';
14698						$out .= ' /FunctionType 2';
14699						$out .= ' /Domain [0 1]';
14700						$out .= ' /C0 ['.$grad['colors'][($i - 1)]['opacity'].']';
14701						$out .= ' /C1 ['.$grad['colors'][$i]['opacity'].']';
14702						$out .= ' /N '.$grad['colors'][$i]['exponent'];
14703						$out .= ' >>';
14704						$out .= "\n".'endobj';
14705						$this->_out($out);
14706					}
14707				}
14708			}
14709			// set shading object
14710			$this->_newobj();
14711			$out = '<< /ShadingType '.$grad['type'];
14712			if (isset($grad['colspace'])) {
14713				$out .= ' /ColorSpace /'.$grad['colspace'];
14714			} else {
14715				$out .= ' /ColorSpace /DeviceRGB';
14716			}
14717			if (isset($grad['background']) AND !empty($grad['background'])) {
14718				$out .= ' /Background ['.$grad['background'].']';
14719			}
14720			if (isset($grad['antialias']) AND ($grad['antialias'] === true)) {
14721				$out .= ' /AntiAlias true';
14722			}
14723			if ($grad['type'] == 2) {
14724				$out .= ' '.sprintf('/Coords [%F %F %F %F]', $grad['coords'][0], $grad['coords'][1], $grad['coords'][2], $grad['coords'][3]);
14725				$out .= ' /Domain [0 1]';
14726				$out .= ' /Function '.$fc.' 0 R';
14727				$out .= ' /Extend [true true]';
14728				$out .= ' >>';
14729			} elseif ($grad['type'] == 3) {
14730				//x0, y0, r0, x1, y1, r1
14731				//at this this time radius of inner circle is 0
14732				$out .= ' '.sprintf('/Coords [%F %F 0 %F %F %F]', $grad['coords'][0], $grad['coords'][1], $grad['coords'][2], $grad['coords'][3], $grad['coords'][4]);
14733				$out .= ' /Domain [0 1]';
14734				$out .= ' /Function '.$fc.' 0 R';
14735				$out .= ' /Extend [true true]';
14736				$out .= ' >>';
14737			} elseif ($grad['type'] == 6) {
14738				$out .= ' /BitsPerCoordinate 16';
14739				$out .= ' /BitsPerComponent 8';
14740				$out .= ' /Decode[0 1 0 1 0 1 0 1 0 1]';
14741				$out .= ' /BitsPerFlag 8';
14742				$stream = $this->_getrawstream($grad['stream']);
14743				$out .= ' /Length '.strlen($stream);
14744				$out .= ' >>';
14745				$out .= ' stream'."\n".$stream."\n".'endstream';
14746			}
14747			$out .= "\n".'endobj';
14748			$this->_out($out);
14749			if ($grad['transparency']) {
14750				$shading_transparency = preg_replace('/\/ColorSpace \/[^\s]+/si', '/ColorSpace /DeviceGray', $out);
14751				$shading_transparency = preg_replace('/\/Function [0-9]+ /si', '/Function '.$ft.' ', $shading_transparency);
14752			}
14753			$this->gradients[$id]['id'] = $this->n;
14754			// set pattern object
14755			$this->_newobj();
14756			$out = '<< /Type /Pattern /PatternType 2';
14757			$out .= ' /Shading '.$this->gradients[$id]['id'].' 0 R';
14758			$out .= ' >>';
14759			$out .= "\n".'endobj';
14760			$this->_out($out);
14761			$this->gradients[$id]['pattern'] = $this->n;
14762			// set shading and pattern for transparency mask
14763			if ($grad['transparency']) {
14764				// luminosity pattern
14765				$idgs = $id + $idt;
14766				$this->_newobj();
14767				$this->_out($shading_transparency);
14768				$this->gradients[$idgs]['id'] = $this->n;
14769				$this->_newobj();
14770				$out = '<< /Type /Pattern /PatternType 2';
14771				$out .= ' /Shading '.$this->gradients[$idgs]['id'].' 0 R';
14772				$out .= ' >>';
14773				$out .= "\n".'endobj';
14774				$this->_out($out);
14775				$this->gradients[$idgs]['pattern'] = $this->n;
14776				// luminosity XObject
14777				$oid = $this->_newobj();
14778				$this->xobjects['LX'.$oid] = array('n' => $oid);
14779				$filter = '';
14780				$stream = 'q /a0 gs /Pattern cs /p'.$idgs.' scn 0 0 '.$this->wPt.' '.$this->hPt.' re f Q';
14781				if ($this->compress) {
14782					$filter = ' /Filter /FlateDecode';
14783					$stream = gzcompress($stream);
14784				}
14785				$stream = $this->_getrawstream($stream);
14786				$out = '<< /Type /XObject /Subtype /Form /FormType 1'.$filter;
14787				$out .= ' /Length '.strlen($stream);
14788				$rect = sprintf('%F %F', $this->wPt, $this->hPt);
14789				$out .= ' /BBox [0 0 '.$rect.']';
14790				$out .= ' /Group << /Type /Group /S /Transparency /CS /DeviceGray >>';
14791				$out .= ' /Resources <<';
14792				$out .= ' /ExtGState << /a0 << /ca 1 /CA 1 >> >>';
14793				$out .= ' /Pattern << /p'.$idgs.' '.$this->gradients[$idgs]['pattern'].' 0 R >>';
14794				$out .= ' >>';
14795				$out .= ' >> ';
14796				$out .= ' stream'."\n".$stream."\n".'endstream';
14797				$out .= "\n".'endobj';
14798				$this->_out($out);
14799				// SMask
14800				$this->_newobj();
14801				$out = '<< /Type /Mask /S /Luminosity /G '.($this->n - 1).' 0 R >>'."\n".'endobj';
14802				$this->_out($out);
14803				// ExtGState
14804				$this->_newobj();
14805				$out = '<< /Type /ExtGState /SMask '.($this->n - 1).' 0 R /AIS false >>'."\n".'endobj';
14806				$this->_out($out);
14807				$this->extgstates[] = array('n' => $this->n, 'name' => 'TGS'.$id);
14808			}
14809		}
14810	}
14811
14812	/**
14813	 * Draw the sector of a circle.
14814	 * It can be used for instance to render pie charts.
14815	 * @param $xc (float) abscissa of the center.
14816	 * @param $yc (float) ordinate of the center.
14817	 * @param $r (float) radius.
14818	 * @param $a (float) start angle (in degrees).
14819	 * @param $b (float) end angle (in degrees).
14820	 * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
14821	 * @param $cw: (float) indicates whether to go clockwise (default: true).
14822	 * @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.
14823	 * @author Maxime Delorme, Nicola Asuni
14824	 * @since 3.1.000 (2008-06-09)
14825	 * @public
14826	 */
14827	public function PieSector($xc, $yc, $r, $a, $b, $style='FD', $cw=true, $o=90) {
14828		$this->PieSectorXY($xc, $yc, $r, $r, $a, $b, $style, $cw, $o);
14829	}
14830
14831	/**
14832	 * Draw the sector of an ellipse.
14833	 * It can be used for instance to render pie charts.
14834	 * @param $xc (float) abscissa of the center.
14835	 * @param $yc (float) ordinate of the center.
14836	 * @param $rx (float) the x-axis radius.
14837	 * @param $ry (float) the y-axis radius.
14838	 * @param $a (float) start angle (in degrees).
14839	 * @param $b (float) end angle (in degrees).
14840	 * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
14841	 * @param $cw: (float) indicates whether to go clockwise.
14842	 * @param $o: (float) origin of angles (0 for 3 o'clock, 90 for noon, 180 for 9 o'clock, 270 for 6 o'clock).
14843	 * @param $nc (integer) Number of curves used to draw a 90 degrees portion of arc.
14844	 * @author Maxime Delorme, Nicola Asuni
14845	 * @since 3.1.000 (2008-06-09)
14846	 * @public
14847	 */
14848	public function PieSectorXY($xc, $yc, $rx, $ry, $a, $b, $style='FD', $cw=false, $o=0, $nc=2) {
14849		if ($this->state != 2) {
14850			 return;
14851		}
14852		if ($this->rtl) {
14853			$xc = ($this->w - $xc);
14854		}
14855		$op = TCPDF_STATIC::getPathPaintOperator($style);
14856		if ($op == 'f') {
14857			$line_style = array();
14858		}
14859		if ($cw) {
14860			$d = $b;
14861			$b = (360 - $a + $o);
14862			$a = (360 - $d + $o);
14863		} else {
14864			$b += $o;
14865			$a += $o;
14866		}
14867		$this->_outellipticalarc($xc, $yc, $rx, $ry, 0, $a, $b, true, $nc);
14868		$this->_out($op);
14869	}
14870
14871	/**
14872	 * Embed vector-based Adobe Illustrator (AI) or AI-compatible EPS files.
14873	 * NOTE: EPS is not yet fully implemented, use the setRasterizeVectorImages() method to enable/disable rasterization of vector images using ImageMagick library.
14874	 * Only vector drawing is supported, not text or bitmap.
14875	 * 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).
14876	 * @param $file (string) Name of the file containing the image or a '@' character followed by the EPS/AI data string.
14877	 * @param $x (float) Abscissa of the upper-left corner.
14878	 * @param $y (float) Ordinate of the upper-left corner.
14879	 * @param $w (float) Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
14880	 * @param $h (float) Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
14881	 * @param $link (mixed) URL or identifier returned by AddLink().
14882	 * @param $useBoundingBox (boolean) specifies whether to position the bounding box (true) or the complete canvas (false) at location (x,y). Default value is true.
14883	 * @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>
14884	 * @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>
14885	 * @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)))
14886	 * @param $fitonpage (boolean) if true the image is resized to not exceed page dimensions.
14887	 * @param $fixoutvals (boolean) if true remove values outside the bounding box.
14888	 * @author Valentin Schmidt, Nicola Asuni
14889	 * @since 3.1.000 (2008-06-09)
14890	 * @public
14891	 */
14892	public function ImageEps($file, $x='', $y='', $w=0, $h=0, $link='', $useBoundingBox=true, $align='', $palign='', $border=0, $fitonpage=false, $fixoutvals=false) {
14893		if ($this->state != 2) {
14894			 return;
14895		}
14896		if ($this->rasterize_vector_images AND ($w > 0) AND ($h > 0)) {
14897			// convert EPS to raster image using GD or ImageMagick libraries
14898			return $this->Image($file, $x, $y, $w, $h, 'EPS', $link, $align, true, 300, $palign, false, false, $border, false, false, $fitonpage);
14899		}
14900		if ($x === '') {
14901			$x = $this->x;
14902		}
14903		if ($y === '') {
14904			$y = $this->y;
14905		}
14906		// check page for no-write regions and adapt page margins if necessary
14907		list($x, $y) = $this->checkPageRegions($h, $x, $y);
14908		$k = $this->k;
14909		if ($file[0] === '@') { // image from string
14910			$data = substr($file, 1);
14911		} else { // EPS/AI file
14912			$data = TCPDF_STATIC::fileGetContents($file);
14913		}
14914		if ($data === FALSE) {
14915			$this->Error('EPS file not found: '.$file);
14916		}
14917		$regs = array();
14918		// EPS/AI compatibility check (only checks files created by Adobe Illustrator!)
14919		preg_match("/%%Creator:([^\r\n]+)/", $data, $regs); # find Creator
14920		if (count($regs) > 1) {
14921			$version_str = trim($regs[1]); # e.g. "Adobe Illustrator(R) 8.0"
14922			if (strpos($version_str, 'Adobe Illustrator') !== false) {
14923				$versexp = explode(' ', $version_str);
14924				$version = (float)array_pop($versexp);
14925				if ($version >= 9) {
14926					$this->Error('This version of Adobe Illustrator file is not supported: '.$file);
14927				}
14928			}
14929		}
14930		// strip binary bytes in front of PS-header
14931		$start = strpos($data, '%!PS-Adobe');
14932		if ($start > 0) {
14933			$data = substr($data, $start);
14934		}
14935		// find BoundingBox params
14936		preg_match("/%%BoundingBox:([^\r\n]+)/", $data, $regs);
14937		if (count($regs) > 1) {
14938			list($x1, $y1, $x2, $y2) = explode(' ', trim($regs[1]));
14939		} else {
14940			$this->Error('No BoundingBox found in EPS/AI file: '.$file);
14941		}
14942		$start = strpos($data, '%%EndSetup');
14943		if ($start === false) {
14944			$start = strpos($data, '%%EndProlog');
14945		}
14946		if ($start === false) {
14947			$start = strpos($data, '%%BoundingBox');
14948		}
14949		$data = substr($data, $start);
14950		$end = strpos($data, '%%PageTrailer');
14951		if ($end===false) {
14952			$end = strpos($data, 'showpage');
14953		}
14954		if ($end) {
14955			$data = substr($data, 0, $end);
14956		}
14957		// calculate image width and height on document
14958		if (($w <= 0) AND ($h <= 0)) {
14959			$w = ($x2 - $x1) / $k;
14960			$h = ($y2 - $y1) / $k;
14961		} elseif ($w <= 0) {
14962			$w = ($x2-$x1) / $k * ($h / (($y2 - $y1) / $k));
14963		} elseif ($h <= 0) {
14964			$h = ($y2 - $y1) / $k * ($w / (($x2 - $x1) / $k));
14965		}
14966		// fit the image on available space
14967		list($w, $h, $x, $y) = $this->fitBlock($w, $h, $x, $y, $fitonpage);
14968		if ($this->rasterize_vector_images) {
14969			// convert EPS to raster image using GD or ImageMagick libraries
14970			return $this->Image($file, $x, $y, $w, $h, 'EPS', $link, $align, true, 300, $palign, false, false, $border, false, false, $fitonpage);
14971		}
14972		// set scaling factors
14973		$scale_x = $w / (($x2 - $x1) / $k);
14974		$scale_y = $h / (($y2 - $y1) / $k);
14975		// set alignment
14976		$this->img_rb_y = $y + $h;
14977		// set alignment
14978		if ($this->rtl) {
14979			if ($palign == 'L') {
14980				$ximg = $this->lMargin;
14981			} elseif ($palign == 'C') {
14982				$ximg = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
14983			} elseif ($palign == 'R') {
14984				$ximg = $this->w - $this->rMargin - $w;
14985			} else {
14986				$ximg = $x - $w;
14987			}
14988			$this->img_rb_x = $ximg;
14989		} else {
14990			if ($palign == 'L') {
14991				$ximg = $this->lMargin;
14992			} elseif ($palign == 'C') {
14993				$ximg = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
14994			} elseif ($palign == 'R') {
14995				$ximg = $this->w - $this->rMargin - $w;
14996			} else {
14997				$ximg = $x;
14998			}
14999			$this->img_rb_x = $ximg + $w;
15000		}
15001		if ($useBoundingBox) {
15002			$dx = $ximg * $k - $x1;
15003			$dy = $y * $k - $y1;
15004		} else {
15005			$dx = $ximg * $k;
15006			$dy = $y * $k;
15007		}
15008		// save the current graphic state
15009		$this->_out('q'.$this->epsmarker);
15010		// translate
15011		$this->_out(sprintf('%F %F %F %F %F %F cm', 1, 0, 0, 1, $dx, $dy + ($this->hPt - (2 * $y * $k) - ($y2 - $y1))));
15012		// scale
15013		if (isset($scale_x)) {
15014			$this->_out(sprintf('%F %F %F %F %F %F cm', $scale_x, 0, 0, $scale_y, $x1 * (1 - $scale_x), $y2 * (1 - $scale_y)));
15015		}
15016		// handle pc/unix/mac line endings
15017		$lines = preg_split('/[\r\n]+/si', $data, -1, PREG_SPLIT_NO_EMPTY);
15018		$u=0;
15019		$cnt = count($lines);
15020		for ($i=0; $i < $cnt; ++$i) {
15021			$line = $lines[$i];
15022			if (($line == '') OR ($line[0] == '%')) {
15023				continue;
15024			}
15025			$len = strlen($line);
15026			// check for spot color names
15027			$color_name = '';
15028			if (strcasecmp('x', substr(trim($line), -1)) == 0) {
15029				if (preg_match('/\([^\)]*\)/', $line, $matches) > 0) {
15030					// extract spot color name
15031					$color_name = $matches[0];
15032					// remove color name from string
15033					$line = str_replace(' '.$color_name, '', $line);
15034					// remove pharentesis from color name
15035					$color_name = substr($color_name, 1, -1);
15036				}
15037			}
15038			$chunks = explode(' ', $line);
15039			$cmd = trim(array_pop($chunks));
15040			// RGB
15041			if (($cmd == 'Xa') OR ($cmd == 'XA')) {
15042				$b = array_pop($chunks);
15043				$g = array_pop($chunks);
15044				$r = array_pop($chunks);
15045				$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!
15046				continue;
15047			}
15048			$skip = false;
15049			if ($fixoutvals) {
15050				// check for values outside the bounding box
15051				switch ($cmd) {
15052					case 'm':
15053					case 'l':
15054					case 'L': {
15055						// skip values outside bounding box
15056						foreach ($chunks as $key => $val) {
15057							if ((($key % 2) == 0) AND (($val < $x1) OR ($val > $x2))) {
15058								$skip = true;
15059							} elseif ((($key % 2) != 0) AND (($val < $y1) OR ($val > $y2))) {
15060								$skip = true;
15061							}
15062						}
15063					}
15064				}
15065			}
15066			switch ($cmd) {
15067				case 'm':
15068				case 'l':
15069				case 'v':
15070				case 'y':
15071				case 'c':
15072				case 'k':
15073				case 'K':
15074				case 'g':
15075				case 'G':
15076				case 's':
15077				case 'S':
15078				case 'J':
15079				case 'j':
15080				case 'w':
15081				case 'M':
15082				case 'd':
15083				case 'n': {
15084					if ($skip) {
15085						break;
15086					}
15087					$this->_out($line);
15088					break;
15089				}
15090				case 'x': {// custom fill color
15091					if (empty($color_name)) {
15092						// CMYK color
15093						list($col_c, $col_m, $col_y, $col_k) = $chunks;
15094						$this->_out(''.$col_c.' '.$col_m.' '.$col_y.' '.$col_k.' k');
15095					} else {
15096						// Spot Color (CMYK + tint)
15097						list($col_c, $col_m, $col_y, $col_k, $col_t) = $chunks;
15098						$this->AddSpotColor($color_name, ($col_c * 100), ($col_m * 100), ($col_y * 100), ($col_k * 100));
15099						$color_cmd = sprintf('/CS%d cs %F scn', $this->spot_colors[$color_name]['i'], (1 - $col_t));
15100						$this->_out($color_cmd);
15101					}
15102					break;
15103				}
15104				case 'X': { // custom stroke color
15105					if (empty($color_name)) {
15106						// CMYK color
15107						list($col_c, $col_m, $col_y, $col_k) = $chunks;
15108						$this->_out(''.$col_c.' '.$col_m.' '.$col_y.' '.$col_k.' K');
15109					} else {
15110						// Spot Color (CMYK + tint)
15111						list($col_c, $col_m, $col_y, $col_k, $col_t) = $chunks;
15112						$this->AddSpotColor($color_name, ($col_c * 100), ($col_m * 100), ($col_y * 100), ($col_k * 100));
15113						$color_cmd = sprintf('/CS%d CS %F SCN', $this->spot_colors[$color_name]['i'], (1 - $col_t));
15114						$this->_out($color_cmd);
15115					}
15116					break;
15117				}
15118				case 'Y':
15119				case 'N':
15120				case 'V':
15121				case 'L':
15122				case 'C': {
15123					if ($skip) {
15124						break;
15125					}
15126					$line[($len - 1)] = strtolower($cmd);
15127					$this->_out($line);
15128					break;
15129				}
15130				case 'b':
15131				case 'B': {
15132					$this->_out($cmd . '*');
15133					break;
15134				}
15135				case 'f':
15136				case 'F': {
15137					if ($u > 0) {
15138						$isU = false;
15139						$max = min(($i + 5), $cnt);
15140						for ($j = ($i + 1); $j < $max; ++$j) {
15141							$isU = ($isU OR (($lines[$j] == 'U') OR ($lines[$j] == '*U')));
15142						}
15143						if ($isU) {
15144							$this->_out('f*');
15145						}
15146					} else {
15147						$this->_out('f*');
15148					}
15149					break;
15150				}
15151				case '*u': {
15152					++$u;
15153					break;
15154				}
15155				case '*U': {
15156					--$u;
15157					break;
15158				}
15159			}
15160		}
15161		// restore previous graphic state
15162		$this->_out($this->epsmarker.'Q');
15163		if (!empty($border)) {
15164			$bx = $this->x;
15165			$by = $this->y;
15166			$this->x = $ximg;
15167			if ($this->rtl) {
15168				$this->x += $w;
15169			}
15170			$this->y = $y;
15171			$this->Cell($w, $h, '', $border, 0, '', 0, '', 0, true);
15172			$this->x = $bx;
15173			$this->y = $by;
15174		}
15175		if ($link) {
15176			$this->Link($ximg, $y, $w, $h, $link, 0);
15177		}
15178		// set pointer to align the next text/objects
15179		switch($align) {
15180			case 'T':{
15181				$this->y = $y;
15182				$this->x = $this->img_rb_x;
15183				break;
15184			}
15185			case 'M':{
15186				$this->y = $y + round($h/2);
15187				$this->x = $this->img_rb_x;
15188				break;
15189			}
15190			case 'B':{
15191				$this->y = $this->img_rb_y;
15192				$this->x = $this->img_rb_x;
15193				break;
15194			}
15195			case 'N':{
15196				$this->SetY($this->img_rb_y);
15197				break;
15198			}
15199			default:{
15200				break;
15201			}
15202		}
15203		$this->endlinex = $this->img_rb_x;
15204	}
15205
15206	/**
15207	 * Set document barcode.
15208	 * @param $bc (string) barcode
15209	 * @public
15210	 */
15211	public function setBarcode($bc='') {
15212		$this->barcode = $bc;
15213	}
15214
15215	/**
15216	 * Get current barcode.
15217	 * @return string
15218	 * @public
15219	 * @since 4.0.012 (2008-07-24)
15220	 */
15221	public function getBarcode() {
15222		return $this->barcode;
15223	}
15224
15225	/**
15226	 * Print a Linear Barcode.
15227	 * @param $code (string) code to print
15228	 * @param $type (string) type of barcode (see tcpdf_barcodes_1d.php for supported formats).
15229	 * @param $x (int) x position in user units (empty string = current x position)
15230	 * @param $y (int) y position in user units (empty string = current y position)
15231	 * @param $w (int) width in user units (empty string = remaining page width)
15232	 * @param $h (int) height in user units (empty string = remaining page height)
15233	 * @param $xres (float) width of the smallest bar in user units (empty string = default value = 0.4mm)
15234	 * @param $style (array) array of options:<ul>
15235	 * <li>boolean $style['border'] if true prints a border</li>
15236	 * <li>int $style['padding'] padding to leave around the barcode in user units (set to 'auto' for automatic padding)</li>
15237	 * <li>int $style['hpadding'] horizontal padding in user units (set to 'auto' for automatic padding)</li>
15238	 * <li>int $style['vpadding'] vertical padding in user units (set to 'auto' for automatic padding)</li>
15239	 * <li>array $style['fgcolor'] color array for bars and text</li>
15240	 * <li>mixed $style['bgcolor'] color array for background (set to false for transparent)</li>
15241	 * <li>boolean $style['text'] if true prints text below the barcode</li>
15242	 * <li>string $style['label'] override default label</li>
15243	 * <li>string $style['font'] font name for text</li><li>int $style['fontsize'] font size for text</li>
15244	 * <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>
15245	 * <li>string $style['position'] horizontal position of the containing barcode cell on the page: L = left margin; C = center; R = right margin.</li>
15246	 * <li>string $style['align'] horizontal position of the barcode on the containing rectangle: L = left; C = center; R = right.</li>
15247	 * <li>string $style['stretch'] if true stretch the barcode to best fit the available width, otherwise uses $xres resolution for a single bar.</li>
15248	 * <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>
15249	 * <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>
15250	 * @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>
15251	 * @author Nicola Asuni
15252	 * @since 3.1.000 (2008-06-09)
15253	 * @public
15254	 */
15255	public function write1DBarcode($code, $type, $x='', $y='', $w='', $h='', $xres='', $style=array(), $align='') {
15256		if (TCPDF_STATIC::empty_string(trim($code))) {
15257			return;
15258		}
15259		require_once(dirname(__FILE__).'/tcpdf_barcodes_1d.php');
15260		// save current graphic settings
15261		$gvars = $this->getGraphicVars();
15262		// create new barcode object
15263		$barcodeobj = new TCPDFBarcode($code, $type);
15264		$arrcode = $barcodeobj->getBarcodeArray();
15265		if (($arrcode === false) OR empty($arrcode) OR ($arrcode['maxw'] <= 0)) {
15266			$this->Error('Error in 1D barcode string');
15267		}
15268		if ($arrcode['maxh'] <= 0) {
15269			$arrcode['maxh'] = 1;
15270		}
15271		// set default values
15272		if (!isset($style['position'])) {
15273			$style['position'] = '';
15274		} elseif ($style['position'] == 'S') {
15275			// keep this for backward compatibility
15276			$style['position'] = '';
15277			$style['stretch'] = true;
15278		}
15279		if (!isset($style['fitwidth'])) {
15280			if (!isset($style['stretch'])) {
15281				$style['fitwidth'] = true;
15282			} else {
15283				$style['fitwidth'] = false;
15284			}
15285		}
15286		if ($style['fitwidth']) {
15287			// disable stretch
15288			$style['stretch'] = false;
15289		}
15290		if (!isset($style['stretch'])) {
15291			if (($w === '') OR ($w <= 0)) {
15292				$style['stretch'] = false;
15293			} else {
15294				$style['stretch'] = true;
15295			}
15296		}
15297		if (!isset($style['fgcolor'])) {
15298			$style['fgcolor'] = array(0,0,0); // default black
15299		}
15300		if (!isset($style['bgcolor'])) {
15301			$style['bgcolor'] = false; // default transparent
15302		}
15303		if (!isset($style['border'])) {
15304			$style['border'] = false;
15305		}
15306		$fontsize = 0;
15307		if (!isset($style['text'])) {
15308			$style['text'] = false;
15309		}
15310		if ($style['text'] AND isset($style['font'])) {
15311			if (isset($style['fontsize'])) {
15312				$fontsize = $style['fontsize'];
15313			}
15314			$this->SetFont($style['font'], '', $fontsize);
15315		}
15316		if (!isset($style['stretchtext'])) {
15317			$style['stretchtext'] = 4;
15318		}
15319		if ($x === '') {
15320			$x = $this->x;
15321		}
15322		if ($y === '') {
15323			$y = $this->y;
15324		}
15325		// check page for no-write regions and adapt page margins if necessary
15326		list($x, $y) = $this->checkPageRegions($h, $x, $y);
15327		if (($w === '') OR ($w <= 0)) {
15328			if ($this->rtl) {
15329				$w = $x - $this->lMargin;
15330			} else {
15331				$w = $this->w - $this->rMargin - $x;
15332			}
15333		}
15334		// padding
15335		if (!isset($style['padding'])) {
15336			$padding = 0;
15337		} elseif ($style['padding'] === 'auto') {
15338			$padding = 10 * ($w / ($arrcode['maxw'] + 20));
15339		} else {
15340			$padding = floatval($style['padding']);
15341		}
15342		// horizontal padding
15343		if (!isset($style['hpadding'])) {
15344			$hpadding = $padding;
15345		} elseif ($style['hpadding'] === 'auto') {
15346			$hpadding = 10 * ($w / ($arrcode['maxw'] + 20));
15347		} else {
15348			$hpadding = floatval($style['hpadding']);
15349		}
15350		// vertical padding
15351		if (!isset($style['vpadding'])) {
15352			$vpadding = $padding;
15353		} elseif ($style['vpadding'] === 'auto') {
15354			$vpadding = ($hpadding / 2);
15355		} else {
15356			$vpadding = floatval($style['vpadding']);
15357		}
15358		// calculate xres (single bar width)
15359		$max_xres = ($w - (2 * $hpadding)) / $arrcode['maxw'];
15360		if ($style['stretch']) {
15361			$xres = $max_xres;
15362		} else {
15363			if (TCPDF_STATIC::empty_string($xres)) {
15364				$xres = (0.141 * $this->k); // default bar width = 0.4 mm
15365			}
15366			if ($xres > $max_xres) {
15367				// correct xres to fit on $w
15368				$xres = $max_xres;
15369			}
15370			if ((isset($style['padding']) AND ($style['padding'] === 'auto'))
15371				OR (isset($style['hpadding']) AND ($style['hpadding'] === 'auto'))) {
15372				$hpadding = 10 * $xres;
15373				if (isset($style['vpadding']) AND ($style['vpadding'] === 'auto')) {
15374					$vpadding = ($hpadding / 2);
15375				}
15376			}
15377		}
15378		if ($style['fitwidth']) {
15379			$wold = $w;
15380			$w = (($arrcode['maxw'] * $xres) + (2 * $hpadding));
15381			if (isset($style['cellfitalign'])) {
15382				switch ($style['cellfitalign']) {
15383					case 'L': {
15384						if ($this->rtl) {
15385							$x -= ($wold - $w);
15386						}
15387						break;
15388					}
15389					case 'R': {
15390						if (!$this->rtl) {
15391							$x += ($wold - $w);
15392						}
15393						break;
15394					}
15395					case 'C': {
15396						if ($this->rtl) {
15397							$x -= (($wold - $w) / 2);
15398						} else {
15399							$x += (($wold - $w) / 2);
15400						}
15401						break;
15402					}
15403					default : {
15404						break;
15405					}
15406				}
15407			}
15408		}
15409		$text_height = $this->getCellHeight($fontsize / $this->k);
15410		// height
15411		if (($h === '') OR ($h <= 0)) {
15412			// set default height
15413			$h = (($arrcode['maxw'] * $xres) / 3) + (2 * $vpadding) + $text_height;
15414		}
15415		$barh = $h - $text_height - (2 * $vpadding);
15416		if ($barh <=0) {
15417			// try to reduce font or padding to fit barcode on available height
15418			if ($text_height > $h) {
15419				$fontsize = (($h * $this->k) / (4 * $this->cell_height_ratio));
15420				$text_height = $this->getCellHeight($fontsize / $this->k);
15421				$this->SetFont($style['font'], '', $fontsize);
15422			}
15423			if ($vpadding > 0) {
15424				$vpadding = (($h - $text_height) / 4);
15425			}
15426			$barh = $h - $text_height - (2 * $vpadding);
15427		}
15428		// fit the barcode on available space
15429		list($w, $h, $x, $y) = $this->fitBlock($w, $h, $x, $y, false);
15430		// set alignment
15431		$this->img_rb_y = $y + $h;
15432		// set alignment
15433		if ($this->rtl) {
15434			if ($style['position'] == 'L') {
15435				$xpos = $this->lMargin;
15436			} elseif ($style['position'] == 'C') {
15437				$xpos = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
15438			} elseif ($style['position'] == 'R') {
15439				$xpos = $this->w - $this->rMargin - $w;
15440			} else {
15441				$xpos = $x - $w;
15442			}
15443			$this->img_rb_x = $xpos;
15444		} else {
15445			if ($style['position'] == 'L') {
15446				$xpos = $this->lMargin;
15447			} elseif ($style['position'] == 'C') {
15448				$xpos = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
15449			} elseif ($style['position'] == 'R') {
15450				$xpos = $this->w - $this->rMargin - $w;
15451			} else {
15452				$xpos = $x;
15453			}
15454			$this->img_rb_x = $xpos + $w;
15455		}
15456		$xpos_rect = $xpos;
15457		if (!isset($style['align'])) {
15458			$style['align'] = 'C';
15459		}
15460		switch ($style['align']) {
15461			case 'L': {
15462				$xpos = $xpos_rect + $hpadding;
15463				break;
15464			}
15465			case 'R': {
15466				$xpos = $xpos_rect + ($w - ($arrcode['maxw'] * $xres)) - $hpadding;
15467				break;
15468			}
15469			case 'C':
15470			default : {
15471				$xpos = $xpos_rect + (($w - ($arrcode['maxw'] * $xres)) / 2);
15472				break;
15473			}
15474		}
15475		$xpos_text = $xpos;
15476		// barcode is always printed in LTR direction
15477		$tempRTL = $this->rtl;
15478		$this->rtl = false;
15479		// print background color
15480		if ($style['bgcolor']) {
15481			$this->Rect($xpos_rect, $y, $w, $h, $style['border'] ? 'DF' : 'F', '', $style['bgcolor']);
15482		} elseif ($style['border']) {
15483			$this->Rect($xpos_rect, $y, $w, $h, 'D');
15484		}
15485		// set foreground color
15486		$this->SetDrawColorArray($style['fgcolor']);
15487		$this->SetTextColorArray($style['fgcolor']);
15488		// print bars
15489		foreach ($arrcode['bcode'] as $k => $v) {
15490			$bw = ($v['w'] * $xres);
15491			if ($v['t']) {
15492				// draw a vertical bar
15493				$ypos = $y + $vpadding + ($v['p'] * $barh / $arrcode['maxh']);
15494				$this->Rect($xpos, $ypos, $bw, ($v['h'] * $barh / $arrcode['maxh']), 'F', array(), $style['fgcolor']);
15495			}
15496			$xpos += $bw;
15497		}
15498		// print text
15499		if ($style['text']) {
15500			if (isset($style['label']) AND !TCPDF_STATIC::empty_string($style['label'])) {
15501				$label = $style['label'];
15502			} else {
15503				$label = $code;
15504			}
15505			$txtwidth = ($arrcode['maxw'] * $xres);
15506			if ($this->GetStringWidth($label) > $txtwidth) {
15507				$style['stretchtext'] = 2;
15508			}
15509			// print text
15510			$this->x = $xpos_text;
15511			$this->y = $y + $vpadding + $barh;
15512			$cellpadding = $this->cell_padding;
15513			$this->SetCellPadding(0);
15514			$this->Cell($txtwidth, '', $label, 0, 0, 'C', false, '', $style['stretchtext'], false, 'T', 'T');
15515			$this->cell_padding = $cellpadding;
15516		}
15517		// restore original direction
15518		$this->rtl = $tempRTL;
15519		// restore previous settings
15520		$this->setGraphicVars($gvars);
15521		// set pointer to align the next text/objects
15522		switch($align) {
15523			case 'T':{
15524				$this->y = $y;
15525				$this->x = $this->img_rb_x;
15526				break;
15527			}
15528			case 'M':{
15529				$this->y = $y + round($h / 2);
15530				$this->x = $this->img_rb_x;
15531				break;
15532			}
15533			case 'B':{
15534				$this->y = $this->img_rb_y;
15535				$this->x = $this->img_rb_x;
15536				break;
15537			}
15538			case 'N':{
15539				$this->SetY($this->img_rb_y);
15540				break;
15541			}
15542			default:{
15543				break;
15544			}
15545		}
15546		$this->endlinex = $this->img_rb_x;
15547	}
15548
15549	/**
15550	 * Print 2D Barcode.
15551	 * @param $code (string) code to print
15552	 * @param $type (string) type of barcode (see tcpdf_barcodes_2d.php for supported formats).
15553	 * @param $x (int) x position in user units
15554	 * @param $y (int) y position in user units
15555	 * @param $w (int) width in user units
15556	 * @param $h (int) height in user units
15557	 * @param $style (array) array of options:<ul>
15558	 * <li>boolean $style['border'] if true prints a border around the barcode</li>
15559	 * <li>int $style['padding'] padding to leave around the barcode in barcode units (set to 'auto' for automatic padding)</li>
15560	 * <li>int $style['hpadding'] horizontal padding in barcode units (set to 'auto' for automatic padding)</li>
15561	 * <li>int $style['vpadding'] vertical padding in barcode units (set to 'auto' for automatic padding)</li>
15562	 * <li>int $style['module_width'] width of a single module in points</li>
15563	 * <li>int $style['module_height'] height of a single module in points</li>
15564	 * <li>array $style['fgcolor'] color array for bars and text</li>
15565	 * <li>mixed $style['bgcolor'] color array for background or false for transparent</li>
15566	 * <li>string $style['position'] barcode position on the page: L = left margin; C = center; R = right margin; S = stretch</li>
15567	 * @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>
15568	 * @param $distort (boolean) if true distort the barcode to fit width and height, otherwise preserve aspect ratio
15569	 * @author Nicola Asuni
15570	 * @since 4.5.037 (2009-04-07)
15571	 * @public
15572	 */
15573	public function write2DBarcode($code, $type, $x='', $y='', $w='', $h='', $style=array(), $align='', $distort=false) {
15574		if (TCPDF_STATIC::empty_string(trim($code))) {
15575			return;
15576		}
15577		require_once(dirname(__FILE__).'/tcpdf_barcodes_2d.php');
15578		// save current graphic settings
15579		$gvars = $this->getGraphicVars();
15580		// create new barcode object
15581		$barcodeobj = new TCPDF2DBarcode($code, $type);
15582		$arrcode = $barcodeobj->getBarcodeArray();
15583		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)) {
15584			$this->Error('Error in 2D barcode string');
15585		}
15586		// set default values
15587		if (!isset($style['position'])) {
15588			$style['position'] = '';
15589		}
15590		if (!isset($style['fgcolor'])) {
15591			$style['fgcolor'] = array(0,0,0); // default black
15592		}
15593		if (!isset($style['bgcolor'])) {
15594			$style['bgcolor'] = false; // default transparent
15595		}
15596		if (!isset($style['border'])) {
15597			$style['border'] = false;
15598		}
15599		// padding
15600		if (!isset($style['padding'])) {
15601			$style['padding'] = 0;
15602		} elseif ($style['padding'] === 'auto') {
15603			$style['padding'] = 4;
15604		}
15605		if (!isset($style['hpadding'])) {
15606			$style['hpadding'] = $style['padding'];
15607		} elseif ($style['hpadding'] === 'auto') {
15608			$style['hpadding'] = 4;
15609		}
15610		if (!isset($style['vpadding'])) {
15611			$style['vpadding'] = $style['padding'];
15612		} elseif ($style['vpadding'] === 'auto') {
15613			$style['vpadding'] = 4;
15614		}
15615		$hpad = (2 * $style['hpadding']);
15616		$vpad = (2 * $style['vpadding']);
15617		// cell (module) dimension
15618		if (!isset($style['module_width'])) {
15619			$style['module_width'] = 1; // width of a single module in points
15620		}
15621		if (!isset($style['module_height'])) {
15622			$style['module_height'] = 1; // height of a single module in points
15623		}
15624		if ($x === '') {
15625			$x = $this->x;
15626		}
15627		if ($y === '') {
15628			$y = $this->y;
15629		}
15630		// check page for no-write regions and adapt page margins if necessary
15631		list($x, $y) = $this->checkPageRegions($h, $x, $y);
15632		// number of barcode columns and rows
15633		$rows = $arrcode['num_rows'];
15634		$cols = $arrcode['num_cols'];
15635		if (($rows <= 0) || ($cols <= 0)){
15636			$this->Error('Error in 2D barcode string');
15637		}
15638		// module width and height
15639		$mw = $style['module_width'];
15640		$mh = $style['module_height'];
15641		if (($mw <= 0) OR ($mh <= 0)) {
15642			$this->Error('Error in 2D barcode string');
15643		}
15644		// get max dimensions
15645		if ($this->rtl) {
15646			$maxw = $x - $this->lMargin;
15647		} else {
15648			$maxw = $this->w - $this->rMargin - $x;
15649		}
15650		$maxh = ($this->h - $this->tMargin - $this->bMargin);
15651		$ratioHW = ((($rows * $mh) + $hpad) / (($cols * $mw) + $vpad));
15652		$ratioWH = ((($cols * $mw) + $vpad) / (($rows * $mh) + $hpad));
15653		if (!$distort) {
15654			if (($maxw * $ratioHW) > $maxh) {
15655				$maxw = $maxh * $ratioWH;
15656			}
15657			if (($maxh * $ratioWH) > $maxw) {
15658				$maxh = $maxw * $ratioHW;
15659			}
15660		}
15661		// set maximum dimensions
15662		if ($w > $maxw) {
15663			$w = $maxw;
15664		}
15665		if ($h > $maxh) {
15666			$h = $maxh;
15667		}
15668		// set dimensions
15669		if ((($w === '') OR ($w <= 0)) AND (($h === '') OR ($h <= 0))) {
15670			$w = ($cols + $hpad) * ($mw / $this->k);
15671			$h = ($rows + $vpad) * ($mh / $this->k);
15672		} elseif (($w === '') OR ($w <= 0)) {
15673			$w = $h * $ratioWH;
15674		} elseif (($h === '') OR ($h <= 0)) {
15675			$h = $w * $ratioHW;
15676		}
15677		// barcode size (excluding padding)
15678		$bw = ($w * $cols) / ($cols + $hpad);
15679		$bh = ($h * $rows) / ($rows + $vpad);
15680		// dimension of single barcode cell unit
15681		$cw = $bw / $cols;
15682		$ch = $bh / $rows;
15683		if (!$distort) {
15684			if (($cw / $ch) > ($mw / $mh)) {
15685				// correct horizontal distortion
15686				$cw = $ch * $mw / $mh;
15687				$bw = $cw * $cols;
15688				$style['hpadding'] = ($w - $bw) / (2 * $cw);
15689			} else {
15690				// correct vertical distortion
15691				$ch = $cw * $mh / $mw;
15692				$bh = $ch * $rows;
15693				$style['vpadding'] = ($h - $bh) / (2 * $ch);
15694			}
15695		}
15696		// fit the barcode on available space
15697		list($w, $h, $x, $y) = $this->fitBlock($w, $h, $x, $y, false);
15698		// set alignment
15699		$this->img_rb_y = $y + $h;
15700		// set alignment
15701		if ($this->rtl) {
15702			if ($style['position'] == 'L') {
15703				$xpos = $this->lMargin;
15704			} elseif ($style['position'] == 'C') {
15705				$xpos = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
15706			} elseif ($style['position'] == 'R') {
15707				$xpos = $this->w - $this->rMargin - $w;
15708			} else {
15709				$xpos = $x - $w;
15710			}
15711			$this->img_rb_x = $xpos;
15712		} else {
15713			if ($style['position'] == 'L') {
15714				$xpos = $this->lMargin;
15715			} elseif ($style['position'] == 'C') {
15716				$xpos = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
15717			} elseif ($style['position'] == 'R') {
15718				$xpos = $this->w - $this->rMargin - $w;
15719			} else {
15720				$xpos = $x;
15721			}
15722			$this->img_rb_x = $xpos + $w;
15723		}
15724		$xstart = $xpos + ($style['hpadding'] * $cw);
15725		$ystart = $y + ($style['vpadding'] * $ch);
15726		// barcode is always printed in LTR direction
15727		$tempRTL = $this->rtl;
15728		$this->rtl = false;
15729		// print background color
15730		if ($style['bgcolor']) {
15731			$this->Rect($xpos, $y, $w, $h, $style['border'] ? 'DF' : 'F', '', $style['bgcolor']);
15732		} elseif ($style['border']) {
15733			$this->Rect($xpos, $y, $w, $h, 'D');
15734		}
15735		// set foreground color
15736		$this->SetDrawColorArray($style['fgcolor']);
15737		// print barcode cells
15738		// for each row
15739		for ($r = 0; $r < $rows; ++$r) {
15740			$xr = $xstart;
15741			// for each column
15742			for ($c = 0; $c < $cols; ++$c) {
15743				if ($arrcode['bcode'][$r][$c] == 1) {
15744					// draw a single barcode cell
15745					$this->Rect($xr, $ystart, $cw, $ch, 'F', array(), $style['fgcolor']);
15746				}
15747				$xr += $cw;
15748			}
15749			$ystart += $ch;
15750		}
15751		// restore original direction
15752		$this->rtl = $tempRTL;
15753		// restore previous settings
15754		$this->setGraphicVars($gvars);
15755		// set pointer to align the next text/objects
15756		switch($align) {
15757			case 'T':{
15758				$this->y = $y;
15759				$this->x = $this->img_rb_x;
15760				break;
15761			}
15762			case 'M':{
15763				$this->y = $y + round($h/2);
15764				$this->x = $this->img_rb_x;
15765				break;
15766			}
15767			case 'B':{
15768				$this->y = $this->img_rb_y;
15769				$this->x = $this->img_rb_x;
15770				break;
15771			}
15772			case 'N':{
15773				$this->SetY($this->img_rb_y);
15774				break;
15775			}
15776			default:{
15777				break;
15778			}
15779		}
15780		$this->endlinex = $this->img_rb_x;
15781	}
15782
15783	/**
15784	 * Returns an array containing current margins:
15785	 * <ul>
15786			<li>$ret['left'] = left margin</li>
15787			<li>$ret['right'] = right margin</li>
15788			<li>$ret['top'] = top margin</li>
15789			<li>$ret['bottom'] = bottom margin</li>
15790			<li>$ret['header'] = header margin</li>
15791			<li>$ret['footer'] = footer margin</li>
15792			<li>$ret['cell'] = cell padding array</li>
15793			<li>$ret['padding_left'] = cell left padding</li>
15794			<li>$ret['padding_top'] = cell top padding</li>
15795			<li>$ret['padding_right'] = cell right padding</li>
15796			<li>$ret['padding_bottom'] = cell bottom padding</li>
15797	 * </ul>
15798	 * @return array containing all margins measures
15799	 * @public
15800	 * @since 3.2.000 (2008-06-23)
15801	 */
15802	public function getMargins() {
15803		$ret = array(
15804			'left' => $this->lMargin,
15805			'right' => $this->rMargin,
15806			'top' => $this->tMargin,
15807			'bottom' => $this->bMargin,
15808			'header' => $this->header_margin,
15809			'footer' => $this->footer_margin,
15810			'cell' => $this->cell_padding,
15811			'padding_left' => $this->cell_padding['L'],
15812			'padding_top' => $this->cell_padding['T'],
15813			'padding_right' => $this->cell_padding['R'],
15814			'padding_bottom' => $this->cell_padding['B']
15815		);
15816		return $ret;
15817	}
15818
15819	/**
15820	 * Returns an array containing original margins:
15821	 * <ul>
15822			<li>$ret['left'] = left margin</li>
15823			<li>$ret['right'] = right margin</li>
15824	 * </ul>
15825	 * @return array containing all margins measures
15826	 * @public
15827	 * @since 4.0.012 (2008-07-24)
15828	 */
15829	public function getOriginalMargins() {
15830		$ret = array(
15831			'left' => $this->original_lMargin,
15832			'right' => $this->original_rMargin
15833		);
15834		return $ret;
15835	}
15836
15837	/**
15838	 * Returns the current font size.
15839	 * @return current font size
15840	 * @public
15841	 * @since 3.2.000 (2008-06-23)
15842	 */
15843	public function getFontSize() {
15844		return $this->FontSize;
15845	}
15846
15847	/**
15848	 * Returns the current font size in points unit.
15849	 * @return current font size in points unit
15850	 * @public
15851	 * @since 3.2.000 (2008-06-23)
15852	 */
15853	public function getFontSizePt() {
15854		return $this->FontSizePt;
15855	}
15856
15857	/**
15858	 * Returns the current font family name.
15859	 * @return string current font family name
15860	 * @public
15861	 * @since 4.3.008 (2008-12-05)
15862	 */
15863	public function getFontFamily() {
15864		return $this->FontFamily;
15865	}
15866
15867	/**
15868	 * Returns the current font style.
15869	 * @return string current font style
15870	 * @public
15871	 * @since 4.3.008 (2008-12-05)
15872	 */
15873	public function getFontStyle() {
15874		return $this->FontStyle;
15875	}
15876
15877	/**
15878	 * Cleanup HTML code (requires HTML Tidy library).
15879	 * @param $html (string) htmlcode to fix
15880	 * @param $default_css (string) CSS commands to add
15881	 * @param $tagvs (array) parameters for setHtmlVSpace method
15882	 * @param $tidy_options (array) options for tidy_parse_string function
15883	 * @return string XHTML code cleaned up
15884	 * @author Nicola Asuni
15885	 * @public
15886	 * @since 5.9.017 (2010-11-16)
15887	 * @see setHtmlVSpace()
15888	 */
15889	public function fixHTMLCode($html, $default_css='', $tagvs='', $tidy_options='') {
15890		return TCPDF_STATIC::fixHTMLCode($html, $default_css, $tagvs, $tidy_options, $this->tagvspaces);
15891	}
15892
15893	/**
15894	 * Returns the border width from CSS property
15895	 * @param $width (string) border width
15896	 * @return int with in user units
15897	 * @protected
15898	 * @since 5.7.000 (2010-08-02)
15899	 */
15900	protected function getCSSBorderWidth($width) {
15901		if ($width == 'thin') {
15902			$width = (2 / $this->k);
15903		} elseif ($width == 'medium') {
15904			$width = (4 / $this->k);
15905		} elseif ($width == 'thick') {
15906			$width = (6 / $this->k);
15907		} else {
15908			$width = $this->getHTMLUnitToUnits($width, 1, 'px', false);
15909		}
15910		return $width;
15911	}
15912
15913	/**
15914	 * Returns the border dash style from CSS property
15915	 * @param $style (string) border style to convert
15916	 * @return int sash style (return -1 in case of none or hidden border)
15917	 * @protected
15918	 * @since 5.7.000 (2010-08-02)
15919	 */
15920	protected function getCSSBorderDashStyle($style) {
15921		switch (strtolower($style)) {
15922			case 'none':
15923			case 'hidden': {
15924				$dash = -1;
15925				break;
15926			}
15927			case 'dotted': {
15928				$dash = 1;
15929				break;
15930			}
15931			case 'dashed': {
15932				$dash = 3;
15933				break;
15934			}
15935			case 'double':
15936			case 'groove':
15937			case 'ridge':
15938			case 'inset':
15939			case 'outset':
15940			case 'solid':
15941			default: {
15942				$dash = 0;
15943				break;
15944			}
15945		}
15946		return $dash;
15947	}
15948
15949	/**
15950	 * Returns the border style array from CSS border properties
15951	 * @param $cssborder (string) border properties
15952	 * @return array containing border properties
15953	 * @protected
15954	 * @since 5.7.000 (2010-08-02)
15955	 */
15956	protected function getCSSBorderStyle($cssborder) {
15957		$bprop = preg_split('/[\s]+/', trim($cssborder));
15958		$border = array(); // value to be returned
15959		switch (count($bprop)) {
15960			case 3: {
15961				$width = $bprop[0];
15962				$style = $bprop[1];
15963				$color = $bprop[2];
15964				break;
15965			}
15966			case 2: {
15967				$width = 'medium';
15968				$style = $bprop[0];
15969				$color = $bprop[1];
15970				break;
15971			}
15972			case 1: {
15973				$width = 'medium';
15974				$style = $bprop[0];
15975				$color = 'black';
15976				break;
15977			}
15978			default: {
15979				$width = 'medium';
15980				$style = 'solid';
15981				$color = 'black';
15982				break;
15983			}
15984		}
15985		if ($style == 'none') {
15986			return array();
15987		}
15988		$border['cap'] = 'square';
15989		$border['join'] = 'miter';
15990		$border['dash'] = $this->getCSSBorderDashStyle($style);
15991		if ($border['dash'] < 0) {
15992			return array();
15993		}
15994		$border['width'] = $this->getCSSBorderWidth($width);
15995		$border['color'] = TCPDF_COLORS::convertHTMLColorToDec($color, $this->spot_colors);
15996		return $border;
15997	}
15998
15999	/**
16000	 * Get the internal Cell padding from CSS attribute.
16001	 * @param $csspadding (string) padding properties
16002	 * @param $width (float) width of the containing element
16003	 * @return array of cell paddings
16004	 * @public
16005	 * @since 5.9.000 (2010-10-04)
16006	 */
16007	public function getCSSPadding($csspadding, $width=0) {
16008		$padding = preg_split('/[\s]+/', trim($csspadding));
16009		$cell_padding = array(); // value to be returned
16010		switch (count($padding)) {
16011			case 4: {
16012				$cell_padding['T'] = $padding[0];
16013				$cell_padding['R'] = $padding[1];
16014				$cell_padding['B'] = $padding[2];
16015				$cell_padding['L'] = $padding[3];
16016				break;
16017			}
16018			case 3: {
16019				$cell_padding['T'] = $padding[0];
16020				$cell_padding['R'] = $padding[1];
16021				$cell_padding['B'] = $padding[2];
16022				$cell_padding['L'] = $padding[1];
16023				break;
16024			}
16025			case 2: {
16026				$cell_padding['T'] = $padding[0];
16027				$cell_padding['R'] = $padding[1];
16028				$cell_padding['B'] = $padding[0];
16029				$cell_padding['L'] = $padding[1];
16030				break;
16031			}
16032			case 1: {
16033				$cell_padding['T'] = $padding[0];
16034				$cell_padding['R'] = $padding[0];
16035				$cell_padding['B'] = $padding[0];
16036				$cell_padding['L'] = $padding[0];
16037				break;
16038			}
16039			default: {
16040				return $this->cell_padding;
16041			}
16042		}
16043		if ($width == 0) {
16044			$width = $this->w - $this->lMargin - $this->rMargin;
16045		}
16046		$cell_padding['T'] = $this->getHTMLUnitToUnits($cell_padding['T'], $width, 'px', false);
16047		$cell_padding['R'] = $this->getHTMLUnitToUnits($cell_padding['R'], $width, 'px', false);
16048		$cell_padding['B'] = $this->getHTMLUnitToUnits($cell_padding['B'], $width, 'px', false);
16049		$cell_padding['L'] = $this->getHTMLUnitToUnits($cell_padding['L'], $width, 'px', false);
16050		return $cell_padding;
16051	}
16052
16053	/**
16054	 * Get the internal Cell margin from CSS attribute.
16055	 * @param $cssmargin (string) margin properties
16056	 * @param $width (float) width of the containing element
16057	 * @return array of cell margins
16058	 * @public
16059	 * @since 5.9.000 (2010-10-04)
16060	 */
16061	public function getCSSMargin($cssmargin, $width=0) {
16062		$margin = preg_split('/[\s]+/', trim($cssmargin));
16063		$cell_margin = array(); // value to be returned
16064		switch (count($margin)) {
16065			case 4: {
16066				$cell_margin['T'] = $margin[0];
16067				$cell_margin['R'] = $margin[1];
16068				$cell_margin['B'] = $margin[2];
16069				$cell_margin['L'] = $margin[3];
16070				break;
16071			}
16072			case 3: {
16073				$cell_margin['T'] = $margin[0];
16074				$cell_margin['R'] = $margin[1];
16075				$cell_margin['B'] = $margin[2];
16076				$cell_margin['L'] = $margin[1];
16077				break;
16078			}
16079			case 2: {
16080				$cell_margin['T'] = $margin[0];
16081				$cell_margin['R'] = $margin[1];
16082				$cell_margin['B'] = $margin[0];
16083				$cell_margin['L'] = $margin[1];
16084				break;
16085			}
16086			case 1: {
16087				$cell_margin['T'] = $margin[0];
16088				$cell_margin['R'] = $margin[0];
16089				$cell_margin['B'] = $margin[0];
16090				$cell_margin['L'] = $margin[0];
16091				break;
16092			}
16093			default: {
16094				return $this->cell_margin;
16095			}
16096		}
16097		if ($width == 0) {
16098			$width = $this->w - $this->lMargin - $this->rMargin;
16099		}
16100		$cell_margin['T'] = $this->getHTMLUnitToUnits(str_replace('auto', '0', $cell_margin['T']), $width, 'px', false);
16101		$cell_margin['R'] = $this->getHTMLUnitToUnits(str_replace('auto', '0', $cell_margin['R']), $width, 'px', false);
16102		$cell_margin['B'] = $this->getHTMLUnitToUnits(str_replace('auto', '0', $cell_margin['B']), $width, 'px', false);
16103		$cell_margin['L'] = $this->getHTMLUnitToUnits(str_replace('auto', '0', $cell_margin['L']), $width, 'px', false);
16104		return $cell_margin;
16105	}
16106
16107	/**
16108	 * Get the border-spacing from CSS attribute.
16109	 * @param $cssbspace (string) border-spacing CSS properties
16110	 * @param $width (float) width of the containing element
16111	 * @return array of border spacings
16112	 * @public
16113	 * @since 5.9.010 (2010-10-27)
16114	 */
16115	public function getCSSBorderMargin($cssbspace, $width=0) {
16116		$space = preg_split('/[\s]+/', trim($cssbspace));
16117		$border_spacing = array(); // value to be returned
16118		switch (count($space)) {
16119			case 2: {
16120				$border_spacing['H'] = $space[0];
16121				$border_spacing['V'] = $space[1];
16122				break;
16123			}
16124			case 1: {
16125				$border_spacing['H'] = $space[0];
16126				$border_spacing['V'] = $space[0];
16127				break;
16128			}
16129			default: {
16130				return array('H' => 0, 'V' => 0);
16131			}
16132		}
16133		if ($width == 0) {
16134			$width = $this->w - $this->lMargin - $this->rMargin;
16135		}
16136		$border_spacing['H'] = $this->getHTMLUnitToUnits($border_spacing['H'], $width, 'px', false);
16137		$border_spacing['V'] = $this->getHTMLUnitToUnits($border_spacing['V'], $width, 'px', false);
16138		return $border_spacing;
16139	}
16140
16141	/**
16142	 * Returns the letter-spacing value from CSS value
16143	 * @param $spacing (string) letter-spacing value
16144	 * @param $parent (float) font spacing (tracking) value of the parent element
16145	 * @return float quantity to increases or decreases the space between characters in a text.
16146	 * @protected
16147	 * @since 5.9.000 (2010-10-02)
16148	 */
16149	protected function getCSSFontSpacing($spacing, $parent=0) {
16150		$val = 0; // value to be returned
16151		$spacing = trim($spacing);
16152		switch ($spacing) {
16153			case 'normal': {
16154				$val = 0;
16155				break;
16156			}
16157			case 'inherit': {
16158				if ($parent == 'normal') {
16159					$val = 0;
16160				} else {
16161					$val = $parent;
16162				}
16163				break;
16164			}
16165			default: {
16166				$val = $this->getHTMLUnitToUnits($spacing, 0, 'px', false);
16167			}
16168		}
16169		return $val;
16170	}
16171
16172	/**
16173	 * Returns the percentage of font stretching from CSS value
16174	 * @param $stretch (string) stretch mode
16175	 * @param $parent (float) stretch value of the parent element
16176	 * @return float font stretching percentage
16177	 * @protected
16178	 * @since 5.9.000 (2010-10-02)
16179	 */
16180	protected function getCSSFontStretching($stretch, $parent=100) {
16181		$val = 100; // value to be returned
16182		$stretch = trim($stretch);
16183		switch ($stretch) {
16184			case 'ultra-condensed': {
16185				$val = 40;
16186				break;
16187			}
16188			case 'extra-condensed': {
16189				$val = 55;
16190				break;
16191			}
16192			case 'condensed': {
16193				$val = 70;
16194				break;
16195			}
16196			case 'semi-condensed': {
16197				$val = 85;
16198				break;
16199			}
16200			case 'normal': {
16201				$val = 100;
16202				break;
16203			}
16204			case 'semi-expanded': {
16205				$val = 115;
16206				break;
16207			}
16208			case 'expanded': {
16209				$val = 130;
16210				break;
16211			}
16212			case 'extra-expanded': {
16213				$val = 145;
16214				break;
16215			}
16216			case 'ultra-expanded': {
16217				$val = 160;
16218				break;
16219			}
16220			case 'wider': {
16221				$val = ($parent + 10);
16222				break;
16223			}
16224			case 'narrower': {
16225				$val = ($parent - 10);
16226				break;
16227			}
16228			case 'inherit': {
16229				if ($parent == 'normal') {
16230					$val = 100;
16231				} else {
16232					$val = $parent;
16233				}
16234				break;
16235			}
16236			default: {
16237				$val = $this->getHTMLUnitToUnits($stretch, 100, '%', false);
16238			}
16239		}
16240		return $val;
16241	}
16242
16243	/**
16244	 * Convert HTML string containing font size value to points
16245	 * @param $val (string) String containing font size value and unit.
16246	 * @param $refsize (float) Reference font size in points.
16247	 * @param $parent_size (float) Parent font size in points.
16248	 * @param $defaultunit (string) Default unit (can be one of the following: %, em, ex, px, in, mm, pc, pt).
16249	 * @return float value in points
16250	 * @public
16251	 */
16252	public function getHTMLFontUnits($val, $refsize=12, $parent_size=12, $defaultunit='pt') {
16253		$refsize = TCPDF_FONTS::getFontRefSize($refsize);
16254		$parent_size = TCPDF_FONTS::getFontRefSize($parent_size, $refsize);
16255		switch ($val) {
16256			case 'xx-small': {
16257				$size = ($refsize - 4);
16258				break;
16259			}
16260			case 'x-small': {
16261				$size = ($refsize - 3);
16262				break;
16263			}
16264			case 'small': {
16265				$size = ($refsize - 2);
16266				break;
16267			}
16268			case 'medium': {
16269				$size = $refsize;
16270				break;
16271			}
16272			case 'large': {
16273				$size = ($refsize + 2);
16274				break;
16275			}
16276			case 'x-large': {
16277				$size = ($refsize + 4);
16278				break;
16279			}
16280			case 'xx-large': {
16281				$size = ($refsize + 6);
16282				break;
16283			}
16284			case 'smaller': {
16285				$size = ($parent_size - 3);
16286				break;
16287			}
16288			case 'larger': {
16289				$size = ($parent_size + 3);
16290				break;
16291			}
16292			default: {
16293				$size = $this->getHTMLUnitToUnits($val, $parent_size, $defaultunit, true);
16294			}
16295		}
16296		return $size;
16297	}
16298
16299	/**
16300	 * Returns the HTML DOM array.
16301	 * @param $html (string) html code
16302	 * @return array
16303	 * @protected
16304	 * @since 3.2.000 (2008-06-20)
16305	 */
16306	protected function getHtmlDomArray($html) {
16307		// array of CSS styles ( selector => properties).
16308		$css = array();
16309		// get CSS array defined at previous call
16310		$matches = array();
16311		if (preg_match_all('/<cssarray>([^\<]*)<\/cssarray>/isU', $html, $matches) > 0) {
16312			if (isset($matches[1][0])) {
16313				$css = array_merge($css, json_decode($this->unhtmlentities($matches[1][0]), true));
16314			}
16315			$html = preg_replace('/<cssarray>(.*?)<\/cssarray>/isU', '', $html);
16316		}
16317		// extract external CSS files
16318		$matches = array();
16319		if (preg_match_all('/<link([^\>]*)>/isU', $html, $matches) > 0) {
16320			foreach ($matches[1] as $key => $link) {
16321				$type = array();
16322				if (preg_match('/type[\s]*=[\s]*"text\/css"/', $link, $type)) {
16323					$type = array();
16324					preg_match('/media[\s]*=[\s]*"([^"]*)"/', $link, $type);
16325					// get 'all' and 'print' media, other media types are discarded
16326					// (all, braille, embossed, handheld, print, projection, screen, speech, tty, tv)
16327					if (empty($type) OR (isset($type[1]) AND (($type[1] == 'all') OR ($type[1] == 'print')))) {
16328						$type = array();
16329						if (preg_match('/href[\s]*=[\s]*"([^"]*)"/', $link, $type) > 0) {
16330							// read CSS data file
16331							$cssdata = TCPDF_STATIC::fileGetContents(trim($type[1]));
16332							if (($cssdata !== FALSE) AND (strlen($cssdata) > 0)) {
16333								$css = array_merge($css, TCPDF_STATIC::extractCSSproperties($cssdata));
16334							}
16335						}
16336					}
16337				}
16338			}
16339		}
16340		// extract style tags
16341		$matches = array();
16342		if (preg_match_all('/<style([^\>]*)>([^\<]*)<\/style>/isU', $html, $matches) > 0) {
16343			foreach ($matches[1] as $key => $media) {
16344				$type = array();
16345				preg_match('/media[\s]*=[\s]*"([^"]*)"/', $media, $type);
16346				// get 'all' and 'print' media, other media types are discarded
16347				// (all, braille, embossed, handheld, print, projection, screen, speech, tty, tv)
16348				if (empty($type) OR (isset($type[1]) AND (($type[1] == 'all') OR ($type[1] == 'print')))) {
16349					$cssdata = $matches[2][$key];
16350					$css = array_merge($css, TCPDF_STATIC::extractCSSproperties($cssdata));
16351				}
16352			}
16353		}
16354		// create a special tag to contain the CSS array (used for table content)
16355		$csstagarray = '<cssarray>'.htmlentities(json_encode($css)).'</cssarray>';
16356		// remove head and style blocks
16357		$html = preg_replace('/<head([^\>]*)>(.*?)<\/head>/siU', '', $html);
16358		$html = preg_replace('/<style([^\>]*)>([^\<]*)<\/style>/isU', '', $html);
16359		// define block tags
16360		$blocktags = array('blockquote','br','dd','dl','div','dt','h1','h2','h3','h4','h5','h6','hr','li','ol','p','pre','ul','tcpdf','table','tr','td');
16361		// define self-closing tags
16362		$selfclosingtags = array('area','base','basefont','br','hr','input','img','link','meta');
16363		// remove all unsupported tags (the line below lists all supported tags)
16364		$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>');
16365		//replace some blank characters
16366		$html = preg_replace('/<pre/', '<xre', $html); // preserve pre tag
16367		$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);
16368		$html = preg_replace('@(\r\n|\r)@', "\n", $html);
16369		$repTable = array("\t" => ' ', "\0" => ' ', "\x0B" => ' ', "\\" => "\\\\");
16370		$html = strtr($html, $repTable);
16371		$offset = 0;
16372		while (($offset < strlen($html)) AND ($pos = strpos($html, '</pre>', $offset)) !== false) {
16373			$html_a = substr($html, 0, $offset);
16374			$html_b = substr($html, $offset, ($pos - $offset + 6));
16375			while (preg_match("'<xre([^\>]*)>(.*?)\n(.*?)</pre>'si", $html_b)) {
16376				// preserve newlines on <pre> tag
16377				$html_b = preg_replace("'<xre([^\>]*)>(.*?)\n(.*?)</pre>'si", "<xre\\1>\\2<br />\\3</pre>", $html_b);
16378			}
16379			while (preg_match("'<xre([^\>]*)>(.*?)".$this->re_space['p']."(.*?)</pre>'".$this->re_space['m'], $html_b)) {
16380				// preserve spaces on <pre> tag
16381				$html_b = preg_replace("'<xre([^\>]*)>(.*?)".$this->re_space['p']."(.*?)</pre>'".$this->re_space['m'], "<xre\\1>\\2&nbsp;\\3</pre>", $html_b);
16382			}
16383			$html = $html_a.$html_b.substr($html, $pos + 6);
16384			$offset = strlen($html_a.$html_b);
16385		}
16386		$offset = 0;
16387		while (($offset < strlen($html)) AND ($pos = strpos($html, '</textarea>', $offset)) !== false) {
16388			$html_a = substr($html, 0, $offset);
16389			$html_b = substr($html, $offset, ($pos - $offset + 11));
16390			while (preg_match("'<textarea([^\>]*)>(.*?)\n(.*?)</textarea>'si", $html_b)) {
16391				// preserve newlines on <textarea> tag
16392				$html_b = preg_replace("'<textarea([^\>]*)>(.*?)\n(.*?)</textarea>'si", "<textarea\\1>\\2<TBR>\\3</textarea>", $html_b);
16393				$html_b = preg_replace("'<textarea([^\>]*)>(.*?)[\"](.*?)</textarea>'si", "<textarea\\1>\\2''\\3</textarea>", $html_b);
16394			}
16395			$html = $html_a.$html_b.substr($html, $pos + 11);
16396			$offset = strlen($html_a.$html_b);
16397		}
16398		$html = preg_replace('/([\s]*)<option/si', '<option', $html);
16399		$html = preg_replace('/<\/option>([\s]*)/si', '</option>', $html);
16400		$offset = 0;
16401		while (($offset < strlen($html)) AND ($pos = strpos($html, '</option>', $offset)) !== false) {
16402			$html_a = substr($html, 0, $offset);
16403			$html_b = substr($html, $offset, ($pos - $offset + 9));
16404			while (preg_match("'<option([^\>]*)>(.*?)</option>'si", $html_b)) {
16405				$html_b = preg_replace("'<option([\s]+)value=\"([^\"]*)\"([^\>]*)>(.*?)</option>'si", "\\2#!TaB!#\\4#!NwL!#", $html_b);
16406				$html_b = preg_replace("'<option([^\>]*)>(.*?)</option>'si", "\\2#!NwL!#", $html_b);
16407			}
16408			$html = $html_a.$html_b.substr($html, $pos + 9);
16409			$offset = strlen($html_a.$html_b);
16410		}
16411		if (preg_match("'</select'si", $html)) {
16412			$html = preg_replace("'<select([^\>]*)>'si", "<select\\1 opt=\"", $html);
16413			$html = preg_replace("'#!NwL!#</select>'si", "\" />", $html);
16414		}
16415		$html = str_replace("\n", ' ', $html);
16416		// restore textarea newlines
16417		$html = str_replace('<TBR>', "\n", $html);
16418		// remove extra spaces from code
16419		$html = preg_replace('/[\s]+<\/(table|tr|ul|ol|dl)>/', '</\\1>', $html);
16420		$html = preg_replace('/'.$this->re_space['p'].'+<\/(td|th|li|dt|dd)>/'.$this->re_space['m'], '</\\1>', $html);
16421		$html = preg_replace('/[\s]+<(tr|td|th|li|dt|dd)/', '<\\1', $html);
16422		$html = preg_replace('/'.$this->re_space['p'].'+<(ul|ol|dl|br)/'.$this->re_space['m'], '<\\1', $html);
16423		$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);
16424		$html = preg_replace('/<\/(td|th)>/', '<marker style="font-size:0"/></\\1>', $html);
16425		$html = preg_replace('/<\/table>([\s]*)<marker style="font-size:0"\/>/', '</table>', $html);
16426		$html = preg_replace('/'.$this->re_space['p'].'+<img/'.$this->re_space['m'], chr(32).'<img', $html);
16427		$html = preg_replace('/<img([^\>]*)>[\s]+([^\<])/xi', '<img\\1>&nbsp;\\2', $html);
16428		$html = preg_replace('/<img([^\>]*)>/xi', '<img\\1><span><marker style="font-size:0"/></span>', $html);
16429		$html = preg_replace('/<xre/', '<pre', $html); // restore pre tag
16430		$html = preg_replace('/<textarea([^\>]*)>([^\<]*)<\/textarea>/xi', '<textarea\\1 value="\\2" />', $html);
16431		$html = preg_replace('/<li([^\>]*)><\/li>/', '<li\\1>&nbsp;</li>', $html);
16432		$html = preg_replace('/<li([^\>]*)>'.$this->re_space['p'].'*<img/'.$this->re_space['m'], '<li\\1><font size="1">&nbsp;</font><img', $html);
16433		$html = preg_replace('/<([^\>\/]*)>[\s]/', '<\\1>&nbsp;', $html); // preserve some spaces
16434		$html = preg_replace('/[\s]<\/([^\>]*)>/', '&nbsp;</\\1>', $html); // preserve some spaces
16435		$html = preg_replace('/<su([bp])/', '<zws/><su\\1', $html); // fix sub/sup alignment
16436		$html = preg_replace('/<\/su([bp])>/', '</su\\1><zws/>', $html); // fix sub/sup alignment
16437		$html = preg_replace('/'.$this->re_space['p'].'+/'.$this->re_space['m'], chr(32), $html); // replace multiple spaces with a single space
16438		// trim string
16439		$html = $this->stringTrim($html);
16440		// fix br tag after li
16441		$html = preg_replace('/<li><br([^\>]*)>/', '<li> <br\\1>', $html);
16442		// fix first image tag alignment
16443		$html = preg_replace('/^<img/', '<span style="font-size:0"><br /></span> <img', $html, 1);
16444		// pattern for generic tag
16445		$tagpattern = '/(<[^>]+>)/';
16446		// explodes the string
16447		$a = preg_split($tagpattern, $html, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
16448		// count elements
16449		$maxel = count($a);
16450		$elkey = 0;
16451		$key = 0;
16452		// create an array of elements
16453		$dom = array();
16454		$dom[$key] = array();
16455		// set inheritable properties fot the first void element
16456		// 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
16457		$dom[$key]['tag'] = false;
16458		$dom[$key]['block'] = false;
16459		$dom[$key]['value'] = '';
16460		$dom[$key]['parent'] = 0;
16461		$dom[$key]['hide'] = false;
16462		$dom[$key]['fontname'] = $this->FontFamily;
16463		$dom[$key]['fontstyle'] = $this->FontStyle;
16464		$dom[$key]['fontsize'] = $this->FontSizePt;
16465		$dom[$key]['font-stretch'] = $this->font_stretching;
16466		$dom[$key]['letter-spacing'] = $this->font_spacing;
16467		$dom[$key]['stroke'] = $this->textstrokewidth;
16468		$dom[$key]['fill'] = (($this->textrendermode % 2) == 0);
16469		$dom[$key]['clip'] = ($this->textrendermode > 3);
16470		$dom[$key]['line-height'] = $this->cell_height_ratio;
16471		$dom[$key]['bgcolor'] = false;
16472		$dom[$key]['fgcolor'] = $this->fgcolor; // color
16473		$dom[$key]['strokecolor'] = $this->strokecolor;
16474		$dom[$key]['align'] = '';
16475		$dom[$key]['listtype'] = '';
16476		$dom[$key]['text-indent'] = 0;
16477		$dom[$key]['text-transform'] = '';
16478		$dom[$key]['border'] = array();
16479		$dom[$key]['dir'] = $this->rtl?'rtl':'ltr';
16480		$thead = false; // true when we are inside the THEAD tag
16481		++$key;
16482		$level = array();
16483		array_push($level, 0); // root
16484		while ($elkey < $maxel) {
16485			$dom[$key] = array();
16486			$element = $a[$elkey];
16487			$dom[$key]['elkey'] = $elkey;
16488			if (preg_match($tagpattern, $element)) {
16489				// html tag
16490				$element = substr($element, 1, -1);
16491				// get tag name
16492				preg_match('/[\/]?([a-zA-Z0-9]*)/', $element, $tag);
16493				$tagname = strtolower($tag[1]);
16494				// check if we are inside a table header
16495				if ($tagname == 'thead') {
16496					if ($element[0] == '/') {
16497						$thead = false;
16498					} else {
16499						$thead = true;
16500					}
16501					++$elkey;
16502					continue;
16503				}
16504				$dom[$key]['tag'] = true;
16505				$dom[$key]['value'] = $tagname;
16506				if (in_array($dom[$key]['value'], $blocktags)) {
16507					$dom[$key]['block'] = true;
16508				} else {
16509					$dom[$key]['block'] = false;
16510				}
16511				if ($element[0] == '/') {
16512					// *** closing html tag
16513					$dom[$key]['opening'] = false;
16514					$dom[$key]['parent'] = end($level);
16515					array_pop($level);
16516					$dom[$key]['hide'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['hide'];
16517					$dom[$key]['fontname'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fontname'];
16518					$dom[$key]['fontstyle'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fontstyle'];
16519					$dom[$key]['fontsize'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fontsize'];
16520					$dom[$key]['font-stretch'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['font-stretch'];
16521					$dom[$key]['letter-spacing'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['letter-spacing'];
16522					$dom[$key]['stroke'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['stroke'];
16523					$dom[$key]['fill'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fill'];
16524					$dom[$key]['clip'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['clip'];
16525					$dom[$key]['line-height'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['line-height'];
16526					$dom[$key]['bgcolor'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['bgcolor'];
16527					$dom[$key]['fgcolor'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fgcolor'];
16528					$dom[$key]['strokecolor'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['strokecolor'];
16529					$dom[$key]['align'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['align'];
16530					$dom[$key]['text-transform'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['text-transform'];
16531					$dom[$key]['dir'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['dir'];
16532					if (isset($dom[($dom[($dom[$key]['parent'])]['parent'])]['listtype'])) {
16533						$dom[$key]['listtype'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['listtype'];
16534					}
16535					// set the number of columns in table tag
16536					if (($dom[$key]['value'] == 'tr') AND (!isset($dom[($dom[($dom[$key]['parent'])]['parent'])]['cols']))) {
16537						$dom[($dom[($dom[$key]['parent'])]['parent'])]['cols'] = $dom[($dom[$key]['parent'])]['cols'];
16538					}
16539					if (($dom[$key]['value'] == 'td') OR ($dom[$key]['value'] == 'th')) {
16540						$dom[($dom[$key]['parent'])]['content'] = $csstagarray;
16541						for ($i = ($dom[$key]['parent'] + 1); $i < $key; ++$i) {
16542							$dom[($dom[$key]['parent'])]['content'] .= stripslashes($a[$dom[$i]['elkey']]);
16543						}
16544						$key = $i;
16545						// mark nested tables
16546						$dom[($dom[$key]['parent'])]['content'] = str_replace('<table', '<table nested="true"', $dom[($dom[$key]['parent'])]['content']);
16547						// remove thead sections from nested tables
16548						$dom[($dom[$key]['parent'])]['content'] = str_replace('<thead>', '', $dom[($dom[$key]['parent'])]['content']);
16549						$dom[($dom[$key]['parent'])]['content'] = str_replace('</thead>', '', $dom[($dom[$key]['parent'])]['content']);
16550					}
16551					// store header rows on a new table
16552					if (($dom[$key]['value'] == 'tr') AND ($dom[($dom[$key]['parent'])]['thead'] === true)) {
16553						if (TCPDF_STATIC::empty_string($dom[($dom[($dom[$key]['parent'])]['parent'])]['thead'])) {
16554							$dom[($dom[($dom[$key]['parent'])]['parent'])]['thead'] = $csstagarray.$a[$dom[($dom[($dom[$key]['parent'])]['parent'])]['elkey']];
16555						}
16556						for ($i = $dom[$key]['parent']; $i <= $key; ++$i) {
16557							$dom[($dom[($dom[$key]['parent'])]['parent'])]['thead'] .= $a[$dom[$i]['elkey']];
16558						}
16559						if (!isset($dom[($dom[$key]['parent'])]['attribute'])) {
16560							$dom[($dom[$key]['parent'])]['attribute'] = array();
16561						}
16562						// header elements must be always contained in a single page
16563						$dom[($dom[$key]['parent'])]['attribute']['nobr'] = 'true';
16564					}
16565					if (($dom[$key]['value'] == 'table') AND (!TCPDF_STATIC::empty_string($dom[($dom[$key]['parent'])]['thead']))) {
16566						// remove the nobr attributes from the table header
16567						$dom[($dom[$key]['parent'])]['thead'] = str_replace(' nobr="true"', '', $dom[($dom[$key]['parent'])]['thead']);
16568						$dom[($dom[$key]['parent'])]['thead'] .= '</tablehead>';
16569					}
16570				} else {
16571					// *** opening or self-closing html tag
16572					$dom[$key]['opening'] = true;
16573					$dom[$key]['parent'] = end($level);
16574					if ((substr($element, -1, 1) == '/') OR (in_array($dom[$key]['value'], $selfclosingtags))) {
16575						// self-closing tag
16576						$dom[$key]['self'] = true;
16577					} else {
16578						// opening tag
16579						array_push($level, $key);
16580						$dom[$key]['self'] = false;
16581					}
16582					// copy some values from parent
16583					$parentkey = 0;
16584					if ($key > 0) {
16585						$parentkey = $dom[$key]['parent'];
16586						$dom[$key]['hide'] = $dom[$parentkey]['hide'];
16587						$dom[$key]['fontname'] = $dom[$parentkey]['fontname'];
16588						$dom[$key]['fontstyle'] = $dom[$parentkey]['fontstyle'];
16589						$dom[$key]['fontsize'] = $dom[$parentkey]['fontsize'];
16590						$dom[$key]['font-stretch'] = $dom[$parentkey]['font-stretch'];
16591						$dom[$key]['letter-spacing'] = $dom[$parentkey]['letter-spacing'];
16592						$dom[$key]['stroke'] = $dom[$parentkey]['stroke'];
16593						$dom[$key]['fill'] = $dom[$parentkey]['fill'];
16594						$dom[$key]['clip'] = $dom[$parentkey]['clip'];
16595						$dom[$key]['line-height'] = $dom[$parentkey]['line-height'];
16596						$dom[$key]['bgcolor'] = $dom[$parentkey]['bgcolor'];
16597						$dom[$key]['fgcolor'] = $dom[$parentkey]['fgcolor'];
16598						$dom[$key]['strokecolor'] = $dom[$parentkey]['strokecolor'];
16599						$dom[$key]['align'] = $dom[$parentkey]['align'];
16600						$dom[$key]['listtype'] = $dom[$parentkey]['listtype'];
16601						$dom[$key]['text-indent'] = $dom[$parentkey]['text-indent'];
16602						$dom[$key]['text-transform'] = $dom[$parentkey]['text-transform'];
16603						$dom[$key]['border'] = array();
16604						$dom[$key]['dir'] = $dom[$parentkey]['dir'];
16605					}
16606					// get attributes
16607					preg_match_all('/([^=\s]*)[\s]*=[\s]*"([^"]*)"/', $element, $attr_array, PREG_PATTERN_ORDER);
16608					$dom[$key]['attribute'] = array(); // reset attribute array
16609                    foreach($attr_array[1] as $id => $name) {
16610                        $dom[$key]['attribute'][strtolower($name)] = $attr_array[2][$id];
16611                    }
16612					if (!empty($css)) {
16613						// merge CSS style to current style
16614						list($dom[$key]['csssel'], $dom[$key]['cssdata']) = TCPDF_STATIC::getCSSdataArray($dom, $key, $css);
16615						$dom[$key]['attribute']['style'] = TCPDF_STATIC::getTagStyleFromCSSarray($dom[$key]['cssdata']);
16616					}
16617					// split style attributes
16618					if (isset($dom[$key]['attribute']['style']) AND !empty($dom[$key]['attribute']['style'])) {
16619						// get style attributes
16620						preg_match_all('/([^;:\s]*):([^;]*)/', $dom[$key]['attribute']['style'], $style_array, PREG_PATTERN_ORDER);
16621						$dom[$key]['style'] = array(); // reset style attribute array
16622                        foreach($style_array[1] as $id => $name) {
16623                            // in case of duplicate attribute the last replace the previous
16624                            $dom[$key]['style'][strtolower($name)] = trim($style_array[2][$id]);
16625                        }
16626						// --- get some style attributes ---
16627						// text direction
16628						if (isset($dom[$key]['style']['direction'])) {
16629							$dom[$key]['dir'] = $dom[$key]['style']['direction'];
16630						}
16631						// display
16632						if (isset($dom[$key]['style']['display'])) {
16633							$dom[$key]['hide'] = (trim(strtolower($dom[$key]['style']['display'])) == 'none');
16634						}
16635						// font family
16636						if (isset($dom[$key]['style']['font-family'])) {
16637							$dom[$key]['fontname'] = $this->getFontFamilyName($dom[$key]['style']['font-family']);
16638						}
16639						// list-style-type
16640						if (isset($dom[$key]['style']['list-style-type'])) {
16641							$dom[$key]['listtype'] = trim(strtolower($dom[$key]['style']['list-style-type']));
16642							if ($dom[$key]['listtype'] == 'inherit') {
16643								$dom[$key]['listtype'] = $dom[$parentkey]['listtype'];
16644							}
16645						}
16646						// text-indent
16647						if (isset($dom[$key]['style']['text-indent'])) {
16648							$dom[$key]['text-indent'] = $this->getHTMLUnitToUnits($dom[$key]['style']['text-indent']);
16649							if ($dom[$key]['text-indent'] == 'inherit') {
16650								$dom[$key]['text-indent'] = $dom[$parentkey]['text-indent'];
16651							}
16652						}
16653						// text-transform
16654						if (isset($dom[$key]['style']['text-transform'])) {
16655							$dom[$key]['text-transform'] = $dom[$key]['style']['text-transform'];
16656						}
16657						// font size
16658						if (isset($dom[$key]['style']['font-size'])) {
16659							$fsize = trim($dom[$key]['style']['font-size']);
16660							$dom[$key]['fontsize'] = $this->getHTMLFontUnits($fsize, $dom[0]['fontsize'], $dom[$parentkey]['fontsize'], 'pt');
16661						}
16662						// font-stretch
16663						if (isset($dom[$key]['style']['font-stretch'])) {
16664							$dom[$key]['font-stretch'] = $this->getCSSFontStretching($dom[$key]['style']['font-stretch'], $dom[$parentkey]['font-stretch']);
16665						}
16666						// letter-spacing
16667						if (isset($dom[$key]['style']['letter-spacing'])) {
16668							$dom[$key]['letter-spacing'] = $this->getCSSFontSpacing($dom[$key]['style']['letter-spacing'], $dom[$parentkey]['letter-spacing']);
16669						}
16670						// line-height (internally is the cell height ratio)
16671						if (isset($dom[$key]['style']['line-height'])) {
16672							$lineheight = trim($dom[$key]['style']['line-height']);
16673							switch ($lineheight) {
16674								// A normal line height. This is default
16675								case 'normal': {
16676									$dom[$key]['line-height'] = $dom[0]['line-height'];
16677									break;
16678								}
16679								case 'inherit': {
16680									$dom[$key]['line-height'] = $dom[$parentkey]['line-height'];
16681								}
16682								default: {
16683									if (is_numeric($lineheight)) {
16684										// convert to percentage of font height
16685										$lineheight = ($lineheight * 100).'%';
16686									}
16687									$dom[$key]['line-height'] = $this->getHTMLUnitToUnits($lineheight, 1, '%', true);
16688									if (substr($lineheight, -1) !== '%') {
16689										if ($dom[$key]['fontsize'] <= 0) {
16690											$dom[$key]['line-height'] = 1;
16691										} else {
16692											$dom[$key]['line-height'] = (($dom[$key]['line-height'] - $this->cell_padding['T'] - $this->cell_padding['B']) / $dom[$key]['fontsize']);
16693										}
16694									}
16695								}
16696							}
16697						}
16698						// font style
16699						if (isset($dom[$key]['style']['font-weight'])) {
16700							if (strtolower($dom[$key]['style']['font-weight'][0]) == 'n') {
16701								if (strpos($dom[$key]['fontstyle'], 'B') !== false) {
16702									$dom[$key]['fontstyle'] = str_replace('B', '', $dom[$key]['fontstyle']);
16703								}
16704							} elseif (strtolower($dom[$key]['style']['font-weight'][0]) == 'b') {
16705								$dom[$key]['fontstyle'] .= 'B';
16706							}
16707						}
16708						if (isset($dom[$key]['style']['font-style']) AND (strtolower($dom[$key]['style']['font-style'][0]) == 'i')) {
16709							$dom[$key]['fontstyle'] .= 'I';
16710						}
16711						// font color
16712						if (isset($dom[$key]['style']['color']) AND (!TCPDF_STATIC::empty_string($dom[$key]['style']['color']))) {
16713							$dom[$key]['fgcolor'] = TCPDF_COLORS::convertHTMLColorToDec($dom[$key]['style']['color'], $this->spot_colors);
16714						} elseif ($dom[$key]['value'] == 'a') {
16715							$dom[$key]['fgcolor'] = $this->htmlLinkColorArray;
16716						}
16717						// background color
16718						if (isset($dom[$key]['style']['background-color']) AND (!TCPDF_STATIC::empty_string($dom[$key]['style']['background-color']))) {
16719							$dom[$key]['bgcolor'] = TCPDF_COLORS::convertHTMLColorToDec($dom[$key]['style']['background-color'], $this->spot_colors);
16720						}
16721						// text-decoration
16722						if (isset($dom[$key]['style']['text-decoration'])) {
16723							$decors = explode(' ', strtolower($dom[$key]['style']['text-decoration']));
16724							foreach ($decors as $dec) {
16725								$dec = trim($dec);
16726								if (!TCPDF_STATIC::empty_string($dec)) {
16727									if ($dec[0] == 'u') {
16728										// underline
16729										$dom[$key]['fontstyle'] .= 'U';
16730									} elseif ($dec[0] == 'l') {
16731										// line-through
16732										$dom[$key]['fontstyle'] .= 'D';
16733									} elseif ($dec[0] == 'o') {
16734										// overline
16735										$dom[$key]['fontstyle'] .= 'O';
16736									}
16737								}
16738							}
16739						} elseif ($dom[$key]['value'] == 'a') {
16740							$dom[$key]['fontstyle'] = $this->htmlLinkFontStyle;
16741						}
16742						// check for width attribute
16743						if (isset($dom[$key]['style']['width'])) {
16744							$dom[$key]['width'] = $dom[$key]['style']['width'];
16745						}
16746						// check for height attribute
16747						if (isset($dom[$key]['style']['height'])) {
16748							$dom[$key]['height'] = $dom[$key]['style']['height'];
16749						}
16750						// check for text alignment
16751						if (isset($dom[$key]['style']['text-align'])) {
16752							$dom[$key]['align'] = strtoupper($dom[$key]['style']['text-align'][0]);
16753						}
16754						// check for CSS border properties
16755						if (isset($dom[$key]['style']['border'])) {
16756							$borderstyle = $this->getCSSBorderStyle($dom[$key]['style']['border']);
16757							if (!empty($borderstyle)) {
16758								$dom[$key]['border']['LTRB'] = $borderstyle;
16759							}
16760						}
16761						if (isset($dom[$key]['style']['border-color'])) {
16762							$brd_colors = preg_split('/[\s]+/', trim($dom[$key]['style']['border-color']));
16763							if (isset($brd_colors[3])) {
16764								$dom[$key]['border']['L']['color'] = TCPDF_COLORS::convertHTMLColorToDec($brd_colors[3], $this->spot_colors);
16765							}
16766							if (isset($brd_colors[1])) {
16767								$dom[$key]['border']['R']['color'] = TCPDF_COLORS::convertHTMLColorToDec($brd_colors[1], $this->spot_colors);
16768							}
16769							if (isset($brd_colors[0])) {
16770								$dom[$key]['border']['T']['color'] = TCPDF_COLORS::convertHTMLColorToDec($brd_colors[0], $this->spot_colors);
16771							}
16772							if (isset($brd_colors[2])) {
16773								$dom[$key]['border']['B']['color'] = TCPDF_COLORS::convertHTMLColorToDec($brd_colors[2], $this->spot_colors);
16774							}
16775						}
16776						if (isset($dom[$key]['style']['border-width'])) {
16777							$brd_widths = preg_split('/[\s]+/', trim($dom[$key]['style']['border-width']));
16778							if (isset($brd_widths[3])) {
16779								$dom[$key]['border']['L']['width'] = $this->getCSSBorderWidth($brd_widths[3]);
16780							}
16781							if (isset($brd_widths[1])) {
16782								$dom[$key]['border']['R']['width'] = $this->getCSSBorderWidth($brd_widths[1]);
16783							}
16784							if (isset($brd_widths[0])) {
16785								$dom[$key]['border']['T']['width'] = $this->getCSSBorderWidth($brd_widths[0]);
16786							}
16787							if (isset($brd_widths[2])) {
16788								$dom[$key]['border']['B']['width'] = $this->getCSSBorderWidth($brd_widths[2]);
16789							}
16790						}
16791						if (isset($dom[$key]['style']['border-style'])) {
16792							$brd_styles = preg_split('/[\s]+/', trim($dom[$key]['style']['border-style']));
16793							if (isset($brd_styles[3]) AND ($brd_styles[3]!='none')) {
16794								$dom[$key]['border']['L']['cap'] = 'square';
16795								$dom[$key]['border']['L']['join'] = 'miter';
16796								$dom[$key]['border']['L']['dash'] = $this->getCSSBorderDashStyle($brd_styles[3]);
16797								if ($dom[$key]['border']['L']['dash'] < 0) {
16798									$dom[$key]['border']['L'] = array();
16799								}
16800							}
16801							if (isset($brd_styles[1])) {
16802								$dom[$key]['border']['R']['cap'] = 'square';
16803								$dom[$key]['border']['R']['join'] = 'miter';
16804								$dom[$key]['border']['R']['dash'] = $this->getCSSBorderDashStyle($brd_styles[1]);
16805								if ($dom[$key]['border']['R']['dash'] < 0) {
16806									$dom[$key]['border']['R'] = array();
16807								}
16808							}
16809							if (isset($brd_styles[0])) {
16810								$dom[$key]['border']['T']['cap'] = 'square';
16811								$dom[$key]['border']['T']['join'] = 'miter';
16812								$dom[$key]['border']['T']['dash'] = $this->getCSSBorderDashStyle($brd_styles[0]);
16813								if ($dom[$key]['border']['T']['dash'] < 0) {
16814									$dom[$key]['border']['T'] = array();
16815								}
16816							}
16817							if (isset($brd_styles[2])) {
16818								$dom[$key]['border']['B']['cap'] = 'square';
16819								$dom[$key]['border']['B']['join'] = 'miter';
16820								$dom[$key]['border']['B']['dash'] = $this->getCSSBorderDashStyle($brd_styles[2]);
16821								if ($dom[$key]['border']['B']['dash'] < 0) {
16822									$dom[$key]['border']['B'] = array();
16823								}
16824							}
16825						}
16826						$cellside = array('L' => 'left', 'R' => 'right', 'T' => 'top', 'B' => 'bottom');
16827						foreach ($cellside as $bsk => $bsv) {
16828							if (isset($dom[$key]['style']['border-'.$bsv])) {
16829								$borderstyle = $this->getCSSBorderStyle($dom[$key]['style']['border-'.$bsv]);
16830								if (!empty($borderstyle)) {
16831									$dom[$key]['border'][$bsk] = $borderstyle;
16832								}
16833							}
16834							if (isset($dom[$key]['style']['border-'.$bsv.'-color'])) {
16835								$dom[$key]['border'][$bsk]['color'] = TCPDF_COLORS::convertHTMLColorToDec($dom[$key]['style']['border-'.$bsv.'-color'], $this->spot_colors);
16836							}
16837							if (isset($dom[$key]['style']['border-'.$bsv.'-width'])) {
16838								$dom[$key]['border'][$bsk]['width'] = $this->getCSSBorderWidth($dom[$key]['style']['border-'.$bsv.'-width']);
16839							}
16840							if (isset($dom[$key]['style']['border-'.$bsv.'-style'])) {
16841								$dom[$key]['border'][$bsk]['dash'] = $this->getCSSBorderDashStyle($dom[$key]['style']['border-'.$bsv.'-style']);
16842								if ($dom[$key]['border'][$bsk]['dash'] < 0) {
16843									$dom[$key]['border'][$bsk] = array();
16844								}
16845							}
16846						}
16847						// check for CSS padding properties
16848						if (isset($dom[$key]['style']['padding'])) {
16849							$dom[$key]['padding'] = $this->getCSSPadding($dom[$key]['style']['padding']);
16850						} else {
16851							$dom[$key]['padding'] = $this->cell_padding;
16852						}
16853						foreach ($cellside as $psk => $psv) {
16854							if (isset($dom[$key]['style']['padding-'.$psv])) {
16855								$dom[$key]['padding'][$psk] = $this->getHTMLUnitToUnits($dom[$key]['style']['padding-'.$psv], 0, 'px', false);
16856							}
16857						}
16858						// check for CSS margin properties
16859						if (isset($dom[$key]['style']['margin'])) {
16860							$dom[$key]['margin'] = $this->getCSSMargin($dom[$key]['style']['margin']);
16861						} else {
16862							$dom[$key]['margin'] = $this->cell_margin;
16863						}
16864						foreach ($cellside as $psk => $psv) {
16865							if (isset($dom[$key]['style']['margin-'.$psv])) {
16866								$dom[$key]['margin'][$psk] = $this->getHTMLUnitToUnits(str_replace('auto', '0', $dom[$key]['style']['margin-'.$psv]), 0, 'px', false);
16867							}
16868						}
16869						// check for CSS border-spacing properties
16870						if (isset($dom[$key]['style']['border-spacing'])) {
16871							$dom[$key]['border-spacing'] = $this->getCSSBorderMargin($dom[$key]['style']['border-spacing']);
16872						}
16873						// page-break-inside
16874						if (isset($dom[$key]['style']['page-break-inside']) AND ($dom[$key]['style']['page-break-inside'] == 'avoid')) {
16875							$dom[$key]['attribute']['nobr'] = 'true';
16876						}
16877						// page-break-before
16878						if (isset($dom[$key]['style']['page-break-before'])) {
16879							if ($dom[$key]['style']['page-break-before'] == 'always') {
16880								$dom[$key]['attribute']['pagebreak'] = 'true';
16881							} elseif ($dom[$key]['style']['page-break-before'] == 'left') {
16882								$dom[$key]['attribute']['pagebreak'] = 'left';
16883							} elseif ($dom[$key]['style']['page-break-before'] == 'right') {
16884								$dom[$key]['attribute']['pagebreak'] = 'right';
16885							}
16886						}
16887						// page-break-after
16888						if (isset($dom[$key]['style']['page-break-after'])) {
16889							if ($dom[$key]['style']['page-break-after'] == 'always') {
16890								$dom[$key]['attribute']['pagebreakafter'] = 'true';
16891							} elseif ($dom[$key]['style']['page-break-after'] == 'left') {
16892								$dom[$key]['attribute']['pagebreakafter'] = 'left';
16893							} elseif ($dom[$key]['style']['page-break-after'] == 'right') {
16894								$dom[$key]['attribute']['pagebreakafter'] = 'right';
16895							}
16896						}
16897					}
16898					if (isset($dom[$key]['attribute']['display'])) {
16899						$dom[$key]['hide'] = (trim(strtolower($dom[$key]['attribute']['display'])) == 'none');
16900					}
16901					if (isset($dom[$key]['attribute']['border']) AND ($dom[$key]['attribute']['border'] != 0)) {
16902						$borderstyle = $this->getCSSBorderStyle($dom[$key]['attribute']['border'].' solid black');
16903						if (!empty($borderstyle)) {
16904							$dom[$key]['border']['LTRB'] = $borderstyle;
16905						}
16906					}
16907					// check for font tag
16908					if ($dom[$key]['value'] == 'font') {
16909						// font family
16910						if (isset($dom[$key]['attribute']['face'])) {
16911							$dom[$key]['fontname'] = $this->getFontFamilyName($dom[$key]['attribute']['face']);
16912						}
16913						// font size
16914						if (isset($dom[$key]['attribute']['size'])) {
16915							if ($key > 0) {
16916								if ($dom[$key]['attribute']['size'][0] == '+') {
16917									$dom[$key]['fontsize'] = $dom[($dom[$key]['parent'])]['fontsize'] + intval(substr($dom[$key]['attribute']['size'], 1));
16918								} elseif ($dom[$key]['attribute']['size'][0] == '-') {
16919									$dom[$key]['fontsize'] = $dom[($dom[$key]['parent'])]['fontsize'] - intval(substr($dom[$key]['attribute']['size'], 1));
16920								} else {
16921									$dom[$key]['fontsize'] = intval($dom[$key]['attribute']['size']);
16922								}
16923							} else {
16924								$dom[$key]['fontsize'] = intval($dom[$key]['attribute']['size']);
16925							}
16926						}
16927					}
16928					// force natural alignment for lists
16929					if ((($dom[$key]['value'] == 'ul') OR ($dom[$key]['value'] == 'ol') OR ($dom[$key]['value'] == 'dl'))
16930						AND (!isset($dom[$key]['align']) OR TCPDF_STATIC::empty_string($dom[$key]['align']) OR ($dom[$key]['align'] != 'J'))) {
16931						if ($this->rtl) {
16932							$dom[$key]['align'] = 'R';
16933						} else {
16934							$dom[$key]['align'] = 'L';
16935						}
16936					}
16937					if (($dom[$key]['value'] == 'small') OR ($dom[$key]['value'] == 'sup') OR ($dom[$key]['value'] == 'sub')) {
16938						if (!isset($dom[$key]['attribute']['size']) AND !isset($dom[$key]['style']['font-size'])) {
16939							$dom[$key]['fontsize'] = $dom[$key]['fontsize'] * K_SMALL_RATIO;
16940						}
16941					}
16942					if (($dom[$key]['value'] == 'strong') OR ($dom[$key]['value'] == 'b')) {
16943						$dom[$key]['fontstyle'] .= 'B';
16944					}
16945					if (($dom[$key]['value'] == 'em') OR ($dom[$key]['value'] == 'i')) {
16946						$dom[$key]['fontstyle'] .= 'I';
16947					}
16948					if ($dom[$key]['value'] == 'u') {
16949						$dom[$key]['fontstyle'] .= 'U';
16950					}
16951					if (($dom[$key]['value'] == 'del') OR ($dom[$key]['value'] == 's') OR ($dom[$key]['value'] == 'strike')) {
16952						$dom[$key]['fontstyle'] .= 'D';
16953					}
16954					if (!isset($dom[$key]['style']['text-decoration']) AND ($dom[$key]['value'] == 'a')) {
16955						$dom[$key]['fontstyle'] = $this->htmlLinkFontStyle;
16956					}
16957					if (($dom[$key]['value'] == 'pre') OR ($dom[$key]['value'] == 'tt')) {
16958						$dom[$key]['fontname'] = $this->default_monospaced_font;
16959					}
16960					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)) {
16961						// headings h1, h2, h3, h4, h5, h6
16962						if (!isset($dom[$key]['attribute']['size']) AND !isset($dom[$key]['style']['font-size'])) {
16963							$headsize = (4 - intval($dom[$key]['value'][1])) * 2;
16964							$dom[$key]['fontsize'] = $dom[0]['fontsize'] + $headsize;
16965						}
16966						if (!isset($dom[$key]['style']['font-weight'])) {
16967							$dom[$key]['fontstyle'] .= 'B';
16968						}
16969					}
16970					if (($dom[$key]['value'] == 'table')) {
16971						$dom[$key]['rows'] = 0; // number of rows
16972						$dom[$key]['trids'] = array(); // IDs of TR elements
16973						$dom[$key]['thead'] = ''; // table header rows
16974					}
16975					if (($dom[$key]['value'] == 'tr')) {
16976						$dom[$key]['cols'] = 0;
16977						if ($thead) {
16978							$dom[$key]['thead'] = true;
16979							// rows on thead block are printed as a separate table
16980						} else {
16981							$dom[$key]['thead'] = false;
16982							// store the number of rows on table element
16983							++$dom[($dom[$key]['parent'])]['rows'];
16984							// store the TR elements IDs on table element
16985							array_push($dom[($dom[$key]['parent'])]['trids'], $key);
16986						}
16987					}
16988					if (($dom[$key]['value'] == 'th') OR ($dom[$key]['value'] == 'td')) {
16989						if (isset($dom[$key]['attribute']['colspan'])) {
16990							$colspan = intval($dom[$key]['attribute']['colspan']);
16991						} else {
16992							$colspan = 1;
16993						}
16994						$dom[$key]['attribute']['colspan'] = $colspan;
16995						$dom[($dom[$key]['parent'])]['cols'] += $colspan;
16996					}
16997					// text direction
16998					if (isset($dom[$key]['attribute']['dir'])) {
16999						$dom[$key]['dir'] = $dom[$key]['attribute']['dir'];
17000					}
17001					// set foreground color attribute
17002					if (isset($dom[$key]['attribute']['color']) AND (!TCPDF_STATIC::empty_string($dom[$key]['attribute']['color']))) {
17003						$dom[$key]['fgcolor'] = TCPDF_COLORS::convertHTMLColorToDec($dom[$key]['attribute']['color'], $this->spot_colors);
17004					} elseif (!isset($dom[$key]['style']['color']) AND ($dom[$key]['value'] == 'a')) {
17005						$dom[$key]['fgcolor'] = $this->htmlLinkColorArray;
17006					}
17007					// set background color attribute
17008					if (isset($dom[$key]['attribute']['bgcolor']) AND (!TCPDF_STATIC::empty_string($dom[$key]['attribute']['bgcolor']))) {
17009						$dom[$key]['bgcolor'] = TCPDF_COLORS::convertHTMLColorToDec($dom[$key]['attribute']['bgcolor'], $this->spot_colors);
17010					}
17011					// set stroke color attribute
17012					if (isset($dom[$key]['attribute']['strokecolor']) AND (!TCPDF_STATIC::empty_string($dom[$key]['attribute']['strokecolor']))) {
17013						$dom[$key]['strokecolor'] = TCPDF_COLORS::convertHTMLColorToDec($dom[$key]['attribute']['strokecolor'], $this->spot_colors);
17014					}
17015					// check for width attribute
17016					if (isset($dom[$key]['attribute']['width'])) {
17017						$dom[$key]['width'] = $dom[$key]['attribute']['width'];
17018					}
17019					// check for height attribute
17020					if (isset($dom[$key]['attribute']['height'])) {
17021						$dom[$key]['height'] = $dom[$key]['attribute']['height'];
17022					}
17023					// check for text alignment
17024					if (isset($dom[$key]['attribute']['align']) AND (!TCPDF_STATIC::empty_string($dom[$key]['attribute']['align'])) AND ($dom[$key]['value'] !== 'img')) {
17025						$dom[$key]['align'] = strtoupper($dom[$key]['attribute']['align'][0]);
17026					}
17027					// check for text rendering mode (the following attributes do not exist in HTML)
17028					if (isset($dom[$key]['attribute']['stroke'])) {
17029						// font stroke width
17030						$dom[$key]['stroke'] = $this->getHTMLUnitToUnits($dom[$key]['attribute']['stroke'], $dom[$key]['fontsize'], 'pt', true);
17031					}
17032					if (isset($dom[$key]['attribute']['fill'])) {
17033						// font fill
17034						if ($dom[$key]['attribute']['fill'] == 'true') {
17035							$dom[$key]['fill'] = true;
17036						} else {
17037							$dom[$key]['fill'] = false;
17038						}
17039					}
17040					if (isset($dom[$key]['attribute']['clip'])) {
17041						// clipping mode
17042						if ($dom[$key]['attribute']['clip'] == 'true') {
17043							$dom[$key]['clip'] = true;
17044						} else {
17045							$dom[$key]['clip'] = false;
17046						}
17047					}
17048				} // end opening tag
17049			} else {
17050				// text
17051				$dom[$key]['tag'] = false;
17052				$dom[$key]['block'] = false;
17053				$dom[$key]['parent'] = end($level);
17054				$dom[$key]['dir'] = $dom[$dom[$key]['parent']]['dir'];
17055				if (!empty($dom[$dom[$key]['parent']]['text-transform'])) {
17056					// text-transform for unicode requires mb_convert_case (Multibyte String Functions)
17057					if (function_exists('mb_convert_case')) {
17058						$ttm = array('capitalize' => MB_CASE_TITLE, 'uppercase' => MB_CASE_UPPER, 'lowercase' => MB_CASE_LOWER);
17059						if (isset($ttm[$dom[$dom[$key]['parent']]['text-transform']])) {
17060							$element = mb_convert_case($element, $ttm[$dom[$dom[$key]['parent']]['text-transform']], $this->encoding);
17061						}
17062					} elseif (!$this->isunicode) {
17063						switch ($dom[$dom[$key]['parent']]['text-transform']) {
17064							case 'capitalize': {
17065								$element = ucwords(strtolower($element));
17066								break;
17067							}
17068							case 'uppercase': {
17069								$element = strtoupper($element);
17070								break;
17071							}
17072							case 'lowercase': {
17073								$element = strtolower($element);
17074								break;
17075							}
17076						}
17077					}
17078				}
17079				$dom[$key]['value'] = stripslashes($this->unhtmlentities($element));
17080			}
17081			++$elkey;
17082			++$key;
17083		}
17084		return $dom;
17085	}
17086
17087	/**
17088	 * Returns the string used to find spaces
17089	 * @return string
17090	 * @protected
17091	 * @author Nicola Asuni
17092	 * @since 4.8.024 (2010-01-15)
17093	 */
17094	protected function getSpaceString() {
17095		$spacestr = chr(32);
17096		if ($this->isUnicodeFont()) {
17097			$spacestr = chr(0).chr(32);
17098		}
17099		return $spacestr;
17100	}
17101
17102	/**
17103	 * Return an hash code used to ensure that the serialized data has been generated by this TCPDF instance.
17104	 * @param $data (string) serialized data
17105	 * @return string
17106	 * @public static
17107	 */
17108	protected function getHashForTCPDFtagParams($data) {
17109		return md5(strlen($data).$this->file_id.$data);
17110	}
17111
17112	/**
17113	 * Serialize an array of parameters to be used with TCPDF tag in HTML code.
17114	 * @param $data (array) parameters array
17115	 * @return string containing serialized data
17116	 * @public static
17117	 */
17118	public function serializeTCPDFtagParameters($data) {
17119		$encoded = urlencode(json_encode($data));
17120		return $this->getHashForTCPDFtagParams($encoded).$encoded;
17121	}
17122
17123	/**
17124	 * Unserialize parameters to be used with TCPDF tag in HTML code.
17125	 * @param $data (string) serialized data
17126	 * @return array containing unserialized data
17127	 * @protected static
17128	 */
17129	protected function unserializeTCPDFtagParameters($data) {
17130		$hash = substr($data, 0, 32);
17131		$encoded = substr($data, 32);
17132		if ($hash != $this->getHashForTCPDFtagParams($encoded)) {
17133			$this->Error('Invalid parameters');
17134		}
17135		return json_decode(urldecode($encoded), true);
17136	}
17137
17138	/**
17139	 * Prints a cell (rectangular area) with optional borders, background color and html text string.
17140	 * 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 />
17141	 * If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting.
17142	 * IMPORTANT: The HTML must be well formatted - try to clean-up it using an application like HTML-Tidy before submitting.
17143	 * 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
17144	 * NOTE: all the HTML attributes must be enclosed in double-quote.
17145	 * @param $w (float) Cell width. If 0, the cell extends up to the right margin.
17146	 * @param $h (float) Cell minimum height. The cell extends automatically if needed.
17147	 * @param $x (float) upper-left corner X coordinate
17148	 * @param $y (float) upper-left corner Y coordinate
17149	 * @param $html (string) html text to print. Default value: empty string.
17150	 * @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)))
17151	 * @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>
17152Putting 1 is equivalent to putting 0 and calling Ln() just after. Default value: 0.
17153	 * @param $fill (boolean) Indicates if the cell background must be painted (true) or transparent (false).
17154	 * @param $reseth (boolean) if true reset the last cell height (default true).
17155	 * @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>
17156	 * @param $autopadding (boolean) if true, uses internal padding and automatically adjust it to account for line width.
17157	 * @see Multicell(), writeHTML()
17158	 * @public
17159	 */
17160	public function writeHTMLCell($w, $h, $x, $y, $html='', $border=0, $ln=0, $fill=false, $reseth=true, $align='', $autopadding=true) {
17161		return $this->MultiCell($w, $h, $html, $border, $align, $fill, $ln, $x, $y, $reseth, 0, true, $autopadding, 0, 'T', false);
17162	}
17163
17164	/**
17165	 * Allows to preserve some HTML formatting (limited support).<br />
17166	 * IMPORTANT: The HTML must be well formatted - try to clean-up it using an application like HTML-Tidy before submitting.
17167	 * 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
17168	 * NOTE: all the HTML attributes must be enclosed in double-quote.
17169	 * @param $html (string) text to display
17170	 * @param $ln (boolean) if true add a new line after text (default = true)
17171	 * @param $fill (boolean) Indicates if the background must be painted (true) or transparent (false).
17172	 * @param $reseth (boolean) if true reset the last cell height (default false).
17173	 * @param $cell (boolean) if true add the current left (or right for RTL) padding to each Write (default false).
17174	 * @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>
17175	 * @public
17176	 */
17177	public function writeHTML($html, $ln=true, $fill=false, $reseth=false, $cell=false, $align='') {
17178		$gvars = $this->getGraphicVars();
17179		// store current values
17180		$prev_cell_margin = $this->cell_margin;
17181		$prev_cell_padding = $this->cell_padding;
17182		$prevPage = $this->page;
17183		$prevlMargin = $this->lMargin;
17184		$prevrMargin = $this->rMargin;
17185		$curfontname = $this->FontFamily;
17186		$curfontstyle = $this->FontStyle;
17187		$curfontsize = $this->FontSizePt;
17188		$curfontascent = $this->getFontAscent($curfontname, $curfontstyle, $curfontsize);
17189		$curfontdescent = $this->getFontDescent($curfontname, $curfontstyle, $curfontsize);
17190		$curfontstretcing = $this->font_stretching;
17191		$curfonttracking = $this->font_spacing;
17192		$this->newline = true;
17193		$newline = true;
17194		$startlinepage = $this->page;
17195		$minstartliney = $this->y;
17196		$maxbottomliney = 0;
17197		$startlinex = $this->x;
17198		$startliney = $this->y;
17199		$yshift = 0;
17200		$loop = 0;
17201		$curpos = 0;
17202		$this_method_vars = array();
17203		$undo = false;
17204		$fontaligned = false;
17205		$reverse_dir = false; // true when the text direction is reversed
17206		$this->premode = false;
17207		if ($this->inxobj) {
17208			// we are inside an XObject template
17209			$pask = count($this->xobjects[$this->xobjid]['annotations']);
17210		} elseif (isset($this->PageAnnots[$this->page])) {
17211			$pask = count($this->PageAnnots[$this->page]);
17212		} else {
17213			$pask = 0;
17214		}
17215		if ($this->inxobj) {
17216			// we are inside an XObject template
17217			$startlinepos = strlen($this->xobjects[$this->xobjid]['outdata']);
17218		} elseif (!$this->InFooter) {
17219			if (isset($this->footerlen[$this->page])) {
17220				$this->footerpos[$this->page] = $this->pagelen[$this->page] - $this->footerlen[$this->page];
17221			} else {
17222				$this->footerpos[$this->page] = $this->pagelen[$this->page];
17223			}
17224			$startlinepos = $this->footerpos[$this->page];
17225		} else {
17226			// we are inside the footer
17227			$startlinepos = $this->pagelen[$this->page];
17228		}
17229		$lalign = $align;
17230		$plalign = $align;
17231		if ($this->rtl) {
17232			$w = $this->x - $this->lMargin;
17233		} else {
17234			$w = $this->w - $this->rMargin - $this->x;
17235		}
17236		$w -= ($this->cell_padding['L'] + $this->cell_padding['R']);
17237		if ($cell) {
17238			if ($this->rtl) {
17239				$this->x -= $this->cell_padding['R'];
17240				$this->lMargin += $this->cell_padding['L'];
17241			} else {
17242				$this->x += $this->cell_padding['L'];
17243				$this->rMargin += $this->cell_padding['R'];
17244			}
17245		}
17246		if ($this->customlistindent >= 0) {
17247			$this->listindent = $this->customlistindent;
17248		} else {
17249			$this->listindent = $this->GetStringWidth('000000');
17250		}
17251		$this->listindentlevel = 0;
17252		// save previous states
17253		$prev_cell_height_ratio = $this->cell_height_ratio;
17254		$prev_listnum = $this->listnum;
17255		$prev_listordered = $this->listordered;
17256		$prev_listcount = $this->listcount;
17257		$prev_lispacer = $this->lispacer;
17258		$this->listnum = 0;
17259		$this->listordered = array();
17260		$this->listcount = array();
17261		$this->lispacer = '';
17262		if ((TCPDF_STATIC::empty_string($this->lasth)) OR ($reseth)) {
17263			// reset row height
17264			$this->resetLastH();
17265		}
17266		$dom = $this->getHtmlDomArray($html);
17267		$maxel = count($dom);
17268		$key = 0;
17269		while ($key < $maxel) {
17270			if ($dom[$key]['tag'] AND $dom[$key]['opening'] AND $dom[$key]['hide']) {
17271				// store the node key
17272				$hidden_node_key = $key;
17273				if ($dom[$key]['self']) {
17274					// skip just this self-closing tag
17275					++$key;
17276				} else {
17277					// skip this and all children tags
17278					while (($key < $maxel) AND (!$dom[$key]['tag'] OR $dom[$key]['opening'] OR ($dom[$key]['parent'] != $hidden_node_key))) {
17279						// skip hidden objects
17280						++$key;
17281					}
17282					++$key;
17283				}
17284			}
17285			if ($dom[$key]['tag'] AND isset($dom[$key]['attribute']['pagebreak'])) {
17286				// check for pagebreak
17287				if (($dom[$key]['attribute']['pagebreak'] == 'true') OR ($dom[$key]['attribute']['pagebreak'] == 'left') OR ($dom[$key]['attribute']['pagebreak'] == 'right')) {
17288					// add a page (or trig AcceptPageBreak() for multicolumn mode)
17289					$this->checkPageBreak($this->PageBreakTrigger + 1);
17290					$this->htmlvspace = ($this->PageBreakTrigger + 1);
17291				}
17292				if ((($dom[$key]['attribute']['pagebreak'] == 'left') AND (((!$this->rtl) AND (($this->page % 2) == 0)) OR (($this->rtl) AND (($this->page % 2) != 0))))
17293					OR (($dom[$key]['attribute']['pagebreak'] == 'right') AND (((!$this->rtl) AND (($this->page % 2) != 0)) OR (($this->rtl) AND (($this->page % 2) == 0))))) {
17294					// add a page (or trig AcceptPageBreak() for multicolumn mode)
17295					$this->checkPageBreak($this->PageBreakTrigger + 1);
17296					$this->htmlvspace = ($this->PageBreakTrigger + 1);
17297				}
17298			}
17299			if ($dom[$key]['tag'] AND $dom[$key]['opening'] AND isset($dom[$key]['attribute']['nobr']) AND ($dom[$key]['attribute']['nobr'] == 'true')) {
17300				if (isset($dom[($dom[$key]['parent'])]['attribute']['nobr']) AND ($dom[($dom[$key]['parent'])]['attribute']['nobr'] == 'true')) {
17301					$dom[$key]['attribute']['nobr'] = false;
17302				} else {
17303					// store current object
17304					$this->startTransaction();
17305					// save this method vars
17306					$this_method_vars['html'] = $html;
17307					$this_method_vars['ln'] = $ln;
17308					$this_method_vars['fill'] = $fill;
17309					$this_method_vars['reseth'] = $reseth;
17310					$this_method_vars['cell'] = $cell;
17311					$this_method_vars['align'] = $align;
17312					$this_method_vars['gvars'] = $gvars;
17313					$this_method_vars['prevPage'] = $prevPage;
17314					$this_method_vars['prev_cell_margin'] = $prev_cell_margin;
17315					$this_method_vars['prev_cell_padding'] = $prev_cell_padding;
17316					$this_method_vars['prevlMargin'] = $prevlMargin;
17317					$this_method_vars['prevrMargin'] = $prevrMargin;
17318					$this_method_vars['curfontname'] = $curfontname;
17319					$this_method_vars['curfontstyle'] = $curfontstyle;
17320					$this_method_vars['curfontsize'] = $curfontsize;
17321					$this_method_vars['curfontascent'] = $curfontascent;
17322					$this_method_vars['curfontdescent'] = $curfontdescent;
17323					$this_method_vars['curfontstretcing'] = $curfontstretcing;
17324					$this_method_vars['curfonttracking'] = $curfonttracking;
17325					$this_method_vars['minstartliney'] = $minstartliney;
17326					$this_method_vars['maxbottomliney'] = $maxbottomliney;
17327					$this_method_vars['yshift'] = $yshift;
17328					$this_method_vars['startlinepage'] = $startlinepage;
17329					$this_method_vars['startlinepos'] = $startlinepos;
17330					$this_method_vars['startlinex'] = $startlinex;
17331					$this_method_vars['startliney'] = $startliney;
17332					$this_method_vars['newline'] = $newline;
17333					$this_method_vars['loop'] = $loop;
17334					$this_method_vars['curpos'] = $curpos;
17335					$this_method_vars['pask'] = $pask;
17336					$this_method_vars['lalign'] = $lalign;
17337					$this_method_vars['plalign'] = $plalign;
17338					$this_method_vars['w'] = $w;
17339					$this_method_vars['prev_cell_height_ratio'] = $prev_cell_height_ratio;
17340					$this_method_vars['prev_listnum'] = $prev_listnum;
17341					$this_method_vars['prev_listordered'] = $prev_listordered;
17342					$this_method_vars['prev_listcount'] = $prev_listcount;
17343					$this_method_vars['prev_lispacer'] = $prev_lispacer;
17344					$this_method_vars['fontaligned'] = $fontaligned;
17345					$this_method_vars['key'] = $key;
17346					$this_method_vars['dom'] = $dom;
17347				}
17348			}
17349			// print THEAD block
17350			if (($dom[$key]['value'] == 'tr') AND isset($dom[$key]['thead']) AND $dom[$key]['thead']) {
17351				if (isset($dom[$key]['parent']) AND isset($dom[$dom[$key]['parent']]['thead']) AND !TCPDF_STATIC::empty_string($dom[$dom[$key]['parent']]['thead'])) {
17352					$this->inthead = true;
17353					// print table header (thead)
17354					$this->writeHTML($this->thead, false, false, false, false, '');
17355					// check if we are on a new page or on a new column
17356					if (($this->y < $this->start_transaction_y) OR ($this->checkPageBreak($this->lasth, '', false))) {
17357						// we are on a new page or on a new column and the total object height is less than the available vertical space.
17358						// restore previous object
17359						$this->rollbackTransaction(true);
17360						// restore previous values
17361						foreach ($this_method_vars as $vkey => $vval) {
17362							$$vkey = $vval;
17363						}
17364						// disable table header
17365						$tmp_thead = $this->thead;
17366						$this->thead = '';
17367						// add a page (or trig AcceptPageBreak() for multicolumn mode)
17368						$pre_y = $this->y;
17369						if ((!$this->checkPageBreak($this->PageBreakTrigger + 1)) AND ($this->y < $pre_y)) {
17370							// fix for multicolumn mode
17371							$startliney = $this->y;
17372						}
17373						$this->start_transaction_page = $this->page;
17374						$this->start_transaction_y = $this->y;
17375						// restore table header
17376						$this->thead = $tmp_thead;
17377						// fix table border properties
17378						if (isset($dom[$dom[$key]['parent']]['attribute']['cellspacing'])) {
17379							$tmp_cellspacing = $this->getHTMLUnitToUnits($dom[$dom[$key]['parent']]['attribute']['cellspacing'], 1, 'px');
17380						} elseif (isset($dom[$dom[$key]['parent']]['border-spacing'])) {
17381							$tmp_cellspacing = $dom[$dom[$key]['parent']]['border-spacing']['V'];
17382						} else {
17383							$tmp_cellspacing = 0;
17384						}
17385						$dom[$dom[$key]['parent']]['borderposition']['page'] = $this->page;
17386						$dom[$dom[$key]['parent']]['borderposition']['column'] = $this->current_column;
17387						$dom[$dom[$key]['parent']]['borderposition']['y'] = $this->y + $tmp_cellspacing;
17388						$xoffset = ($this->x - $dom[$dom[$key]['parent']]['borderposition']['x']);
17389						$dom[$dom[$key]['parent']]['borderposition']['x'] += $xoffset;
17390						$dom[$dom[$key]['parent']]['borderposition']['xmax'] += $xoffset;
17391						// print table header (thead)
17392						$this->writeHTML($this->thead, false, false, false, false, '');
17393					}
17394				}
17395				// move $key index forward to skip THEAD block
17396				while ( ($key < $maxel) AND (!(
17397					($dom[$key]['tag'] AND $dom[$key]['opening'] AND ($dom[$key]['value'] == 'tr') AND (!isset($dom[$key]['thead']) OR !$dom[$key]['thead']))
17398					OR ($dom[$key]['tag'] AND (!$dom[$key]['opening']) AND ($dom[$key]['value'] == 'table'))) )) {
17399					++$key;
17400				}
17401			}
17402			if ($dom[$key]['tag'] OR ($key == 0)) {
17403				if ((($dom[$key]['value'] == 'table') OR ($dom[$key]['value'] == 'tr')) AND (isset($dom[$key]['align']))) {
17404					$dom[$key]['align'] = ($this->rtl) ? 'R' : 'L';
17405				}
17406				// vertically align image in line
17407				if ((!$this->newline) AND ($dom[$key]['value'] == 'img') AND (isset($dom[$key]['height'])) AND ($dom[$key]['height'] > 0)) {
17408					// get image height
17409					$imgh = $this->getHTMLUnitToUnits($dom[$key]['height'], ($dom[$key]['fontsize'] / $this->k), 'px');
17410					$autolinebreak = false;
17411					if (!empty($dom[$key]['width'])) {
17412						$imgw = $this->getHTMLUnitToUnits($dom[$key]['width'], ($dom[$key]['fontsize'] / $this->k), 'px', false);
17413						if (($imgw <= ($this->w - $this->lMargin - $this->rMargin - $this->cell_padding['L'] - $this->cell_padding['R']))
17414							AND ((($this->rtl) AND (($this->x - $imgw) < ($this->lMargin + $this->cell_padding['L'])))
17415							OR ((!$this->rtl) AND (($this->x + $imgw) > ($this->w - $this->rMargin - $this->cell_padding['R']))))) {
17416							// add automatic line break
17417							$autolinebreak = true;
17418							$this->Ln('', $cell);
17419							if ((!$dom[($key-1)]['tag']) AND ($dom[($key-1)]['value'] == ' ')) {
17420								// go back to evaluate this line break
17421								--$key;
17422							}
17423						}
17424					}
17425					if (!$autolinebreak) {
17426						if ($this->inPageBody()) {
17427							$pre_y = $this->y;
17428							// check for page break
17429							if ((!$this->checkPageBreak($imgh)) AND ($this->y < $pre_y)) {
17430								// fix for multicolumn mode
17431								$startliney = $this->y;
17432							}
17433						}
17434						if ($this->page > $startlinepage) {
17435							// fix line splitted over two pages
17436							if (isset($this->footerlen[$startlinepage])) {
17437								$curpos = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
17438							}
17439							// line to be moved one page forward
17440							$pagebuff = $this->getPageBuffer($startlinepage);
17441							$linebeg = substr($pagebuff, $startlinepos, ($curpos - $startlinepos));
17442							$tstart = substr($pagebuff, 0, $startlinepos);
17443							$tend = substr($this->getPageBuffer($startlinepage), $curpos);
17444							// remove line from previous page
17445							$this->setPageBuffer($startlinepage, $tstart.''.$tend);
17446							$pagebuff = $this->getPageBuffer($this->page);
17447							$tstart = substr($pagebuff, 0, $this->cntmrk[$this->page]);
17448							$tend = substr($pagebuff, $this->cntmrk[$this->page]);
17449							// add line start to current page
17450							$yshift = ($minstartliney - $this->y);
17451							if ($fontaligned) {
17452								$yshift += ($curfontsize / $this->k);
17453							}
17454							$try = sprintf('1 0 0 1 0 %F cm', ($yshift * $this->k));
17455							$this->setPageBuffer($this->page, $tstart."\nq\n".$try."\n".$linebeg."\nQ\n".$tend);
17456							// shift the annotations and links
17457							if (isset($this->PageAnnots[$this->page])) {
17458								$next_pask = count($this->PageAnnots[$this->page]);
17459							} else {
17460								$next_pask = 0;
17461							}
17462							if (isset($this->PageAnnots[$startlinepage])) {
17463								foreach ($this->PageAnnots[$startlinepage] as $pak => $pac) {
17464									if ($pak >= $pask) {
17465										$this->PageAnnots[$this->page][] = $pac;
17466										unset($this->PageAnnots[$startlinepage][$pak]);
17467										$npak = count($this->PageAnnots[$this->page]) - 1;
17468										$this->PageAnnots[$this->page][$npak]['y'] -= $yshift;
17469									}
17470								}
17471							}
17472							$pask = $next_pask;
17473							$startlinepos = $this->cntmrk[$this->page];
17474							$startlinepage = $this->page;
17475							$startliney = $this->y;
17476							$this->newline = false;
17477						}
17478						$this->y += ($this->getCellHeight($curfontsize / $this->k) - ($curfontdescent * $this->cell_height_ratio) - $imgh);
17479						$minstartliney = min($this->y, $minstartliney);
17480						$maxbottomliney = ($startliney + $this->getCellHeight($curfontsize / $this->k));
17481					}
17482				} elseif (isset($dom[$key]['fontname']) OR isset($dom[$key]['fontstyle']) OR isset($dom[$key]['fontsize']) OR isset($dom[$key]['line-height'])) {
17483					// account for different font size
17484					$pfontname = $curfontname;
17485					$pfontstyle = $curfontstyle;
17486					$pfontsize = $curfontsize;
17487					$fontname = (isset($dom[$key]['fontname']) ? $dom[$key]['fontname'] : $curfontname);
17488					$fontstyle = (isset($dom[$key]['fontstyle']) ? $dom[$key]['fontstyle'] : $curfontstyle);
17489					$fontsize = (isset($dom[$key]['fontsize']) ? $dom[$key]['fontsize'] : $curfontsize);
17490					$fontascent = $this->getFontAscent($fontname, $fontstyle, $fontsize);
17491					$fontdescent = $this->getFontDescent($fontname, $fontstyle, $fontsize);
17492					if (($fontname != $curfontname) OR ($fontstyle != $curfontstyle) OR ($fontsize != $curfontsize)
17493						OR ($this->cell_height_ratio != $dom[$key]['line-height'])
17494						OR ($dom[$key]['tag'] AND $dom[$key]['opening'] AND ($dom[$key]['value'] == 'li')) ) {
17495						if (($key < ($maxel - 1)) AND (
17496								($dom[$key]['tag'] AND $dom[$key]['opening'] AND ($dom[$key]['value'] == 'li'))
17497								OR ($this->cell_height_ratio != $dom[$key]['line-height'])
17498								OR (!$this->newline AND is_numeric($fontsize) AND is_numeric($curfontsize)
17499								AND ($fontsize >= 0) AND ($curfontsize >= 0)
17500								AND (($fontsize != $curfontsize) OR ($fontstyle != $curfontstyle) OR ($fontname != $curfontname)))
17501							)) {
17502							if ($this->page > $startlinepage) {
17503								// fix lines splitted over two pages
17504								if (isset($this->footerlen[$startlinepage])) {
17505									$curpos = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
17506								}
17507								// line to be moved one page forward
17508								$pagebuff = $this->getPageBuffer($startlinepage);
17509								$linebeg = substr($pagebuff, $startlinepos, ($curpos - $startlinepos));
17510								$tstart = substr($pagebuff, 0, $startlinepos);
17511								$tend = substr($this->getPageBuffer($startlinepage), $curpos);
17512								// remove line start from previous page
17513								$this->setPageBuffer($startlinepage, $tstart.''.$tend);
17514								$pagebuff = $this->getPageBuffer($this->page);
17515								$tstart = substr($pagebuff, 0, $this->cntmrk[$this->page]);
17516								$tend = substr($pagebuff, $this->cntmrk[$this->page]);
17517								// add line start to current page
17518								$yshift = ($minstartliney - $this->y);
17519								$try = sprintf('1 0 0 1 0 %F cm', ($yshift * $this->k));
17520								$this->setPageBuffer($this->page, $tstart."\nq\n".$try."\n".$linebeg."\nQ\n".$tend);
17521								// shift the annotations and links
17522								if (isset($this->PageAnnots[$this->page])) {
17523									$next_pask = count($this->PageAnnots[$this->page]);
17524								} else {
17525									$next_pask = 0;
17526								}
17527								if (isset($this->PageAnnots[$startlinepage])) {
17528									foreach ($this->PageAnnots[$startlinepage] as $pak => $pac) {
17529										if ($pak >= $pask) {
17530											$this->PageAnnots[$this->page][] = $pac;
17531											unset($this->PageAnnots[$startlinepage][$pak]);
17532											$npak = count($this->PageAnnots[$this->page]) - 1;
17533											$this->PageAnnots[$this->page][$npak]['y'] -= $yshift;
17534										}
17535									}
17536								}
17537								$pask = $next_pask;
17538								$startlinepos = $this->cntmrk[$this->page];
17539								$startlinepage = $this->page;
17540								$startliney = $this->y;
17541							}
17542							if (!isset($dom[$key]['line-height'])) {
17543								$dom[$key]['line-height'] = $this->cell_height_ratio;
17544							}
17545							if (!$dom[$key]['block']) {
17546								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']))) {
17547									$this->y += (((($curfontsize * $this->cell_height_ratio) - ($fontsize * $dom[$key]['line-height'])) / $this->k) + $curfontascent - $fontascent - $curfontdescent + $fontdescent) / 2;
17548								}
17549								if (($dom[$key]['value'] != 'sup') AND ($dom[$key]['value'] != 'sub')) {
17550									$current_line_align_data = array($key, $minstartliney, $maxbottomliney);
17551									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)))) {
17552										$minstartliney = min($this->y, $line_align_data[1]);
17553										$maxbottomliney = max(($this->y + $this->getCellHeight($fontsize / $this->k)), $line_align_data[2]);
17554									} else {
17555										$minstartliney = min($this->y, $minstartliney);
17556										$maxbottomliney = max(($this->y + $this->getCellHeight($fontsize / $this->k)), $maxbottomliney);
17557									}
17558									$line_align_data = $current_line_align_data;
17559								}
17560							}
17561							$this->cell_height_ratio = $dom[$key]['line-height'];
17562							$fontaligned = true;
17563						}
17564						$this->SetFont($fontname, $fontstyle, $fontsize);
17565						// reset row height
17566						$this->resetLastH();
17567						$curfontname = $fontname;
17568						$curfontstyle = $fontstyle;
17569						$curfontsize = $fontsize;
17570						$curfontascent = $fontascent;
17571						$curfontdescent = $fontdescent;
17572					}
17573				}
17574				// set text rendering mode
17575				$textstroke = isset($dom[$key]['stroke']) ? $dom[$key]['stroke'] : $this->textstrokewidth;
17576				$textfill = isset($dom[$key]['fill']) ? $dom[$key]['fill'] : (($this->textrendermode % 2) == 0);
17577				$textclip = isset($dom[$key]['clip']) ? $dom[$key]['clip'] : ($this->textrendermode > 3);
17578				$this->setTextRenderingMode($textstroke, $textfill, $textclip);
17579				if (isset($dom[$key]['font-stretch']) AND ($dom[$key]['font-stretch'] !== false)) {
17580					$this->setFontStretching($dom[$key]['font-stretch']);
17581				}
17582				if (isset($dom[$key]['letter-spacing']) AND ($dom[$key]['letter-spacing'] !== false)) {
17583					$this->setFontSpacing($dom[$key]['letter-spacing']);
17584				}
17585				if (($plalign == 'J') AND $dom[$key]['block']) {
17586					$plalign = '';
17587				}
17588				// get current position on page buffer
17589				$curpos = $this->pagelen[$startlinepage];
17590				if (isset($dom[$key]['bgcolor']) AND ($dom[$key]['bgcolor'] !== false)) {
17591					$this->SetFillColorArray($dom[$key]['bgcolor']);
17592					$wfill = true;
17593				} else {
17594					$wfill = $fill | false;
17595				}
17596				if (isset($dom[$key]['fgcolor']) AND ($dom[$key]['fgcolor'] !== false)) {
17597					$this->SetTextColorArray($dom[$key]['fgcolor']);
17598				}
17599				if (isset($dom[$key]['strokecolor']) AND ($dom[$key]['strokecolor'] !== false)) {
17600					$this->SetDrawColorArray($dom[$key]['strokecolor']);
17601				}
17602				if (isset($dom[$key]['align'])) {
17603					$lalign = $dom[$key]['align'];
17604				}
17605				if (TCPDF_STATIC::empty_string($lalign)) {
17606					$lalign = $align;
17607				}
17608			}
17609			// align lines
17610			if ($this->newline AND (strlen($dom[$key]['value']) > 0) AND ($dom[$key]['value'] != 'td') AND ($dom[$key]['value'] != 'th')) {
17611				$newline = true;
17612				$fontaligned = false;
17613				// we are at the beginning of a new line
17614				if (isset($startlinex)) {
17615					$yshift = ($minstartliney - $startliney);
17616					if (($yshift > 0) OR ($this->page > $startlinepage)) {
17617						$yshift = 0;
17618					}
17619					$t_x = 0;
17620					// the last line must be shifted to be aligned as requested
17621					$linew = abs($this->endlinex - $startlinex);
17622					if ($this->inxobj) {
17623						// we are inside an XObject template
17624						$pstart = substr($this->xobjects[$this->xobjid]['outdata'], 0, $startlinepos);
17625						if (isset($opentagpos)) {
17626							$midpos = $opentagpos;
17627						} else {
17628							$midpos = 0;
17629						}
17630						if ($midpos > 0) {
17631							$pmid = substr($this->xobjects[$this->xobjid]['outdata'], $startlinepos, ($midpos - $startlinepos));
17632							$pend = substr($this->xobjects[$this->xobjid]['outdata'], $midpos);
17633						} else {
17634							$pmid = substr($this->xobjects[$this->xobjid]['outdata'], $startlinepos);
17635							$pend = '';
17636						}
17637					} else {
17638						$pstart = substr($this->getPageBuffer($startlinepage), 0, $startlinepos);
17639						if (isset($opentagpos) AND isset($this->footerlen[$startlinepage]) AND (!$this->InFooter)) {
17640							$this->footerpos[$startlinepage] = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
17641							$midpos = min($opentagpos, $this->footerpos[$startlinepage]);
17642						} elseif (isset($opentagpos)) {
17643							$midpos = $opentagpos;
17644						} elseif (isset($this->footerlen[$startlinepage]) AND (!$this->InFooter)) {
17645							$this->footerpos[$startlinepage] = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
17646							$midpos = $this->footerpos[$startlinepage];
17647						} else {
17648							$midpos = 0;
17649						}
17650						if ($midpos > 0) {
17651							$pmid = substr($this->getPageBuffer($startlinepage), $startlinepos, ($midpos - $startlinepos));
17652							$pend = substr($this->getPageBuffer($startlinepage), $midpos);
17653						} else {
17654							$pmid = substr($this->getPageBuffer($startlinepage), $startlinepos);
17655							$pend = '';
17656						}
17657					}
17658					if ((isset($plalign) AND ((($plalign == 'C') OR ($plalign == 'J') OR (($plalign == 'R') AND (!$this->rtl)) OR (($plalign == 'L') AND ($this->rtl)))))) {
17659						// calculate shifting amount
17660						$tw = $w;
17661						if (($plalign == 'J') AND $this->isRTLTextDir() AND ($this->num_columns > 1)) {
17662							$tw += $this->cell_padding['R'];
17663						}
17664						if ($this->lMargin != $prevlMargin) {
17665							$tw += ($prevlMargin - $this->lMargin);
17666						}
17667						if ($this->rMargin != $prevrMargin) {
17668							$tw += ($prevrMargin - $this->rMargin);
17669						}
17670						$one_space_width = $this->GetStringWidth(chr(32));
17671						$no = 0; // number of spaces on a line contained on a single block
17672						if ($this->isRTLTextDir()) { // RTL
17673							// remove left space if exist
17674							$pos1 = TCPDF_STATIC::revstrpos($pmid, '[(');
17675							if ($pos1 > 0) {
17676								$pos1 = intval($pos1);
17677								if ($this->isUnicodeFont()) {
17678									$pos2 = intval(TCPDF_STATIC::revstrpos($pmid, '[('.chr(0).chr(32)));
17679									$spacelen = 2;
17680								} else {
17681									$pos2 = intval(TCPDF_STATIC::revstrpos($pmid, '[('.chr(32)));
17682									$spacelen = 1;
17683								}
17684								if ($pos1 == $pos2) {
17685									$pmid = substr($pmid, 0, ($pos1 + 2)).substr($pmid, ($pos1 + 2 + $spacelen));
17686									if (substr($pmid, $pos1, 4) == '[()]') {
17687										$linew -= $one_space_width;
17688									} elseif ($pos1 == strpos($pmid, '[(')) {
17689										$no = 1;
17690									}
17691								}
17692							}
17693						} else { // LTR
17694							// remove right space if exist
17695							$pos1 = TCPDF_STATIC::revstrpos($pmid, ')]');
17696							if ($pos1 > 0) {
17697								$pos1 = intval($pos1);
17698								if ($this->isUnicodeFont()) {
17699									$pos2 = intval(TCPDF_STATIC::revstrpos($pmid, chr(0).chr(32).')]')) + 2;
17700									$spacelen = 2;
17701								} else {
17702									$pos2 = intval(TCPDF_STATIC::revstrpos($pmid, chr(32).')]')) + 1;
17703									$spacelen = 1;
17704								}
17705								if ($pos1 == $pos2) {
17706									$pmid = substr($pmid, 0, ($pos1 - $spacelen)).substr($pmid, $pos1);
17707									$linew -= $one_space_width;
17708								}
17709							}
17710						}
17711						$mdiff = ($tw - $linew);
17712						if ($plalign == 'C') {
17713							if ($this->rtl) {
17714								$t_x = -($mdiff / 2);
17715							} else {
17716								$t_x = ($mdiff / 2);
17717							}
17718						} elseif ($plalign == 'R') {
17719							// right alignment on LTR document
17720							$t_x = $mdiff;
17721						} elseif ($plalign == 'L') {
17722							// left alignment on RTL document
17723							$t_x = -$mdiff;
17724						} elseif (($plalign == 'J') AND ($plalign == $lalign)) {
17725							// Justification
17726							if ($this->isRTLTextDir()) {
17727								// align text on the left
17728								$t_x = -$mdiff;
17729							}
17730							$ns = 0; // number of spaces
17731							$pmidtemp = $pmid;
17732							// escape special characters
17733							$pmidtemp = preg_replace('/[\\\][\(]/x', '\\#!#OP#!#', $pmidtemp);
17734							$pmidtemp = preg_replace('/[\\\][\)]/x', '\\#!#CP#!#', $pmidtemp);
17735							// search spaces
17736							if (preg_match_all('/\[\(([^\)]*)\)\]/x', $pmidtemp, $lnstring, PREG_PATTERN_ORDER)) {
17737								$spacestr = $this->getSpaceString();
17738								$maxkk = count($lnstring[1]) - 1;
17739								for ($kk=0; $kk <= $maxkk; ++$kk) {
17740									// restore special characters
17741									$lnstring[1][$kk] = str_replace('#!#OP#!#', '(', $lnstring[1][$kk]);
17742									$lnstring[1][$kk] = str_replace('#!#CP#!#', ')', $lnstring[1][$kk]);
17743									// store number of spaces on the strings
17744									$lnstring[2][$kk] = substr_count($lnstring[1][$kk], $spacestr);
17745									// count total spaces on line
17746									$ns += $lnstring[2][$kk];
17747									$lnstring[3][$kk] = $ns;
17748								}
17749								if ($ns == 0) {
17750									$ns = 1;
17751								}
17752								// calculate additional space to add to each existing space
17753								$spacewidth = ($mdiff / ($ns - $no)) * $this->k;
17754								if ($this->FontSize <= 0) {
17755									$this->FontSize = 1;
17756								}
17757								$spacewidthu = -1000 * ($mdiff + (($ns + $no) * $one_space_width)) / $ns / $this->FontSize;
17758								if ($this->font_spacing != 0) {
17759									// fixed spacing mode
17760									$osw = -1000 * $this->font_spacing / $this->FontSize;
17761									$spacewidthu += $osw;
17762								}
17763								$nsmax = $ns;
17764								$ns = 0;
17765								reset($lnstring);
17766								$offset = 0;
17767								$strcount = 0;
17768								$prev_epsposbeg = 0;
17769								$textpos = 0;
17770								if ($this->isRTLTextDir()) {
17771									$textpos = $this->wPt;
17772								}
17773								while (preg_match('/([0-9\.\+\-]*)[\s](Td|cm|m|l|c|re)[\s]/x', $pmid, $strpiece, PREG_OFFSET_CAPTURE, $offset) == 1) {
17774									// check if we are inside a string section '[( ... )]'
17775									$stroffset = strpos($pmid, '[(', $offset);
17776									if (($stroffset !== false) AND ($stroffset <= $strpiece[2][1])) {
17777										// set offset to the end of string section
17778										$offset = strpos($pmid, ')]', $stroffset);
17779										while (($offset !== false) AND ($pmid[($offset - 1)] == '\\')) {
17780											$offset = strpos($pmid, ')]', ($offset + 1));
17781										}
17782										if ($offset === false) {
17783											$this->Error('HTML Justification: malformed PDF code.');
17784										}
17785										continue;
17786									}
17787									if ($this->isRTLTextDir()) {
17788										$spacew = ($spacewidth * ($nsmax - $ns));
17789									} else {
17790										$spacew = ($spacewidth * $ns);
17791									}
17792									$offset = $strpiece[2][1] + strlen($strpiece[2][0]);
17793									$epsposend = strpos($pmid, $this->epsmarker.'Q', $offset);
17794									if ($epsposend !== null) {
17795										$epsposend += strlen($this->epsmarker.'Q');
17796										$epsposbeg = strpos($pmid, 'q'.$this->epsmarker, $offset);
17797										if ($epsposbeg === null) {
17798											$epsposbeg = strpos($pmid, 'q'.$this->epsmarker, ($prev_epsposbeg - 6));
17799											$prev_epsposbeg = $epsposbeg;
17800										}
17801										if (($epsposbeg > 0) AND ($epsposend > 0) AND ($offset > $epsposbeg) AND ($offset < $epsposend)) {
17802											// shift EPS images
17803											$trx = sprintf('1 0 0 1 %F 0 cm', $spacew);
17804											$pmid_b = substr($pmid, 0, $epsposbeg);
17805											$pmid_m = substr($pmid, $epsposbeg, ($epsposend - $epsposbeg));
17806											$pmid_e = substr($pmid, $epsposend);
17807											$pmid = $pmid_b."\nq\n".$trx."\n".$pmid_m."\nQ\n".$pmid_e;
17808											$offset = $epsposend;
17809											continue;
17810										}
17811									}
17812									$currentxpos = 0;
17813									// shift blocks of code
17814									switch ($strpiece[2][0]) {
17815										case 'Td':
17816										case 'cm':
17817										case 'm':
17818										case 'l': {
17819											// get current X position
17820											preg_match('/([0-9\.\+\-]*)[\s]('.$strpiece[1][0].')[\s]('.$strpiece[2][0].')([\s]*)/x', $pmid, $xmatches);
17821											if (!isset($xmatches[1])) {
17822												break;
17823											}
17824											$currentxpos = $xmatches[1];
17825											$textpos = $currentxpos;
17826											if (($strcount <= $maxkk) AND ($strpiece[2][0] == 'Td')) {
17827												$ns = $lnstring[3][$strcount];
17828												if ($this->isRTLTextDir()) {
17829													$spacew = ($spacewidth * ($nsmax - $ns));
17830												}
17831												++$strcount;
17832											}
17833											// justify block
17834											if (preg_match('/([0-9\.\+\-]*)[\s]('.$strpiece[1][0].')[\s]('.$strpiece[2][0].')([\s]*)/x', $pmid, $pmatch) == 1) {
17835												$newpmid = sprintf('%F',(floatval($pmatch[1]) + $spacew)).' '.$pmatch[2].' x*#!#*x'.$pmatch[3].$pmatch[4];
17836												$pmid = str_replace($pmatch[0], $newpmid, $pmid);
17837												unset($pmatch, $newpmid);
17838											}
17839											break;
17840										}
17841										case 're': {
17842											// justify block
17843											if (!TCPDF_STATIC::empty_string($this->lispacer)) {
17844												$this->lispacer = '';
17845												break;
17846											}
17847											preg_match('/([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]('.$strpiece[1][0].')[\s](re)([\s]*)/x', $pmid, $xmatches);
17848											if (!isset($xmatches[1])) {
17849												break;
17850											}
17851											$currentxpos = $xmatches[1];
17852											$x_diff = 0;
17853											$w_diff = 0;
17854											if ($this->isRTLTextDir()) { // RTL
17855												if ($currentxpos < $textpos) {
17856													$x_diff = ($spacewidth * ($nsmax - $lnstring[3][$strcount]));
17857													$w_diff = ($spacewidth * $lnstring[2][$strcount]);
17858												} else {
17859													if ($strcount > 0) {
17860														$x_diff = ($spacewidth * ($nsmax - $lnstring[3][($strcount - 1)]));
17861														$w_diff = ($spacewidth * $lnstring[2][($strcount - 1)]);
17862													}
17863												}
17864											} else { // LTR
17865												if ($currentxpos > $textpos) {
17866													if ($strcount > 0) {
17867														$x_diff = ($spacewidth * $lnstring[3][($strcount - 1)]);
17868													}
17869													$w_diff = ($spacewidth * $lnstring[2][$strcount]);
17870												} else {
17871													if ($strcount > 1) {
17872														$x_diff = ($spacewidth * $lnstring[3][($strcount - 2)]);
17873													}
17874													if ($strcount > 0) {
17875														$w_diff = ($spacewidth * $lnstring[2][($strcount - 1)]);
17876													}
17877												}
17878											}
17879											if (preg_match('/('.$xmatches[1].')[\s]('.$xmatches[2].')[\s]('.$xmatches[3].')[\s]('.$strpiece[1][0].')[\s](re)([\s]*)/x', $pmid, $pmatch) == 1) {
17880												$newx = sprintf('%F',(floatval($pmatch[1]) + $x_diff));
17881												$neww = sprintf('%F',(floatval($pmatch[3]) + $w_diff));
17882												$newpmid = $newx.' '.$pmatch[2].' '.$neww.' '.$pmatch[4].' x*#!#*x'.$pmatch[5].$pmatch[6];
17883												$pmid = str_replace($pmatch[0], $newpmid, $pmid);
17884												unset($pmatch, $newpmid, $newx, $neww);
17885											}
17886											break;
17887										}
17888										case 'c': {
17889											// get current X position
17890											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);
17891											if (!isset($xmatches[1])) {
17892												break;
17893											}
17894											$currentxpos = $xmatches[1];
17895											// justify block
17896											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) {
17897												$newx1 = sprintf('%F',(floatval($pmatch[1]) + $spacew));
17898												$newx2 = sprintf('%F',(floatval($pmatch[3]) + $spacew));
17899												$newx3 = sprintf('%F',(floatval($pmatch[5]) + $spacew));
17900												$newpmid = $newx1.' '.$pmatch[2].' '.$newx2.' '.$pmatch[4].' '.$newx3.' '.$pmatch[6].' x*#!#*x'.$pmatch[7].$pmatch[8];
17901												$pmid = str_replace($pmatch[0], $newpmid, $pmid);
17902												unset($pmatch, $newpmid, $newx1, $newx2, $newx3);
17903											}
17904											break;
17905										}
17906									}
17907									// shift the annotations and links
17908									$cxpos = ($currentxpos / $this->k);
17909									$lmpos = ($this->lMargin + $this->cell_padding['L'] + $this->feps);
17910									if ($this->inxobj) {
17911										// we are inside an XObject template
17912										foreach ($this->xobjects[$this->xobjid]['annotations'] as $pak => $pac) {
17913											if (($pac['y'] >= $minstartliney) AND (($pac['x'] * $this->k) >= ($currentxpos - $this->feps)) AND (($pac['x'] * $this->k) <= ($currentxpos + $this->feps))) {
17914												if ($cxpos > $lmpos) {
17915													$this->xobjects[$this->xobjid]['annotations'][$pak]['x'] += ($spacew / $this->k);
17916													$this->xobjects[$this->xobjid]['annotations'][$pak]['w'] += (($spacewidth * $pac['numspaces']) / $this->k);
17917												} else {
17918													$this->xobjects[$this->xobjid]['annotations'][$pak]['w'] += (($spacewidth * $pac['numspaces']) / $this->k);
17919												}
17920												break;
17921											}
17922										}
17923									} elseif (isset($this->PageAnnots[$this->page])) {
17924										foreach ($this->PageAnnots[$this->page] as $pak => $pac) {
17925											if (($pac['y'] >= $minstartliney) AND (($pac['x'] * $this->k) >= ($currentxpos - $this->feps)) AND (($pac['x'] * $this->k) <= ($currentxpos + $this->feps))) {
17926												if ($cxpos > $lmpos) {
17927													$this->PageAnnots[$this->page][$pak]['x'] += ($spacew / $this->k);
17928													$this->PageAnnots[$this->page][$pak]['w'] += (($spacewidth * $pac['numspaces']) / $this->k);
17929												} else {
17930													$this->PageAnnots[$this->page][$pak]['w'] += (($spacewidth * $pac['numspaces']) / $this->k);
17931												}
17932												break;
17933											}
17934										}
17935									}
17936								} // end of while
17937								// remove markers
17938								$pmid = str_replace('x*#!#*x', '', $pmid);
17939								if ($this->isUnicodeFont()) {
17940									// multibyte characters
17941									$spacew = $spacewidthu;
17942									if ($this->font_stretching != 100) {
17943										// word spacing is affected by stretching
17944										$spacew /= ($this->font_stretching / 100);
17945									}
17946									// escape special characters
17947									$pos = 0;
17948									$pmid = preg_replace('/[\\\][\(]/x', '\\#!#OP#!#', $pmid);
17949									$pmid = preg_replace('/[\\\][\)]/x', '\\#!#CP#!#', $pmid);
17950									if (preg_match_all('/\[\(([^\)]*)\)\]/x', $pmid, $pamatch) > 0) {
17951										foreach($pamatch[0] as $pk => $pmatch) {
17952											$replace = $pamatch[1][$pk];
17953											$replace = str_replace('#!#OP#!#', '(', $replace);
17954											$replace = str_replace('#!#CP#!#', ')', $replace);
17955											$newpmid = '[('.str_replace(chr(0).chr(32), ') '.sprintf('%F', $spacew).' (', $replace).')]';
17956											$pos = strpos($pmid, $pmatch, $pos);
17957											if ($pos !== FALSE) {
17958												$pmid = substr_replace($pmid, $newpmid, $pos, strlen($pmatch));
17959											}
17960											++$pos;
17961										}
17962										unset($pamatch);
17963									}
17964									if ($this->inxobj) {
17965										// we are inside an XObject template
17966										$this->xobjects[$this->xobjid]['outdata'] = $pstart."\n".$pmid."\n".$pend;
17967									} else {
17968										$this->setPageBuffer($startlinepage, $pstart."\n".$pmid."\n".$pend);
17969									}
17970									$endlinepos = strlen($pstart."\n".$pmid."\n");
17971								} else {
17972									// non-unicode (single-byte characters)
17973									if ($this->font_stretching != 100) {
17974										// word spacing (Tw) is affected by stretching
17975										$spacewidth /= ($this->font_stretching / 100);
17976									}
17977									$rs = sprintf('%F Tw', $spacewidth);
17978									$pmid = preg_replace("/\[\(/x", $rs.' [(', $pmid);
17979									if ($this->inxobj) {
17980										// we are inside an XObject template
17981										$this->xobjects[$this->xobjid]['outdata'] = $pstart."\n".$pmid."\nBT 0 Tw ET\n".$pend;
17982									} else {
17983										$this->setPageBuffer($startlinepage, $pstart."\n".$pmid."\nBT 0 Tw ET\n".$pend);
17984									}
17985									$endlinepos = strlen($pstart."\n".$pmid."\nBT 0 Tw ET\n");
17986								}
17987							}
17988						} // end of J
17989					} // end if $startlinex
17990					if (($t_x != 0) OR ($yshift < 0)) {
17991						// shift the line
17992						$trx = sprintf('1 0 0 1 %F %F cm', ($t_x * $this->k), ($yshift * $this->k));
17993						$pstart .= "\nq\n".$trx."\n".$pmid."\nQ\n";
17994						$endlinepos = strlen($pstart);
17995						if ($this->inxobj) {
17996							// we are inside an XObject template
17997							$this->xobjects[$this->xobjid]['outdata'] = $pstart.$pend;
17998							foreach ($this->xobjects[$this->xobjid]['annotations'] as $pak => $pac) {
17999								if ($pak >= $pask) {
18000									$this->xobjects[$this->xobjid]['annotations'][$pak]['x'] += $t_x;
18001									$this->xobjects[$this->xobjid]['annotations'][$pak]['y'] -= $yshift;
18002								}
18003							}
18004						} else {
18005							$this->setPageBuffer($startlinepage, $pstart.$pend);
18006							// shift the annotations and links
18007							if (isset($this->PageAnnots[$this->page])) {
18008								foreach ($this->PageAnnots[$this->page] as $pak => $pac) {
18009									if ($pak >= $pask) {
18010										$this->PageAnnots[$this->page][$pak]['x'] += $t_x;
18011										$this->PageAnnots[$this->page][$pak]['y'] -= $yshift;
18012									}
18013								}
18014							}
18015						}
18016						$this->y -= $yshift;
18017					}
18018				}
18019				$pbrk = $this->checkPageBreak($this->lasth);
18020				$this->newline = false;
18021				$startlinex = $this->x;
18022				$startliney = $this->y;
18023				if ($dom[$dom[$key]['parent']]['value'] == 'sup') {
18024					$startliney -= ((0.3 * $this->FontSizePt) / $this->k);
18025				} elseif ($dom[$dom[$key]['parent']]['value'] == 'sub') {
18026					$startliney -= (($this->FontSizePt / 0.7) / $this->k);
18027				} else {
18028					$minstartliney = $startliney;
18029					$maxbottomliney = ($this->y + $this->getCellHeight($fontsize / $this->k));
18030				}
18031				$startlinepage = $this->page;
18032				if (isset($endlinepos) AND (!$pbrk)) {
18033					$startlinepos = $endlinepos;
18034				} else {
18035					if ($this->inxobj) {
18036						// we are inside an XObject template
18037						$startlinepos = strlen($this->xobjects[$this->xobjid]['outdata']);
18038					} elseif (!$this->InFooter) {
18039						if (isset($this->footerlen[$this->page])) {
18040							$this->footerpos[$this->page] = $this->pagelen[$this->page] - $this->footerlen[$this->page];
18041						} else {
18042							$this->footerpos[$this->page] = $this->pagelen[$this->page];
18043						}
18044						$startlinepos = $this->footerpos[$this->page];
18045					} else {
18046						$startlinepos = $this->pagelen[$this->page];
18047					}
18048				}
18049				unset($endlinepos);
18050				$plalign = $lalign;
18051				if (isset($this->PageAnnots[$this->page])) {
18052					$pask = count($this->PageAnnots[$this->page]);
18053				} else {
18054					$pask = 0;
18055				}
18056				if (!($dom[$key]['tag'] AND !$dom[$key]['opening'] AND ($dom[$key]['value'] == 'table')
18057					AND (isset($this->emptypagemrk[$this->page]))
18058					AND ($this->emptypagemrk[$this->page] == $this->pagelen[$this->page]))) {
18059					$this->SetFont($fontname, $fontstyle, $fontsize);
18060					if ($wfill) {
18061						$this->SetFillColorArray($this->bgcolor);
18062					}
18063				}
18064			} // end newline
18065			if (isset($opentagpos)) {
18066				unset($opentagpos);
18067			}
18068			if ($dom[$key]['tag']) {
18069				if ($dom[$key]['opening']) {
18070					// get text indentation (if any)
18071					if (isset($dom[$key]['text-indent']) AND $dom[$key]['block']) {
18072						$this->textindent = $dom[$key]['text-indent'];
18073						$this->newline = true;
18074					}
18075					// table
18076					if (($dom[$key]['value'] == 'table') AND isset($dom[$key]['cols']) AND ($dom[$key]['cols'] > 0)) {
18077						// available page width
18078						if ($this->rtl) {
18079							$wtmp = $this->x - $this->lMargin;
18080						} else {
18081							$wtmp = $this->w - $this->rMargin - $this->x;
18082						}
18083						// get cell spacing
18084						if (isset($dom[$key]['attribute']['cellspacing'])) {
18085							$clsp = $this->getHTMLUnitToUnits($dom[$key]['attribute']['cellspacing'], 1, 'px');
18086							$cellspacing = array('H' => $clsp, 'V' => $clsp);
18087						} elseif (isset($dom[$key]['border-spacing'])) {
18088							$cellspacing = $dom[$key]['border-spacing'];
18089						} else {
18090							$cellspacing = array('H' => 0, 'V' => 0);
18091						}
18092						// table width
18093						if (isset($dom[$key]['width'])) {
18094							$table_width = $this->getHTMLUnitToUnits($dom[$key]['width'], $wtmp, 'px');
18095						} else {
18096							$table_width = $wtmp;
18097						}
18098						$table_width -= (2 * $cellspacing['H']);
18099						if (!$this->inthead) {
18100							$this->y += $cellspacing['V'];
18101						}
18102						if ($this->rtl) {
18103							$cellspacingx = -$cellspacing['H'];
18104						} else {
18105							$cellspacingx = $cellspacing['H'];
18106						}
18107						// total table width without cellspaces
18108						$table_columns_width = ($table_width - ($cellspacing['H'] * ($dom[$key]['cols'] - 1)));
18109						// minimum column width
18110						$table_min_column_width = ($table_columns_width / $dom[$key]['cols']);
18111						// array of custom column widths
18112						$table_colwidths = array_fill(0, $dom[$key]['cols'], $table_min_column_width);
18113					}
18114					// table row
18115					if ($dom[$key]['value'] == 'tr') {
18116						// reset column counter
18117						$colid = 0;
18118					}
18119					// table cell
18120					if (($dom[$key]['value'] == 'td') OR ($dom[$key]['value'] == 'th')) {
18121						$trid = $dom[$key]['parent'];
18122						$table_el = $dom[$trid]['parent'];
18123						if (!isset($dom[$table_el]['cols'])) {
18124							$dom[$table_el]['cols'] = $dom[$trid]['cols'];
18125						}
18126						// store border info
18127						$tdborder = 0;
18128						if (isset($dom[$key]['border']) AND !empty($dom[$key]['border'])) {
18129							$tdborder = $dom[$key]['border'];
18130						}
18131						$colspan = intval($dom[$key]['attribute']['colspan']);
18132						if ($colspan <= 0) {
18133							$colspan = 1;
18134						}
18135						$old_cell_padding = $this->cell_padding;
18136						if (isset($dom[($dom[$trid]['parent'])]['attribute']['cellpadding'])) {
18137							$crclpd = $this->getHTMLUnitToUnits($dom[($dom[$trid]['parent'])]['attribute']['cellpadding'], 1, 'px');
18138							$current_cell_padding = array('L' => $crclpd, 'T' => $crclpd, 'R' => $crclpd, 'B' => $crclpd);
18139						} elseif (isset($dom[($dom[$trid]['parent'])]['padding'])) {
18140							$current_cell_padding = $dom[($dom[$trid]['parent'])]['padding'];
18141						} else {
18142							$current_cell_padding = array('L' => 0, 'T' => 0, 'R' => 0, 'B' => 0);
18143						}
18144						$this->cell_padding = $current_cell_padding;
18145						if (isset($dom[$key]['height'])) {
18146							// minimum cell height
18147							$cellh = $this->getHTMLUnitToUnits($dom[$key]['height'], 0, 'px');
18148						} else {
18149							$cellh = 0;
18150						}
18151						if (isset($dom[$key]['content'])) {
18152							$cell_content = $dom[$key]['content'];
18153						} else {
18154							$cell_content = '&nbsp;';
18155						}
18156						$tagtype = $dom[$key]['value'];
18157						$parentid = $key;
18158						while (($key < $maxel) AND (!(($dom[$key]['tag']) AND (!$dom[$key]['opening']) AND ($dom[$key]['value'] == $tagtype) AND ($dom[$key]['parent'] == $parentid)))) {
18159							// move $key index forward
18160							++$key;
18161						}
18162						if (!isset($dom[$trid]['startpage'])) {
18163							$dom[$trid]['startpage'] = $this->page;
18164						} else {
18165							$this->setPage($dom[$trid]['startpage']);
18166						}
18167						if (!isset($dom[$trid]['startcolumn'])) {
18168							$dom[$trid]['startcolumn'] = $this->current_column;
18169						} elseif ($this->current_column != $dom[$trid]['startcolumn']) {
18170							$tmpx = $this->x;
18171							$this->selectColumn($dom[$trid]['startcolumn']);
18172							$this->x = $tmpx;
18173						}
18174						if (!isset($dom[$trid]['starty'])) {
18175							$dom[$trid]['starty'] = $this->y;
18176						} else {
18177							$this->y = $dom[$trid]['starty'];
18178						}
18179						if (!isset($dom[$trid]['startx'])) {
18180							$dom[$trid]['startx'] = $this->x;
18181							$this->x += $cellspacingx;
18182						} else {
18183							$this->x += ($cellspacingx / 2);
18184						}
18185						if (isset($dom[$parentid]['attribute']['rowspan'])) {
18186							$rowspan = intval($dom[$parentid]['attribute']['rowspan']);
18187						} else {
18188							$rowspan = 1;
18189						}
18190						// skip row-spanned cells started on the previous rows
18191						if (isset($dom[$table_el]['rowspans'])) {
18192							$rsk = 0;
18193							$rskmax = count($dom[$table_el]['rowspans']);
18194							while ($rsk < $rskmax) {
18195								$trwsp = $dom[$table_el]['rowspans'][$rsk];
18196								$rsstartx = $trwsp['startx'];
18197								$rsendx = $trwsp['endx'];
18198								// account for margin changes
18199								if ($trwsp['startpage'] < $this->page) {
18200									if (($this->rtl) AND ($this->pagedim[$this->page]['orm'] != $this->pagedim[$trwsp['startpage']]['orm'])) {
18201										$dl = ($this->pagedim[$this->page]['orm'] - $this->pagedim[$trwsp['startpage']]['orm']);
18202										$rsstartx -= $dl;
18203										$rsendx -= $dl;
18204									} elseif ((!$this->rtl) AND ($this->pagedim[$this->page]['olm'] != $this->pagedim[$trwsp['startpage']]['olm'])) {
18205										$dl = ($this->pagedim[$this->page]['olm'] - $this->pagedim[$trwsp['startpage']]['olm']);
18206										$rsstartx += $dl;
18207										$rsendx += $dl;
18208									}
18209								}
18210								if (($trwsp['rowspan'] > 0)
18211									AND ($rsstartx > ($this->x - $cellspacing['H'] - $current_cell_padding['L'] - $this->feps))
18212									AND ($rsstartx < ($this->x + $cellspacing['H'] + $current_cell_padding['R'] + $this->feps))
18213									AND (($trwsp['starty'] < ($this->y - $this->feps)) OR ($trwsp['startpage'] < $this->page) OR ($trwsp['startcolumn'] < $this->current_column))) {
18214									// set the starting X position of the current cell
18215									$this->x = $rsendx + $cellspacingx;
18216									// increment column indicator
18217									$colid += $trwsp['colspan'];
18218									if (($trwsp['rowspan'] == 1)
18219										AND (isset($dom[$trid]['endy']))
18220										AND (isset($dom[$trid]['endpage']))
18221										AND (isset($dom[$trid]['endcolumn']))
18222										AND ($trwsp['endpage'] == $dom[$trid]['endpage'])
18223										AND ($trwsp['endcolumn'] == $dom[$trid]['endcolumn'])) {
18224										// set ending Y position for row
18225										$dom[$table_el]['rowspans'][$rsk]['endy'] = max($dom[$trid]['endy'], $trwsp['endy']);
18226										$dom[$trid]['endy'] = $dom[$table_el]['rowspans'][$rsk]['endy'];
18227									}
18228									$rsk = 0;
18229								} else {
18230									++$rsk;
18231								}
18232							}
18233						}
18234						if (isset($dom[$parentid]['width'])) {
18235							// user specified width
18236							$cellw = $this->getHTMLUnitToUnits($dom[$parentid]['width'], $table_columns_width, 'px');
18237							$tmpcw = ($cellw / $colspan);
18238							for ($i = 0; $i < $colspan; ++$i) {
18239								$table_colwidths[($colid + $i)] = $tmpcw;
18240							}
18241						} else {
18242							// inherit column width
18243							$cellw = 0;
18244							for ($i = 0; $i < $colspan; ++$i) {
18245								$cellw += (isset($table_colwidths[($colid + $i)]) ? $table_colwidths[($colid + $i)] : 0);
18246							}
18247						}
18248						$cellw += (($colspan - 1) * $cellspacing['H']);
18249						// increment column indicator
18250						$colid += $colspan;
18251						// add rowspan information to table element
18252						if ($rowspan > 1) {
18253							$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));
18254						}
18255						$cellid = array_push($dom[$trid]['cellpos'], array('startx' => $this->x));
18256						if ($rowspan > 1) {
18257							$dom[$trid]['cellpos'][($cellid - 1)]['rowspanid'] = ($trsid - 1);
18258						}
18259						// push background colors
18260						if (isset($dom[$parentid]['bgcolor']) AND ($dom[$parentid]['bgcolor'] !== false)) {
18261							$dom[$trid]['cellpos'][($cellid - 1)]['bgcolor'] = $dom[$parentid]['bgcolor'];
18262						}
18263						// store border info
18264						if (isset($tdborder) AND !empty($tdborder)) {
18265							$dom[$trid]['cellpos'][($cellid - 1)]['border'] = $tdborder;
18266						}
18267						$prevLastH = $this->lasth;
18268						// store some info for multicolumn mode
18269						if ($this->rtl) {
18270							$this->colxshift['x'] = $this->w - $this->x - $this->rMargin;
18271						} else {
18272							$this->colxshift['x'] = $this->x - $this->lMargin;
18273						}
18274						$this->colxshift['s'] = $cellspacing;
18275						$this->colxshift['p'] = $current_cell_padding;
18276						// ****** write the cell content ******
18277						$this->MultiCell($cellw, $cellh, $cell_content, false, $lalign, false, 2, '', '', true, 0, true, true, 0, 'T', false);
18278						// restore some values
18279						$this->colxshift = array('x' => 0, 's' => array('H' => 0, 'V' => 0), 'p' => array('L' => 0, 'T' => 0, 'R' => 0, 'B' => 0));
18280						$this->lasth = $prevLastH;
18281						$this->cell_padding = $old_cell_padding;
18282						$dom[$trid]['cellpos'][($cellid - 1)]['endx'] = $this->x;
18283						// update the end of row position
18284						if ($rowspan <= 1) {
18285							if (isset($dom[$trid]['endy'])) {
18286								if (($this->page == $dom[$trid]['endpage']) AND ($this->current_column == $dom[$trid]['endcolumn'])) {
18287									$dom[$trid]['endy'] = max($this->y, $dom[$trid]['endy']);
18288								} elseif (($this->page > $dom[$trid]['endpage']) OR ($this->current_column > $dom[$trid]['endcolumn'])) {
18289									$dom[$trid]['endy'] = $this->y;
18290								}
18291							} else {
18292								$dom[$trid]['endy'] = $this->y;
18293							}
18294							if (isset($dom[$trid]['endpage'])) {
18295								$dom[$trid]['endpage'] = max($this->page, $dom[$trid]['endpage']);
18296							} else {
18297								$dom[$trid]['endpage'] = $this->page;
18298							}
18299							if (isset($dom[$trid]['endcolumn'])) {
18300								$dom[$trid]['endcolumn'] = max($this->current_column, $dom[$trid]['endcolumn']);
18301							} else {
18302								$dom[$trid]['endcolumn'] = $this->current_column;
18303							}
18304						} else {
18305							// account for row-spanned cells
18306							$dom[$table_el]['rowspans'][($trsid - 1)]['endx'] = $this->x;
18307							$dom[$table_el]['rowspans'][($trsid - 1)]['endy'] = $this->y;
18308							$dom[$table_el]['rowspans'][($trsid - 1)]['endpage'] = $this->page;
18309							$dom[$table_el]['rowspans'][($trsid - 1)]['endcolumn'] = $this->current_column;
18310						}
18311						if (isset($dom[$table_el]['rowspans'])) {
18312							// update endy and endpage on rowspanned cells
18313							foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
18314								if ($trwsp['rowspan'] > 0) {
18315									if (isset($dom[$trid]['endpage'])) {
18316										if (($trwsp['endpage'] == $dom[$trid]['endpage']) AND ($trwsp['endcolumn'] == $dom[$trid]['endcolumn'])) {
18317											$dom[$table_el]['rowspans'][$k]['endy'] = max($dom[$trid]['endy'], $trwsp['endy']);
18318										} elseif (($trwsp['endpage'] < $dom[$trid]['endpage']) OR ($trwsp['endcolumn'] < $dom[$trid]['endcolumn'])) {
18319											$dom[$table_el]['rowspans'][$k]['endy'] = $dom[$trid]['endy'];
18320											$dom[$table_el]['rowspans'][$k]['endpage'] = $dom[$trid]['endpage'];
18321											$dom[$table_el]['rowspans'][$k]['endcolumn'] = $dom[$trid]['endcolumn'];
18322										} else {
18323											$dom[$trid]['endy'] = $this->pagedim[$dom[$trid]['endpage']]['hk'] - $this->pagedim[$dom[$trid]['endpage']]['bm'];
18324										}
18325									}
18326								}
18327							}
18328						}
18329						$this->x += ($cellspacingx / 2);
18330					} else {
18331						// opening tag (or self-closing tag)
18332						if (!isset($opentagpos)) {
18333							if ($this->inxobj) {
18334								// we are inside an XObject template
18335								$opentagpos = strlen($this->xobjects[$this->xobjid]['outdata']);
18336							} elseif (!$this->InFooter) {
18337								if (isset($this->footerlen[$this->page])) {
18338									$this->footerpos[$this->page] = $this->pagelen[$this->page] - $this->footerlen[$this->page];
18339								} else {
18340									$this->footerpos[$this->page] = $this->pagelen[$this->page];
18341								}
18342								$opentagpos = $this->footerpos[$this->page];
18343							}
18344						}
18345						$dom = $this->openHTMLTagHandler($dom, $key, $cell);
18346					}
18347				} else { // closing tag
18348					$prev_numpages = $this->numpages;
18349					$old_bordermrk = $this->bordermrk[$this->page];
18350					$dom = $this->closeHTMLTagHandler($dom, $key, $cell, $maxbottomliney);
18351					if ($this->bordermrk[$this->page] > $old_bordermrk) {
18352						$startlinepos += ($this->bordermrk[$this->page] - $old_bordermrk);
18353					}
18354					if ($prev_numpages > $this->numpages) {
18355						$startlinepage = $this->page;
18356					}
18357				}
18358			} elseif (strlen($dom[$key]['value']) > 0) {
18359				// print list-item
18360				if (!TCPDF_STATIC::empty_string($this->lispacer) AND ($this->lispacer != '^')) {
18361					$this->SetFont($pfontname, $pfontstyle, $pfontsize);
18362					$this->resetLastH();
18363					$minstartliney = $this->y;
18364					$maxbottomliney = ($startliney + $this->getCellHeight($this->FontSize));
18365					if (is_numeric($pfontsize) AND ($pfontsize > 0)) {
18366						$this->putHtmlListBullet($this->listnum, $this->lispacer, $pfontsize);
18367					}
18368					$this->SetFont($curfontname, $curfontstyle, $curfontsize);
18369					$this->resetLastH();
18370					if (is_numeric($pfontsize) AND ($pfontsize > 0) AND is_numeric($curfontsize) AND ($curfontsize > 0) AND ($pfontsize != $curfontsize)) {
18371						$pfontascent = $this->getFontAscent($pfontname, $pfontstyle, $pfontsize);
18372						$pfontdescent = $this->getFontDescent($pfontname, $pfontstyle, $pfontsize);
18373						$this->y += ($this->getCellHeight(($pfontsize - $curfontsize) / $this->k) + $pfontascent - $curfontascent - $pfontdescent + $curfontdescent) / 2;
18374						$minstartliney = min($this->y, $minstartliney);
18375						$maxbottomliney = max(($this->y + $this->getCellHeight($pfontsize / $this->k)), $maxbottomliney);
18376					}
18377				}
18378				// text
18379				$this->htmlvspace = 0;
18380				$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']);
18381				if ((!$this->premode) AND $this->isRTLTextDir() AND !$isRTLString) {
18382					// reverse spaces order
18383					$lsp = ''; // left spaces
18384					$rsp = ''; // right spaces
18385					if (preg_match('/^('.$this->re_space['p'].'+)/'.$this->re_space['m'], $dom[$key]['value'], $matches)) {
18386						$lsp = $matches[1];
18387					}
18388					if (preg_match('/('.$this->re_space['p'].'+)$/'.$this->re_space['m'], $dom[$key]['value'], $matches)) {
18389						$rsp = $matches[1];
18390					}
18391					$dom[$key]['value'] = $rsp.$this->stringTrim($dom[$key]['value']).$lsp;
18392				}
18393				if ($newline) {
18394					if (!$this->premode) {
18395						$prelen = strlen($dom[$key]['value']);
18396						if ($this->isRTLTextDir() AND !$isRTLString) {
18397							// right trim except non-breaking space
18398							$dom[$key]['value'] = $this->stringRightTrim($dom[$key]['value']);
18399						} else {
18400							// left trim except non-breaking space
18401							$dom[$key]['value'] = $this->stringLeftTrim($dom[$key]['value']);
18402						}
18403						$postlen = strlen($dom[$key]['value']);
18404						if (($postlen == 0) AND ($prelen > 0)) {
18405							$dom[$key]['trimmed_space'] = true;
18406						}
18407					}
18408					$newline = false;
18409					$firstblock = true;
18410				} else {
18411					$firstblock = false;
18412					// replace empty multiple spaces string with a single space
18413					$dom[$key]['value'] = preg_replace('/^'.$this->re_space['p'].'+$/'.$this->re_space['m'], chr(32), $dom[$key]['value']);
18414				}
18415				$strrest = '';
18416				if ($this->rtl) {
18417					$this->x -= $this->textindent;
18418				} else {
18419					$this->x += $this->textindent;
18420				}
18421				if (!isset($dom[$key]['trimmed_space']) OR !$dom[$key]['trimmed_space']) {
18422					$strlinelen = $this->GetStringWidth($dom[$key]['value']);
18423					if (!empty($this->HREF) AND (isset($this->HREF['url']))) {
18424						// HTML <a> Link
18425						$hrefcolor = '';
18426						if (isset($dom[($dom[$key]['parent'])]['fgcolor']) AND ($dom[($dom[$key]['parent'])]['fgcolor'] !== false)) {
18427							$hrefcolor = $dom[($dom[$key]['parent'])]['fgcolor'];
18428						}
18429						$hrefstyle = -1;
18430						if (isset($dom[($dom[$key]['parent'])]['fontstyle']) AND ($dom[($dom[$key]['parent'])]['fontstyle'] !== false)) {
18431							$hrefstyle = $dom[($dom[$key]['parent'])]['fontstyle'];
18432						}
18433						$strrest = $this->addHtmlLink($this->HREF['url'], $dom[$key]['value'], $wfill, true, $hrefcolor, $hrefstyle, true);
18434					} else {
18435						$wadj = 0; // space to leave for block continuity
18436						if ($this->rtl) {
18437							$cwa = ($this->x - $this->lMargin);
18438						} else {
18439							$cwa = ($this->w - $this->rMargin - $this->x);
18440						}
18441						if (($strlinelen < $cwa) AND (isset($dom[($key + 1)])) AND ($dom[($key + 1)]['tag']) AND (!$dom[($key + 1)]['block'])) {
18442							// check the next text blocks for continuity
18443							$nkey = ($key + 1);
18444							$write_block = true;
18445							$same_textdir = true;
18446							$tmp_fontname = $this->FontFamily;
18447							$tmp_fontstyle = $this->FontStyle;
18448							$tmp_fontsize = $this->FontSizePt;
18449							while ($write_block AND isset($dom[$nkey])) {
18450								if ($dom[$nkey]['tag']) {
18451									if ($dom[$nkey]['block']) {
18452										// end of block
18453										$write_block = false;
18454									}
18455									$tmp_fontname = isset($dom[$nkey]['fontname']) ? $dom[$nkey]['fontname'] : $this->FontFamily;
18456									$tmp_fontstyle = isset($dom[$nkey]['fontstyle']) ? $dom[$nkey]['fontstyle'] : $this->FontStyle;
18457									$tmp_fontsize = isset($dom[$nkey]['fontsize']) ? $dom[$nkey]['fontsize'] : $this->FontSizePt;
18458									$same_textdir = ($dom[$nkey]['dir'] == $dom[$key]['dir']);
18459								} else {
18460									$nextstr = TCPDF_STATIC::pregSplit('/'.$this->re_space['p'].'+/', $this->re_space['m'], $dom[$nkey]['value']);
18461									if (isset($nextstr[0]) AND $same_textdir) {
18462										$wadj += $this->GetStringWidth($nextstr[0], $tmp_fontname, $tmp_fontstyle, $tmp_fontsize);
18463										if (isset($nextstr[1])) {
18464											$write_block = false;
18465										}
18466									}
18467								}
18468								++$nkey;
18469							}
18470						}
18471						if (($wadj > 0) AND (($strlinelen + $wadj) >= $cwa)) {
18472							$wadj = 0;
18473							$nextstr = TCPDF_STATIC::pregSplit('/'.$this->re_space['p'].'/', $this->re_space['m'], $dom[$key]['value']);
18474							$numblks = count($nextstr);
18475							if ($numblks > 1) {
18476								// try to split on blank spaces
18477								$wadj = ($cwa - $strlinelen + $this->GetStringWidth($nextstr[($numblks - 1)]));
18478							} else {
18479								// set the entire block on new line
18480								$wadj = $this->GetStringWidth($nextstr[0]);
18481							}
18482						}
18483						// check for reversed text direction
18484						if (($wadj > 0) AND (($this->rtl AND ($this->tmprtl === 'L')) OR (!$this->rtl AND ($this->tmprtl === 'R')))) {
18485							// LTR text on RTL direction or RTL text on LTR direction
18486							$reverse_dir = true;
18487							$this->rtl = !$this->rtl;
18488							$revshift = ($strlinelen + $wadj + 0.000001); // add little quantity for rounding problems
18489							if ($this->rtl) {
18490								$this->x += $revshift;
18491							} else {
18492								$this->x -= $revshift;
18493							}
18494							$xws = $this->x;
18495						}
18496						// ****** write only until the end of the line and get the rest ******
18497						$strrest = $this->Write($this->lasth, $dom[$key]['value'], '', $wfill, '', false, 0, true, $firstblock, 0, $wadj);
18498						// restore default direction
18499						if ($reverse_dir AND ($wadj == 0)) {
18500							$this->x = $xws;
18501							$this->rtl = !$this->rtl;
18502							$reverse_dir = false;
18503						}
18504					}
18505				}
18506				$this->textindent = 0;
18507				if (strlen($strrest) > 0) {
18508					// store the remaining string on the previous $key position
18509					$this->newline = true;
18510					if ($strrest == $dom[$key]['value']) {
18511						// used to avoid infinite loop
18512						++$loop;
18513					} else {
18514						$loop = 0;
18515					}
18516					$dom[$key]['value'] = $strrest;
18517					if ($cell) {
18518						if ($this->rtl) {
18519							$this->x -= $this->cell_padding['R'];
18520						} else {
18521							$this->x += $this->cell_padding['L'];
18522						}
18523					}
18524					if ($loop < 3) {
18525						--$key;
18526					}
18527				} else {
18528					$loop = 0;
18529					// add the positive font spacing of the last character (if any)
18530					 if ($this->font_spacing > 0) {
18531					 	if ($this->rtl) {
18532							$this->x -= $this->font_spacing;
18533						} else {
18534							$this->x += $this->font_spacing;
18535						}
18536					}
18537				}
18538			}
18539			++$key;
18540			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')) {
18541				// check if we are on a new page or on a new column
18542				if ((!$undo) AND (($this->y < $this->start_transaction_y) OR (($dom[$key]['value'] == 'tr') AND ($dom[($dom[$key]['parent'])]['endy'] < $this->start_transaction_y)))) {
18543					// we are on a new page or on a new column and the total object height is less than the available vertical space.
18544					// restore previous object
18545					$this->rollbackTransaction(true);
18546					// restore previous values
18547					foreach ($this_method_vars as $vkey => $vval) {
18548						$$vkey = $vval;
18549					}
18550					if (!empty($dom[$key]['thead'])) {
18551						$this->inthead = true;
18552					}
18553					// add a page (or trig AcceptPageBreak() for multicolumn mode)
18554					$pre_y = $this->y;
18555					if ((!$this->checkPageBreak($this->PageBreakTrigger + 1)) AND ($this->y < $pre_y)) {
18556						$startliney = $this->y;
18557					}
18558					$undo = true; // avoid infinite loop
18559				} else {
18560					$undo = false;
18561				}
18562			}
18563		} // end for each $key
18564		// align the last line
18565		if (isset($startlinex)) {
18566			$yshift = ($minstartliney - $startliney);
18567			if (($yshift > 0) OR ($this->page > $startlinepage)) {
18568				$yshift = 0;
18569			}
18570			$t_x = 0;
18571			// the last line must be shifted to be aligned as requested
18572			$linew = abs($this->endlinex - $startlinex);
18573			if ($this->inxobj) {
18574				// we are inside an XObject template
18575				$pstart = substr($this->xobjects[$this->xobjid]['outdata'], 0, $startlinepos);
18576				if (isset($opentagpos)) {
18577					$midpos = $opentagpos;
18578				} else {
18579					$midpos = 0;
18580				}
18581				if ($midpos > 0) {
18582					$pmid = substr($this->xobjects[$this->xobjid]['outdata'], $startlinepos, ($midpos - $startlinepos));
18583					$pend = substr($this->xobjects[$this->xobjid]['outdata'], $midpos);
18584				} else {
18585					$pmid = substr($this->xobjects[$this->xobjid]['outdata'], $startlinepos);
18586					$pend = '';
18587				}
18588			} else {
18589				$pstart = substr($this->getPageBuffer($startlinepage), 0, $startlinepos);
18590				if (isset($opentagpos) AND isset($this->footerlen[$startlinepage]) AND (!$this->InFooter)) {
18591					$this->footerpos[$startlinepage] = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
18592					$midpos = min($opentagpos, $this->footerpos[$startlinepage]);
18593				} elseif (isset($opentagpos)) {
18594					$midpos = $opentagpos;
18595				} elseif (isset($this->footerlen[$startlinepage]) AND (!$this->InFooter)) {
18596					$this->footerpos[$startlinepage] = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
18597					$midpos = $this->footerpos[$startlinepage];
18598				} else {
18599					$midpos = 0;
18600				}
18601				if ($midpos > 0) {
18602					$pmid = substr($this->getPageBuffer($startlinepage), $startlinepos, ($midpos - $startlinepos));
18603					$pend = substr($this->getPageBuffer($startlinepage), $midpos);
18604				} else {
18605					$pmid = substr($this->getPageBuffer($startlinepage), $startlinepos);
18606					$pend = '';
18607				}
18608			}
18609			if ((isset($plalign) AND ((($plalign == 'C') OR (($plalign == 'R') AND (!$this->rtl)) OR (($plalign == 'L') AND ($this->rtl)))))) {
18610				// calculate shifting amount
18611				$tw = $w;
18612				if ($this->lMargin != $prevlMargin) {
18613					$tw += ($prevlMargin - $this->lMargin);
18614				}
18615				if ($this->rMargin != $prevrMargin) {
18616					$tw += ($prevrMargin - $this->rMargin);
18617				}
18618				$one_space_width = $this->GetStringWidth(chr(32));
18619				$no = 0; // number of spaces on a line contained on a single block
18620				if ($this->isRTLTextDir()) { // RTL
18621					// remove left space if exist
18622					$pos1 = TCPDF_STATIC::revstrpos($pmid, '[(');
18623					if ($pos1 > 0) {
18624						$pos1 = intval($pos1);
18625						if ($this->isUnicodeFont()) {
18626							$pos2 = intval(TCPDF_STATIC::revstrpos($pmid, '[('.chr(0).chr(32)));
18627							$spacelen = 2;
18628						} else {
18629							$pos2 = intval(TCPDF_STATIC::revstrpos($pmid, '[('.chr(32)));
18630							$spacelen = 1;
18631						}
18632						if ($pos1 == $pos2) {
18633							$pmid = substr($pmid, 0, ($pos1 + 2)).substr($pmid, ($pos1 + 2 + $spacelen));
18634							if (substr($pmid, $pos1, 4) == '[()]') {
18635								$linew -= $one_space_width;
18636							} elseif ($pos1 == strpos($pmid, '[(')) {
18637								$no = 1;
18638							}
18639						}
18640					}
18641				} else { // LTR
18642					// remove right space if exist
18643					$pos1 = TCPDF_STATIC::revstrpos($pmid, ')]');
18644					if ($pos1 > 0) {
18645						$pos1 = intval($pos1);
18646						if ($this->isUnicodeFont()) {
18647							$pos2 = intval(TCPDF_STATIC::revstrpos($pmid, chr(0).chr(32).')]')) + 2;
18648							$spacelen = 2;
18649						} else {
18650							$pos2 = intval(TCPDF_STATIC::revstrpos($pmid, chr(32).')]')) + 1;
18651							$spacelen = 1;
18652						}
18653						if ($pos1 == $pos2) {
18654							$pmid = substr($pmid, 0, ($pos1 - $spacelen)).substr($pmid, $pos1);
18655							$linew -= $one_space_width;
18656						}
18657					}
18658				}
18659				$mdiff = ($tw - $linew);
18660				if ($plalign == 'C') {
18661					if ($this->rtl) {
18662						$t_x = -($mdiff / 2);
18663					} else {
18664						$t_x = ($mdiff / 2);
18665					}
18666				} elseif ($plalign == 'R') {
18667					// right alignment on LTR document
18668					$t_x = $mdiff;
18669				} elseif ($plalign == 'L') {
18670					// left alignment on RTL document
18671					$t_x = -$mdiff;
18672				}
18673			} // end if startlinex
18674			if (($t_x != 0) OR ($yshift < 0)) {
18675				// shift the line
18676				$trx = sprintf('1 0 0 1 %F %F cm', ($t_x * $this->k), ($yshift * $this->k));
18677				$pstart .= "\nq\n".$trx."\n".$pmid."\nQ\n";
18678				$endlinepos = strlen($pstart);
18679				if ($this->inxobj) {
18680					// we are inside an XObject template
18681					$this->xobjects[$this->xobjid]['outdata'] = $pstart.$pend;
18682					foreach ($this->xobjects[$this->xobjid]['annotations'] as $pak => $pac) {
18683						if ($pak >= $pask) {
18684							$this->xobjects[$this->xobjid]['annotations'][$pak]['x'] += $t_x;
18685							$this->xobjects[$this->xobjid]['annotations'][$pak]['y'] -= $yshift;
18686						}
18687					}
18688				} else {
18689					$this->setPageBuffer($startlinepage, $pstart.$pend);
18690					// shift the annotations and links
18691					if (isset($this->PageAnnots[$this->page])) {
18692						foreach ($this->PageAnnots[$this->page] as $pak => $pac) {
18693							if ($pak >= $pask) {
18694								$this->PageAnnots[$this->page][$pak]['x'] += $t_x;
18695								$this->PageAnnots[$this->page][$pak]['y'] -= $yshift;
18696							}
18697						}
18698					}
18699				}
18700				$this->y -= $yshift;
18701				$yshift = 0;
18702			}
18703		}
18704		// restore previous values
18705		$this->setGraphicVars($gvars);
18706		if ($this->num_columns > 1) {
18707			$this->selectColumn();
18708		} elseif ($this->page > $prevPage) {
18709			$this->lMargin = $this->pagedim[$this->page]['olm'];
18710			$this->rMargin = $this->pagedim[$this->page]['orm'];
18711		}
18712		// restore previous list state
18713		$this->cell_height_ratio = $prev_cell_height_ratio;
18714		$this->listnum = $prev_listnum;
18715		$this->listordered = $prev_listordered;
18716		$this->listcount = $prev_listcount;
18717		$this->lispacer = $prev_lispacer;
18718		if ($ln AND (!($cell AND ($dom[$key-1]['value'] == 'table')))) {
18719			$this->Ln($this->lasth);
18720			if (($this->y < $maxbottomliney) AND ($startlinepage == $this->page)) {
18721				$this->y = $maxbottomliney;
18722			}
18723		}
18724		unset($dom);
18725	}
18726
18727	/**
18728	 * Process opening tags.
18729	 * @param $dom (array) html dom array
18730	 * @param $key (int) current element id
18731	 * @param $cell (boolean) if true add the default left (or right if RTL) padding to each new line (default false).
18732	 * @return $dom array
18733	 * @protected
18734	 */
18735	protected function openHTMLTagHandler($dom, $key, $cell) {
18736		$tag = $dom[$key];
18737		$parent = $dom[($dom[$key]['parent'])];
18738		$firsttag = ($key == 1);
18739		// check for text direction attribute
18740		if (isset($tag['dir'])) {
18741			$this->setTempRTL($tag['dir']);
18742		} else {
18743			$this->tmprtl = false;
18744		}
18745		if ($tag['block']) {
18746			$hbz = 0; // distance from y to line bottom
18747			$hb = 0; // vertical space between block tags
18748			// calculate vertical space for block tags
18749			if (isset($this->tagvspaces[$tag['value']][0]['h']) && !empty($this->tagvspaces[$tag['value']][0]['h']) && ($this->tagvspaces[$tag['value']][0]['h'] >= 0)) {
18750				$cur_h = $this->tagvspaces[$tag['value']][0]['h'];
18751			} elseif (isset($tag['fontsize'])) {
18752				$cur_h = $this->getCellHeight($tag['fontsize'] / $this->k);
18753			} else {
18754				$cur_h = $this->getCellHeight($this->FontSize);
18755			}
18756			if (isset($this->tagvspaces[$tag['value']][0]['n'])) {
18757				$on = $this->tagvspaces[$tag['value']][0]['n'];
18758			} elseif (preg_match('/[h][0-9]/', $tag['value']) > 0) {
18759				$on = 0.6;
18760			} else {
18761				$on = 1;
18762			}
18763			if ((!isset($this->tagvspaces[$tag['value']])) AND (in_array($tag['value'], array('div', 'dt', 'dd', 'li', 'br', 'hr')))) {
18764				$hb = 0;
18765			} else {
18766				$hb = ($on * $cur_h);
18767			}
18768			if (($this->htmlvspace <= 0) AND ($on > 0)) {
18769				if (isset($parent['fontsize'])) {
18770					$hbz = (($parent['fontsize'] / $this->k) * $this->cell_height_ratio);
18771				} else {
18772					$hbz = $this->getCellHeight($this->FontSize);
18773				}
18774			}
18775			if (isset($dom[($key - 1)]) AND ($dom[($key - 1)]['value'] == 'table')) {
18776				// fix vertical space after table
18777				$hbz = 0;
18778			}
18779			// closing vertical space
18780			$hbc = 0;
18781			if (isset($this->tagvspaces[$tag['value']][1]['h']) && !empty($this->tagvspaces[$tag['value']][1]['h']) && ($this->tagvspaces[$tag['value']][1]['h'] >= 0)) {
18782				$pre_h = $this->tagvspaces[$tag['value']][1]['h'];
18783			} elseif (isset($parent['fontsize'])) {
18784				$pre_h = $this->getCellHeight($parent['fontsize'] / $this->k);
18785			} else {
18786				$pre_h = $this->getCellHeight($this->FontSize);
18787			}
18788			if (isset($this->tagvspaces[$tag['value']][1]['n'])) {
18789				$cn = $this->tagvspaces[$tag['value']][1]['n'];
18790			} elseif (preg_match('/[h][0-9]/', $tag['value']) > 0) {
18791				$cn = 0.6;
18792			} else {
18793				$cn = 1;
18794			}
18795			if (isset($this->tagvspaces[$tag['value']][1])) {
18796				$hbc = ($cn * $pre_h);
18797			}
18798		}
18799		// Opening tag
18800		switch($tag['value']) {
18801			case 'table': {
18802				$cp = 0;
18803				$cs = 0;
18804				$dom[$key]['rowspans'] = array();
18805				if (!isset($dom[$key]['attribute']['nested']) OR ($dom[$key]['attribute']['nested'] != 'true')) {
18806					$this->htmlvspace = 0;
18807					// set table header
18808					if (!TCPDF_STATIC::empty_string($dom[$key]['thead'])) {
18809						// set table header
18810						$this->thead = $dom[$key]['thead'];
18811						if (!isset($this->theadMargins) OR (empty($this->theadMargins))) {
18812							$this->theadMargins = array();
18813							$this->theadMargins['cell_padding'] = $this->cell_padding;
18814							$this->theadMargins['lmargin'] = $this->lMargin;
18815							$this->theadMargins['rmargin'] = $this->rMargin;
18816							$this->theadMargins['page'] = $this->page;
18817							$this->theadMargins['cell'] = $cell;
18818							$this->theadMargins['gvars'] = $this->getGraphicVars();
18819						}
18820					}
18821				}
18822				// store current margins and page
18823				$dom[$key]['old_cell_padding'] = $this->cell_padding;
18824				if (isset($tag['attribute']['cellpadding'])) {
18825					$pad = $this->getHTMLUnitToUnits($tag['attribute']['cellpadding'], 1, 'px');
18826					$this->SetCellPadding($pad);
18827				} elseif (isset($tag['padding'])) {
18828					$this->cell_padding = $tag['padding'];
18829				}
18830				if (isset($tag['attribute']['cellspacing'])) {
18831					$cs = $this->getHTMLUnitToUnits($tag['attribute']['cellspacing'], 1, 'px');
18832				} elseif (isset($tag['border-spacing'])) {
18833					$cs = $tag['border-spacing']['V'];
18834				}
18835				$prev_y = $this->y;
18836				if ($this->checkPageBreak(((2 * $cp) + (2 * $cs) + $this->lasth), '', false) OR ($this->y < $prev_y)) {
18837					$this->inthead = true;
18838					// add a page (or trig AcceptPageBreak() for multicolumn mode)
18839					$this->checkPageBreak($this->PageBreakTrigger + 1);
18840				}
18841				break;
18842			}
18843			case 'tr': {
18844				// array of columns positions
18845				$dom[$key]['cellpos'] = array();
18846				break;
18847			}
18848			case 'hr': {
18849				if ((isset($tag['height'])) AND ($tag['height'] != '')) {
18850					$hrHeight = $this->getHTMLUnitToUnits($tag['height'], 1, 'px');
18851				} else {
18852					$hrHeight = $this->GetLineWidth();
18853				}
18854				$this->addHTMLVertSpace($hbz, max($hb, ($hrHeight / 2)), $cell, $firsttag);
18855				$x = $this->GetX();
18856				$y = $this->GetY();
18857				$wtmp = $this->w - $this->lMargin - $this->rMargin;
18858				if ($cell) {
18859					$wtmp -= ($this->cell_padding['L'] + $this->cell_padding['R']);
18860				}
18861				if ((isset($tag['width'])) AND ($tag['width'] != '')) {
18862					$hrWidth = $this->getHTMLUnitToUnits($tag['width'], $wtmp, 'px');
18863				} else {
18864					$hrWidth = $wtmp;
18865				}
18866				$prevlinewidth = $this->GetLineWidth();
18867				$this->SetLineWidth($hrHeight);
18868				$this->Line($x, $y, $x + $hrWidth, $y);
18869				$this->SetLineWidth($prevlinewidth);
18870				$this->addHTMLVertSpace(max($hbc, ($hrHeight / 2)), 0, $cell, !isset($dom[($key + 1)]));
18871				break;
18872			}
18873			case 'a': {
18874				if (array_key_exists('href', $tag['attribute'])) {
18875					$this->HREF['url'] = $tag['attribute']['href'];
18876				}
18877				break;
18878			}
18879			case 'img': {
18880				if (empty($tag['attribute']['src'])) {
18881					break;
18882				}
18883				$imgsrc = $tag['attribute']['src'];
18884				if ($imgsrc[0] === '@') {
18885					// data stream
18886					$imgsrc = '@'.base64_decode(substr($imgsrc, 1));
18887					$type = '';
18888				} else {
18889					if (($imgsrc[0] === '/') AND !empty($_SERVER['DOCUMENT_ROOT']) AND ($_SERVER['DOCUMENT_ROOT'] != '/')) {
18890						// fix image path
18891						$findroot = strpos($imgsrc, $_SERVER['DOCUMENT_ROOT']);
18892						if (($findroot === false) OR ($findroot > 1)) {
18893							if (substr($_SERVER['DOCUMENT_ROOT'], -1) == '/') {
18894								$imgsrc = substr($_SERVER['DOCUMENT_ROOT'], 0, -1).$imgsrc;
18895							} else {
18896								$imgsrc = $_SERVER['DOCUMENT_ROOT'].$imgsrc;
18897							}
18898						}
18899						$imgsrc = urldecode($imgsrc);
18900						$testscrtype = @parse_url($imgsrc);
18901						if (empty($testscrtype['query'])) {
18902							// convert URL to server path
18903							$imgsrc = str_replace(K_PATH_URL, K_PATH_MAIN, $imgsrc);
18904						} elseif (preg_match('|^https?://|', $imgsrc) !== 1) {
18905							// convert URL to server path
18906							$imgsrc = str_replace(K_PATH_MAIN, K_PATH_URL, $imgsrc);
18907						}
18908					}
18909					// get image type
18910					$type = TCPDF_IMAGES::getImageFileType($imgsrc);
18911				}
18912				if (!isset($tag['width'])) {
18913					$tag['width'] = 0;
18914				}
18915				if (!isset($tag['height'])) {
18916					$tag['height'] = 0;
18917				}
18918				//if (!isset($tag['attribute']['align'])) {
18919					// the only alignment supported is "bottom"
18920					// further development is required for other modes.
18921					$tag['attribute']['align'] = 'bottom';
18922				//}
18923				switch($tag['attribute']['align']) {
18924					case 'top': {
18925						$align = 'T';
18926						break;
18927					}
18928					case 'middle': {
18929						$align = 'M';
18930						break;
18931					}
18932					case 'bottom': {
18933						$align = 'B';
18934						break;
18935					}
18936					default: {
18937						$align = 'B';
18938						break;
18939					}
18940				}
18941				$prevy = $this->y;
18942				$xpos = $this->x;
18943				$imglink = '';
18944				if (isset($this->HREF['url']) AND !TCPDF_STATIC::empty_string($this->HREF['url'])) {
18945					$imglink = $this->HREF['url'];
18946					if ($imglink[0] == '#') {
18947						// convert url to internal link
18948						$lnkdata = explode(',', $imglink);
18949						if (isset($lnkdata[0])) {
18950							$page = intval(substr($lnkdata[0], 1));
18951							if (empty($page) OR ($page <= 0)) {
18952								$page = $this->page;
18953							}
18954							if (isset($lnkdata[1]) AND (strlen($lnkdata[1]) > 0)) {
18955								$lnky = floatval($lnkdata[1]);
18956							} else {
18957								$lnky = 0;
18958							}
18959							$imglink = $this->AddLink();
18960							$this->SetLink($imglink, $lnky, $page);
18961						}
18962					}
18963				}
18964				$border = 0;
18965				if (isset($tag['border']) AND !empty($tag['border'])) {
18966					// currently only support 1 (frame) or a combination of 'LTRB'
18967					$border = $tag['border'];
18968				}
18969				$iw = '';
18970				if (isset($tag['width'])) {
18971					$iw = $this->getHTMLUnitToUnits($tag['width'], ($tag['fontsize'] / $this->k), 'px', false);
18972				}
18973				$ih = '';
18974				if (isset($tag['height'])) {
18975					$ih = $this->getHTMLUnitToUnits($tag['height'], ($tag['fontsize'] / $this->k), 'px', false);
18976				}
18977				if (($type == 'eps') OR ($type == 'ai')) {
18978					$this->ImageEps($imgsrc, $xpos, $this->y, $iw, $ih, $imglink, true, $align, '', $border, true);
18979				} elseif ($type == 'svg') {
18980					$this->ImageSVG($imgsrc, $xpos, $this->y, $iw, $ih, $imglink, $align, '', $border, true);
18981				} else {
18982					$this->Image($imgsrc, $xpos, $this->y, $iw, $ih, '', $imglink, $align, false, 300, '', false, false, $border, false, false, true);
18983				}
18984				switch($align) {
18985					case 'T': {
18986						$this->y = $prevy;
18987						break;
18988					}
18989					case 'M': {
18990						$this->y = (($this->img_rb_y + $prevy - ($this->getCellHeight($tag['fontsize'] / $this->k))) / 2);
18991						break;
18992					}
18993					case 'B': {
18994						$this->y = $this->img_rb_y - ($this->getCellHeight($tag['fontsize'] / $this->k) - ($this->getFontDescent($tag['fontname'], $tag['fontstyle'], $tag['fontsize']) * $this->cell_height_ratio));
18995						break;
18996					}
18997				}
18998				break;
18999			}
19000			case 'dl': {
19001				++$this->listnum;
19002				if ($this->listnum == 1) {
19003					$this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
19004				} else {
19005					$this->addHTMLVertSpace(0, 0, $cell, $firsttag);
19006				}
19007				break;
19008			}
19009			case 'dt': {
19010				$this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
19011				break;
19012			}
19013			case 'dd': {
19014				if ($this->rtl) {
19015					$this->rMargin += $this->listindent;
19016				} else {
19017					$this->lMargin += $this->listindent;
19018				}
19019				++$this->listindentlevel;
19020				$this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
19021				break;
19022			}
19023			case 'ul':
19024			case 'ol': {
19025				++$this->listnum;
19026				if ($tag['value'] == 'ol') {
19027					$this->listordered[$this->listnum] = true;
19028				} else {
19029					$this->listordered[$this->listnum] = false;
19030				}
19031				if (isset($tag['attribute']['start'])) {
19032					$this->listcount[$this->listnum] = intval($tag['attribute']['start']) - 1;
19033				} else {
19034					$this->listcount[$this->listnum] = 0;
19035				}
19036				if ($this->rtl) {
19037					$this->rMargin += $this->listindent;
19038					$this->x -= $this->listindent;
19039				} else {
19040					$this->lMargin += $this->listindent;
19041					$this->x += $this->listindent;
19042				}
19043				++$this->listindentlevel;
19044				if ($this->listnum == 1) {
19045					if ($key > 1) {
19046						$this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
19047					}
19048				} else {
19049					$this->addHTMLVertSpace(0, 0, $cell, $firsttag);
19050				}
19051				break;
19052			}
19053			case 'li': {
19054				if ($key > 2) {
19055					$this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
19056				}
19057				if ($this->listordered[$this->listnum]) {
19058					// ordered item
19059					if (isset($parent['attribute']['type']) AND !TCPDF_STATIC::empty_string($parent['attribute']['type'])) {
19060						$this->lispacer = $parent['attribute']['type'];
19061					} elseif (isset($parent['listtype']) AND !TCPDF_STATIC::empty_string($parent['listtype'])) {
19062						$this->lispacer = $parent['listtype'];
19063					} elseif (isset($this->lisymbol) AND !TCPDF_STATIC::empty_string($this->lisymbol)) {
19064						$this->lispacer = $this->lisymbol;
19065					} else {
19066						$this->lispacer = '#';
19067					}
19068					++$this->listcount[$this->listnum];
19069					if (isset($tag['attribute']['value'])) {
19070						$this->listcount[$this->listnum] = intval($tag['attribute']['value']);
19071					}
19072				} else {
19073					// unordered item
19074					if (isset($parent['attribute']['type']) AND !TCPDF_STATIC::empty_string($parent['attribute']['type'])) {
19075						$this->lispacer = $parent['attribute']['type'];
19076					} elseif (isset($parent['listtype']) AND !TCPDF_STATIC::empty_string($parent['listtype'])) {
19077						$this->lispacer = $parent['listtype'];
19078					} elseif (isset($this->lisymbol) AND !TCPDF_STATIC::empty_string($this->lisymbol)) {
19079						$this->lispacer = $this->lisymbol;
19080					} else {
19081						$this->lispacer = '!';
19082					}
19083				}
19084				break;
19085			}
19086			case 'blockquote': {
19087				if ($this->rtl) {
19088					$this->rMargin += $this->listindent;
19089				} else {
19090					$this->lMargin += $this->listindent;
19091				}
19092				++$this->listindentlevel;
19093				$this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
19094				break;
19095			}
19096			case 'br': {
19097				$this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
19098				break;
19099			}
19100			case 'div': {
19101				$this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
19102				break;
19103			}
19104			case 'p': {
19105				$this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
19106				break;
19107			}
19108			case 'pre': {
19109				$this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
19110				$this->premode = true;
19111				break;
19112			}
19113			case 'sup': {
19114				$this->SetXY($this->GetX(), $this->GetY() - ((0.7 * $this->FontSizePt) / $this->k));
19115				break;
19116			}
19117			case 'sub': {
19118				$this->SetXY($this->GetX(), $this->GetY() + ((0.3 * $this->FontSizePt) / $this->k));
19119				break;
19120			}
19121			case 'h1':
19122			case 'h2':
19123			case 'h3':
19124			case 'h4':
19125			case 'h5':
19126			case 'h6': {
19127				$this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
19128				break;
19129			}
19130			// Form fields (since 4.8.000 - 2009-09-07)
19131			case 'form': {
19132				if (isset($tag['attribute']['action'])) {
19133					$this->form_action = $tag['attribute']['action'];
19134				} else {
19135					$this->Error('Please explicitly set action attribute path!');
19136				}
19137				if (isset($tag['attribute']['enctype'])) {
19138					$this->form_enctype = $tag['attribute']['enctype'];
19139				} else {
19140					$this->form_enctype = 'application/x-www-form-urlencoded';
19141				}
19142				if (isset($tag['attribute']['method'])) {
19143					$this->form_mode = $tag['attribute']['method'];
19144				} else {
19145					$this->form_mode = 'post';
19146				}
19147				break;
19148			}
19149			case 'input': {
19150				if (isset($tag['attribute']['name']) AND !TCPDF_STATIC::empty_string($tag['attribute']['name'])) {
19151					$name = $tag['attribute']['name'];
19152				} else {
19153					break;
19154				}
19155				$prop = array();
19156				$opt = array();
19157				if (isset($tag['attribute']['readonly']) AND !TCPDF_STATIC::empty_string($tag['attribute']['readonly'])) {
19158					$prop['readonly'] = true;
19159				}
19160				if (isset($tag['attribute']['value']) AND !TCPDF_STATIC::empty_string($tag['attribute']['value'])) {
19161					$value = $tag['attribute']['value'];
19162				}
19163				if (isset($tag['attribute']['maxlength']) AND !TCPDF_STATIC::empty_string($tag['attribute']['maxlength'])) {
19164					$opt['maxlen'] = intval($tag['attribute']['maxlength']);
19165				}
19166				$h = $this->getCellHeight($this->FontSize);
19167				if (isset($tag['attribute']['size']) AND !TCPDF_STATIC::empty_string($tag['attribute']['size'])) {
19168					$w = intval($tag['attribute']['size']) * $this->GetStringWidth(chr(32)) * 2;
19169				} else {
19170					$w = $h;
19171				}
19172				if (isset($tag['attribute']['checked']) AND (($tag['attribute']['checked'] == 'checked') OR ($tag['attribute']['checked'] == 'true'))) {
19173					$checked = true;
19174				} else {
19175					$checked = false;
19176				}
19177				if (isset($tag['align'])) {
19178					switch ($tag['align']) {
19179						case 'C': {
19180							$opt['q'] = 1;
19181							break;
19182						}
19183						case 'R': {
19184							$opt['q'] = 2;
19185							break;
19186						}
19187						case 'L':
19188						default: {
19189							break;
19190						}
19191					}
19192				}
19193				switch ($tag['attribute']['type']) {
19194					case 'text': {
19195						if (isset($value)) {
19196							$opt['v'] = $value;
19197						}
19198						$this->TextField($name, $w, $h, $prop, $opt, '', '', false);
19199						break;
19200					}
19201					case 'password': {
19202						if (isset($value)) {
19203							$opt['v'] = $value;
19204						}
19205						$prop['password'] = 'true';
19206						$this->TextField($name, $w, $h, $prop, $opt, '', '', false);
19207						break;
19208					}
19209					case 'checkbox': {
19210						if (!isset($value)) {
19211							break;
19212						}
19213						$this->CheckBox($name, $w, $checked, $prop, $opt, $value, '', '', false);
19214						break;
19215					}
19216					case 'radio': {
19217						if (!isset($value)) {
19218							break;
19219						}
19220						$this->RadioButton($name, $w, $prop, $opt, $value, $checked, '', '', false);
19221						break;
19222					}
19223					case 'submit': {
19224						if (!isset($value)) {
19225							$value = 'submit';
19226						}
19227						$w = $this->GetStringWidth($value) * 1.5;
19228						$h *= 1.6;
19229						$prop = array('lineWidth'=>1, 'borderStyle'=>'beveled', 'fillColor'=>array(196, 196, 196), 'strokeColor'=>array(255, 255, 255));
19230						$action = array();
19231						$action['S'] = 'SubmitForm';
19232						$action['F'] = $this->form_action;
19233						if ($this->form_enctype != 'FDF') {
19234							$action['Flags'] = array('ExportFormat');
19235						}
19236						if ($this->form_mode == 'get') {
19237							$action['Flags'] = array('GetMethod');
19238						}
19239						$this->Button($name, $w, $h, $value, $action, $prop, $opt, '', '', false);
19240						break;
19241					}
19242					case 'reset': {
19243						if (!isset($value)) {
19244							$value = 'reset';
19245						}
19246						$w = $this->GetStringWidth($value) * 1.5;
19247						$h *= 1.6;
19248						$prop = array('lineWidth'=>1, 'borderStyle'=>'beveled', 'fillColor'=>array(196, 196, 196), 'strokeColor'=>array(255, 255, 255));
19249						$this->Button($name, $w, $h, $value, array('S'=>'ResetForm'), $prop, $opt, '', '', false);
19250						break;
19251					}
19252					case 'file': {
19253						$prop['fileSelect'] = 'true';
19254						$this->TextField($name, $w, $h, $prop, $opt, '', '', false);
19255						if (!isset($value)) {
19256							$value = '*';
19257						}
19258						$w = $this->GetStringWidth($value) * 2;
19259						$h *= 1.2;
19260						$prop = array('lineWidth'=>1, 'borderStyle'=>'beveled', 'fillColor'=>array(196, 196, 196), 'strokeColor'=>array(255, 255, 255));
19261						$jsaction = 'var f=this.getField(\''.$name.'\'); f.browseForFileToSubmit();';
19262						$this->Button('FB_'.$name, $w, $h, $value, $jsaction, $prop, $opt, '', '', false);
19263						break;
19264					}
19265					case 'hidden': {
19266						if (isset($value)) {
19267							$opt['v'] = $value;
19268						}
19269						$opt['f'] = array('invisible', 'hidden');
19270						$this->TextField($name, 0, 0, $prop, $opt, '', '', false);
19271						break;
19272					}
19273					case 'image': {
19274						// THIS TYPE MUST BE FIXED
19275						if (isset($tag['attribute']['src']) AND !TCPDF_STATIC::empty_string($tag['attribute']['src'])) {
19276							$img = $tag['attribute']['src'];
19277						} else {
19278							break;
19279						}
19280						$value = 'img';
19281						//$opt['mk'] = array('i'=>$img, 'tp'=>1, 'if'=>array('sw'=>'A', 's'=>'A', 'fb'=>false));
19282						if (isset($tag['attribute']['onclick']) AND !empty($tag['attribute']['onclick'])) {
19283							$jsaction = $tag['attribute']['onclick'];
19284						} else {
19285							$jsaction = '';
19286						}
19287						$this->Button($name, $w, $h, $value, $jsaction, $prop, $opt, '', '', false);
19288						break;
19289					}
19290					case 'button': {
19291						if (!isset($value)) {
19292							$value = ' ';
19293						}
19294						$w = $this->GetStringWidth($value) * 1.5;
19295						$h *= 1.6;
19296						$prop = array('lineWidth'=>1, 'borderStyle'=>'beveled', 'fillColor'=>array(196, 196, 196), 'strokeColor'=>array(255, 255, 255));
19297						if (isset($tag['attribute']['onclick']) AND !empty($tag['attribute']['onclick'])) {
19298							$jsaction = $tag['attribute']['onclick'];
19299						} else {
19300							$jsaction = '';
19301						}
19302						$this->Button($name, $w, $h, $value, $jsaction, $prop, $opt, '', '', false);
19303						break;
19304					}
19305				}
19306				break;
19307			}
19308			case 'textarea': {
19309				$prop = array();
19310				$opt = array();
19311				if (isset($tag['attribute']['readonly']) AND !TCPDF_STATIC::empty_string($tag['attribute']['readonly'])) {
19312					$prop['readonly'] = true;
19313				}
19314				if (isset($tag['attribute']['name']) AND !TCPDF_STATIC::empty_string($tag['attribute']['name'])) {
19315					$name = $tag['attribute']['name'];
19316				} else {
19317					break;
19318				}
19319				if (isset($tag['attribute']['value']) AND !TCPDF_STATIC::empty_string($tag['attribute']['value'])) {
19320					$opt['v'] = $tag['attribute']['value'];
19321				}
19322				if (isset($tag['attribute']['cols']) AND !TCPDF_STATIC::empty_string($tag['attribute']['cols'])) {
19323					$w = intval($tag['attribute']['cols']) * $this->GetStringWidth(chr(32)) * 2;
19324				} else {
19325					$w = 40;
19326				}
19327				if (isset($tag['attribute']['rows']) AND !TCPDF_STATIC::empty_string($tag['attribute']['rows'])) {
19328					$h = intval($tag['attribute']['rows']) * $this->getCellHeight($this->FontSize);
19329				} else {
19330					$h = 10;
19331				}
19332				$prop['multiline'] = 'true';
19333				$this->TextField($name, $w, $h, $prop, $opt, '', '', false);
19334				break;
19335			}
19336			case 'select': {
19337				$h = $this->getCellHeight($this->FontSize);
19338				if (isset($tag['attribute']['size']) AND !TCPDF_STATIC::empty_string($tag['attribute']['size'])) {
19339					$h *= ($tag['attribute']['size'] + 1);
19340				}
19341				$prop = array();
19342				$opt = array();
19343				if (isset($tag['attribute']['name']) AND !TCPDF_STATIC::empty_string($tag['attribute']['name'])) {
19344					$name = $tag['attribute']['name'];
19345				} else {
19346					break;
19347				}
19348				$w = 0;
19349				if (isset($tag['attribute']['opt']) AND !TCPDF_STATIC::empty_string($tag['attribute']['opt'])) {
19350					$options = explode('#!NwL!#', $tag['attribute']['opt']);
19351					$values = array();
19352					foreach ($options as $val) {
19353						if (strpos($val, '#!TaB!#') !== false) {
19354							$opts = explode('#!TaB!#', $val);
19355							$values[] = $opts;
19356							$w = max($w, $this->GetStringWidth($opts[1]));
19357						} else {
19358							$values[] = $val;
19359							$w = max($w, $this->GetStringWidth($val));
19360						}
19361					}
19362				} else {
19363					break;
19364				}
19365				$w *= 2;
19366				if (isset($tag['attribute']['multiple']) AND ($tag['attribute']['multiple']='multiple')) {
19367					$prop['multipleSelection'] = 'true';
19368					$this->ListBox($name, $w, $h, $values, $prop, $opt, '', '', false);
19369				} else {
19370					$this->ComboBox($name, $w, $h, $values, $prop, $opt, '', '', false);
19371				}
19372				break;
19373			}
19374			case 'tcpdf': {
19375				if (defined('K_TCPDF_CALLS_IN_HTML') AND (K_TCPDF_CALLS_IN_HTML === true)) {
19376					// Special tag used to call TCPDF methods
19377					if (isset($tag['attribute']['method'])) {
19378						$tcpdf_method = $tag['attribute']['method'];
19379						if (method_exists($this, $tcpdf_method)) {
19380							if (isset($tag['attribute']['params']) AND (!empty($tag['attribute']['params']))) {
19381								$params = $this->unserializeTCPDFtagParameters($tag['attribute']['params']);
19382								call_user_func_array(array($this, $tcpdf_method), $params);
19383							} else {
19384								$this->$tcpdf_method();
19385							}
19386							$this->newline = true;
19387						}
19388					}
19389				}
19390				break;
19391			}
19392			default: {
19393				break;
19394			}
19395		}
19396		// define tags that support borders and background colors
19397		$bordertags = array('blockquote','br','dd','dl','div','dt','h1','h2','h3','h4','h5','h6','hr','li','ol','p','pre','ul','tcpdf','table');
19398		if (in_array($tag['value'], $bordertags)) {
19399			// set border
19400			$dom[$key]['borderposition'] = $this->getBorderStartPosition();
19401		}
19402		if ($dom[$key]['self'] AND isset($dom[$key]['attribute']['pagebreakafter'])) {
19403			$pba = $dom[$key]['attribute']['pagebreakafter'];
19404			// check for pagebreak
19405			if (($pba == 'true') OR ($pba == 'left') OR ($pba == 'right')) {
19406				// add a page (or trig AcceptPageBreak() for multicolumn mode)
19407				$this->checkPageBreak($this->PageBreakTrigger + 1);
19408			}
19409			if ((($pba == 'left') AND (((!$this->rtl) AND (($this->page % 2) == 0)) OR (($this->rtl) AND (($this->page % 2) != 0))))
19410				OR (($pba == 'right') AND (((!$this->rtl) AND (($this->page % 2) != 0)) OR (($this->rtl) AND (($this->page % 2) == 0))))) {
19411				// add a page (or trig AcceptPageBreak() for multicolumn mode)
19412				$this->checkPageBreak($this->PageBreakTrigger + 1);
19413			}
19414		}
19415		return $dom;
19416	}
19417
19418	/**
19419	 * Process closing tags.
19420	 * @param $dom (array) html dom array
19421	 * @param $key (int) current element id
19422	 * @param $cell (boolean) if true add the default left (or right if RTL) padding to each new line (default false).
19423	 * @param $maxbottomliney (int) maximum y value of current line
19424	 * @return $dom array
19425	 * @protected
19426	 */
19427	protected function closeHTMLTagHandler($dom, $key, $cell, $maxbottomliney=0) {
19428		$tag = $dom[$key];
19429		$parent = $dom[($dom[$key]['parent'])];
19430		$lasttag = ((!isset($dom[($key + 1)])) OR ((!isset($dom[($key + 2)])) AND ($dom[($key + 1)]['value'] == 'marker')));
19431		$in_table_head = false;
19432		// maximum x position (used to draw borders)
19433		if ($this->rtl) {
19434			$xmax = $this->w;
19435		} else {
19436			$xmax = 0;
19437		}
19438		if ($tag['block']) {
19439			$hbz = 0; // distance from y to line bottom
19440			$hb = 0; // vertical space between block tags
19441			// calculate vertical space for block tags
19442			if (isset($this->tagvspaces[$tag['value']][1]['h']) && !empty($this->tagvspaces[$tag['value']][1]['h']) && ($this->tagvspaces[$tag['value']][1]['h'] >= 0)) {
19443				$pre_h = $this->tagvspaces[$tag['value']][1]['h'];
19444			} elseif (isset($parent['fontsize'])) {
19445				$pre_h = $this->getCellHeight($parent['fontsize'] / $this->k);
19446			} else {
19447				$pre_h = $this->getCellHeight($this->FontSize);
19448			}
19449			if (isset($this->tagvspaces[$tag['value']][1]['n'])) {
19450				$cn = $this->tagvspaces[$tag['value']][1]['n'];
19451			} elseif (preg_match('/[h][0-9]/', $tag['value']) > 0) {
19452				$cn = 0.6;
19453			} else {
19454				$cn = 1;
19455			}
19456			if ((!isset($this->tagvspaces[$tag['value']])) AND ($tag['value'] == 'div')) {
19457				$hb = 0;
19458			} else {
19459				$hb = ($cn * $pre_h);
19460			}
19461			if ($maxbottomliney > $this->PageBreakTrigger) {
19462				$hbz = $this->getCellHeight($this->FontSize);
19463			} elseif ($this->y < $maxbottomliney) {
19464				$hbz = ($maxbottomliney - $this->y);
19465			}
19466		}
19467		// Closing tag
19468		switch($tag['value']) {
19469			case 'tr': {
19470				$table_el = $dom[($dom[$key]['parent'])]['parent'];
19471				if (!isset($parent['endy'])) {
19472					$dom[($dom[$key]['parent'])]['endy'] = $this->y;
19473					$parent['endy'] = $this->y;
19474				}
19475				if (!isset($parent['endpage'])) {
19476					$dom[($dom[$key]['parent'])]['endpage'] = $this->page;
19477					$parent['endpage'] = $this->page;
19478				}
19479				if (!isset($parent['endcolumn'])) {
19480					$dom[($dom[$key]['parent'])]['endcolumn'] = $this->current_column;
19481					$parent['endcolumn'] = $this->current_column;
19482				}
19483				// update row-spanned cells
19484				if (isset($dom[$table_el]['rowspans'])) {
19485					foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
19486						$dom[$table_el]['rowspans'][$k]['rowspan'] -= 1;
19487						if ($dom[$table_el]['rowspans'][$k]['rowspan'] == 0) {
19488							if (($dom[$table_el]['rowspans'][$k]['endpage'] == $parent['endpage']) AND ($dom[$table_el]['rowspans'][$k]['endcolumn'] == $parent['endcolumn'])) {
19489								$dom[($dom[$key]['parent'])]['endy'] = max($dom[$table_el]['rowspans'][$k]['endy'], $parent['endy']);
19490							} elseif (($dom[$table_el]['rowspans'][$k]['endpage'] > $parent['endpage']) OR ($dom[$table_el]['rowspans'][$k]['endcolumn'] > $parent['endcolumn'])) {
19491								$dom[($dom[$key]['parent'])]['endy'] = $dom[$table_el]['rowspans'][$k]['endy'];
19492								$dom[($dom[$key]['parent'])]['endpage'] = $dom[$table_el]['rowspans'][$k]['endpage'];
19493								$dom[($dom[$key]['parent'])]['endcolumn'] = $dom[$table_el]['rowspans'][$k]['endcolumn'];
19494							}
19495						}
19496					}
19497					// report new endy and endpage to the rowspanned cells
19498					foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
19499						if ($dom[$table_el]['rowspans'][$k]['rowspan'] == 0) {
19500							$dom[$table_el]['rowspans'][$k]['endpage'] = max($dom[$table_el]['rowspans'][$k]['endpage'], $dom[($dom[$key]['parent'])]['endpage']);
19501							$dom[($dom[$key]['parent'])]['endpage'] = $dom[$table_el]['rowspans'][$k]['endpage'];
19502							$dom[$table_el]['rowspans'][$k]['endcolumn'] = max($dom[$table_el]['rowspans'][$k]['endcolumn'], $dom[($dom[$key]['parent'])]['endcolumn']);
19503							$dom[($dom[$key]['parent'])]['endcolumn'] = $dom[$table_el]['rowspans'][$k]['endcolumn'];
19504							$dom[$table_el]['rowspans'][$k]['endy'] = max($dom[$table_el]['rowspans'][$k]['endy'], $dom[($dom[$key]['parent'])]['endy']);
19505							$dom[($dom[$key]['parent'])]['endy'] = $dom[$table_el]['rowspans'][$k]['endy'];
19506						}
19507					}
19508					// update remaining rowspanned cells
19509					foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
19510						if ($dom[$table_el]['rowspans'][$k]['rowspan'] == 0) {
19511							$dom[$table_el]['rowspans'][$k]['endpage'] = $dom[($dom[$key]['parent'])]['endpage'];
19512							$dom[$table_el]['rowspans'][$k]['endcolumn'] = $dom[($dom[$key]['parent'])]['endcolumn'];
19513							$dom[$table_el]['rowspans'][$k]['endy'] = $dom[($dom[$key]['parent'])]['endy'];
19514						}
19515					}
19516				}
19517				$prev_page = $this->page;
19518				$this->setPage($dom[($dom[$key]['parent'])]['endpage']);
19519				if ($this->num_columns > 1) {
19520					if (($prev_page < $this->page)
19521						AND ((($this->current_column == 0) AND ($dom[($dom[$key]['parent'])]['endcolumn'] == ($this->num_columns - 1)))
19522							OR ($this->current_column == $dom[($dom[$key]['parent'])]['endcolumn']))) {
19523						// page jump
19524						$this->selectColumn(0);
19525						$dom[($dom[$key]['parent'])]['endcolumn'] = 0;
19526						$dom[($dom[$key]['parent'])]['endy'] = $this->y;
19527					} else {
19528						$this->selectColumn($dom[($dom[$key]['parent'])]['endcolumn']);
19529						$this->y = $dom[($dom[$key]['parent'])]['endy'];
19530					}
19531				} else {
19532					$this->y = $dom[($dom[$key]['parent'])]['endy'];
19533				}
19534				if (isset($dom[$table_el]['attribute']['cellspacing'])) {
19535					$this->y += $this->getHTMLUnitToUnits($dom[$table_el]['attribute']['cellspacing'], 1, 'px');
19536				} elseif (isset($dom[$table_el]['border-spacing'])) {
19537					$this->y += $dom[$table_el]['border-spacing']['V'];
19538				}
19539				$this->Ln(0, $cell);
19540				if ($this->current_column == $parent['startcolumn']) {
19541					$this->x = $parent['startx'];
19542				}
19543				// account for booklet mode
19544				if ($this->page > $parent['startpage']) {
19545					if (($this->rtl) AND ($this->pagedim[$this->page]['orm'] != $this->pagedim[$parent['startpage']]['orm'])) {
19546						$this->x -= ($this->pagedim[$this->page]['orm'] - $this->pagedim[$parent['startpage']]['orm']);
19547					} elseif ((!$this->rtl) AND ($this->pagedim[$this->page]['olm'] != $this->pagedim[$parent['startpage']]['olm'])) {
19548						$this->x += ($this->pagedim[$this->page]['olm'] - $this->pagedim[$parent['startpage']]['olm']);
19549					}
19550				}
19551				break;
19552			}
19553			case 'tablehead':
19554				// closing tag used for the thead part
19555				$in_table_head = true;
19556				$this->inthead = false;
19557			case 'table': {
19558				$table_el = $parent;
19559				// set default border
19560				if (isset($table_el['attribute']['border']) AND ($table_el['attribute']['border'] > 0)) {
19561					// set default border
19562					$border = array('LTRB' => array('width' => $this->getCSSBorderWidth($table_el['attribute']['border']), 'cap'=>'square', 'join'=>'miter', 'dash'=> 0, 'color'=>array(0,0,0)));
19563				} else {
19564					$border = 0;
19565				}
19566				$default_border = $border;
19567				// fix bottom line alignment of last line before page break
19568				foreach ($dom[($dom[$key]['parent'])]['trids'] as $j => $trkey) {
19569					// update row-spanned cells
19570					if (isset($dom[($dom[$key]['parent'])]['rowspans'])) {
19571						foreach ($dom[($dom[$key]['parent'])]['rowspans'] as $k => $trwsp) {
19572							if (isset($prevtrkey) AND ($trwsp['trid'] == $prevtrkey) AND ($trwsp['mrowspan'] > 0)) {
19573								$dom[($dom[$key]['parent'])]['rowspans'][$k]['trid'] = $trkey;
19574							}
19575							if ($dom[($dom[$key]['parent'])]['rowspans'][$k]['trid'] == $trkey) {
19576								$dom[($dom[$key]['parent'])]['rowspans'][$k]['mrowspan'] -= 1;
19577							}
19578						}
19579					}
19580					if (isset($prevtrkey) AND ($dom[$trkey]['startpage'] > $dom[$prevtrkey]['endpage'])) {
19581						$pgendy = $this->pagedim[$dom[$prevtrkey]['endpage']]['hk'] - $this->pagedim[$dom[$prevtrkey]['endpage']]['bm'];
19582						$dom[$prevtrkey]['endy'] = $pgendy;
19583						// update row-spanned cells
19584						if (isset($dom[($dom[$key]['parent'])]['rowspans'])) {
19585							foreach ($dom[($dom[$key]['parent'])]['rowspans'] as $k => $trwsp) {
19586								if (($trwsp['trid'] == $prevtrkey) AND ($trwsp['mrowspan'] >= 0) AND ($trwsp['endpage'] == $dom[$prevtrkey]['endpage'])) {
19587									$dom[($dom[$key]['parent'])]['rowspans'][$k]['endy'] = $pgendy;
19588									$dom[($dom[$key]['parent'])]['rowspans'][$k]['mrowspan'] = -1;
19589								}
19590							}
19591						}
19592					}
19593					$prevtrkey = $trkey;
19594					$table_el = $dom[($dom[$key]['parent'])];
19595				}
19596				// for each row
19597				if (count($table_el['trids']) > 0) {
19598					unset($xmax);
19599				}
19600				foreach ($table_el['trids'] as $j => $trkey) {
19601					$parent = $dom[$trkey];
19602					if (!isset($xmax)) {
19603						$xmax = $parent['cellpos'][(count($parent['cellpos']) - 1)]['endx'];
19604					}
19605					// for each cell on the row
19606					foreach ($parent['cellpos'] as $k => $cellpos) {
19607						if (isset($cellpos['rowspanid']) AND ($cellpos['rowspanid'] >= 0)) {
19608							$cellpos['startx'] = $table_el['rowspans'][($cellpos['rowspanid'])]['startx'];
19609							$cellpos['endx'] = $table_el['rowspans'][($cellpos['rowspanid'])]['endx'];
19610							$endy = $table_el['rowspans'][($cellpos['rowspanid'])]['endy'];
19611							$startpage = $table_el['rowspans'][($cellpos['rowspanid'])]['startpage'];
19612							$endpage = $table_el['rowspans'][($cellpos['rowspanid'])]['endpage'];
19613							$startcolumn = $table_el['rowspans'][($cellpos['rowspanid'])]['startcolumn'];
19614							$endcolumn = $table_el['rowspans'][($cellpos['rowspanid'])]['endcolumn'];
19615						} else {
19616							$endy = $parent['endy'];
19617							$startpage = $parent['startpage'];
19618							$endpage = $parent['endpage'];
19619							$startcolumn = $parent['startcolumn'];
19620							$endcolumn = $parent['endcolumn'];
19621						}
19622						if ($this->num_columns == 0) {
19623							$this->num_columns = 1;
19624						}
19625						if (isset($cellpos['border'])) {
19626							$border = $cellpos['border'];
19627						}
19628						if (isset($cellpos['bgcolor']) AND ($cellpos['bgcolor']) !== false) {
19629							$this->SetFillColorArray($cellpos['bgcolor']);
19630							$fill = true;
19631						} else {
19632							$fill = false;
19633						}
19634						$x = $cellpos['startx'];
19635						$y = $parent['starty'];
19636						$starty = $y;
19637						$w = abs($cellpos['endx'] - $cellpos['startx']);
19638						// get border modes
19639						$border_start = TCPDF_STATIC::getBorderMode($border, $position='start', $this->opencell);
19640						$border_end = TCPDF_STATIC::getBorderMode($border, $position='end', $this->opencell);
19641						$border_middle = TCPDF_STATIC::getBorderMode($border, $position='middle', $this->opencell);
19642						// design borders around HTML cells.
19643						for ($page = $startpage; $page <= $endpage; ++$page) { // for each page
19644							$ccode = '';
19645							$this->setPage($page);
19646							if ($this->num_columns < 2) {
19647								// single-column mode
19648								$this->x = $x;
19649								$this->y = $this->tMargin;
19650							}
19651							// account for margin changes
19652							if ($page > $startpage) {
19653								if (($this->rtl) AND ($this->pagedim[$page]['orm'] != $this->pagedim[$startpage]['orm'])) {
19654									$this->x -= ($this->pagedim[$page]['orm'] - $this->pagedim[$startpage]['orm']);
19655								} elseif ((!$this->rtl) AND ($this->pagedim[$page]['olm'] != $this->pagedim[$startpage]['olm'])) {
19656									$this->x += ($this->pagedim[$page]['olm'] - $this->pagedim[$startpage]['olm']);
19657								}
19658							}
19659							if ($startpage == $endpage) { // single page
19660								$deltacol = 0;
19661								$deltath = 0;
19662								for ($column = $startcolumn; $column <= $endcolumn; ++$column) { // for each column
19663									$this->selectColumn($column);
19664									if ($startcolumn == $endcolumn) { // single column
19665										$cborder = $border;
19666										$h = $endy - $parent['starty'];
19667										$this->y = $y;
19668										$this->x = $x;
19669									} elseif ($column == $startcolumn) { // first column
19670										$cborder = $border_start;
19671										$this->y = $starty;
19672										$this->x = $x;
19673										$h = $this->h - $this->y - $this->bMargin;
19674										if ($this->rtl) {
19675											$deltacol = $this->x + $this->rMargin - $this->w;
19676										} else {
19677											$deltacol = $this->x - $this->lMargin;
19678										}
19679									} elseif ($column == $endcolumn) { // end column
19680										$cborder = $border_end;
19681										if (isset($this->columns[$column]['th']['\''.$page.'\''])) {
19682											$this->y = $this->columns[$column]['th']['\''.$page.'\''];
19683										}
19684										$this->x += $deltacol;
19685										$h = $endy - $this->y;
19686									} else { // middle column
19687										$cborder = $border_middle;
19688										if (isset($this->columns[$column]['th']['\''.$page.'\''])) {
19689											$this->y = $this->columns[$column]['th']['\''.$page.'\''];
19690										}
19691										$this->x += $deltacol;
19692										$h = $this->h - $this->y - $this->bMargin;
19693									}
19694									$ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
19695								} // end for each column
19696							} elseif ($page == $startpage) { // first page
19697								$deltacol = 0;
19698								$deltath = 0;
19699								for ($column = $startcolumn; $column < $this->num_columns; ++$column) { // for each column
19700									$this->selectColumn($column);
19701									if ($column == $startcolumn) { // first column
19702										$cborder = $border_start;
19703										$this->y = $starty;
19704										$this->x = $x;
19705										$h = $this->h - $this->y - $this->bMargin;
19706										if ($this->rtl) {
19707											$deltacol = $this->x + $this->rMargin - $this->w;
19708										} else {
19709											$deltacol = $this->x - $this->lMargin;
19710										}
19711									} else { // middle column
19712										$cborder = $border_middle;
19713										if (isset($this->columns[$column]['th']['\''.$page.'\''])) {
19714											$this->y = $this->columns[$column]['th']['\''.$page.'\''];
19715										}
19716										$this->x += $deltacol;
19717										$h = $this->h - $this->y - $this->bMargin;
19718									}
19719									$ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
19720								} // end for each column
19721							} elseif ($page == $endpage) { // last page
19722								$deltacol = 0;
19723								$deltath = 0;
19724								for ($column = 0; $column <= $endcolumn; ++$column) { // for each column
19725									$this->selectColumn($column);
19726									if ($column == $endcolumn) { // end column
19727										$cborder = $border_end;
19728										if (isset($this->columns[$column]['th']['\''.$page.'\''])) {
19729											$this->y = $this->columns[$column]['th']['\''.$page.'\''];
19730										}
19731										$this->x += $deltacol;
19732										$h = $endy - $this->y;
19733									} else { // middle column
19734										$cborder = $border_middle;
19735										if (isset($this->columns[$column]['th']['\''.$page.'\''])) {
19736											$this->y = $this->columns[$column]['th']['\''.$page.'\''];
19737										}
19738										$this->x += $deltacol;
19739										$h = $this->h - $this->y - $this->bMargin;
19740									}
19741									$ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
19742								} // end for each column
19743							} else { // middle page
19744								$deltacol = 0;
19745								$deltath = 0;
19746								for ($column = 0; $column < $this->num_columns; ++$column) { // for each column
19747									$this->selectColumn($column);
19748									$cborder = $border_middle;
19749									if (isset($this->columns[$column]['th']['\''.$page.'\''])) {
19750										$this->y = $this->columns[$column]['th']['\''.$page.'\''];
19751									}
19752									$this->x += $deltacol;
19753									$h = $this->h - $this->y - $this->bMargin;
19754									$ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
19755								} // end for each column
19756							}
19757							if (!empty($cborder) OR !empty($fill)) {
19758								$offsetlen = strlen($ccode);
19759								// draw border and fill
19760								if ($this->inxobj) {
19761									// we are inside an XObject template
19762									if (end($this->xobjects[$this->xobjid]['transfmrk']) !== false) {
19763										$pagemarkkey = key($this->xobjects[$this->xobjid]['transfmrk']);
19764										$pagemark = $this->xobjects[$this->xobjid]['transfmrk'][$pagemarkkey];
19765										$this->xobjects[$this->xobjid]['transfmrk'][$pagemarkkey] += $offsetlen;
19766									} else {
19767										$pagemark = $this->xobjects[$this->xobjid]['intmrk'];
19768										$this->xobjects[$this->xobjid]['intmrk'] += $offsetlen;
19769									}
19770									$pagebuff = $this->xobjects[$this->xobjid]['outdata'];
19771									$pstart = substr($pagebuff, 0, $pagemark);
19772									$pend = substr($pagebuff, $pagemark);
19773									$this->xobjects[$this->xobjid]['outdata'] = $pstart.$ccode.$pend;
19774								} else {
19775									// draw border and fill
19776									if (end($this->transfmrk[$this->page]) !== false) {
19777										$pagemarkkey = key($this->transfmrk[$this->page]);
19778										$pagemark = $this->transfmrk[$this->page][$pagemarkkey];
19779									} elseif ($this->InFooter) {
19780										$pagemark = $this->footerpos[$this->page];
19781									} else {
19782										$pagemark = $this->intmrk[$this->page];
19783									}
19784									$pagebuff = $this->getPageBuffer($this->page);
19785									$pstart = substr($pagebuff, 0, $pagemark);
19786									$pend = substr($pagebuff, $pagemark);
19787									$this->setPageBuffer($this->page, $pstart.$ccode.$pend);
19788								}
19789							}
19790						} // end for each page
19791						// restore default border
19792						$border = $default_border;
19793					} // end for each cell on the row
19794					if (isset($table_el['attribute']['cellspacing'])) {
19795						$this->y += $this->getHTMLUnitToUnits($table_el['attribute']['cellspacing'], 1, 'px');
19796					} elseif (isset($table_el['border-spacing'])) {
19797						$this->y += $table_el['border-spacing']['V'];
19798					}
19799					$this->Ln(0, $cell);
19800					$this->x = $parent['startx'];
19801					if ($endpage > $startpage) {
19802						if (($this->rtl) AND ($this->pagedim[$endpage]['orm'] != $this->pagedim[$startpage]['orm'])) {
19803							$this->x += ($this->pagedim[$endpage]['orm'] - $this->pagedim[$startpage]['orm']);
19804						} elseif ((!$this->rtl) AND ($this->pagedim[$endpage]['olm'] != $this->pagedim[$startpage]['olm'])) {
19805							$this->x += ($this->pagedim[$endpage]['olm'] - $this->pagedim[$startpage]['olm']);
19806						}
19807					}
19808				}
19809				if (!$in_table_head) { // we are not inside a thead section
19810					$this->cell_padding = $table_el['old_cell_padding'];
19811					// reset row height
19812					$this->resetLastH();
19813					if (($this->page == ($this->numpages - 1)) AND ($this->pageopen[$this->numpages])) {
19814						$plendiff = ($this->pagelen[$this->numpages] - $this->emptypagemrk[$this->numpages]);
19815						if (($plendiff > 0) AND ($plendiff < 60)) {
19816							$pagediff = substr($this->getPageBuffer($this->numpages), $this->emptypagemrk[$this->numpages], $plendiff);
19817							if (substr($pagediff, 0, 5) == 'BT /F') {
19818								// the difference is only a font setting
19819								$plendiff = 0;
19820							}
19821						}
19822						if ($plendiff == 0) {
19823							// remove last blank page
19824							$this->deletePage($this->numpages);
19825						}
19826					}
19827					if (isset($this->theadMargins['top'])) {
19828						// restore top margin
19829						$this->tMargin = $this->theadMargins['top'];
19830					}
19831					if (!isset($table_el['attribute']['nested']) OR ($table_el['attribute']['nested'] != 'true')) {
19832						// reset main table header
19833						$this->thead = '';
19834						$this->theadMargins = array();
19835						$this->pagedim[$this->page]['tm'] = $this->tMargin;
19836					}
19837				}
19838				$parent = $table_el;
19839				break;
19840			}
19841			case 'a': {
19842				$this->HREF = array();
19843				break;
19844			}
19845			case 'sup': {
19846				$this->SetXY($this->GetX(), $this->GetY() + ((0.7 * $parent['fontsize']) / $this->k));
19847				break;
19848			}
19849			case 'sub': {
19850				$this->SetXY($this->GetX(), $this->GetY() - ((0.3 * $parent['fontsize']) / $this->k));
19851				break;
19852			}
19853			case 'div': {
19854				$this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
19855				break;
19856			}
19857			case 'blockquote': {
19858				if ($this->rtl) {
19859					$this->rMargin -= $this->listindent;
19860				} else {
19861					$this->lMargin -= $this->listindent;
19862				}
19863				--$this->listindentlevel;
19864				$this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
19865				break;
19866			}
19867			case 'p': {
19868				$this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
19869				break;
19870			}
19871			case 'pre': {
19872				$this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
19873				$this->premode = false;
19874				break;
19875			}
19876			case 'dl': {
19877				--$this->listnum;
19878				if ($this->listnum <= 0) {
19879					$this->listnum = 0;
19880					$this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
19881				} else {
19882					$this->addHTMLVertSpace(0, 0, $cell, false, $lasttag);
19883				}
19884				$this->resetLastH();
19885				break;
19886			}
19887			case 'dt': {
19888				$this->lispacer = '';
19889				$this->addHTMLVertSpace(0, 0, $cell, false, $lasttag);
19890				break;
19891			}
19892			case 'dd': {
19893				$this->lispacer = '';
19894				if ($this->rtl) {
19895					$this->rMargin -= $this->listindent;
19896				} else {
19897					$this->lMargin -= $this->listindent;
19898				}
19899				--$this->listindentlevel;
19900				$this->addHTMLVertSpace(0, 0, $cell, false, $lasttag);
19901				break;
19902			}
19903			case 'ul':
19904			case 'ol': {
19905				--$this->listnum;
19906				$this->lispacer = '';
19907				if ($this->rtl) {
19908					$this->rMargin -= $this->listindent;
19909				} else {
19910					$this->lMargin -= $this->listindent;
19911				}
19912				--$this->listindentlevel;
19913				if ($this->listnum <= 0) {
19914					$this->listnum = 0;
19915					$this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
19916				} else {
19917					$this->addHTMLVertSpace(0, 0, $cell, false, $lasttag);
19918				}
19919				$this->resetLastH();
19920				break;
19921			}
19922			case 'li': {
19923				$this->lispacer = '';
19924				$this->addHTMLVertSpace(0, 0, $cell, false, $lasttag);
19925				break;
19926			}
19927			case 'h1':
19928			case 'h2':
19929			case 'h3':
19930			case 'h4':
19931			case 'h5':
19932			case 'h6': {
19933				$this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
19934				break;
19935			}
19936			// Form fields (since 4.8.000 - 2009-09-07)
19937			case 'form': {
19938				$this->form_action = '';
19939				$this->form_enctype = 'application/x-www-form-urlencoded';
19940				break;
19941			}
19942			default : {
19943				break;
19944			}
19945		}
19946		// draw border and background (if any)
19947		$this->drawHTMLTagBorder($parent, $xmax);
19948		if (isset($dom[($dom[$key]['parent'])]['attribute']['pagebreakafter'])) {
19949			$pba = $dom[($dom[$key]['parent'])]['attribute']['pagebreakafter'];
19950			// check for pagebreak
19951			if (($pba == 'true') OR ($pba == 'left') OR ($pba == 'right')) {
19952				// add a page (or trig AcceptPageBreak() for multicolumn mode)
19953				$this->checkPageBreak($this->PageBreakTrigger + 1);
19954			}
19955			if ((($pba == 'left') AND (((!$this->rtl) AND (($this->page % 2) == 0)) OR (($this->rtl) AND (($this->page % 2) != 0))))
19956				OR (($pba == 'right') AND (((!$this->rtl) AND (($this->page % 2) != 0)) OR (($this->rtl) AND (($this->page % 2) == 0))))) {
19957				// add a page (or trig AcceptPageBreak() for multicolumn mode)
19958				$this->checkPageBreak($this->PageBreakTrigger + 1);
19959			}
19960		}
19961		$this->tmprtl = false;
19962		return $dom;
19963	}
19964
19965	/**
19966	 * Add vertical spaces if needed.
19967	 * @param $hbz (string) Distance between current y and line bottom.
19968	 * @param $hb (string) The height of the break.
19969	 * @param $cell (boolean) if true add the default left (or right if RTL) padding to each new line (default false).
19970	 * @param $firsttag (boolean) set to true when the tag is the first.
19971	 * @param $lasttag (boolean) set to true when the tag is the last.
19972	 * @protected
19973	 */
19974	protected function addHTMLVertSpace($hbz=0, $hb=0, $cell=false, $firsttag=false, $lasttag=false) {
19975		if ($firsttag) {
19976			$this->Ln(0, $cell);
19977			$this->htmlvspace = 0;
19978			return;
19979		}
19980		if ($lasttag) {
19981			$this->Ln($hbz, $cell);
19982			$this->htmlvspace = 0;
19983			return;
19984		}
19985		if ($hb < $this->htmlvspace) {
19986			$hd = 0;
19987		} else {
19988			$hd = $hb - $this->htmlvspace;
19989			$this->htmlvspace = $hb;
19990		}
19991		$this->Ln(($hbz + $hd), $cell);
19992	}
19993
19994	/**
19995	 * Return the starting coordinates to draw an html border
19996	 * @return array containing top-left border coordinates
19997	 * @protected
19998	 * @since 5.7.000 (2010-08-03)
19999	 */
20000	protected function getBorderStartPosition() {
20001		if ($this->rtl) {
20002			$xmax = $this->lMargin;
20003		} else {
20004			$xmax = $this->w - $this->rMargin;
20005		}
20006		return array('page' => $this->page, 'column' => $this->current_column, 'x' => $this->x, 'y' => $this->y, 'xmax' => $xmax);
20007	}
20008
20009	/**
20010	 * Draw an HTML block border and fill
20011	 * @param $tag (array) array of tag properties.
20012	 * @param $xmax (int) end X coordinate for border.
20013	 * @protected
20014	 * @since 5.7.000 (2010-08-03)
20015	 */
20016	protected function drawHTMLTagBorder($tag, $xmax) {
20017		if (!isset($tag['borderposition'])) {
20018			// nothing to draw
20019			return;
20020		}
20021		$prev_x = $this->x;
20022		$prev_y = $this->y;
20023		$prev_lasth = $this->lasth;
20024		$border = 0;
20025		$fill = false;
20026		$this->lasth = 0;
20027		if (isset($tag['border']) AND !empty($tag['border'])) {
20028			// get border style
20029			$border = $tag['border'];
20030			if (!TCPDF_STATIC::empty_string($this->thead) AND (!$this->inthead)) {
20031				// border for table header
20032				$border = TCPDF_STATIC::getBorderMode($border, $position='middle', $this->opencell);
20033			}
20034		}
20035		if (isset($tag['bgcolor']) AND ($tag['bgcolor'] !== false)) {
20036			// get background color
20037			$old_bgcolor = $this->bgcolor;
20038			$this->SetFillColorArray($tag['bgcolor']);
20039			$fill = true;
20040		}
20041		if (!$border AND !$fill) {
20042			// nothing to draw
20043			return;
20044		}
20045		if (isset($tag['attribute']['cellspacing'])) {
20046			$clsp = $this->getHTMLUnitToUnits($tag['attribute']['cellspacing'], 1, 'px');
20047			$cellspacing = array('H' => $clsp, 'V' => $clsp);
20048		} elseif (isset($tag['border-spacing'])) {
20049			$cellspacing = $tag['border-spacing'];
20050		} else {
20051			$cellspacing = array('H' => 0, 'V' => 0);
20052		}
20053		if (($tag['value'] != 'table') AND (is_array($border)) AND (!empty($border))) {
20054			// draw the border externally respect the sqare edge.
20055			$border['mode'] = 'ext';
20056		}
20057		if ($this->rtl) {
20058			if ($xmax >= $tag['borderposition']['x']) {
20059				$xmax = $tag['borderposition']['xmax'];
20060			}
20061			$w = ($tag['borderposition']['x'] - $xmax);
20062		} else {
20063			if ($xmax <= $tag['borderposition']['x']) {
20064				$xmax = $tag['borderposition']['xmax'];
20065			}
20066			$w = ($xmax - $tag['borderposition']['x']);
20067		}
20068		if ($w <= 0) {
20069			return;
20070		}
20071		$w += $cellspacing['H'];
20072		$startpage = $tag['borderposition']['page'];
20073		$startcolumn = $tag['borderposition']['column'];
20074		$x = $tag['borderposition']['x'];
20075		$y = $tag['borderposition']['y'];
20076		$endpage = $this->page;
20077		$starty = $tag['borderposition']['y'] - $cellspacing['V'];
20078		$currentY = $this->y;
20079		$this->x = $x;
20080		// get latest column
20081		$endcolumn = $this->current_column;
20082		if ($this->num_columns == 0) {
20083			$this->num_columns = 1;
20084		}
20085		// get border modes
20086		$border_start = TCPDF_STATIC::getBorderMode($border, $position='start', $this->opencell);
20087		$border_end = TCPDF_STATIC::getBorderMode($border, $position='end', $this->opencell);
20088		$border_middle = TCPDF_STATIC::getBorderMode($border, $position='middle', $this->opencell);
20089		// temporary disable page regions
20090		$temp_page_regions = $this->page_regions;
20091		$this->page_regions = array();
20092		// design borders around HTML cells.
20093		for ($page = $startpage; $page <= $endpage; ++$page) { // for each page
20094			$ccode = '';
20095			$this->setPage($page);
20096			if ($this->num_columns < 2) {
20097				// single-column mode
20098				$this->x = $x;
20099				$this->y = $this->tMargin;
20100			}
20101			// account for margin changes
20102			if ($page > $startpage) {
20103				if (($this->rtl) AND ($this->pagedim[$page]['orm'] != $this->pagedim[$startpage]['orm'])) {
20104					$this->x -= ($this->pagedim[$page]['orm'] - $this->pagedim[$startpage]['orm']);
20105				} elseif ((!$this->rtl) AND ($this->pagedim[$page]['olm'] != $this->pagedim[$startpage]['olm'])) {
20106					$this->x += ($this->pagedim[$page]['olm'] - $this->pagedim[$startpage]['olm']);
20107				}
20108			}
20109			if ($startpage == $endpage) {
20110				// single page
20111				for ($column = $startcolumn; $column <= $endcolumn; ++$column) { // for each column
20112					$this->selectColumn($column);
20113					if ($startcolumn == $endcolumn) { // single column
20114						$cborder = $border;
20115						$h = ($currentY - $y) + $cellspacing['V'];
20116						$this->y = $starty;
20117					} elseif ($column == $startcolumn) { // first column
20118						$cborder = $border_start;
20119						$this->y = $starty;
20120						$h = $this->h - $this->y - $this->bMargin;
20121					} elseif ($column == $endcolumn) { // end column
20122						$cborder = $border_end;
20123						$h = $currentY - $this->y;
20124					} else { // middle column
20125						$cborder = $border_middle;
20126						$h = $this->h - $this->y - $this->bMargin;
20127					}
20128					$ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
20129				} // end for each column
20130			} elseif ($page == $startpage) { // first page
20131				for ($column = $startcolumn; $column < $this->num_columns; ++$column) { // for each column
20132					$this->selectColumn($column);
20133					if ($column == $startcolumn) { // first column
20134						$cborder = $border_start;
20135						$this->y = $starty;
20136						$h = $this->h - $this->y - $this->bMargin;
20137					} else { // middle column
20138						$cborder = $border_middle;
20139						$h = $this->h - $this->y - $this->bMargin;
20140					}
20141					$ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
20142				} // end for each column
20143			} elseif ($page == $endpage) { // last page
20144				for ($column = 0; $column <= $endcolumn; ++$column) { // for each column
20145					$this->selectColumn($column);
20146					if ($column == $endcolumn) {
20147						// end column
20148						$cborder = $border_end;
20149						$h = $currentY - $this->y;
20150					} else {
20151						// middle column
20152						$cborder = $border_middle;
20153						$h = $this->h - $this->y - $this->bMargin;
20154					}
20155					$ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
20156				} // end for each column
20157			} else { // middle page
20158				for ($column = 0; $column < $this->num_columns; ++$column) { // for each column
20159					$this->selectColumn($column);
20160					$cborder = $border_middle;
20161					$h = $this->h - $this->y - $this->bMargin;
20162					$ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
20163				} // end for each column
20164			}
20165			if ($cborder OR $fill) {
20166				$offsetlen = strlen($ccode);
20167				// draw border and fill
20168				if ($this->inxobj) {
20169					// we are inside an XObject template
20170					if (end($this->xobjects[$this->xobjid]['transfmrk']) !== false) {
20171						$pagemarkkey = key($this->xobjects[$this->xobjid]['transfmrk']);
20172						$pagemark = $this->xobjects[$this->xobjid]['transfmrk'][$pagemarkkey];
20173						$this->xobjects[$this->xobjid]['transfmrk'][$pagemarkkey] += $offsetlen;
20174					} else {
20175						$pagemark = $this->xobjects[$this->xobjid]['intmrk'];
20176						$this->xobjects[$this->xobjid]['intmrk'] += $offsetlen;
20177					}
20178					$pagebuff = $this->xobjects[$this->xobjid]['outdata'];
20179					$pstart = substr($pagebuff, 0, $pagemark);
20180					$pend = substr($pagebuff, $pagemark);
20181					$this->xobjects[$this->xobjid]['outdata'] = $pstart.$ccode.$pend;
20182				} else {
20183					if (end($this->transfmrk[$this->page]) !== false) {
20184						$pagemarkkey = key($this->transfmrk[$this->page]);
20185						$pagemark = $this->transfmrk[$this->page][$pagemarkkey];
20186					} elseif ($this->InFooter) {
20187						$pagemark = $this->footerpos[$this->page];
20188					} else {
20189						$pagemark = $this->intmrk[$this->page];
20190					}
20191					$pagebuff = $this->getPageBuffer($this->page);
20192					$pstart = substr($pagebuff, 0, $pagemark);
20193					$pend = substr($pagebuff, $pagemark);
20194					$this->setPageBuffer($this->page, $pstart.$ccode.$pend);
20195					$this->bordermrk[$this->page] += $offsetlen;
20196					$this->cntmrk[$this->page] += $offsetlen;
20197				}
20198			}
20199		} // end for each page
20200		// restore page regions
20201		$this->page_regions = $temp_page_regions;
20202		if (isset($old_bgcolor)) {
20203			// restore background color
20204			$this->SetFillColorArray($old_bgcolor);
20205		}
20206		// restore pointer position
20207		$this->x = $prev_x;
20208		$this->y = $prev_y;
20209		$this->lasth = $prev_lasth;
20210	}
20211
20212	/**
20213	 * Set the default bullet to be used as LI bullet symbol
20214	 * @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')
20215	 * @public
20216	 * @since 4.0.028 (2008-09-26)
20217	 */
20218	public function setLIsymbol($symbol='!') {
20219		// check for custom image symbol
20220		if (substr($symbol, 0, 4) == 'img|') {
20221			$this->lisymbol = $symbol;
20222			return;
20223		}
20224		$symbol = strtolower($symbol);
20225		$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');
20226		if (in_array($symbol, $valid_symbols)) {
20227			$this->lisymbol = $symbol;
20228		} else {
20229			$this->lisymbol = '';
20230		}
20231	}
20232
20233	/**
20234	 * Set the booklet mode for double-sided pages.
20235	 * @param $booklet (boolean) true set the booklet mode on, false otherwise.
20236	 * @param $inner (float) Inner page margin.
20237	 * @param $outer (float) Outer page margin.
20238	 * @public
20239	 * @since 4.2.000 (2008-10-29)
20240	 */
20241	public function SetBooklet($booklet=true, $inner=-1, $outer=-1) {
20242		$this->booklet = $booklet;
20243		if ($inner >= 0) {
20244			$this->lMargin = $inner;
20245		}
20246		if ($outer >= 0) {
20247			$this->rMargin = $outer;
20248		}
20249	}
20250
20251	/**
20252	 * Swap the left and right margins.
20253	 * @param $reverse (boolean) if true swap left and right margins.
20254	 * @protected
20255	 * @since 4.2.000 (2008-10-29)
20256	 */
20257	protected function swapMargins($reverse=true) {
20258		if ($reverse) {
20259			// swap left and right margins
20260			$mtemp = $this->original_lMargin;
20261			$this->original_lMargin = $this->original_rMargin;
20262			$this->original_rMargin = $mtemp;
20263			$deltam = $this->original_lMargin - $this->original_rMargin;
20264			$this->lMargin += $deltam;
20265			$this->rMargin -= $deltam;
20266		}
20267	}
20268
20269	/**
20270	 * Set the vertical spaces for HTML tags.
20271	 * The array must have the following structure (example):
20272	 * $tagvs = array('h1' => array(0 => array('h' => '', 'n' => 2), 1 => array('h' => 1.3, 'n' => 1)));
20273	 * The first array level contains the tag names,
20274	 * the second level contains 0 for opening tags or 1 for closing tags,
20275	 * the third level contains the vertical space unit (h) and the number spaces to add (n).
20276	 * If the h parameter is not specified, default values are used.
20277	 * @param $tagvs (array) array of tags and relative vertical spaces.
20278	 * @public
20279	 * @since 4.2.001 (2008-10-30)
20280	 */
20281	public function setHtmlVSpace($tagvs) {
20282		$this->tagvspaces = $tagvs;
20283	}
20284
20285	/**
20286	 * Set custom width for list indentation.
20287	 * @param $width (float) width of the indentation. Use negative value to disable it.
20288	 * @public
20289	 * @since 4.2.007 (2008-11-12)
20290	 */
20291	public function setListIndentWidth($width) {
20292		return $this->customlistindent = floatval($width);
20293	}
20294
20295	/**
20296	 * Set the top/bottom cell sides to be open or closed when the cell cross the page.
20297	 * @param $isopen (boolean) if true keeps the top/bottom border open for the cell sides that cross the page.
20298	 * @public
20299	 * @since 4.2.010 (2008-11-14)
20300	 */
20301	public function setOpenCell($isopen) {
20302		$this->opencell = $isopen;
20303	}
20304
20305	/**
20306	 * Set the color and font style for HTML links.
20307	 * @param $color (array) RGB array of colors
20308	 * @param $fontstyle (string) additional font styles to add
20309	 * @public
20310	 * @since 4.4.003 (2008-12-09)
20311	 */
20312	public function setHtmlLinksStyle($color=array(0,0,255), $fontstyle='U') {
20313		$this->htmlLinkColorArray = $color;
20314		$this->htmlLinkFontStyle = $fontstyle;
20315	}
20316
20317	/**
20318	 * Convert HTML string containing value and unit of measure to user's units or points.
20319	 * @param $htmlval (string) String containing values and unit.
20320	 * @param $refsize (string) Reference value in points.
20321	 * @param $defaultunit (string) Default unit (can be one of the following: %, em, ex, px, in, mm, pc, pt).
20322	 * @param $points (boolean) If true returns points, otherwise returns value in user's units.
20323	 * @return float value in user's unit or point if $points=true
20324	 * @public
20325	 * @since 4.4.004 (2008-12-10)
20326	 */
20327	public function getHTMLUnitToUnits($htmlval, $refsize=1, $defaultunit='px', $points=false) {
20328		$supportedunits = array('%', 'em', 'ex', 'px', 'in', 'cm', 'mm', 'pc', 'pt');
20329		$retval = 0;
20330		$value = 0;
20331		$unit = 'px';
20332		if ($points) {
20333			$k = 1;
20334		} else {
20335			$k = $this->k;
20336		}
20337		if (in_array($defaultunit, $supportedunits)) {
20338			$unit = $defaultunit;
20339		}
20340		if (is_numeric($htmlval)) {
20341			$value = floatval($htmlval);
20342		} elseif (preg_match('/([0-9\.\-\+]+)/', $htmlval, $mnum)) {
20343			$value = floatval($mnum[1]);
20344			if (preg_match('/([a-z%]+)/', $htmlval, $munit)) {
20345				if (in_array($munit[1], $supportedunits)) {
20346					$unit = $munit[1];
20347				}
20348			}
20349		}
20350		switch ($unit) {
20351			// percentage
20352			case '%': {
20353				$retval = (($value * $refsize) / 100);
20354				break;
20355			}
20356			// relative-size
20357			case 'em': {
20358				$retval = ($value * $refsize);
20359				break;
20360			}
20361			// height of lower case 'x' (about half the font-size)
20362			case 'ex': {
20363				$retval = ($value * ($refsize / 2));
20364				break;
20365			}
20366			// absolute-size
20367			case 'in': {
20368				$retval = (($value * $this->dpi) / $k);
20369				break;
20370			}
20371			// centimeters
20372			case 'cm': {
20373				$retval = (($value / 2.54 * $this->dpi) / $k);
20374				break;
20375			}
20376			// millimeters
20377			case 'mm': {
20378				$retval = (($value / 25.4 * $this->dpi) / $k);
20379				break;
20380			}
20381			// one pica is 12 points
20382			case 'pc': {
20383				$retval = (($value * 12) / $k);
20384				break;
20385			}
20386			// points
20387			case 'pt': {
20388				$retval = ($value / $k);
20389				break;
20390			}
20391			// pixels
20392			case 'px': {
20393				$retval = $this->pixelsToUnits($value);
20394				if ($points) {
20395					$retval *= $this->k;
20396				}
20397				break;
20398			}
20399		}
20400		return $retval;
20401	}
20402
20403	/**
20404	 * Output an HTML list bullet or ordered item symbol
20405	 * @param $listdepth (int) list nesting level
20406	 * @param $listtype (string) type of list
20407	 * @param $size (float) current font size
20408	 * @protected
20409	 * @since 4.4.004 (2008-12-10)
20410	 */
20411	protected function putHtmlListBullet($listdepth, $listtype='', $size=10) {
20412		if ($this->state != 2) {
20413			return;
20414		}
20415		$size /= $this->k;
20416		$fill = '';
20417		$bgcolor = $this->bgcolor;
20418		$color = $this->fgcolor;
20419		$strokecolor = $this->strokecolor;
20420		$width = 0;
20421		$textitem = '';
20422		$tmpx = $this->x;
20423		$lspace = $this->GetStringWidth('  ');
20424		if ($listtype == '^') {
20425			// special symbol used for avoid justification of rect bullet
20426			$this->lispacer = '';
20427			return;
20428		} elseif ($listtype == '!') {
20429			// set default list type for unordered list
20430			$deftypes = array('disc', 'circle', 'square');
20431			$listtype = $deftypes[($listdepth - 1) % 3];
20432		} elseif ($listtype == '#') {
20433			// set default list type for ordered list
20434			$listtype = 'decimal';
20435		} elseif (substr($listtype, 0, 4) == 'img|') {
20436			// custom image type ('img|type|width|height|image.ext')
20437			$img = explode('|', $listtype);
20438			$listtype = 'img';
20439		}
20440		switch ($listtype) {
20441			// unordered types
20442			case 'none': {
20443				break;
20444			}
20445			case 'disc': {
20446				$r = $size / 6;
20447				$lspace += (2 * $r);
20448				if ($this->rtl) {
20449					$this->x += $lspace;
20450				} else {
20451					$this->x -= $lspace;
20452				}
20453				$this->Circle(($this->x + $r), ($this->y + ($this->lasth / 2)), $r, 0, 360, 'F', array(), $color, 8);
20454				break;
20455			}
20456			case 'circle': {
20457				$r = $size / 6;
20458				$lspace += (2 * $r);
20459				if ($this->rtl) {
20460					$this->x += $lspace;
20461				} else {
20462					$this->x -= $lspace;
20463				}
20464				$prev_line_style = $this->linestyleWidth.' '.$this->linestyleCap.' '.$this->linestyleJoin.' '.$this->linestyleDash.' '.$this->DrawColor;
20465				$new_line_style = array('width' => ($r / 3), 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'phase' => 0, 'color'=>$color);
20466				$this->Circle(($this->x + $r), ($this->y + ($this->lasth / 2)), ($r * (1 - (1/6))), 0, 360, 'D', $new_line_style, array(), 8);
20467				$this->_out($prev_line_style); // restore line settings
20468				break;
20469			}
20470			case 'square': {
20471				$l = $size / 3;
20472				$lspace += $l;
20473				if ($this->rtl) {;
20474					$this->x += $lspace;
20475				} else {
20476					$this->x -= $lspace;
20477				}
20478				$this->Rect($this->x, ($this->y + (($this->lasth - $l) / 2)), $l, $l, 'F', array(), $color);
20479				break;
20480			}
20481			case 'img': {
20482				// 1=>type, 2=>width, 3=>height, 4=>image.ext
20483				$lspace += $img[2];
20484				if ($this->rtl) {;
20485					$this->x += $lspace;
20486				} else {
20487					$this->x -= $lspace;
20488				}
20489				$imgtype = strtolower($img[1]);
20490				$prev_y = $this->y;
20491				switch ($imgtype) {
20492					case 'svg': {
20493						$this->ImageSVG($img[4], $this->x, ($this->y + (($this->lasth - $img[3]) / 2)), $img[2], $img[3], '', 'T', '', 0, false);
20494						break;
20495					}
20496					case 'ai':
20497					case 'eps': {
20498						$this->ImageEps($img[4], $this->x, ($this->y + (($this->lasth - $img[3]) / 2)), $img[2], $img[3], '', true, 'T', '', 0, false);
20499						break;
20500					}
20501					default: {
20502						$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);
20503						break;
20504					}
20505				}
20506				$this->y = $prev_y;
20507				break;
20508			}
20509			// ordered types
20510			// $this->listcount[$this->listnum];
20511			// $textitem
20512			case '1':
20513			case 'decimal': {
20514				$textitem = $this->listcount[$this->listnum];
20515				break;
20516			}
20517			case 'decimal-leading-zero': {
20518				$textitem = sprintf('%02d', $this->listcount[$this->listnum]);
20519				break;
20520			}
20521			case 'i':
20522			case 'lower-roman': {
20523				$textitem = strtolower(TCPDF_STATIC::intToRoman($this->listcount[$this->listnum]));
20524				break;
20525			}
20526			case 'I':
20527			case 'upper-roman': {
20528				$textitem = TCPDF_STATIC::intToRoman($this->listcount[$this->listnum]);
20529				break;
20530			}
20531			case 'a':
20532			case 'lower-alpha':
20533			case 'lower-latin': {
20534				$textitem = chr(97 + $this->listcount[$this->listnum] - 1);
20535				break;
20536			}
20537			case 'A':
20538			case 'upper-alpha':
20539			case 'upper-latin': {
20540				$textitem = chr(65 + $this->listcount[$this->listnum] - 1);
20541				break;
20542			}
20543			case 'lower-greek': {
20544				$textitem = TCPDF_FONTS::unichr((945 + $this->listcount[$this->listnum] - 1), $this->isunicode);
20545				break;
20546			}
20547			/*
20548			// Types to be implemented (special handling)
20549			case 'hebrew': {
20550				break;
20551			}
20552			case 'armenian': {
20553				break;
20554			}
20555			case 'georgian': {
20556				break;
20557			}
20558			case 'cjk-ideographic': {
20559				break;
20560			}
20561			case 'hiragana': {
20562				break;
20563			}
20564			case 'katakana': {
20565				break;
20566			}
20567			case 'hiragana-iroha': {
20568				break;
20569			}
20570			case 'katakana-iroha': {
20571				break;
20572			}
20573			*/
20574			default: {
20575				$textitem = $this->listcount[$this->listnum];
20576			}
20577		}
20578		if (!TCPDF_STATIC::empty_string($textitem)) {
20579			// Check whether we need a new page or new column
20580			$prev_y = $this->y;
20581			$h = $this->getCellHeight($this->FontSize);
20582			if ($this->checkPageBreak($h) OR ($this->y < $prev_y)) {
20583				$tmpx = $this->x;
20584			}
20585			// print ordered item
20586			if ($this->rtl) {
20587				$textitem = '.'.$textitem;
20588			} else {
20589				$textitem = $textitem.'.';
20590			}
20591			$lspace += $this->GetStringWidth($textitem);
20592			if ($this->rtl) {
20593				$this->x += $lspace;
20594			} else {
20595				$this->x -= $lspace;
20596			}
20597			$this->Write($this->lasth, $textitem, '', false, '', false, 0, false);
20598		}
20599		$this->x = $tmpx;
20600		$this->lispacer = '^';
20601		// restore colors
20602		$this->SetFillColorArray($bgcolor);
20603		$this->SetDrawColorArray($strokecolor);
20604		$this->SettextColorArray($color);
20605	}
20606
20607	/**
20608	 * Returns current graphic variables as array.
20609	 * @return array of graphic variables
20610	 * @protected
20611	 * @since 4.2.010 (2008-11-14)
20612	 */
20613	protected function getGraphicVars() {
20614		$grapvars = array(
20615			'FontFamily' => $this->FontFamily,
20616			'FontStyle' => $this->FontStyle,
20617			'FontSizePt' => $this->FontSizePt,
20618			'rMargin' => $this->rMargin,
20619			'lMargin' => $this->lMargin,
20620			'cell_padding' => $this->cell_padding,
20621			'cell_margin' => $this->cell_margin,
20622			'LineWidth' => $this->LineWidth,
20623			'linestyleWidth' => $this->linestyleWidth,
20624			'linestyleCap' => $this->linestyleCap,
20625			'linestyleJoin' => $this->linestyleJoin,
20626			'linestyleDash' => $this->linestyleDash,
20627			'textrendermode' => $this->textrendermode,
20628			'textstrokewidth' => $this->textstrokewidth,
20629			'DrawColor' => $this->DrawColor,
20630			'FillColor' => $this->FillColor,
20631			'TextColor' => $this->TextColor,
20632			'ColorFlag' => $this->ColorFlag,
20633			'bgcolor' => $this->bgcolor,
20634			'fgcolor' => $this->fgcolor,
20635			'htmlvspace' => $this->htmlvspace,
20636			'listindent' => $this->listindent,
20637			'listindentlevel' => $this->listindentlevel,
20638			'listnum' => $this->listnum,
20639			'listordered' => $this->listordered,
20640			'listcount' => $this->listcount,
20641			'lispacer' => $this->lispacer,
20642			'cell_height_ratio' => $this->cell_height_ratio,
20643			'font_stretching' => $this->font_stretching,
20644			'font_spacing' => $this->font_spacing,
20645			'alpha' => $this->alpha,
20646			// extended
20647			'lasth' => $this->lasth,
20648			'tMargin' => $this->tMargin,
20649			'bMargin' => $this->bMargin,
20650			'AutoPageBreak' => $this->AutoPageBreak,
20651			'PageBreakTrigger' => $this->PageBreakTrigger,
20652			'x' => $this->x,
20653			'y' => $this->y,
20654			'w' => $this->w,
20655			'h' => $this->h,
20656			'wPt' => $this->wPt,
20657			'hPt' => $this->hPt,
20658			'fwPt' => $this->fwPt,
20659			'fhPt' => $this->fhPt,
20660			'page' => $this->page,
20661			'current_column' => $this->current_column,
20662			'num_columns' => $this->num_columns
20663			);
20664		return $grapvars;
20665	}
20666
20667	/**
20668	 * Set graphic variables.
20669	 * @param $gvars (array) array of graphic variablesto restore
20670	 * @param $extended (boolean) if true restore extended graphic variables
20671	 * @protected
20672	 * @since 4.2.010 (2008-11-14)
20673	 */
20674	protected function setGraphicVars($gvars, $extended=false) {
20675		if ($this->state != 2) {
20676			 return;
20677		}
20678		$this->FontFamily = $gvars['FontFamily'];
20679		$this->FontStyle = $gvars['FontStyle'];
20680		$this->FontSizePt = $gvars['FontSizePt'];
20681		$this->rMargin = $gvars['rMargin'];
20682		$this->lMargin = $gvars['lMargin'];
20683		$this->cell_padding = $gvars['cell_padding'];
20684		$this->cell_margin = $gvars['cell_margin'];
20685		$this->LineWidth = $gvars['LineWidth'];
20686		$this->linestyleWidth = $gvars['linestyleWidth'];
20687		$this->linestyleCap = $gvars['linestyleCap'];
20688		$this->linestyleJoin = $gvars['linestyleJoin'];
20689		$this->linestyleDash = $gvars['linestyleDash'];
20690		$this->textrendermode = $gvars['textrendermode'];
20691		$this->textstrokewidth = $gvars['textstrokewidth'];
20692		$this->DrawColor = $gvars['DrawColor'];
20693		$this->FillColor = $gvars['FillColor'];
20694		$this->TextColor = $gvars['TextColor'];
20695		$this->ColorFlag = $gvars['ColorFlag'];
20696		$this->bgcolor = $gvars['bgcolor'];
20697		$this->fgcolor = $gvars['fgcolor'];
20698		$this->htmlvspace = $gvars['htmlvspace'];
20699		$this->listindent = $gvars['listindent'];
20700		$this->listindentlevel = $gvars['listindentlevel'];
20701		$this->listnum = $gvars['listnum'];
20702		$this->listordered = $gvars['listordered'];
20703		$this->listcount = $gvars['listcount'];
20704		$this->lispacer = $gvars['lispacer'];
20705		$this->cell_height_ratio = $gvars['cell_height_ratio'];
20706		$this->font_stretching = $gvars['font_stretching'];
20707		$this->font_spacing = $gvars['font_spacing'];
20708		$this->alpha = $gvars['alpha'];
20709		if ($extended) {
20710			// restore extended values
20711			$this->lasth = $gvars['lasth'];
20712			$this->tMargin = $gvars['tMargin'];
20713			$this->bMargin = $gvars['bMargin'];
20714			$this->AutoPageBreak = $gvars['AutoPageBreak'];
20715			$this->PageBreakTrigger = $gvars['PageBreakTrigger'];
20716			$this->x = $gvars['x'];
20717			$this->y = $gvars['y'];
20718			$this->w = $gvars['w'];
20719			$this->h = $gvars['h'];
20720			$this->wPt = $gvars['wPt'];
20721			$this->hPt = $gvars['hPt'];
20722			$this->fwPt = $gvars['fwPt'];
20723			$this->fhPt = $gvars['fhPt'];
20724			$this->page = $gvars['page'];
20725			$this->current_column = $gvars['current_column'];
20726			$this->num_columns = $gvars['num_columns'];
20727		}
20728		$this->_out(''.$this->linestyleWidth.' '.$this->linestyleCap.' '.$this->linestyleJoin.' '.$this->linestyleDash.' '.$this->DrawColor.' '.$this->FillColor.'');
20729		if (!TCPDF_STATIC::empty_string($this->FontFamily)) {
20730			$this->SetFont($this->FontFamily, $this->FontStyle, $this->FontSizePt);
20731		}
20732	}
20733
20734	/**
20735	 * Outputs the "save graphics state" operator 'q'
20736	 * @protected
20737	 */
20738	protected function _outSaveGraphicsState() {
20739		$this->_out('q');
20740	}
20741
20742	/**
20743	 * Outputs the "restore graphics state" operator 'Q'
20744	 * @protected
20745	 */
20746	protected function _outRestoreGraphicsState() {
20747		$this->_out('Q');
20748	}
20749
20750	/**
20751	 * Set buffer content (always append data).
20752	 * @param $data (string) data
20753	 * @protected
20754	 * @since 4.5.000 (2009-01-02)
20755	 */
20756	protected function setBuffer($data) {
20757		$this->bufferlen += strlen($data);
20758		$this->buffer .= $data;
20759	}
20760
20761	/**
20762	 * Replace the buffer content
20763	 * @param $data (string) data
20764	 * @protected
20765	 * @since 5.5.000 (2010-06-22)
20766	 */
20767	protected function replaceBuffer($data) {
20768		$this->bufferlen = strlen($data);
20769		$this->buffer = $data;
20770	}
20771
20772	/**
20773	 * Get buffer content.
20774	 * @return string buffer content
20775	 * @protected
20776	 * @since 4.5.000 (2009-01-02)
20777	 */
20778	protected function getBuffer() {
20779		return $this->buffer;
20780	}
20781
20782	/**
20783	 * Set page buffer content.
20784	 * @param $page (int) page number
20785	 * @param $data (string) page data
20786	 * @param $append (boolean) if true append data, false replace.
20787	 * @protected
20788	 * @since 4.5.000 (2008-12-31)
20789	 */
20790	protected function setPageBuffer($page, $data, $append=false) {
20791		if ($append) {
20792			$this->pages[$page] .= $data;
20793		} else {
20794			$this->pages[$page] = $data;
20795		}
20796		if ($append AND isset($this->pagelen[$page])) {
20797			$this->pagelen[$page] += strlen($data);
20798		} else {
20799			$this->pagelen[$page] = strlen($data);
20800		}
20801	}
20802
20803	/**
20804	 * Get page buffer content.
20805	 * @param $page (int) page number
20806	 * @return string page buffer content or false in case of error
20807	 * @protected
20808	 * @since 4.5.000 (2008-12-31)
20809	 */
20810	protected function getPageBuffer($page) {
20811		if (isset($this->pages[$page])) {
20812			return $this->pages[$page];
20813		}
20814		return false;
20815	}
20816
20817	/**
20818	 * Set image buffer content.
20819	 * @param $image (string) image key
20820	 * @param $data (array) image data
20821	 * @return int image index number
20822	 * @protected
20823	 * @since 4.5.000 (2008-12-31)
20824	 */
20825	protected function setImageBuffer($image, $data) {
20826		if (($data['i'] = array_search($image, $this->imagekeys)) === FALSE) {
20827			$this->imagekeys[$this->numimages] = $image;
20828			$data['i'] = $this->numimages;
20829			++$this->numimages;
20830		}
20831		$this->images[$image] = $data;
20832		return $data['i'];
20833	}
20834
20835	/**
20836	 * Set image buffer content for a specified sub-key.
20837	 * @param $image (string) image key
20838	 * @param $key (string) image sub-key
20839	 * @param $data (array) image data
20840	 * @protected
20841	 * @since 4.5.000 (2008-12-31)
20842	 */
20843	protected function setImageSubBuffer($image, $key, $data) {
20844		if (!isset($this->images[$image])) {
20845			$this->setImageBuffer($image, array());
20846		}
20847		$this->images[$image][$key] = $data;
20848	}
20849
20850	/**
20851	 * Get image buffer content.
20852	 * @param $image (string) image key
20853	 * @return string image buffer content or false in case of error
20854	 * @protected
20855	 * @since 4.5.000 (2008-12-31)
20856	 */
20857	protected function getImageBuffer($image) {
20858		if (isset($this->images[$image])) {
20859			return $this->images[$image];
20860		}
20861		return false;
20862	}
20863
20864	/**
20865	 * Set font buffer content.
20866	 * @param $font (string) font key
20867	 * @param $data (array) font data
20868	 * @protected
20869	 * @since 4.5.000 (2009-01-02)
20870	 */
20871	protected function setFontBuffer($font, $data) {
20872		$this->fonts[$font] = $data;
20873		if (!in_array($font, $this->fontkeys)) {
20874			$this->fontkeys[] = $font;
20875			// store object ID for current font
20876			++$this->n;
20877			$this->font_obj_ids[$font] = $this->n;
20878			$this->setFontSubBuffer($font, 'n', $this->n);
20879		}
20880	}
20881
20882	/**
20883	 * Set font buffer content.
20884	 * @param $font (string) font key
20885	 * @param $key (string) font sub-key
20886	 * @param $data (array) font data
20887	 * @protected
20888	 * @since 4.5.000 (2009-01-02)
20889	 */
20890	protected function setFontSubBuffer($font, $key, $data) {
20891		if (!isset($this->fonts[$font])) {
20892			$this->setFontBuffer($font, array());
20893		}
20894		$this->fonts[$font][$key] = $data;
20895	}
20896
20897	/**
20898	 * Get font buffer content.
20899	 * @param $font (string) font key
20900	 * @return string font buffer content or false in case of error
20901	 * @protected
20902	 * @since 4.5.000 (2009-01-02)
20903	 */
20904	protected function getFontBuffer($font) {
20905		if (isset($this->fonts[$font])) {
20906			return $this->fonts[$font];
20907		}
20908		return false;
20909	}
20910
20911	/**
20912	 * Move a page to a previous position.
20913	 * @param $frompage (int) number of the source page
20914	 * @param $topage (int) number of the destination page (must be less than $frompage)
20915	 * @return true in case of success, false in case of error.
20916	 * @public
20917	 * @since 4.5.000 (2009-01-02)
20918	 */
20919	public function movePage($frompage, $topage) {
20920		if (($frompage > $this->numpages) OR ($frompage <= $topage)) {
20921			return false;
20922		}
20923		if ($frompage == $this->page) {
20924			// close the page before moving it
20925			$this->endPage();
20926		}
20927		// move all page-related states
20928		$tmppage = $this->getPageBuffer($frompage);
20929		$tmppagedim = $this->pagedim[$frompage];
20930		$tmppagelen = $this->pagelen[$frompage];
20931		$tmpintmrk = $this->intmrk[$frompage];
20932		$tmpbordermrk = $this->bordermrk[$frompage];
20933		$tmpcntmrk = $this->cntmrk[$frompage];
20934		$tmppageobjects = $this->pageobjects[$frompage];
20935		if (isset($this->footerpos[$frompage])) {
20936			$tmpfooterpos = $this->footerpos[$frompage];
20937		}
20938		if (isset($this->footerlen[$frompage])) {
20939			$tmpfooterlen = $this->footerlen[$frompage];
20940		}
20941		if (isset($this->transfmrk[$frompage])) {
20942			$tmptransfmrk = $this->transfmrk[$frompage];
20943		}
20944		if (isset($this->PageAnnots[$frompage])) {
20945			$tmpannots = $this->PageAnnots[$frompage];
20946		}
20947		if (isset($this->newpagegroup) AND !empty($this->newpagegroup)) {
20948			for ($i = $frompage; $i > $topage; --$i) {
20949				if (isset($this->newpagegroup[$i]) AND (($i + $this->pagegroups[$this->newpagegroup[$i]]) > $frompage)) {
20950					--$this->pagegroups[$this->newpagegroup[$i]];
20951					break;
20952				}
20953			}
20954			for ($i = $topage; $i > 0; --$i) {
20955				if (isset($this->newpagegroup[$i]) AND (($i + $this->pagegroups[$this->newpagegroup[$i]]) > $topage)) {
20956					++$this->pagegroups[$this->newpagegroup[$i]];
20957					break;
20958				}
20959			}
20960		}
20961		for ($i = $frompage; $i > $topage; --$i) {
20962			$j = $i - 1;
20963			// shift pages down
20964			$this->setPageBuffer($i, $this->getPageBuffer($j));
20965			$this->pagedim[$i] = $this->pagedim[$j];
20966			$this->pagelen[$i] = $this->pagelen[$j];
20967			$this->intmrk[$i] = $this->intmrk[$j];
20968			$this->bordermrk[$i] = $this->bordermrk[$j];
20969			$this->cntmrk[$i] = $this->cntmrk[$j];
20970			$this->pageobjects[$i] = $this->pageobjects[$j];
20971			if (isset($this->footerpos[$j])) {
20972				$this->footerpos[$i] = $this->footerpos[$j];
20973			} elseif (isset($this->footerpos[$i])) {
20974				unset($this->footerpos[$i]);
20975			}
20976			if (isset($this->footerlen[$j])) {
20977				$this->footerlen[$i] = $this->footerlen[$j];
20978			} elseif (isset($this->footerlen[$i])) {
20979				unset($this->footerlen[$i]);
20980			}
20981			if (isset($this->transfmrk[$j])) {
20982				$this->transfmrk[$i] = $this->transfmrk[$j];
20983			} elseif (isset($this->transfmrk[$i])) {
20984				unset($this->transfmrk[$i]);
20985			}
20986			if (isset($this->PageAnnots[$j])) {
20987				$this->PageAnnots[$i] = $this->PageAnnots[$j];
20988			} elseif (isset($this->PageAnnots[$i])) {
20989				unset($this->PageAnnots[$i]);
20990			}
20991			if (isset($this->newpagegroup[$j])) {
20992				$this->newpagegroup[$i] = $this->newpagegroup[$j];
20993				unset($this->newpagegroup[$j]);
20994			}
20995			if ($this->currpagegroup == $j) {
20996				$this->currpagegroup = $i;
20997			}
20998		}
20999		$this->setPageBuffer($topage, $tmppage);
21000		$this->pagedim[$topage] = $tmppagedim;
21001		$this->pagelen[$topage] = $tmppagelen;
21002		$this->intmrk[$topage] = $tmpintmrk;
21003		$this->bordermrk[$topage] = $tmpbordermrk;
21004		$this->cntmrk[$topage] = $tmpcntmrk;
21005		$this->pageobjects[$topage] = $tmppageobjects;
21006		if (isset($tmpfooterpos)) {
21007			$this->footerpos[$topage] = $tmpfooterpos;
21008		} elseif (isset($this->footerpos[$topage])) {
21009			unset($this->footerpos[$topage]);
21010		}
21011		if (isset($tmpfooterlen)) {
21012			$this->footerlen[$topage] = $tmpfooterlen;
21013		} elseif (isset($this->footerlen[$topage])) {
21014			unset($this->footerlen[$topage]);
21015		}
21016		if (isset($tmptransfmrk)) {
21017			$this->transfmrk[$topage] = $tmptransfmrk;
21018		} elseif (isset($this->transfmrk[$topage])) {
21019			unset($this->transfmrk[$topage]);
21020		}
21021		if (isset($tmpannots)) {
21022			$this->PageAnnots[$topage] = $tmpannots;
21023		} elseif (isset($this->PageAnnots[$topage])) {
21024			unset($this->PageAnnots[$topage]);
21025		}
21026		// adjust outlines
21027		$tmpoutlines = $this->outlines;
21028		foreach ($tmpoutlines as $key => $outline) {
21029			if (!$outline['f']) {
21030				if (($outline['p'] >= $topage) AND ($outline['p'] < $frompage)) {
21031					$this->outlines[$key]['p'] = ($outline['p'] + 1);
21032				} elseif ($outline['p'] == $frompage) {
21033					$this->outlines[$key]['p'] = $topage;
21034				}
21035			}
21036		}
21037		// adjust dests
21038		$tmpdests = $this->dests;
21039		foreach ($tmpdests as $key => $dest) {
21040			if (!$dest['f']) {
21041				if (($dest['p'] >= $topage) AND ($dest['p'] < $frompage)) {
21042					$this->dests[$key]['p'] = ($dest['p'] + 1);
21043				} elseif ($dest['p'] == $frompage) {
21044					$this->dests[$key]['p'] = $topage;
21045				}
21046			}
21047		}
21048		// adjust links
21049		$tmplinks = $this->links;
21050		foreach ($tmplinks as $key => $link) {
21051			if (!$link['f']) {
21052				if (($link['p'] >= $topage) AND ($link['p'] < $frompage)) {
21053					$this->links[$key]['p'] = ($link['p'] + 1);
21054				} elseif ($link['p'] == $frompage) {
21055					$this->links[$key]['p'] = $topage;
21056				}
21057			}
21058		}
21059		// adjust javascript
21060		$jfrompage = $frompage;
21061		$jtopage = $topage;
21062		if (preg_match_all('/this\.addField\(\'([^\']*)\',\'([^\']*)\',([0-9]+)/', $this->javascript, $pamatch) > 0) {
21063			foreach($pamatch[0] as $pk => $pmatch) {
21064				$pagenum = intval($pamatch[3][$pk]) + 1;
21065				if (($pagenum >= $jtopage) AND ($pagenum < $jfrompage)) {
21066					$newpage = ($pagenum + 1);
21067				} elseif ($pagenum == $jfrompage) {
21068					$newpage = $jtopage;
21069				} else {
21070					$newpage = $pagenum;
21071				}
21072				--$newpage;
21073				$newjs = "this.addField(\'".$pamatch[1][$pk]."\',\'".$pamatch[2][$pk]."\',".$newpage;
21074				$this->javascript = str_replace($pmatch, $newjs, $this->javascript);
21075			}
21076			unset($pamatch);
21077		}
21078		// return to last page
21079		$this->lastPage(true);
21080		return true;
21081	}
21082
21083	/**
21084	 * Remove the specified page.
21085	 * @param $page (int) page to remove
21086	 * @return true in case of success, false in case of error.
21087	 * @public
21088	 * @since 4.6.004 (2009-04-23)
21089	 */
21090	public function deletePage($page) {
21091		if (($page < 1) OR ($page > $this->numpages)) {
21092			return false;
21093		}
21094		// delete current page
21095		unset($this->pages[$page]);
21096		unset($this->pagedim[$page]);
21097		unset($this->pagelen[$page]);
21098		unset($this->intmrk[$page]);
21099		unset($this->bordermrk[$page]);
21100		unset($this->cntmrk[$page]);
21101		foreach ($this->pageobjects[$page] as $oid) {
21102			if (isset($this->offsets[$oid])){
21103				unset($this->offsets[$oid]);
21104			}
21105		}
21106		unset($this->pageobjects[$page]);
21107		if (isset($this->footerpos[$page])) {
21108			unset($this->footerpos[$page]);
21109		}
21110		if (isset($this->footerlen[$page])) {
21111			unset($this->footerlen[$page]);
21112		}
21113		if (isset($this->transfmrk[$page])) {
21114			unset($this->transfmrk[$page]);
21115		}
21116		if (isset($this->PageAnnots[$page])) {
21117			unset($this->PageAnnots[$page]);
21118		}
21119		if (isset($this->newpagegroup) AND !empty($this->newpagegroup)) {
21120			for ($i = $page; $i > 0; --$i) {
21121				if (isset($this->newpagegroup[$i]) AND (($i + $this->pagegroups[$this->newpagegroup[$i]]) > $page)) {
21122					--$this->pagegroups[$this->newpagegroup[$i]];
21123					break;
21124				}
21125			}
21126		}
21127		if (isset($this->pageopen[$page])) {
21128			unset($this->pageopen[$page]);
21129		}
21130		if ($page < $this->numpages) {
21131			// update remaining pages
21132			for ($i = $page; $i < $this->numpages; ++$i) {
21133				$j = $i + 1;
21134				// shift pages
21135				$this->setPageBuffer($i, $this->getPageBuffer($j));
21136				$this->pagedim[$i] = $this->pagedim[$j];
21137				$this->pagelen[$i] = $this->pagelen[$j];
21138				$this->intmrk[$i] = $this->intmrk[$j];
21139				$this->bordermrk[$i] = $this->bordermrk[$j];
21140				$this->cntmrk[$i] = $this->cntmrk[$j];
21141				$this->pageobjects[$i] = $this->pageobjects[$j];
21142				if (isset($this->footerpos[$j])) {
21143					$this->footerpos[$i] = $this->footerpos[$j];
21144				} elseif (isset($this->footerpos[$i])) {
21145					unset($this->footerpos[$i]);
21146				}
21147				if (isset($this->footerlen[$j])) {
21148					$this->footerlen[$i] = $this->footerlen[$j];
21149				} elseif (isset($this->footerlen[$i])) {
21150					unset($this->footerlen[$i]);
21151				}
21152				if (isset($this->transfmrk[$j])) {
21153					$this->transfmrk[$i] = $this->transfmrk[$j];
21154				} elseif (isset($this->transfmrk[$i])) {
21155					unset($this->transfmrk[$i]);
21156				}
21157				if (isset($this->PageAnnots[$j])) {
21158					$this->PageAnnots[$i] = $this->PageAnnots[$j];
21159				} elseif (isset($this->PageAnnots[$i])) {
21160					unset($this->PageAnnots[$i]);
21161				}
21162				if (isset($this->newpagegroup[$j])) {
21163					$this->newpagegroup[$i] = $this->newpagegroup[$j];
21164					unset($this->newpagegroup[$j]);
21165				}
21166				if ($this->currpagegroup == $j) {
21167					$this->currpagegroup = $i;
21168				}
21169				if (isset($this->pageopen[$j])) {
21170					$this->pageopen[$i] = $this->pageopen[$j];
21171				} elseif (isset($this->pageopen[$i])) {
21172					unset($this->pageopen[$i]);
21173				}
21174			}
21175			// remove last page
21176			unset($this->pages[$this->numpages]);
21177			unset($this->pagedim[$this->numpages]);
21178			unset($this->pagelen[$this->numpages]);
21179			unset($this->intmrk[$this->numpages]);
21180			unset($this->bordermrk[$this->numpages]);
21181			unset($this->cntmrk[$this->numpages]);
21182			foreach ($this->pageobjects[$this->numpages] as $oid) {
21183				if (isset($this->offsets[$oid])){
21184					unset($this->offsets[$oid]);
21185				}
21186			}
21187			unset($this->pageobjects[$this->numpages]);
21188			if (isset($this->footerpos[$this->numpages])) {
21189				unset($this->footerpos[$this->numpages]);
21190			}
21191			if (isset($this->footerlen[$this->numpages])) {
21192				unset($this->footerlen[$this->numpages]);
21193			}
21194			if (isset($this->transfmrk[$this->numpages])) {
21195				unset($this->transfmrk[$this->numpages]);
21196			}
21197			if (isset($this->PageAnnots[$this->numpages])) {
21198				unset($this->PageAnnots[$this->numpages]);
21199			}
21200			if (isset($this->newpagegroup[$this->numpages])) {
21201				unset($this->newpagegroup[$this->numpages]);
21202			}
21203			if ($this->currpagegroup == $this->numpages) {
21204				$this->currpagegroup = ($this->numpages - 1);
21205			}
21206			if (isset($this->pagegroups[$this->numpages])) {
21207				unset($this->pagegroups[$this->numpages]);
21208			}
21209			if (isset($this->pageopen[$this->numpages])) {
21210				unset($this->pageopen[$this->numpages]);
21211			}
21212		}
21213		--$this->numpages;
21214		$this->page = $this->numpages;
21215		// adjust outlines
21216		$tmpoutlines = $this->outlines;
21217		foreach ($tmpoutlines as $key => $outline) {
21218			if (!$outline['f']) {
21219				if ($outline['p'] > $page) {
21220					$this->outlines[$key]['p'] = $outline['p'] - 1;
21221				} elseif ($outline['p'] == $page) {
21222					unset($this->outlines[$key]);
21223				}
21224			}
21225		}
21226		// adjust dests
21227		$tmpdests = $this->dests;
21228		foreach ($tmpdests as $key => $dest) {
21229			if (!$dest['f']) {
21230				if ($dest['p'] > $page) {
21231					$this->dests[$key]['p'] = $dest['p'] - 1;
21232				} elseif ($dest['p'] == $page) {
21233					unset($this->dests[$key]);
21234				}
21235			}
21236		}
21237		// adjust links
21238		$tmplinks = $this->links;
21239		foreach ($tmplinks as $key => $link) {
21240			if (!$link['f']) {
21241				if ($link['p'] > $page) {
21242					$this->links[$key]['p'] = $link['p'] - 1;
21243				} elseif ($link['p'] == $page) {
21244					unset($this->links[$key]);
21245				}
21246			}
21247		}
21248		// adjust javascript
21249		$jpage = $page;
21250		if (preg_match_all('/this\.addField\(\'([^\']*)\',\'([^\']*)\',([0-9]+)/', $this->javascript, $pamatch) > 0) {
21251			foreach($pamatch[0] as $pk => $pmatch) {
21252				$pagenum = intval($pamatch[3][$pk]) + 1;
21253				if ($pagenum >= $jpage) {
21254					$newpage = ($pagenum - 1);
21255				} elseif ($pagenum == $jpage) {
21256					$newpage = 1;
21257				} else {
21258					$newpage = $pagenum;
21259				}
21260				--$newpage;
21261				$newjs = "this.addField(\'".$pamatch[1][$pk]."\',\'".$pamatch[2][$pk]."\',".$newpage;
21262				$this->javascript = str_replace($pmatch, $newjs, $this->javascript);
21263			}
21264			unset($pamatch);
21265		}
21266		// return to last page
21267		if ($this->numpages > 0) {
21268			$this->lastPage(true);
21269		}
21270		return true;
21271	}
21272
21273	/**
21274	 * Clone the specified page to a new page.
21275	 * @param $page (int) number of page to copy (0 = current page)
21276	 * @return true in case of success, false in case of error.
21277	 * @public
21278	 * @since 4.9.015 (2010-04-20)
21279	 */
21280	public function copyPage($page=0) {
21281		if ($page == 0) {
21282			// default value
21283			$page = $this->page;
21284		}
21285		if (($page < 1) OR ($page > $this->numpages)) {
21286			return false;
21287		}
21288		// close the last page
21289		$this->endPage();
21290		// copy all page-related states
21291		++$this->numpages;
21292		$this->page = $this->numpages;
21293		$this->setPageBuffer($this->page, $this->getPageBuffer($page));
21294		$this->pagedim[$this->page] = $this->pagedim[$page];
21295		$this->pagelen[$this->page] = $this->pagelen[$page];
21296		$this->intmrk[$this->page] = $this->intmrk[$page];
21297		$this->bordermrk[$this->page] = $this->bordermrk[$page];
21298		$this->cntmrk[$this->page] = $this->cntmrk[$page];
21299		$this->pageobjects[$this->page] = $this->pageobjects[$page];
21300		$this->pageopen[$this->page] = false;
21301		if (isset($this->footerpos[$page])) {
21302			$this->footerpos[$this->page] = $this->footerpos[$page];
21303		}
21304		if (isset($this->footerlen[$page])) {
21305			$this->footerlen[$this->page] = $this->footerlen[$page];
21306		}
21307		if (isset($this->transfmrk[$page])) {
21308			$this->transfmrk[$this->page] = $this->transfmrk[$page];
21309		}
21310		if (isset($this->PageAnnots[$page])) {
21311			$this->PageAnnots[$this->page] = $this->PageAnnots[$page];
21312		}
21313		if (isset($this->newpagegroup[$page])) {
21314			// start a new group
21315			$this->newpagegroup[$this->page] = sizeof($this->newpagegroup) + 1;
21316			$this->currpagegroup = $this->newpagegroup[$this->page];
21317			$this->pagegroups[$this->currpagegroup] = 1;
21318		} elseif (isset($this->currpagegroup) AND ($this->currpagegroup > 0)) {
21319			++$this->pagegroups[$this->currpagegroup];
21320		}
21321		// copy outlines
21322		$tmpoutlines = $this->outlines;
21323		foreach ($tmpoutlines as $key => $outline) {
21324			if ($outline['p'] == $page) {
21325				$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']);
21326			}
21327		}
21328		// copy links
21329		$tmplinks = $this->links;
21330		foreach ($tmplinks as $key => $link) {
21331			if ($link['p'] == $page) {
21332				$this->links[] = array('p' => $this->page, 'y' => $link['y'], 'f' => $link['f']);
21333			}
21334		}
21335		// return to last page
21336		$this->lastPage(true);
21337		return true;
21338	}
21339
21340	/**
21341	 * Output a Table of Content Index (TOC).
21342	 * This method must be called after all Bookmarks were set.
21343	 * Before calling this method you have to open the page using the addTOCPage() method.
21344	 * After calling this method you have to call endTOCPage() to close the TOC page.
21345	 * You can override this method to achieve different styles.
21346	 * @param $page (int) page number where this TOC should be inserted (leave empty for current page).
21347	 * @param $numbersfont (string) set the font for page numbers (please use monospaced font for better alignment).
21348	 * @param $filler (string) string used to fill the space between text and page number.
21349	 * @param $toc_name (string) name to use for TOC bookmark.
21350	 * @param $style (string) Font style for title: B = Bold, I = Italic, BI = Bold + Italic.
21351	 * @param $color (array) RGB color array for bookmark title (values from 0 to 255).
21352	 * @public
21353	 * @author Nicola Asuni
21354	 * @since 4.5.000 (2009-01-02)
21355	 * @see addTOCPage(), endTOCPage(), addHTMLTOC()
21356	 */
21357	public function addTOC($page='', $numbersfont='', $filler='.', $toc_name='TOC', $style='', $color=array(0,0,0)) {
21358		$fontsize = $this->FontSizePt;
21359		$fontfamily = $this->FontFamily;
21360		$fontstyle = $this->FontStyle;
21361		$w = $this->w - $this->lMargin - $this->rMargin;
21362		$spacer = $this->GetStringWidth(chr(32)) * 4;
21363		$lmargin = $this->lMargin;
21364		$rmargin = $this->rMargin;
21365		$x_start = $this->GetX();
21366		$page_first = $this->page;
21367		$current_page = $this->page;
21368		$page_fill_start = false;
21369		$page_fill_end = false;
21370		$current_column = $this->current_column;
21371		if (TCPDF_STATIC::empty_string($numbersfont)) {
21372			$numbersfont = $this->default_monospaced_font;
21373		}
21374		if (TCPDF_STATIC::empty_string($filler)) {
21375			$filler = ' ';
21376		}
21377		if (TCPDF_STATIC::empty_string($page)) {
21378			$gap = ' ';
21379		} else {
21380			$gap = '';
21381			if ($page < 1) {
21382				$page = 1;
21383			}
21384		}
21385		$this->SetFont($numbersfont, $fontstyle, $fontsize);
21386		$numwidth = $this->GetStringWidth('00000');
21387		$maxpage = 0; //used for pages on attached documents
21388		foreach ($this->outlines as $key => $outline) {
21389			// check for extra pages (used for attachments)
21390			if (($this->page > $page_first) AND ($outline['p'] >= $this->numpages)) {
21391				$outline['p'] += ($this->page - $page_first);
21392			}
21393			if ($this->rtl) {
21394				$aligntext = 'R';
21395				$alignnum = 'L';
21396			} else {
21397				$aligntext = 'L';
21398				$alignnum = 'R';
21399			}
21400			if ($outline['l'] == 0) {
21401				$this->SetFont($fontfamily, $outline['s'].'B', $fontsize);
21402			} else {
21403				$this->SetFont($fontfamily, $outline['s'], $fontsize - $outline['l']);
21404			}
21405			$this->SetTextColorArray($outline['c']);
21406			// check for page break
21407			$this->checkPageBreak(2 * $this->getCellHeight($this->FontSize));
21408			// set margins and X position
21409			if (($this->page == $current_page) AND ($this->current_column == $current_column)) {
21410				$this->lMargin = $lmargin;
21411				$this->rMargin = $rmargin;
21412			} else {
21413				if ($this->current_column != $current_column) {
21414					if ($this->rtl) {
21415						$x_start = $this->w - $this->columns[$this->current_column]['x'];
21416					} else {
21417						$x_start = $this->columns[$this->current_column]['x'];
21418					}
21419				}
21420				$lmargin = $this->lMargin;
21421				$rmargin = $this->rMargin;
21422				$current_page = $this->page;
21423				$current_column = $this->current_column;
21424			}
21425			$this->SetX($x_start);
21426			$indent = ($spacer * $outline['l']);
21427			if ($this->rtl) {
21428				$this->x -= $indent;
21429				$this->rMargin = $this->w - $this->x;
21430			} else {
21431				$this->x += $indent;
21432				$this->lMargin = $this->x;
21433			}
21434			$link = $this->AddLink();
21435			$this->SetLink($link, $outline['y'], $outline['p']);
21436			// write the text
21437			if ($this->rtl) {
21438				$txt = ' '.$outline['t'];
21439			} else {
21440				$txt = $outline['t'].' ';
21441			}
21442			$this->Write(0, $txt, $link, false, $aligntext, false, 0, false, false, 0, $numwidth, '');
21443			if ($this->rtl) {
21444				$tw = $this->x - $this->lMargin;
21445			} else {
21446				$tw = $this->w - $this->rMargin - $this->x;
21447			}
21448			$this->SetFont($numbersfont, $fontstyle, $fontsize);
21449			if (TCPDF_STATIC::empty_string($page)) {
21450				$pagenum = $outline['p'];
21451			} else {
21452				// placemark to be replaced with the correct number
21453				$pagenum = '{#'.($outline['p']).'}';
21454				if ($this->isUnicodeFont()) {
21455					$pagenum = '{'.$pagenum.'}';
21456				}
21457				$maxpage = max($maxpage, $outline['p']);
21458			}
21459			$fw = ($tw - $this->GetStringWidth($pagenum.$filler));
21460			$wfiller = $this->GetStringWidth($filler);
21461			if ($wfiller > 0) {
21462				$numfills = floor($fw / $wfiller);
21463			} else {
21464				$numfills = 0;
21465			}
21466			if ($numfills > 0) {
21467				$rowfill = str_repeat($filler, $numfills);
21468			} else {
21469				$rowfill = '';
21470			}
21471			if ($this->rtl) {
21472				$pagenum = $pagenum.$gap.$rowfill;
21473			} else {
21474				$pagenum = $rowfill.$gap.$pagenum;
21475			}
21476			// write the number
21477			$this->Cell($tw, 0, $pagenum, 0, 1, $alignnum, 0, $link, 0);
21478		}
21479		$page_last = $this->getPage();
21480		$numpages = ($page_last - $page_first + 1);
21481		// account for booklet mode
21482		if ($this->booklet) {
21483			// check if a blank page is required before TOC
21484			$page_fill_start = ((($page_first % 2) == 0) XOR (($page % 2) == 0));
21485			$page_fill_end = (!((($numpages % 2) == 0) XOR ($page_fill_start)));
21486			if ($page_fill_start) {
21487				// add a page at the end (to be moved before TOC)
21488				$this->addPage();
21489				++$page_last;
21490				++$numpages;
21491			}
21492			if ($page_fill_end) {
21493				// add a page at the end
21494				$this->addPage();
21495				++$page_last;
21496				++$numpages;
21497			}
21498		}
21499		$maxpage = max($maxpage, $page_last);
21500		if (!TCPDF_STATIC::empty_string($page)) {
21501			for ($p = $page_first; $p <= $page_last; ++$p) {
21502				// get page data
21503				$temppage = $this->getPageBuffer($p);
21504				for ($n = 1; $n <= $maxpage; ++$n) {
21505					// update page numbers
21506					$a = '{#'.$n.'}';
21507					// get page number aliases
21508					$pnalias = $this->getInternalPageNumberAliases($a);
21509					// calculate replacement number
21510					if (($n >= $page) AND ($n <= $this->numpages)) {
21511						$np = $n + $numpages;
21512					} else {
21513						$np = $n;
21514					}
21515					$na = TCPDF_STATIC::formatTOCPageNumber(($this->starting_page_number + $np - 1));
21516					$nu = TCPDF_FONTS::UTF8ToUTF16BE($na, false, $this->isunicode, $this->CurrentFont);
21517					// replace aliases with numbers
21518					foreach ($pnalias['u'] as $u) {
21519						$sfill = str_repeat($filler, max(0, (strlen($u) - strlen($nu.' '))));
21520						if ($this->rtl) {
21521							$nr = $nu.TCPDF_FONTS::UTF8ToUTF16BE(' '.$sfill, false, $this->isunicode, $this->CurrentFont);
21522						} else {
21523							$nr = TCPDF_FONTS::UTF8ToUTF16BE($sfill.' ', false, $this->isunicode, $this->CurrentFont).$nu;
21524						}
21525						$temppage = str_replace($u, $nr, $temppage);
21526					}
21527					foreach ($pnalias['a'] as $a) {
21528						$sfill = str_repeat($filler, max(0, (strlen($a) - strlen($na.' '))));
21529						if ($this->rtl) {
21530							$nr = $na.' '.$sfill;
21531						} else {
21532							$nr = $sfill.' '.$na;
21533						}
21534						$temppage = str_replace($a, $nr, $temppage);
21535					}
21536				}
21537				// save changes
21538				$this->setPageBuffer($p, $temppage);
21539			}
21540			// move pages
21541			$this->Bookmark($toc_name, 0, 0, $page_first, $style, $color);
21542			if ($page_fill_start) {
21543				$this->movePage($page_last, $page_first);
21544			}
21545			for ($i = 0; $i < $numpages; ++$i) {
21546				$this->movePage($page_last, $page);
21547			}
21548		}
21549	}
21550
21551	/**
21552	 * Output a Table Of Content Index (TOC) using HTML templates.
21553	 * This method must be called after all Bookmarks were set.
21554	 * Before calling this method you have to open the page using the addTOCPage() method.
21555	 * After calling this method you have to call endTOCPage() to close the TOC page.
21556	 * @param $page (int) page number where this TOC should be inserted (leave empty for current page).
21557	 * @param $toc_name (string) name to use for TOC bookmark.
21558	 * @param $templates (array) array of html templates. Use: "#TOC_DESCRIPTION#" for bookmark title, "#TOC_PAGE_NUMBER#" for page number.
21559	 * @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)
21560	 * @param $style (string) Font style for title: B = Bold, I = Italic, BI = Bold + Italic.
21561	 * @param $color (array) RGB color array for title (values from 0 to 255).
21562	 * @public
21563	 * @author Nicola Asuni
21564	 * @since 5.0.001 (2010-05-06)
21565	 * @see addTOCPage(), endTOCPage(), addTOC()
21566	 */
21567	public function addHTMLTOC($page='', $toc_name='TOC', $templates=array(), $correct_align=true, $style='', $color=array(0,0,0)) {
21568		$filler = ' ';
21569		$prev_htmlLinkColorArray = $this->htmlLinkColorArray;
21570		$prev_htmlLinkFontStyle = $this->htmlLinkFontStyle;
21571		// set new style for link
21572		$this->htmlLinkColorArray = array();
21573		$this->htmlLinkFontStyle = '';
21574		$page_first = $this->getPage();
21575		$page_fill_start = false;
21576		$page_fill_end = false;
21577		// get the font type used for numbers in each template
21578		$current_font = $this->FontFamily;
21579		foreach ($templates as $level => $html) {
21580			$dom = $this->getHtmlDomArray($html);
21581			foreach ($dom as $key => $value) {
21582				if ($value['value'] == '#TOC_PAGE_NUMBER#') {
21583					$this->SetFont($dom[($key - 1)]['fontname']);
21584					$templates['F'.$level] = $this->isUnicodeFont();
21585				}
21586			}
21587		}
21588		$this->SetFont($current_font);
21589		$maxpage = 0; //used for pages on attached documents
21590		foreach ($this->outlines as $key => $outline) {
21591			// get HTML template
21592			$row = $templates[$outline['l']];
21593			if (TCPDF_STATIC::empty_string($page)) {
21594				$pagenum = $outline['p'];
21595			} else {
21596				// placemark to be replaced with the correct number
21597				$pagenum = '{#'.($outline['p']).'}';
21598				if (isset($templates['F'.$outline['l']]) && $templates['F'.$outline['l']]) {
21599					$pagenum = '{'.$pagenum.'}';
21600				}
21601				$maxpage = max($maxpage, $outline['p']);
21602			}
21603			// replace templates with current values
21604			$row = str_replace('#TOC_DESCRIPTION#', $outline['t'], $row);
21605			$row = str_replace('#TOC_PAGE_NUMBER#', $pagenum, $row);
21606			// add link to page
21607			$row = '<a href="#'.$outline['p'].','.$outline['y'].'">'.$row.'</a>';
21608			// write bookmark entry
21609			$this->writeHTML($row, false, false, true, false, '');
21610		}
21611		// restore link styles
21612		$this->htmlLinkColorArray = $prev_htmlLinkColorArray;
21613		$this->htmlLinkFontStyle = $prev_htmlLinkFontStyle;
21614		// move TOC page and replace numbers
21615		$page_last = $this->getPage();
21616		$numpages = ($page_last - $page_first + 1);
21617		// account for booklet mode
21618		if ($this->booklet) {
21619			// check if a blank page is required before TOC
21620			$page_fill_start = ((($page_first % 2) == 0) XOR (($page % 2) == 0));
21621			$page_fill_end = (!((($numpages % 2) == 0) XOR ($page_fill_start)));
21622			if ($page_fill_start) {
21623				// add a page at the end (to be moved before TOC)
21624				$this->addPage();
21625				++$page_last;
21626				++$numpages;
21627			}
21628			if ($page_fill_end) {
21629				// add a page at the end
21630				$this->addPage();
21631				++$page_last;
21632				++$numpages;
21633			}
21634		}
21635		$maxpage = max($maxpage, $page_last);
21636		if (!TCPDF_STATIC::empty_string($page)) {
21637			for ($p = $page_first; $p <= $page_last; ++$p) {
21638				// get page data
21639				$temppage = $this->getPageBuffer($p);
21640				for ($n = 1; $n <= $maxpage; ++$n) {
21641					// update page numbers
21642					$a = '{#'.$n.'}';
21643					// get page number aliases
21644					$pnalias = $this->getInternalPageNumberAliases($a);
21645					// calculate replacement number
21646					if ($n >= $page) {
21647						$np = $n + $numpages;
21648					} else {
21649						$np = $n;
21650					}
21651					$na = TCPDF_STATIC::formatTOCPageNumber(($this->starting_page_number + $np - 1));
21652					$nu = TCPDF_FONTS::UTF8ToUTF16BE($na, false, $this->isunicode, $this->CurrentFont);
21653					// replace aliases with numbers
21654					foreach ($pnalias['u'] as $u) {
21655						if ($correct_align) {
21656							$sfill = str_repeat($filler, (strlen($u) - strlen($nu.' ')));
21657							if ($this->rtl) {
21658								$nr = $nu.TCPDF_FONTS::UTF8ToUTF16BE(' '.$sfill, false, $this->isunicode, $this->CurrentFont);
21659							} else {
21660								$nr = TCPDF_FONTS::UTF8ToUTF16BE($sfill.' ', false, $this->isunicode, $this->CurrentFont).$nu;
21661							}
21662						} else {
21663							$nr = $nu;
21664						}
21665						$temppage = str_replace($u, $nr, $temppage);
21666					}
21667					foreach ($pnalias['a'] as $a) {
21668						if ($correct_align) {
21669							$sfill = str_repeat($filler, (strlen($a) - strlen($na.' ')));
21670							if ($this->rtl) {
21671								$nr = $na.' '.$sfill;
21672							} else {
21673								$nr = $sfill.' '.$na;
21674							}
21675						} else {
21676							$nr = $na;
21677						}
21678						$temppage = str_replace($a, $nr, $temppage);
21679					}
21680				}
21681				// save changes
21682				$this->setPageBuffer($p, $temppage);
21683			}
21684			// move pages
21685			$this->Bookmark($toc_name, 0, 0, $page_first, $style, $color);
21686			if ($page_fill_start) {
21687				$this->movePage($page_last, $page_first);
21688			}
21689			for ($i = 0; $i < $numpages; ++$i) {
21690				$this->movePage($page_last, $page);
21691			}
21692		}
21693	}
21694
21695	/**
21696	 * Stores a copy of the current TCPDF object used for undo operation.
21697	 * @public
21698	 * @since 4.5.029 (2009-03-19)
21699	 */
21700	public function startTransaction() {
21701		if (isset($this->objcopy)) {
21702			// remove previous copy
21703			$this->commitTransaction();
21704		}
21705		// record current page number and Y position
21706		$this->start_transaction_page = $this->page;
21707		$this->start_transaction_y = $this->y;
21708		// clone current object
21709		$this->objcopy = TCPDF_STATIC::objclone($this);
21710	}
21711
21712	/**
21713	 * Delete the copy of the current TCPDF object used for undo operation.
21714	 * @public
21715	 * @since 4.5.029 (2009-03-19)
21716	 */
21717	public function commitTransaction() {
21718		if (isset($this->objcopy)) {
21719			$this->objcopy->_destroy(true, true);
21720			unset($this->objcopy);
21721		}
21722	}
21723
21724	/**
21725	 * This method allows to undo the latest transaction by returning the latest saved TCPDF object with startTransaction().
21726	 * @param $self (boolean) if true restores current class object to previous state without the need of reassignment via the returned value.
21727	 * @return TCPDF object.
21728	 * @public
21729	 * @since 4.5.029 (2009-03-19)
21730	 */
21731	public function rollbackTransaction($self=false) {
21732		if (isset($this->objcopy)) {
21733			$this->_destroy(true, true);
21734			if ($self) {
21735				$objvars = get_object_vars($this->objcopy);
21736				foreach ($objvars as $key => $value) {
21737					$this->$key = $value;
21738				}
21739			}
21740			return $this->objcopy;
21741		}
21742		return $this;
21743	}
21744
21745	// --- MULTI COLUMNS METHODS -----------------------
21746
21747	/**
21748	 * Set multiple columns of the same size
21749	 * @param $numcols (int) number of columns (set to zero to disable columns mode)
21750	 * @param $width (int) column width
21751	 * @param $y (int) column starting Y position (leave empty for current Y position)
21752	 * @public
21753	 * @since 4.9.001 (2010-03-28)
21754	 */
21755	public function setEqualColumns($numcols=0, $width=0, $y='') {
21756		$this->columns = array();
21757		if ($numcols < 2) {
21758			$numcols = 0;
21759			$this->columns = array();
21760		} else {
21761			// maximum column width
21762			$maxwidth = ($this->w - $this->original_lMargin - $this->original_rMargin) / $numcols;
21763			if (($width == 0) OR ($width > $maxwidth)) {
21764				$width = $maxwidth;
21765			}
21766			if (TCPDF_STATIC::empty_string($y)) {
21767				$y = $this->y;
21768			}
21769			// space between columns
21770			$space = (($this->w - $this->original_lMargin - $this->original_rMargin - ($numcols * $width)) / ($numcols - 1));
21771			// fill the columns array (with, space, starting Y position)
21772			for ($i = 0; $i < $numcols; ++$i) {
21773				$this->columns[$i] = array('w' => $width, 's' => $space, 'y' => $y);
21774			}
21775		}
21776		$this->num_columns = $numcols;
21777		$this->current_column = 0;
21778		$this->column_start_page = $this->page;
21779		$this->selectColumn(0);
21780	}
21781
21782	/**
21783	 * Remove columns and reset page margins.
21784	 * @public
21785	 * @since 5.9.072 (2011-04-26)
21786	 */
21787	public function resetColumns() {
21788		$this->lMargin = $this->original_lMargin;
21789		$this->rMargin = $this->original_rMargin;
21790		$this->setEqualColumns();
21791	}
21792
21793	/**
21794	 * Set columns array.
21795	 * Each column is represented by an array of arrays with the following keys: (w = width, s = space between columns, y = column top position).
21796	 * @param $columns (array)
21797	 * @public
21798	 * @since 4.9.001 (2010-03-28)
21799	 */
21800	public function setColumnsArray($columns) {
21801		$this->columns = $columns;
21802		$this->num_columns = count($columns);
21803		$this->current_column = 0;
21804		$this->column_start_page = $this->page;
21805		$this->selectColumn(0);
21806	}
21807
21808	/**
21809	 * Set position at a given column
21810	 * @param $col (int) column number (from 0 to getNumberOfColumns()-1); empty string = current column.
21811	 * @public
21812	 * @since 4.9.001 (2010-03-28)
21813	 */
21814	public function selectColumn($col='') {
21815		if (is_string($col)) {
21816			$col = $this->current_column;
21817		} elseif ($col >= $this->num_columns) {
21818			$col = 0;
21819		}
21820		$xshift = array('x' => 0, 's' => array('H' => 0, 'V' => 0), 'p' => array('L' => 0, 'T' => 0, 'R' => 0, 'B' => 0));
21821		$enable_thead = false;
21822		if ($this->num_columns > 1) {
21823			if ($col != $this->current_column) {
21824				// move Y pointer at the top of the column
21825				if ($this->column_start_page == $this->page) {
21826					$this->y = $this->columns[$col]['y'];
21827				} else {
21828					$this->y = $this->tMargin;
21829				}
21830				// Avoid to write table headers more than once
21831				if (($this->page > $this->maxselcol['page']) OR (($this->page == $this->maxselcol['page']) AND ($col > $this->maxselcol['column']))) {
21832					$enable_thead = true;
21833					$this->maxselcol['page'] = $this->page;
21834					$this->maxselcol['column'] = $col;
21835				}
21836			}
21837			$xshift = $this->colxshift;
21838			// set X position of the current column by case
21839			$listindent = ($this->listindentlevel * $this->listindent);
21840			// calculate column X position
21841			$colpos = 0;
21842			for ($i = 0; $i < $col; ++$i) {
21843				$colpos += ($this->columns[$i]['w'] + $this->columns[$i]['s']);
21844			}
21845			if ($this->rtl) {
21846				$x = $this->w - $this->original_rMargin - $colpos;
21847				$this->rMargin = ($this->w - $x + $listindent);
21848				$this->lMargin = ($x - $this->columns[$col]['w']);
21849				$this->x = $x - $listindent;
21850			} else {
21851				$x = $this->original_lMargin + $colpos;
21852				$this->lMargin = ($x + $listindent);
21853				$this->rMargin = ($this->w - $x - $this->columns[$col]['w']);
21854				$this->x = $x + $listindent;
21855			}
21856			$this->columns[$col]['x'] = $x;
21857		}
21858		$this->current_column = $col;
21859		// fix for HTML mode
21860		$this->newline = true;
21861		// print HTML table header (if any)
21862		if ((!TCPDF_STATIC::empty_string($this->thead)) AND (!$this->inthead)) {
21863			if ($enable_thead) {
21864				// print table header
21865				$this->writeHTML($this->thead, false, false, false, false, '');
21866				$this->y += $xshift['s']['V'];
21867				// store end of header position
21868				if (!isset($this->columns[$col]['th'])) {
21869					$this->columns[$col]['th'] = array();
21870				}
21871				$this->columns[$col]['th']['\''.$this->page.'\''] = $this->y;
21872				$this->lasth = 0;
21873			} elseif (isset($this->columns[$col]['th']['\''.$this->page.'\''])) {
21874				$this->y = $this->columns[$col]['th']['\''.$this->page.'\''];
21875			}
21876		}
21877		// account for an html table cell over multiple columns
21878		if ($this->rtl) {
21879			$this->rMargin += $xshift['x'];
21880			$this->x -= ($xshift['x'] + $xshift['p']['R']);
21881		} else {
21882			$this->lMargin += $xshift['x'];
21883			$this->x += $xshift['x'] + $xshift['p']['L'];
21884		}
21885	}
21886
21887	/**
21888	 * Return the current column number
21889	 * @return int current column number
21890	 * @public
21891	 * @since 5.5.011 (2010-07-08)
21892	 */
21893	public function getColumn() {
21894		return $this->current_column;
21895	}
21896
21897	/**
21898	 * Return the current number of columns.
21899	 * @return int number of columns
21900	 * @public
21901	 * @since 5.8.018 (2010-08-25)
21902	 */
21903	public function getNumberOfColumns() {
21904		return $this->num_columns;
21905	}
21906
21907	/**
21908	 * Set Text rendering mode.
21909	 * @param $stroke (int) outline size in user units (0 = disable).
21910	 * @param $fill (boolean) if true fills the text (default).
21911	 * @param $clip (boolean) if true activate clipping mode
21912	 * @public
21913	 * @since 4.9.008 (2009-04-02)
21914	 */
21915	public function setTextRenderingMode($stroke=0, $fill=true, $clip=false) {
21916		// Ref.: PDF 32000-1:2008 - 9.3.6 Text Rendering Mode
21917		// convert text rendering parameters
21918		if ($stroke < 0) {
21919			$stroke = 0;
21920		}
21921		if ($fill === true) {
21922			if ($stroke > 0) {
21923				if ($clip === true) {
21924					// Fill, then stroke text and add to path for clipping
21925					$textrendermode = 6;
21926				} else {
21927					// Fill, then stroke text
21928					$textrendermode = 2;
21929				}
21930				$textstrokewidth = $stroke;
21931			} else {
21932				if ($clip === true) {
21933					// Fill text and add to path for clipping
21934					$textrendermode = 4;
21935				} else {
21936					// Fill text
21937					$textrendermode = 0;
21938				}
21939			}
21940		} else {
21941			if ($stroke > 0) {
21942				if ($clip === true) {
21943					// Stroke text and add to path for clipping
21944					$textrendermode = 5;
21945				} else {
21946					// Stroke text
21947					$textrendermode = 1;
21948				}
21949				$textstrokewidth = $stroke;
21950			} else {
21951				if ($clip === true) {
21952					// Add text to path for clipping
21953					$textrendermode = 7;
21954				} else {
21955					// Neither fill nor stroke text (invisible)
21956					$textrendermode = 3;
21957				}
21958			}
21959		}
21960		$this->textrendermode = $textrendermode;
21961		$this->textstrokewidth = $stroke;
21962	}
21963
21964	/**
21965	 * Set parameters for drop shadow effect for text.
21966	 * @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.
21967	 * @since 5.9.174 (2012-07-25)
21968	 * @public
21969	*/
21970	public function setTextShadow($params=array('enabled'=>false, 'depth_w'=>0, 'depth_h'=>0, 'color'=>false, 'opacity'=>1, 'blend_mode'=>'Normal')) {
21971		if (isset($params['enabled'])) {
21972			$this->txtshadow['enabled'] = $params['enabled']?true:false;
21973		} else {
21974			$this->txtshadow['enabled'] = false;
21975		}
21976		if (isset($params['depth_w'])) {
21977			$this->txtshadow['depth_w'] = floatval($params['depth_w']);
21978		} else {
21979			$this->txtshadow['depth_w'] = 0;
21980		}
21981		if (isset($params['depth_h'])) {
21982			$this->txtshadow['depth_h'] = floatval($params['depth_h']);
21983		} else {
21984			$this->txtshadow['depth_h'] = 0;
21985		}
21986		if (isset($params['color']) AND ($params['color'] !== false) AND is_array($params['color'])) {
21987			$this->txtshadow['color'] = $params['color'];
21988		} else {
21989			$this->txtshadow['color'] = $this->strokecolor;
21990		}
21991		if (isset($params['opacity'])) {
21992			$this->txtshadow['opacity'] = min(1, max(0, floatval($params['opacity'])));
21993		} else {
21994			$this->txtshadow['opacity'] = 1;
21995		}
21996		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'))) {
21997			$this->txtshadow['blend_mode'] = $params['blend_mode'];
21998		} else {
21999			$this->txtshadow['blend_mode'] = 'Normal';
22000		}
22001		if ((($this->txtshadow['depth_w'] == 0) AND ($this->txtshadow['depth_h'] == 0)) OR ($this->txtshadow['opacity'] == 0)) {
22002			$this->txtshadow['enabled'] = false;
22003		}
22004	}
22005
22006	/**
22007	 * Return the text shadow parameters array.
22008	 * @return Array of parameters.
22009	 * @since 5.9.174 (2012-07-25)
22010	 * @public
22011	 */
22012	public function getTextShadow() {
22013		return $this->txtshadow;
22014	}
22015
22016	/**
22017	 * Returns an array of chars containing soft hyphens.
22018	 * @param $word (array) array of chars
22019	 * @param $patterns (array) Array of hypenation patterns.
22020	 * @param $dictionary (array) Array of words to be returned without applying the hyphenation algorithm.
22021	 * @param $leftmin (int) Minimum number of character to leave on the left of the word without applying the hyphens.
22022	 * @param $rightmin (int) Minimum number of character to leave on the right of the word without applying the hyphens.
22023	 * @param $charmin (int) Minimum word length to apply the hyphenation algorithm.
22024	 * @param $charmax (int) Maximum length of broken piece of word.
22025	 * @return array text with soft hyphens
22026	 * @author Nicola Asuni
22027	 * @since 4.9.012 (2010-04-12)
22028	 * @protected
22029	 */
22030	protected function hyphenateWord($word, $patterns, $dictionary=array(), $leftmin=1, $rightmin=2, $charmin=1, $charmax=8) {
22031		$hyphenword = array(); // hyphens positions
22032		$numchars = count($word);
22033		if ($numchars <= $charmin) {
22034			return $word;
22035		}
22036		$word_string = TCPDF_FONTS::UTF8ArrSubString($word, '', '', $this->isunicode);
22037		// some words will be returned as-is
22038		$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})(\]?)$/';
22039		if (preg_match($pattern, $word_string) > 0) {
22040			// email
22041			return $word;
22042		}
22043		$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})(\]?)$/';
22044		if (preg_match($pattern, $word_string) > 0) {
22045			// URL
22046			return $word;
22047		}
22048		if (isset($dictionary[$word_string])) {
22049			return TCPDF_FONTS::UTF8StringToArray($dictionary[$word_string], $this->isunicode, $this->CurrentFont);
22050		}
22051		// surround word with '_' characters
22052		$tmpword = array_merge(array(46), $word, array(46));
22053		$tmpnumchars = $numchars + 2;
22054		$maxpos = $tmpnumchars - 1;
22055		for ($pos = 0; $pos < $maxpos; ++$pos) {
22056			$imax = min(($tmpnumchars - $pos), $charmax);
22057			for ($i = 1; $i <= $imax; ++$i) {
22058				$subword = strtolower(TCPDF_FONTS::UTF8ArrSubString($tmpword, $pos, ($pos + $i), $this->isunicode));
22059				if (isset($patterns[$subword])) {
22060					$pattern = TCPDF_FONTS::UTF8StringToArray($patterns[$subword], $this->isunicode, $this->CurrentFont);
22061					$pattern_length = count($pattern);
22062					$digits = 1;
22063					for ($j = 0; $j < $pattern_length; ++$j) {
22064						// check if $pattern[$j] is a number = hyphenation level (only numbers from 1 to 5 are valid)
22065						if (($pattern[$j] >= 48) AND ($pattern[$j] <= 57)) {
22066							if ($j == 0) {
22067								$zero = $pos - 1;
22068							} else {
22069								$zero = $pos + $j - $digits;
22070							}
22071							// get hyphenation level
22072							$level = ($pattern[$j] - 48);
22073							// if two levels from two different patterns match at the same point, the higher one is selected.
22074							if (!isset($hyphenword[$zero]) OR ($hyphenword[$zero] < $level)) {
22075								$hyphenword[$zero] = $level;
22076							}
22077							++$digits;
22078						}
22079					}
22080				}
22081			}
22082		}
22083		$inserted = 0;
22084		$maxpos = $numchars - $rightmin;
22085		for ($i = $leftmin; $i <= $maxpos; ++$i) {
22086			// only odd levels indicate allowed hyphenation points
22087			if (isset($hyphenword[$i]) AND (($hyphenword[$i] % 2) != 0)) {
22088				// 173 = soft hyphen character
22089				array_splice($word, $i + $inserted, 0, 173);
22090				++$inserted;
22091			}
22092		}
22093		return $word;
22094	}
22095
22096	/**
22097	 * Returns text with soft hyphens.
22098	 * @param $text (string) text to process
22099	 * @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/
22100	 * @param $dictionary (array) Array of words to be returned without applying the hyphenation algorithm.
22101	 * @param $leftmin (int) Minimum number of character to leave on the left of the word without applying the hyphens.
22102	 * @param $rightmin (int) Minimum number of character to leave on the right of the word without applying the hyphens.
22103	 * @param $charmin (int) Minimum word length to apply the hyphenation algorithm.
22104	 * @param $charmax (int) Maximum length of broken piece of word.
22105	 * @return array text with soft hyphens
22106	 * @author Nicola Asuni
22107	 * @since 4.9.012 (2010-04-12)
22108	 * @public
22109	 */
22110	public function hyphenateText($text, $patterns, $dictionary=array(), $leftmin=1, $rightmin=2, $charmin=1, $charmax=8) {
22111		$text = $this->unhtmlentities($text);
22112		$word = array(); // last word
22113		$txtarr = array(); // text to be returned
22114		$intag = false; // true if we are inside an HTML tag
22115		$skip = false; // true to skip hyphenation
22116		if (!is_array($patterns)) {
22117			$patterns = TCPDF_STATIC::getHyphenPatternsFromTEX($patterns);
22118		}
22119		// get array of characters
22120		$unichars = TCPDF_FONTS::UTF8StringToArray($text, $this->isunicode, $this->CurrentFont);
22121		// for each char
22122		foreach ($unichars as $char) {
22123			if ((!$intag) AND (!$skip) AND TCPDF_FONT_DATA::$uni_type[$char] == 'L') {
22124				// letter character
22125				$word[] = $char;
22126			} else {
22127				// other type of character
22128				if (!TCPDF_STATIC::empty_string($word)) {
22129					// hypenate the word
22130					$txtarr = array_merge($txtarr, $this->hyphenateWord($word, $patterns, $dictionary, $leftmin, $rightmin, $charmin, $charmax));
22131					$word = array();
22132				}
22133				$txtarr[] = $char;
22134				if (chr($char) == '<') {
22135					// we are inside an HTML tag
22136					$intag = true;
22137				} elseif ($intag AND (chr($char) == '>')) {
22138					// end of HTML tag
22139					$intag = false;
22140					// check for style tag
22141					$expected = array(115, 116, 121, 108, 101); // = 'style'
22142					$current = array_slice($txtarr, -6, 5); // last 5 chars
22143					$compare = array_diff($expected, $current);
22144					if (empty($compare)) {
22145						// check if it is a closing tag
22146						$expected = array(47); // = '/'
22147						$current = array_slice($txtarr, -7, 1);
22148						$compare = array_diff($expected, $current);
22149						if (empty($compare)) {
22150							// closing style tag
22151							$skip = false;
22152						} else {
22153							// opening style tag
22154							$skip = true;
22155						}
22156					}
22157				}
22158			}
22159		}
22160		if (!TCPDF_STATIC::empty_string($word)) {
22161			// hypenate the word
22162			$txtarr = array_merge($txtarr, $this->hyphenateWord($word, $patterns, $dictionary, $leftmin, $rightmin, $charmin, $charmax));
22163		}
22164		// convert char array to string and return
22165		return TCPDF_FONTS::UTF8ArrSubString($txtarr, '', '', $this->isunicode);
22166	}
22167
22168	/**
22169	 * Enable/disable rasterization of vector images using ImageMagick library.
22170	 * @param $mode (boolean) if true enable rasterization, false otherwise.
22171	 * @public
22172	 * @since 5.0.000 (2010-04-27)
22173	 */
22174	public function setRasterizeVectorImages($mode) {
22175		$this->rasterize_vector_images = $mode;
22176	}
22177
22178	/**
22179	 * Enable or disable default option for font subsetting.
22180	 * @param $enable (boolean) if true enable font subsetting by default.
22181	 * @author Nicola Asuni
22182	 * @public
22183	 * @since 5.3.002 (2010-06-07)
22184	 */
22185	public function setFontSubsetting($enable=true) {
22186		if ($this->pdfa_mode) {
22187			$this->font_subsetting = false;
22188		} else {
22189			$this->font_subsetting = $enable ? true : false;
22190		}
22191	}
22192
22193	/**
22194	 * Return the default option for font subsetting.
22195	 * @return boolean default font subsetting state.
22196	 * @author Nicola Asuni
22197	 * @public
22198	 * @since 5.3.002 (2010-06-07)
22199	 */
22200	public function getFontSubsetting() {
22201		return $this->font_subsetting;
22202	}
22203
22204	/**
22205	 * Left trim the input string
22206	 * @param $str (string) string to trim
22207	 * @param $replace (string) string that replace spaces.
22208	 * @return left trimmed string
22209	 * @author Nicola Asuni
22210	 * @public
22211	 * @since 5.8.000 (2010-08-11)
22212	 */
22213	public function stringLeftTrim($str, $replace='') {
22214		return preg_replace('/^'.$this->re_space['p'].'+/'.$this->re_space['m'], $replace, $str);
22215	}
22216
22217	/**
22218	 * Right trim the input string
22219	 * @param $str (string) string to trim
22220	 * @param $replace (string) string that replace spaces.
22221	 * @return right trimmed string
22222	 * @author Nicola Asuni
22223	 * @public
22224	 * @since 5.8.000 (2010-08-11)
22225	 */
22226	public function stringRightTrim($str, $replace='') {
22227		return preg_replace('/'.$this->re_space['p'].'+$/'.$this->re_space['m'], $replace, $str);
22228	}
22229
22230	/**
22231	 * Trim the input string
22232	 * @param $str (string) string to trim
22233	 * @param $replace (string) string that replace spaces.
22234	 * @return trimmed string
22235	 * @author Nicola Asuni
22236	 * @public
22237	 * @since 5.8.000 (2010-08-11)
22238	 */
22239	public function stringTrim($str, $replace='') {
22240		$str = $this->stringLeftTrim($str, $replace);
22241		$str = $this->stringRightTrim($str, $replace);
22242		return $str;
22243	}
22244
22245	/**
22246	 * Return true if the current font is unicode type.
22247	 * @return true for unicode font, false otherwise.
22248	 * @author Nicola Asuni
22249	 * @public
22250	 * @since 5.8.002 (2010-08-14)
22251	 */
22252	public function isUnicodeFont() {
22253		return (($this->CurrentFont['type'] == 'TrueTypeUnicode') OR ($this->CurrentFont['type'] == 'cidfont0'));
22254	}
22255
22256	/**
22257	 * Return normalized font name
22258	 * @param $fontfamily (string) property string containing font family names
22259	 * @return string normalized font name
22260	 * @author Nicola Asuni
22261	 * @public
22262	 * @since 5.8.004 (2010-08-17)
22263	 */
22264	public function getFontFamilyName($fontfamily) {
22265		// remove spaces and symbols
22266		$fontfamily = preg_replace('/[^a-z0-9_\,]/', '', strtolower($fontfamily));
22267		// extract all font names
22268		$fontslist = preg_split('/[,]/', $fontfamily);
22269		// find first valid font name
22270		foreach ($fontslist as $font) {
22271			// replace font variations
22272			$font = preg_replace('/regular$/', '', $font);
22273			$font = preg_replace('/italic$/', 'I', $font);
22274			$font = preg_replace('/oblique$/', 'I', $font);
22275			$font = preg_replace('/bold([I]?)$/', 'B\\1', $font);
22276			// replace common family names and core fonts
22277			$pattern = array();
22278			$replacement = array();
22279			$pattern[] = '/^serif|^cursive|^fantasy|^timesnewroman/';
22280			$replacement[] = 'times';
22281			$pattern[] = '/^sansserif/';
22282			$replacement[] = 'helvetica';
22283			$pattern[] = '/^monospace/';
22284			$replacement[] = 'courier';
22285			$font = preg_replace($pattern, $replacement, $font);
22286			if (in_array(strtolower($font), $this->fontlist) OR in_array($font, $this->fontkeys)) {
22287				return $font;
22288			}
22289		}
22290		// return current font as default
22291		return $this->CurrentFont['fontkey'];
22292	}
22293
22294	/**
22295	 * Start a new XObject Template.
22296	 * 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).
22297	 * 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.
22298	 * Note: X,Y coordinates will be reset to 0,0.
22299	 * @param $w (int) Template width in user units (empty string or zero = page width less margins).
22300	 * @param $h (int) Template height in user units (empty string or zero = page height less margins).
22301	 * @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).
22302	 * @return int the XObject Template ID in case of success or false in case of error.
22303	 * @author Nicola Asuni
22304	 * @public
22305	 * @since 5.8.017 (2010-08-24)
22306	 * @see endTemplate(), printTemplate()
22307	 */
22308	public function startTemplate($w=0, $h=0, $group=false) {
22309		if ($this->inxobj) {
22310			// we are already inside an XObject template
22311			return false;
22312		}
22313		$this->inxobj = true;
22314		++$this->n;
22315		// XObject ID
22316		$this->xobjid = 'XT'.$this->n;
22317		// object ID
22318		$this->xobjects[$this->xobjid] = array('n' => $this->n);
22319		// store current graphic state
22320		$this->xobjects[$this->xobjid]['gvars'] = $this->getGraphicVars();
22321		// initialize data
22322		$this->xobjects[$this->xobjid]['intmrk'] = 0;
22323		$this->xobjects[$this->xobjid]['transfmrk'] = array();
22324		$this->xobjects[$this->xobjid]['outdata'] = '';
22325		$this->xobjects[$this->xobjid]['xobjects'] = array();
22326		$this->xobjects[$this->xobjid]['images'] = array();
22327		$this->xobjects[$this->xobjid]['fonts'] = array();
22328		$this->xobjects[$this->xobjid]['annotations'] = array();
22329		$this->xobjects[$this->xobjid]['extgstates'] = array();
22330		$this->xobjects[$this->xobjid]['gradients'] = array();
22331		$this->xobjects[$this->xobjid]['spot_colors'] = array();
22332		// set new environment
22333		$this->num_columns = 1;
22334		$this->current_column = 0;
22335		$this->SetAutoPageBreak(false);
22336		if (($w === '') OR ($w <= 0)) {
22337			$w = $this->w - $this->lMargin - $this->rMargin;
22338		}
22339		if (($h === '') OR ($h <= 0)) {
22340			$h = $this->h - $this->tMargin - $this->bMargin;
22341		}
22342		$this->xobjects[$this->xobjid]['x'] = 0;
22343		$this->xobjects[$this->xobjid]['y'] = 0;
22344		$this->xobjects[$this->xobjid]['w'] = $w;
22345		$this->xobjects[$this->xobjid]['h'] = $h;
22346		$this->w = $w;
22347		$this->h = $h;
22348		$this->wPt = $this->w * $this->k;
22349		$this->hPt = $this->h * $this->k;
22350		$this->fwPt = $this->wPt;
22351		$this->fhPt = $this->hPt;
22352		$this->x = 0;
22353		$this->y = 0;
22354		$this->lMargin = 0;
22355		$this->rMargin = 0;
22356		$this->tMargin = 0;
22357		$this->bMargin = 0;
22358		// set group mode
22359		$this->xobjects[$this->xobjid]['group'] = $group;
22360		return $this->xobjid;
22361	}
22362
22363	/**
22364	 * End the current XObject Template started with startTemplate() and restore the previous graphic state.
22365	 * 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).
22366	 * 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.
22367	 * @return int the XObject Template ID in case of success or false in case of error.
22368	 * @author Nicola Asuni
22369	 * @public
22370	 * @since 5.8.017 (2010-08-24)
22371	 * @see startTemplate(), printTemplate()
22372	 */
22373	public function endTemplate() {
22374		if (!$this->inxobj) {
22375			// we are not inside a template
22376			return false;
22377		}
22378		$this->inxobj = false;
22379		// restore previous graphic state
22380		$this->setGraphicVars($this->xobjects[$this->xobjid]['gvars'], true);
22381		return $this->xobjid;
22382	}
22383
22384	/**
22385	 * Print an XObject Template.
22386	 * You can print an XObject Template inside the currently opened Template.
22387	 * 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).
22388	 * 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.
22389	 * @param $id (string) The ID of XObject Template to print.
22390	 * @param $x (int) X position in user units (empty string = current x position)
22391	 * @param $y (int) Y position in user units (empty string = current y position)
22392	 * @param $w (int) Width in user units (zero = remaining page width)
22393	 * @param $h (int) Height in user units (zero = remaining page height)
22394	 * @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>
22395	 * @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>
22396	 * @param $fitonpage (boolean) If true the template is resized to not exceed page dimensions.
22397	 * @author Nicola Asuni
22398	 * @public
22399	 * @since 5.8.017 (2010-08-24)
22400	 * @see startTemplate(), endTemplate()
22401	 */
22402	public function printTemplate($id, $x='', $y='', $w=0, $h=0, $align='', $palign='', $fitonpage=false) {
22403		if ($this->state != 2) {
22404			 return;
22405		}
22406		if (!isset($this->xobjects[$id])) {
22407			$this->Error('The XObject Template \''.$id.'\' doesn\'t exist!');
22408		}
22409		if ($this->inxobj) {
22410			if ($id == $this->xobjid) {
22411				// close current template
22412				$this->endTemplate();
22413			} else {
22414				// use the template as resource for the template currently opened
22415				$this->xobjects[$this->xobjid]['xobjects'][$id] = $this->xobjects[$id];
22416			}
22417		}
22418		// set default values
22419		if ($x === '') {
22420			$x = $this->x;
22421		}
22422		if ($y === '') {
22423			$y = $this->y;
22424		}
22425		// check page for no-write regions and adapt page margins if necessary
22426		list($x, $y) = $this->checkPageRegions($h, $x, $y);
22427		$ow = $this->xobjects[$id]['w'];
22428		if ($ow <= 0) {
22429			$ow = 1;
22430		}
22431		$oh = $this->xobjects[$id]['h'];
22432		if ($oh <= 0) {
22433			$oh = 1;
22434		}
22435		// calculate template width and height on document
22436		if (($w <= 0) AND ($h <= 0)) {
22437			$w = $ow;
22438			$h = $oh;
22439		} elseif ($w <= 0) {
22440			$w = $h * $ow / $oh;
22441		} elseif ($h <= 0) {
22442			$h = $w * $oh / $ow;
22443		}
22444		// fit the template on available space
22445		list($w, $h, $x, $y) = $this->fitBlock($w, $h, $x, $y, $fitonpage);
22446		// set page alignment
22447		$rb_y = $y + $h;
22448		// set alignment
22449		if ($this->rtl) {
22450			if ($palign == 'L') {
22451				$xt = $this->lMargin;
22452			} elseif ($palign == 'C') {
22453				$xt = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
22454			} elseif ($palign == 'R') {
22455				$xt = $this->w - $this->rMargin - $w;
22456			} else {
22457				$xt = $x - $w;
22458			}
22459			$rb_x = $xt;
22460		} else {
22461			if ($palign == 'L') {
22462				$xt = $this->lMargin;
22463			} elseif ($palign == 'C') {
22464				$xt = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
22465			} elseif ($palign == 'R') {
22466				$xt = $this->w - $this->rMargin - $w;
22467			} else {
22468				$xt = $x;
22469			}
22470			$rb_x = $xt + $w;
22471		}
22472		// print XObject Template + Transformation matrix
22473		$this->StartTransform();
22474		// translate and scale
22475		$sx = ($w / $ow);
22476		$sy = ($h / $oh);
22477		$tm = array();
22478		$tm[0] = $sx;
22479		$tm[1] = 0;
22480		$tm[2] = 0;
22481		$tm[3] = $sy;
22482		$tm[4] = $xt * $this->k;
22483		$tm[5] = ($this->h - $h - $y) * $this->k;
22484		$this->Transform($tm);
22485		// set object
22486		$this->_out('/'.$id.' Do');
22487		$this->StopTransform();
22488		// add annotations
22489		if (!empty($this->xobjects[$id]['annotations'])) {
22490			foreach ($this->xobjects[$id]['annotations'] as $annot) {
22491				// transform original coordinates
22492				$coordlt = TCPDF_STATIC::getTransformationMatrixProduct($tm, array(1, 0, 0, 1, ($annot['x'] * $this->k), (-$annot['y'] * $this->k)));
22493				$ax = ($coordlt[4] / $this->k);
22494				$ay = ($this->h - $h - ($coordlt[5] / $this->k));
22495				$coordrb = TCPDF_STATIC::getTransformationMatrixProduct($tm, array(1, 0, 0, 1, (($annot['x'] + $annot['w']) * $this->k), ((-$annot['y'] - $annot['h']) * $this->k)));
22496				$aw = ($coordrb[4] / $this->k) - $ax;
22497				$ah = ($this->h - $h - ($coordrb[5] / $this->k)) - $ay;
22498				$this->Annotation($ax, $ay, $aw, $ah, $annot['text'], $annot['opt'], $annot['spaces']);
22499			}
22500		}
22501		// set pointer to align the next text/objects
22502		switch($align) {
22503			case 'T': {
22504				$this->y = $y;
22505				$this->x = $rb_x;
22506				break;
22507			}
22508			case 'M': {
22509				$this->y = $y + round($h/2);
22510				$this->x = $rb_x;
22511				break;
22512			}
22513			case 'B': {
22514				$this->y = $rb_y;
22515				$this->x = $rb_x;
22516				break;
22517			}
22518			case 'N': {
22519				$this->SetY($rb_y);
22520				break;
22521			}
22522			default:{
22523				break;
22524			}
22525		}
22526	}
22527
22528	/**
22529	 * Set the percentage of character stretching.
22530	 * @param $perc (int) percentage of stretching (100 = no stretching)
22531	 * @author Nicola Asuni
22532	 * @public
22533	 * @since 5.9.000 (2010-09-29)
22534	 */
22535	public function setFontStretching($perc=100) {
22536		$this->font_stretching = $perc;
22537	}
22538
22539	/**
22540	 * Get the percentage of character stretching.
22541	 * @return float stretching value
22542	 * @author Nicola Asuni
22543	 * @public
22544	 * @since 5.9.000 (2010-09-29)
22545	 */
22546	public function getFontStretching() {
22547		return $this->font_stretching;
22548	}
22549
22550	/**
22551	 * Set the amount to increase or decrease the space between characters in a text.
22552	 * @param $spacing (float) amount to increase or decrease the space between characters in a text (0 = default spacing)
22553	 * @author Nicola Asuni
22554	 * @public
22555	 * @since 5.9.000 (2010-09-29)
22556	 */
22557	public function setFontSpacing($spacing=0) {
22558		$this->font_spacing = $spacing;
22559	}
22560
22561	/**
22562	 * Get the amount to increase or decrease the space between characters in a text.
22563	 * @return int font spacing (tracking) value
22564	 * @author Nicola Asuni
22565	 * @public
22566	 * @since 5.9.000 (2010-09-29)
22567	 */
22568	public function getFontSpacing() {
22569		return $this->font_spacing;
22570	}
22571
22572	/**
22573	 * Return an array of no-write page regions
22574	 * @return array of no-write page regions
22575	 * @author Nicola Asuni
22576	 * @public
22577	 * @since 5.9.003 (2010-10-13)
22578	 * @see setPageRegions(), addPageRegion()
22579	 */
22580	public function getPageRegions() {
22581		return $this->page_regions;
22582	}
22583
22584	/**
22585	 * Set no-write regions on page.
22586	 * 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.
22587	 * A region is always aligned on the left or right side of the page ad is defined using a vertical segment.
22588	 * You can set multiple regions for the same page.
22589	 * @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.
22590	 * @author Nicola Asuni
22591	 * @public
22592	 * @since 5.9.003 (2010-10-13)
22593	 * @see addPageRegion(), getPageRegions()
22594	 */
22595	public function setPageRegions($regions=array()) {
22596		// empty current regions array
22597		$this->page_regions = array();
22598		// add regions
22599		foreach ($regions as $data) {
22600			$this->addPageRegion($data);
22601		}
22602	}
22603
22604	/**
22605	 * Add a single no-write region on selected page.
22606	 * 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.
22607	 * A region is always aligned on the left or right side of the page ad is defined using a vertical segment.
22608	 * You can set multiple regions for the same page.
22609	 * @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).
22610	 * @author Nicola Asuni
22611	 * @public
22612	 * @since 5.9.003 (2010-10-13)
22613	 * @see setPageRegions(), getPageRegions()
22614	 */
22615	public function addPageRegion($region) {
22616		if (!isset($region['page']) OR empty($region['page'])) {
22617			$region['page'] = $this->page;
22618		}
22619		if (isset($region['xt']) AND isset($region['xb']) AND ($region['xt'] > 0) AND ($region['xb'] > 0)
22620			AND isset($region['yt'])  AND isset($region['yb']) AND ($region['yt'] >= 0) AND ($region['yt'] < $region['yb'])
22621			AND isset($region['side']) AND (($region['side'] == 'L') OR ($region['side'] == 'R'))) {
22622			$this->page_regions[] = $region;
22623		}
22624	}
22625
22626	/**
22627	 * Remove a single no-write region.
22628	 * @param $key (int) region key
22629	 * @author Nicola Asuni
22630	 * @public
22631	 * @since 5.9.003 (2010-10-13)
22632	 * @see setPageRegions(), getPageRegions()
22633	 */
22634	public function removePageRegion($key) {
22635		if (isset($this->page_regions[$key])) {
22636			unset($this->page_regions[$key]);
22637		}
22638	}
22639
22640	/**
22641	 * Check page for no-write regions and adapt current coordinates and page margins if necessary.
22642	 * 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.
22643	 * A region is always aligned on the left or right side of the page ad is defined using a vertical segment.
22644	 * @param $h (float) height of the text/image/object to print in user units
22645	 * @param $x (float) current X coordinate in user units
22646	 * @param $y (float) current Y coordinate in user units
22647	 * @return array($x, $y)
22648	 * @author Nicola Asuni
22649	 * @protected
22650	 * @since 5.9.003 (2010-10-13)
22651	 */
22652	protected function checkPageRegions($h, $x, $y) {
22653		// set default values
22654		if ($x === '') {
22655			$x = $this->x;
22656		}
22657		if ($y === '') {
22658			$y = $this->y;
22659		}
22660		if (!$this->check_page_regions OR empty($this->page_regions)) {
22661			// no page regions defined
22662			return array($x, $y);
22663		}
22664		if (empty($h)) {
22665			$h = $this->getCellHeight($this->FontSize);
22666		}
22667		// check for page break
22668		if ($this->checkPageBreak($h, $y)) {
22669			// the content will be printed on a new page
22670			$x = $this->x;
22671			$y = $this->y;
22672		}
22673		if ($this->num_columns > 1) {
22674			if ($this->rtl) {
22675				$this->lMargin = ($this->columns[$this->current_column]['x'] - $this->columns[$this->current_column]['w']);
22676			} else {
22677				$this->rMargin = ($this->w - $this->columns[$this->current_column]['x'] - $this->columns[$this->current_column]['w']);
22678			}
22679		} else {
22680			if ($this->rtl) {
22681				$this->lMargin = max($this->clMargin, $this->original_lMargin);
22682			} else {
22683				$this->rMargin = max($this->crMargin, $this->original_rMargin);
22684			}
22685		}
22686		// adjust coordinates and page margins
22687		foreach ($this->page_regions as $regid => $regdata) {
22688			if ($regdata['page'] == $this->page) {
22689				// check region boundaries
22690				if (($y > ($regdata['yt'] - $h)) AND ($y <= $regdata['yb'])) {
22691					// Y is inside the region
22692					$minv = ($regdata['xb'] - $regdata['xt']) / ($regdata['yb'] - $regdata['yt']); // inverse of angular coefficient
22693					$yt = max($y, $regdata['yt']);
22694					$yb = min(($yt + $h), $regdata['yb']);
22695					$xt = (($yt - $regdata['yt']) * $minv) + $regdata['xt'];
22696					$xb = (($yb - $regdata['yt']) * $minv) + $regdata['xt'];
22697					if ($regdata['side'] == 'L') { // left side
22698						$new_margin = max($xt, $xb);
22699						if ($this->lMargin < $new_margin) {
22700							if ($this->rtl) {
22701								// adjust left page margin
22702								$this->lMargin = max(0, $new_margin);
22703							}
22704							if ($x < $new_margin) {
22705								// adjust x position
22706								$x = $new_margin;
22707								if ($new_margin > ($this->w - $this->rMargin)) {
22708									// adjust y position
22709									$y = $regdata['yb'] - $h;
22710								}
22711							}
22712						}
22713					} elseif ($regdata['side'] == 'R') { // right side
22714						$new_margin = min($xt, $xb);
22715						if (($this->w - $this->rMargin) > $new_margin) {
22716							if (!$this->rtl) {
22717								// adjust right page margin
22718								$this->rMargin = max(0, ($this->w - $new_margin));
22719							}
22720							if ($x > $new_margin) {
22721								// adjust x position
22722								$x = $new_margin;
22723								if ($new_margin > $this->lMargin) {
22724									// adjust y position
22725									$y = $regdata['yb'] - $h;
22726								}
22727							}
22728						}
22729					}
22730				}
22731			}
22732		}
22733		return array($x, $y);
22734	}
22735
22736	// --- SVG METHODS ---------------------------------------------------------
22737
22738	/**
22739	 * Embedd a Scalable Vector Graphics (SVG) image.
22740	 * NOTE: SVG standard is not yet fully implemented, use the setRasterizeVectorImages() method to enable/disable rasterization of vector images using ImageMagick library.
22741	 * @param $file (string) Name of the SVG file or a '@' character followed by the SVG data string.
22742	 * @param $x (float) Abscissa of the upper-left corner.
22743	 * @param $y (float) Ordinate of the upper-left corner.
22744	 * @param $w (float) Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
22745	 * @param $h (float) Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
22746	 * @param $link (mixed) URL or identifier returned by AddLink().
22747	 * @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.
22748	 * @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>
22749	 * @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)))
22750	 * @param $fitonpage (boolean) if true the image is resized to not exceed page dimensions.
22751	 * @author Nicola Asuni
22752	 * @since 5.0.000 (2010-05-02)
22753	 * @public
22754	 */
22755	public function ImageSVG($file, $x='', $y='', $w=0, $h=0, $link='', $align='', $palign='', $border=0, $fitonpage=false) {
22756		if ($this->state != 2) {
22757			 return;
22758		}
22759		// reset SVG vars
22760		$this->svggradients = array();
22761		$this->svggradientid = 0;
22762		$this->svgdefsmode = false;
22763		$this->svgdefs = array();
22764		$this->svgclipmode = false;
22765		$this->svgclippaths = array();
22766		$this->svgcliptm = array();
22767		$this->svgclipid = 0;
22768		$this->svgtext = '';
22769		$this->svgtextmode = array();
22770		if ($this->rasterize_vector_images AND ($w > 0) AND ($h > 0)) {
22771			// convert SVG to raster image using GD or ImageMagick libraries
22772			return $this->Image($file, $x, $y, $w, $h, 'SVG', $link, $align, true, 300, $palign, false, false, $border, false, false, false);
22773		}
22774		if ($file[0] === '@') { // image from string
22775			$this->svgdir = '';
22776			$svgdata = substr($file, 1);
22777		} else { // SVG file
22778			$this->svgdir = dirname($file);
22779			$svgdata = TCPDF_STATIC::fileGetContents($file);
22780		}
22781		if ($svgdata === FALSE) {
22782			$this->Error('SVG file not found: '.$file);
22783		}
22784		if ($x === '') {
22785			$x = $this->x;
22786		}
22787		if ($y === '') {
22788			$y = $this->y;
22789		}
22790		// check page for no-write regions and adapt page margins if necessary
22791		list($x, $y) = $this->checkPageRegions($h, $x, $y);
22792		$k = $this->k;
22793		$ox = 0;
22794		$oy = 0;
22795		$ow = $w;
22796		$oh = $h;
22797		$aspect_ratio_align = 'xMidYMid';
22798		$aspect_ratio_ms = 'meet';
22799		$regs = array();
22800		// get original image width and height
22801		preg_match('/<svg([^\>]*)>/si', $svgdata, $regs);
22802		if (isset($regs[1]) AND !empty($regs[1])) {
22803			$tmp = array();
22804			if (preg_match('/[\s]+x[\s]*=[\s]*"([^"]*)"/si', $regs[1], $tmp)) {
22805				$ox = $this->getHTMLUnitToUnits($tmp[1], 0, $this->svgunit, false);
22806			}
22807			$tmp = array();
22808			if (preg_match('/[\s]+y[\s]*=[\s]*"([^"]*)"/si', $regs[1], $tmp)) {
22809				$oy = $this->getHTMLUnitToUnits($tmp[1], 0, $this->svgunit, false);
22810			}
22811			$tmp = array();
22812			if (preg_match('/[\s]+width[\s]*=[\s]*"([^"]*)"/si', $regs[1], $tmp)) {
22813				$ow = $this->getHTMLUnitToUnits($tmp[1], 1, $this->svgunit, false);
22814			}
22815			$tmp = array();
22816			if (preg_match('/[\s]+height[\s]*=[\s]*"([^"]*)"/si', $regs[1], $tmp)) {
22817				$oh = $this->getHTMLUnitToUnits($tmp[1], 1, $this->svgunit, false);
22818			}
22819			$tmp = array();
22820			$view_box = array();
22821			if (preg_match('/[\s]+viewBox[\s]*=[\s]*"[\s]*([0-9\.\-]+)[\s]+([0-9\.\-]+)[\s]+([0-9\.]+)[\s]+([0-9\.]+)[\s]*"/si', $regs[1], $tmp)) {
22822				if (count($tmp) == 5) {
22823					array_shift($tmp);
22824					foreach ($tmp as $key => $val) {
22825						$view_box[$key] = $this->getHTMLUnitToUnits($val, 0, $this->svgunit, false);
22826					}
22827					$ox = $view_box[0];
22828					$oy = $view_box[1];
22829				}
22830				// get aspect ratio
22831				$tmp = array();
22832				if (preg_match('/[\s]+preserveAspectRatio[\s]*=[\s]*"([^"]*)"/si', $regs[1], $tmp)) {
22833					$aspect_ratio = preg_split('/[\s]+/si', $tmp[1]);
22834					switch (count($aspect_ratio)) {
22835						case 3: {
22836							$aspect_ratio_align = $aspect_ratio[1];
22837							$aspect_ratio_ms = $aspect_ratio[2];
22838							break;
22839						}
22840						case 2: {
22841							$aspect_ratio_align = $aspect_ratio[0];
22842							$aspect_ratio_ms = $aspect_ratio[1];
22843							break;
22844						}
22845						case 1: {
22846							$aspect_ratio_align = $aspect_ratio[0];
22847							$aspect_ratio_ms = 'meet';
22848							break;
22849						}
22850					}
22851				}
22852			}
22853		}
22854		if ($ow <= 0) {
22855			$ow = 1;
22856		}
22857		if ($oh <= 0) {
22858			$oh = 1;
22859		}
22860		// calculate image width and height on document
22861		if (($w <= 0) AND ($h <= 0)) {
22862			// convert image size to document unit
22863			$w = $ow;
22864			$h = $oh;
22865		} elseif ($w <= 0) {
22866			$w = $h * $ow / $oh;
22867		} elseif ($h <= 0) {
22868			$h = $w * $oh / $ow;
22869		}
22870		// fit the image on available space
22871		list($w, $h, $x, $y) = $this->fitBlock($w, $h, $x, $y, $fitonpage);
22872		if ($this->rasterize_vector_images) {
22873			// convert SVG to raster image using GD or ImageMagick libraries
22874			return $this->Image($file, $x, $y, $w, $h, 'SVG', $link, $align, true, 300, $palign, false, false, $border, false, false, false);
22875		}
22876		// set alignment
22877		$this->img_rb_y = $y + $h;
22878		// set alignment
22879		if ($this->rtl) {
22880			if ($palign == 'L') {
22881				$ximg = $this->lMargin;
22882			} elseif ($palign == 'C') {
22883				$ximg = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
22884			} elseif ($palign == 'R') {
22885				$ximg = $this->w - $this->rMargin - $w;
22886			} else {
22887				$ximg = $x - $w;
22888			}
22889			$this->img_rb_x = $ximg;
22890		} else {
22891			if ($palign == 'L') {
22892				$ximg = $this->lMargin;
22893			} elseif ($palign == 'C') {
22894				$ximg = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
22895			} elseif ($palign == 'R') {
22896				$ximg = $this->w - $this->rMargin - $w;
22897			} else {
22898				$ximg = $x;
22899			}
22900			$this->img_rb_x = $ximg + $w;
22901		}
22902		// store current graphic vars
22903		$gvars = $this->getGraphicVars();
22904		// store SVG position and scale factors
22905		$svgoffset_x = ($ximg - $ox) * $this->k;
22906		$svgoffset_y = -($y - $oy) * $this->k;
22907		if (isset($view_box[2]) AND ($view_box[2] > 0) AND ($view_box[3] > 0)) {
22908			$ow = $view_box[2];
22909			$oh = $view_box[3];
22910		} else {
22911			if ($ow <= 0) {
22912				$ow = $w;
22913			}
22914			if ($oh <= 0) {
22915				$oh = $h;
22916			}
22917		}
22918		$svgscale_x = $w / $ow;
22919		$svgscale_y = $h / $oh;
22920		// scaling and alignment
22921		if ($aspect_ratio_align != 'none') {
22922			// store current scaling values
22923			$svgscale_old_x = $svgscale_x;
22924			$svgscale_old_y = $svgscale_y;
22925			// force uniform scaling
22926			if ($aspect_ratio_ms == 'slice') {
22927				// the entire viewport is covered by the viewBox
22928				if ($svgscale_x > $svgscale_y) {
22929					$svgscale_y = $svgscale_x;
22930				} elseif ($svgscale_x < $svgscale_y) {
22931					$svgscale_x = $svgscale_y;
22932				}
22933			} else { // meet
22934				// the entire viewBox is visible within the viewport
22935				if ($svgscale_x < $svgscale_y) {
22936					$svgscale_y = $svgscale_x;
22937				} elseif ($svgscale_x > $svgscale_y) {
22938					$svgscale_x = $svgscale_y;
22939				}
22940			}
22941			// correct X alignment
22942			switch (substr($aspect_ratio_align, 1, 3)) {
22943				case 'Min': {
22944					// do nothing
22945					break;
22946				}
22947				case 'Max': {
22948					$svgoffset_x += (($w * $this->k) - ($ow * $this->k * $svgscale_x));
22949					break;
22950				}
22951				default:
22952				case 'Mid': {
22953					$svgoffset_x += ((($w * $this->k) - ($ow * $this->k * $svgscale_x)) / 2);
22954					break;
22955				}
22956			}
22957			// correct Y alignment
22958			switch (substr($aspect_ratio_align, 5)) {
22959				case 'Min': {
22960					// do nothing
22961					break;
22962				}
22963				case 'Max': {
22964					$svgoffset_y -= (($h * $this->k) - ($oh * $this->k * $svgscale_y));
22965					break;
22966				}
22967				default:
22968				case 'Mid': {
22969					$svgoffset_y -= ((($h * $this->k) - ($oh * $this->k * $svgscale_y)) / 2);
22970					break;
22971				}
22972			}
22973		}
22974		// store current page break mode
22975		$page_break_mode = $this->AutoPageBreak;
22976		$page_break_margin = $this->getBreakMargin();
22977		$cell_padding = $this->cell_padding;
22978		$this->SetCellPadding(0);
22979		$this->SetAutoPageBreak(false);
22980		// save the current graphic state
22981		$this->_out('q'.$this->epsmarker);
22982		// set initial clipping mask
22983		$this->Rect($ximg, $y, $w, $h, 'CNZ', array(), array());
22984		// scale and translate
22985		$e = $ox * $this->k * (1 - $svgscale_x);
22986		$f = ($this->h - $oy) * $this->k * (1 - $svgscale_y);
22987		$this->_out(sprintf('%F %F %F %F %F %F cm', $svgscale_x, 0, 0, $svgscale_y, ($e + $svgoffset_x), ($f + $svgoffset_y)));
22988		// creates a new XML parser to be used by the other XML functions
22989		$this->parser = xml_parser_create('UTF-8');
22990		// the following function allows to use parser inside object
22991		xml_set_object($this->parser, $this);
22992		// disable case-folding for this XML parser
22993		xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0);
22994		// sets the element handler functions for the XML parser
22995		xml_set_element_handler($this->parser, 'startSVGElementHandler', 'endSVGElementHandler');
22996		// sets the character data handler function for the XML parser
22997		xml_set_character_data_handler($this->parser, 'segSVGContentHandler');
22998		// start parsing an XML document
22999		if (!xml_parse($this->parser, $svgdata)) {
23000			$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));
23001			$this->Error($error_message);
23002		}
23003		// free this XML parser
23004		xml_parser_free($this->parser);
23005		// restore previous graphic state
23006		$this->_out($this->epsmarker.'Q');
23007		// restore graphic vars
23008		$this->setGraphicVars($gvars);
23009		$this->lasth = $gvars['lasth'];
23010		if (!empty($border)) {
23011			$bx = $this->x;
23012			$by = $this->y;
23013			$this->x = $ximg;
23014			if ($this->rtl) {
23015				$this->x += $w;
23016			}
23017			$this->y = $y;
23018			$this->Cell($w, $h, '', $border, 0, '', 0, '', 0, true);
23019			$this->x = $bx;
23020			$this->y = $by;
23021		}
23022		if ($link) {
23023			$this->Link($ximg, $y, $w, $h, $link, 0);
23024		}
23025		// set pointer to align the next text/objects
23026		switch($align) {
23027			case 'T':{
23028				$this->y = $y;
23029				$this->x = $this->img_rb_x;
23030				break;
23031			}
23032			case 'M':{
23033				$this->y = $y + round($h/2);
23034				$this->x = $this->img_rb_x;
23035				break;
23036			}
23037			case 'B':{
23038				$this->y = $this->img_rb_y;
23039				$this->x = $this->img_rb_x;
23040				break;
23041			}
23042			case 'N':{
23043				$this->SetY($this->img_rb_y);
23044				break;
23045			}
23046			default:{
23047				// restore pointer to starting position
23048				$this->x = $gvars['x'];
23049				$this->y = $gvars['y'];
23050				$this->page = $gvars['page'];
23051				$this->current_column = $gvars['current_column'];
23052				$this->tMargin = $gvars['tMargin'];
23053				$this->bMargin = $gvars['bMargin'];
23054				$this->w = $gvars['w'];
23055				$this->h = $gvars['h'];
23056				$this->wPt = $gvars['wPt'];
23057				$this->hPt = $gvars['hPt'];
23058				$this->fwPt = $gvars['fwPt'];
23059				$this->fhPt = $gvars['fhPt'];
23060				break;
23061			}
23062		}
23063		$this->endlinex = $this->img_rb_x;
23064		// restore page break
23065		$this->SetAutoPageBreak($page_break_mode, $page_break_margin);
23066		$this->cell_padding = $cell_padding;
23067	}
23068
23069	/**
23070	 * Convert SVG transformation matrix to PDF.
23071	 * @param $tm (array) original SVG transformation matrix
23072	 * @return array transformation matrix
23073	 * @protected
23074	 * @since 5.0.000 (2010-05-02)
23075	 */
23076	protected function convertSVGtMatrix($tm) {
23077		$a = $tm[0];
23078		$b = -$tm[1];
23079		$c = -$tm[2];
23080		$d = $tm[3];
23081		$e = $this->getHTMLUnitToUnits($tm[4], 1, $this->svgunit, false) * $this->k;
23082		$f = -$this->getHTMLUnitToUnits($tm[5], 1, $this->svgunit, false) * $this->k;
23083		$x = 0;
23084		$y = $this->h * $this->k;
23085		$e = ($x * (1 - $a)) - ($y * $c) + $e;
23086		$f = ($y * (1 - $d)) - ($x * $b) + $f;
23087		return array($a, $b, $c, $d, $e, $f);
23088	}
23089
23090	/**
23091	 * Apply SVG graphic transformation matrix.
23092	 * @param $tm (array) original SVG transformation matrix
23093	 * @protected
23094	 * @since 5.0.000 (2010-05-02)
23095	 */
23096	protected function SVGTransform($tm) {
23097		$this->Transform($this->convertSVGtMatrix($tm));
23098	}
23099
23100	/**
23101	 * Apply the requested SVG styles (*** TO BE COMPLETED ***)
23102	 * @param $svgstyle (array) array of SVG styles to apply
23103	 * @param $prevsvgstyle (array) array of previous SVG style
23104	 * @param $x (int) X origin of the bounding box
23105	 * @param $y (int) Y origin of the bounding box
23106	 * @param $w (int) width of the bounding box
23107	 * @param $h (int) height of the bounding box
23108	 * @param $clip_function (string) clip function
23109	 * @param $clip_params (array) array of parameters for clipping function
23110	 * @return object style
23111	 * @author Nicola Asuni
23112	 * @since 5.0.000 (2010-05-02)
23113	 * @protected
23114	 */
23115	protected function setSVGStyles($svgstyle, $prevsvgstyle, $x=0, $y=0, $w=1, $h=1, $clip_function='', $clip_params=array()) {
23116		if ($this->state != 2) {
23117			 return;
23118		}
23119		$objstyle = '';
23120		$minlen = (0.01 / $this->k); // minimum acceptable length
23121		if (!isset($svgstyle['opacity'])) {
23122			return $objstyle;
23123		}
23124		// clip-path
23125		$regs = array();
23126		if (preg_match('/url\([\s]*\#([^\)]*)\)/si', $svgstyle['clip-path'], $regs)) {
23127			$clip_path = $this->svgclippaths[$regs[1]];
23128			foreach ($clip_path as $cp) {
23129				$this->startSVGElementHandler('clip-path', $cp['name'], $cp['attribs'], $cp['tm']);
23130			}
23131		}
23132		// opacity
23133		if ($svgstyle['opacity'] != 1) {
23134			$this->setAlpha($svgstyle['opacity'], 'Normal', $svgstyle['opacity'], false);
23135		}
23136		// color
23137		$fill_color = TCPDF_COLORS::convertHTMLColorToDec($svgstyle['color'], $this->spot_colors);
23138		$this->SetFillColorArray($fill_color);
23139		// text color
23140		$text_color = TCPDF_COLORS::convertHTMLColorToDec($svgstyle['text-color'], $this->spot_colors);
23141		$this->SetTextColorArray($text_color);
23142		// clip
23143		if (preg_match('/rect\(([a-z0-9\-\.]*)[\s]*([a-z0-9\-\.]*)[\s]*([a-z0-9\-\.]*)[\s]*([a-z0-9\-\.]*)\)/si', $svgstyle['clip'], $regs)) {
23144			$top = (isset($regs[1])?$this->getHTMLUnitToUnits($regs[1], 0, $this->svgunit, false):0);
23145			$right = (isset($regs[2])?$this->getHTMLUnitToUnits($regs[2], 0, $this->svgunit, false):0);
23146			$bottom = (isset($regs[3])?$this->getHTMLUnitToUnits($regs[3], 0, $this->svgunit, false):0);
23147			$left = (isset($regs[4])?$this->getHTMLUnitToUnits($regs[4], 0, $this->svgunit, false):0);
23148			$cx = $x + $left;
23149			$cy = $y + $top;
23150			$cw = $w - $left - $right;
23151			$ch = $h - $top - $bottom;
23152			if ($svgstyle['clip-rule'] == 'evenodd') {
23153				$clip_rule = 'CNZ';
23154			} else {
23155				$clip_rule = 'CEO';
23156			}
23157			$this->Rect($cx, $cy, $cw, $ch, $clip_rule, array(), array());
23158		}
23159		// fill
23160		$regs = array();
23161		if (preg_match('/url\([\s]*\#([^\)]*)\)/si', $svgstyle['fill'], $regs)) {
23162			// gradient
23163			$gradient = $this->svggradients[$regs[1]];
23164			if (isset($gradient['xref'])) {
23165				// reference to another gradient definition
23166				$newgradient = $this->svggradients[$gradient['xref']];
23167				$newgradient['coords'] = $gradient['coords'];
23168				$newgradient['mode'] = $gradient['mode'];
23169				$newgradient['type'] = $gradient['type'];
23170				$newgradient['gradientUnits'] = $gradient['gradientUnits'];
23171				if (isset($gradient['gradientTransform'])) {
23172					$newgradient['gradientTransform'] = $gradient['gradientTransform'];
23173				}
23174				$gradient = $newgradient;
23175			}
23176			//save current Graphic State
23177			$this->_outSaveGraphicsState();
23178			//set clipping area
23179			if (!empty($clip_function) AND method_exists($this, $clip_function)) {
23180				$bbox = call_user_func_array(array($this, $clip_function), $clip_params);
23181				if ((!isset($gradient['type']) OR ($gradient['type'] != 3)) AND is_array($bbox) AND (count($bbox) == 4)) {
23182					list($x, $y, $w, $h) = $bbox;
23183				}
23184			}
23185			if ($gradient['mode'] == 'measure') {
23186				if (!isset($gradient['coords'][4])) {
23187					$gradient['coords'][4] = 0.5;
23188				}
23189				if (isset($gradient['gradientTransform']) AND !empty($gradient['gradientTransform'])) {
23190					$gtm = $gradient['gradientTransform'];
23191					// apply transformation matrix
23192					$xa = ($gtm[0] * $gradient['coords'][0]) + ($gtm[2] * $gradient['coords'][1]) + $gtm[4];
23193					$ya = ($gtm[1] * $gradient['coords'][0]) + ($gtm[3] * $gradient['coords'][1]) + $gtm[5];
23194					$xb = ($gtm[0] * $gradient['coords'][2]) + ($gtm[2] * $gradient['coords'][3]) + $gtm[4];
23195					$yb = ($gtm[1] * $gradient['coords'][2]) + ($gtm[3] * $gradient['coords'][3]) + $gtm[5];
23196					$r = sqrt(pow(($gtm[0] * $gradient['coords'][4]), 2) + pow(($gtm[1] * $gradient['coords'][4]), 2));
23197					$gradient['coords'][0] = $xa;
23198					$gradient['coords'][1] = $ya;
23199					$gradient['coords'][2] = $xb;
23200					$gradient['coords'][3] = $yb;
23201					$gradient['coords'][4] = $r;
23202				}
23203				// convert SVG coordinates to user units
23204				$gradient['coords'][0] = $this->getHTMLUnitToUnits($gradient['coords'][0], 0, $this->svgunit, false);
23205				$gradient['coords'][1] = $this->getHTMLUnitToUnits($gradient['coords'][1], 0, $this->svgunit, false);
23206				$gradient['coords'][2] = $this->getHTMLUnitToUnits($gradient['coords'][2], 0, $this->svgunit, false);
23207				$gradient['coords'][3] = $this->getHTMLUnitToUnits($gradient['coords'][3], 0, $this->svgunit, false);
23208				$gradient['coords'][4] = $this->getHTMLUnitToUnits($gradient['coords'][4], 0, $this->svgunit, false);
23209				if ($w <= $minlen) {
23210					$w = $minlen;
23211				}
23212				if ($h <= $minlen) {
23213					$h = $minlen;
23214				}
23215				// shift units
23216				if ($gradient['gradientUnits'] == 'objectBoundingBox') {
23217					// convert to SVG coordinate system
23218					$gradient['coords'][0] += $x;
23219					$gradient['coords'][1] += $y;
23220					$gradient['coords'][2] += $x;
23221					$gradient['coords'][3] += $y;
23222				}
23223				// calculate percentages
23224				$gradient['coords'][0] = (($gradient['coords'][0] - $x) / $w);
23225				$gradient['coords'][1] = (($gradient['coords'][1] - $y) / $h);
23226				$gradient['coords'][2] = (($gradient['coords'][2] - $x) / $w);
23227				$gradient['coords'][3] = (($gradient['coords'][3] - $y) / $h);
23228				$gradient['coords'][4] /= $w;
23229			} elseif ($gradient['mode'] == 'percentage') {
23230				foreach($gradient['coords'] as $key => $val) {
23231					$gradient['coords'][$key] = (intval($val) / 100);
23232					if ($val < 0) {
23233						$gradient['coords'][$key] = 0;
23234					} elseif ($val > 1) {
23235						$gradient['coords'][$key] = 1;
23236					}
23237				}
23238			}
23239			if (($gradient['type'] == 2) AND ($gradient['coords'][0] == $gradient['coords'][2]) AND ($gradient['coords'][1] == $gradient['coords'][3])) {
23240				// single color (no shading)
23241				$gradient['coords'][0] = 1;
23242				$gradient['coords'][1] = 0;
23243				$gradient['coords'][2] = 0.999;
23244				$gradient['coords'][3] = 0;
23245			}
23246			// swap Y coordinates
23247			$tmp = $gradient['coords'][1];
23248			$gradient['coords'][1] = $gradient['coords'][3];
23249			$gradient['coords'][3] = $tmp;
23250			// set transformation map for gradient
23251			$cy = ($this->h - $y);
23252			if ($gradient['type'] == 3) {
23253				// circular gradient
23254				$cy -= ($gradient['coords'][1] * ($w + $h));
23255				$h = $w = max($w, $h);
23256			} else {
23257				$cy -= $h;
23258			}
23259			$this->_out(sprintf('%F 0 0 %F %F %F cm', ($w * $this->k), ($h * $this->k), ($x * $this->k), ($cy * $this->k)));
23260			if (count($gradient['stops']) > 1) {
23261				$this->Gradient($gradient['type'], $gradient['coords'], $gradient['stops'], array(), false);
23262			}
23263		} elseif ($svgstyle['fill'] != 'none') {
23264			$fill_color = TCPDF_COLORS::convertHTMLColorToDec($svgstyle['fill'], $this->spot_colors);
23265			if ($svgstyle['fill-opacity'] != 1) {
23266				$this->setAlpha($this->alpha['CA'], 'Normal', $svgstyle['fill-opacity'], false);
23267			}
23268			$this->SetFillColorArray($fill_color);
23269			if ($svgstyle['fill-rule'] == 'evenodd') {
23270				$objstyle .= 'F*';
23271			} else {
23272				$objstyle .= 'F';
23273			}
23274		}
23275		// stroke
23276		if ($svgstyle['stroke'] != 'none') {
23277			if ($svgstyle['stroke-opacity'] != 1) {
23278				$this->setAlpha($svgstyle['stroke-opacity'], 'Normal', $this->alpha['ca'], false);
23279			} elseif (preg_match('/rgba\(\d+%?,\s*\d+%?,\s*\d+%?,\s*(\d+(?:\.\d+)?)\)/i', $svgstyle['stroke'], $rgba_matches)) {
23280				$this->setAlpha($rgba_matches[1], 'Normal', $this->alpha['ca'], false);
23281			}
23282			$stroke_style = array(
23283				'color' => TCPDF_COLORS::convertHTMLColorToDec($svgstyle['stroke'], $this->spot_colors),
23284				'width' => $this->getHTMLUnitToUnits($svgstyle['stroke-width'], 0, $this->svgunit, false),
23285				'cap' => $svgstyle['stroke-linecap'],
23286				'join' => $svgstyle['stroke-linejoin']
23287				);
23288			if (isset($svgstyle['stroke-dasharray']) AND !empty($svgstyle['stroke-dasharray']) AND ($svgstyle['stroke-dasharray'] != 'none')) {
23289				$stroke_style['dash'] = $svgstyle['stroke-dasharray'];
23290			}
23291			$this->SetLineStyle($stroke_style);
23292			$objstyle .= 'D';
23293		}
23294		// font
23295		$regs = array();
23296		if (!empty($svgstyle['font'])) {
23297			if (preg_match('/font-family[\s]*:[\s]*([^\;\"]*)/si', $svgstyle['font'], $regs)) {
23298				$font_family = $this->getFontFamilyName($regs[1]);
23299			} else {
23300				$font_family = $svgstyle['font-family'];
23301			}
23302			if (preg_match('/font-size[\s]*:[\s]*([^\s\;\"]*)/si', $svgstyle['font'], $regs)) {
23303				$font_size = trim($regs[1]);
23304			} else {
23305				$font_size = $svgstyle['font-size'];
23306			}
23307			if (preg_match('/font-style[\s]*:[\s]*([^\s\;\"]*)/si', $svgstyle['font'], $regs)) {
23308				$font_style = trim($regs[1]);
23309			} else {
23310				$font_style = $svgstyle['font-style'];
23311			}
23312			if (preg_match('/font-weight[\s]*:[\s]*([^\s\;\"]*)/si', $svgstyle['font'], $regs)) {
23313				$font_weight = trim($regs[1]);
23314			} else {
23315				$font_weight = $svgstyle['font-weight'];
23316			}
23317			if (preg_match('/font-stretch[\s]*:[\s]*([^\s\;\"]*)/si', $svgstyle['font'], $regs)) {
23318				$font_stretch = trim($regs[1]);
23319			} else {
23320				$font_stretch = $svgstyle['font-stretch'];
23321			}
23322			if (preg_match('/letter-spacing[\s]*:[\s]*([^\s\;\"]*)/si', $svgstyle['font'], $regs)) {
23323				$font_spacing = trim($regs[1]);
23324			} else {
23325				$font_spacing = $svgstyle['letter-spacing'];
23326			}
23327		} else {
23328			$font_family = $this->getFontFamilyName($svgstyle['font-family']);
23329			$font_size = $svgstyle['font-size'];
23330			$font_style = $svgstyle['font-style'];
23331			$font_weight = $svgstyle['font-weight'];
23332			$font_stretch = $svgstyle['font-stretch'];
23333			$font_spacing = $svgstyle['letter-spacing'];
23334		}
23335		$font_size = $this->getHTMLFontUnits($font_size, $this->svgstyles[0]['font-size'], $prevsvgstyle['font-size'], $this->svgunit);
23336		$font_stretch = $this->getCSSFontStretching($font_stretch, $svgstyle['font-stretch']);
23337		$font_spacing = $this->getCSSFontSpacing($font_spacing, $svgstyle['letter-spacing']);
23338		switch ($font_style) {
23339			case 'italic': {
23340				$font_style = 'I';
23341				break;
23342			}
23343			case 'oblique': {
23344				$font_style = 'I';
23345				break;
23346			}
23347			default:
23348			case 'normal': {
23349				$font_style = '';
23350				break;
23351			}
23352		}
23353		switch ($font_weight) {
23354			case 'bold':
23355			case 'bolder': {
23356				$font_style .= 'B';
23357				break;
23358			}
23359			case 'normal': {
23360				if ((substr($font_family, -1) == 'I') AND (substr($font_family, -2, 1) == 'B')) {
23361					$font_family = substr($font_family, 0, -2).'I';
23362				} elseif (substr($font_family, -1) == 'B') {
23363					$font_family = substr($font_family, 0, -1);
23364				}
23365				break;
23366			}
23367		}
23368		switch ($svgstyle['text-decoration']) {
23369			case 'underline': {
23370				$font_style .= 'U';
23371				break;
23372			}
23373			case 'overline': {
23374				$font_style .= 'O';
23375				break;
23376			}
23377			case 'line-through': {
23378				$font_style .= 'D';
23379				break;
23380			}
23381			default:
23382			case 'none': {
23383				break;
23384			}
23385		}
23386		$this->SetFont($font_family, $font_style, $font_size);
23387		$this->setFontStretching($font_stretch);
23388		$this->setFontSpacing($font_spacing);
23389		return $objstyle;
23390	}
23391
23392	/**
23393	 * Draws an SVG path
23394	 * @param $d (string) attribute d of the path SVG element
23395	 * @param $style (string) Style of rendering. Possible values are:
23396	 * <ul>
23397	 *	 <li>D or empty string: Draw (default).</li>
23398	 *	 <li>F: Fill.</li>
23399	 *	 <li>F*: Fill using the even-odd rule to determine which regions lie inside the clipping path.</li>
23400	 *	 <li>DF or FD: Draw and fill.</li>
23401	 *	 <li>DF* or FD*: Draw and fill using the even-odd rule to determine which regions lie inside the clipping path.</li>
23402	 *	 <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
23403	 *	 <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
23404	 * </ul>
23405	 * @return array of container box measures (x, y, w, h)
23406	 * @author Nicola Asuni
23407	 * @since 5.0.000 (2010-05-02)
23408	 * @protected
23409	 */
23410	protected function SVGPath($d, $style='') {
23411		if ($this->state != 2) {
23412			return;
23413		}
23414		// set fill/stroke style
23415		$op = TCPDF_STATIC::getPathPaintOperator($style, '');
23416		if (empty($op)) {
23417			return;
23418		}
23419		$paths = array();
23420		$d = preg_replace('/([0-9ACHLMQSTVZ])([\-\+])/si', '\\1 \\2', $d);
23421		preg_match_all('/([ACHLMQSTVZ])[\s]*([^ACHLMQSTVZ\"]*)/si', $d, $paths, PREG_SET_ORDER);
23422		$x = 0;
23423		$y = 0;
23424		$x1 = 0;
23425		$y1 = 0;
23426		$x2 = 0;
23427		$y2 = 0;
23428		$xmin = 2147483647;
23429		$xmax = 0;
23430		$ymin = 2147483647;
23431		$ymax = 0;
23432		$xinitial = 0;
23433		$yinitial = 0;
23434		$relcoord = false;
23435		$minlen = (0.01 / $this->k); // minimum acceptable length (3 point)
23436		$firstcmd = true; // used to print first point
23437		// draw curve pieces
23438		foreach ($paths as $key => $val) {
23439			// get curve type
23440			$cmd = trim($val[1]);
23441			if (strtolower($cmd) == $cmd) {
23442				// use relative coordinated instead of absolute
23443				$relcoord = true;
23444				$xoffset = $x;
23445				$yoffset = $y;
23446			} else {
23447				$relcoord = false;
23448				$xoffset = 0;
23449				$yoffset = 0;
23450			}
23451			$params = array();
23452			if (isset($val[2])) {
23453				// get curve parameters
23454				$rawparams = preg_split('/([\,\s]+)/si', trim($val[2]));
23455				$params = array();
23456				foreach ($rawparams as $ck => $cp) {
23457					$params[$ck] = $this->getHTMLUnitToUnits($cp, 0, $this->svgunit, false);
23458					if (abs($params[$ck]) < $minlen) {
23459						// approximate little values to zero
23460						$params[$ck] = 0;
23461					}
23462				}
23463			}
23464			// store current origin point
23465			$x0 = $x;
23466			$y0 = $y;
23467			switch (strtoupper($cmd)) {
23468				case 'M': { // moveto
23469					foreach ($params as $ck => $cp) {
23470						if (($ck % 2) == 0) {
23471							$x = $cp + $xoffset;
23472						} else {
23473							$y = $cp + $yoffset;
23474							if ($firstcmd OR (abs($x0 - $x) >= $minlen) OR (abs($y0 - $y) >= $minlen)) {
23475								if ($ck == 1) {
23476									$this->_outPoint($x, $y);
23477									$firstcmd = false;
23478									$xinitial = $x;
23479									$yinitial = $y;
23480								} else {
23481									$this->_outLine($x, $y);
23482								}
23483								$x0 = $x;
23484								$y0 = $y;
23485							}
23486							$xmin = min($xmin, $x);
23487							$ymin = min($ymin, $y);
23488							$xmax = max($xmax, $x);
23489							$ymax = max($ymax, $y);
23490							if ($relcoord) {
23491								$xoffset = $x;
23492								$yoffset = $y;
23493							}
23494						}
23495					}
23496					break;
23497				}
23498				case 'L': { // lineto
23499					foreach ($params as $ck => $cp) {
23500						if (($ck % 2) == 0) {
23501							$x = $cp + $xoffset;
23502						} else {
23503							$y = $cp + $yoffset;
23504							if ((abs($x0 - $x) >= $minlen) OR (abs($y0 - $y) >= $minlen)) {
23505								$this->_outLine($x, $y);
23506								$x0 = $x;
23507								$y0 = $y;
23508							}
23509							$xmin = min($xmin, $x);
23510							$ymin = min($ymin, $y);
23511							$xmax = max($xmax, $x);
23512							$ymax = max($ymax, $y);
23513							if ($relcoord) {
23514								$xoffset = $x;
23515								$yoffset = $y;
23516							}
23517						}
23518					}
23519					break;
23520				}
23521				case 'H': { // horizontal lineto
23522					foreach ($params as $ck => $cp) {
23523						$x = $cp + $xoffset;
23524						if ((abs($x0 - $x) >= $minlen) OR (abs($y0 - $y) >= $minlen)) {
23525							$this->_outLine($x, $y);
23526							$x0 = $x;
23527							$y0 = $y;
23528						}
23529						$xmin = min($xmin, $x);
23530						$xmax = max($xmax, $x);
23531						if ($relcoord) {
23532							$xoffset = $x;
23533						}
23534					}
23535					break;
23536				}
23537				case 'V': { // vertical lineto
23538					foreach ($params as $ck => $cp) {
23539						$y = $cp + $yoffset;
23540						if ((abs($x0 - $x) >= $minlen) OR (abs($y0 - $y) >= $minlen)) {
23541							$this->_outLine($x, $y);
23542							$x0 = $x;
23543							$y0 = $y;
23544						}
23545						$ymin = min($ymin, $y);
23546						$ymax = max($ymax, $y);
23547						if ($relcoord) {
23548							$yoffset = $y;
23549						}
23550					}
23551					break;
23552				}
23553				case 'C': { // curveto
23554					foreach ($params as $ck => $cp) {
23555						$params[$ck] = $cp;
23556						if ((($ck + 1) % 6) == 0) {
23557							$x1 = $params[($ck - 5)] + $xoffset;
23558							$y1 = $params[($ck - 4)] + $yoffset;
23559							$x2 = $params[($ck - 3)] + $xoffset;
23560							$y2 = $params[($ck - 2)] + $yoffset;
23561							$x = $params[($ck - 1)] + $xoffset;
23562							$y = $params[($ck)] + $yoffset;
23563							$this->_outCurve($x1, $y1, $x2, $y2, $x, $y);
23564							$xmin = min($xmin, $x, $x1, $x2);
23565							$ymin = min($ymin, $y, $y1, $y2);
23566							$xmax = max($xmax, $x, $x1, $x2);
23567							$ymax = max($ymax, $y, $y1, $y2);
23568							if ($relcoord) {
23569								$xoffset = $x;
23570								$yoffset = $y;
23571							}
23572						}
23573					}
23574					break;
23575				}
23576				case 'S': { // shorthand/smooth curveto
23577					foreach ($params as $ck => $cp) {
23578						$params[$ck] = $cp;
23579						if ((($ck + 1) % 4) == 0) {
23580							if (($key > 0) AND ((strtoupper($paths[($key - 1)][1]) == 'C') OR (strtoupper($paths[($key - 1)][1]) == 'S'))) {
23581								$x1 = (2 * $x) - $x2;
23582								$y1 = (2 * $y) - $y2;
23583							} else {
23584								$x1 = $x;
23585								$y1 = $y;
23586							}
23587							$x2 = $params[($ck - 3)] + $xoffset;
23588							$y2 = $params[($ck - 2)] + $yoffset;
23589							$x = $params[($ck - 1)] + $xoffset;
23590							$y = $params[($ck)] + $yoffset;
23591							$this->_outCurve($x1, $y1, $x2, $y2, $x, $y);
23592							$xmin = min($xmin, $x, $x1, $x2);
23593							$ymin = min($ymin, $y, $y1, $y2);
23594							$xmax = max($xmax, $x, $x1, $x2);
23595							$ymax = max($ymax, $y, $y1, $y2);
23596							if ($relcoord) {
23597								$xoffset = $x;
23598								$yoffset = $y;
23599							}
23600						}
23601					}
23602					break;
23603				}
23604				case 'Q': { // quadratic Bezier curveto
23605					foreach ($params as $ck => $cp) {
23606						$params[$ck] = $cp;
23607						if ((($ck + 1) % 4) == 0) {
23608							// convert quadratic points to cubic points
23609							$x1 = $params[($ck - 3)] + $xoffset;
23610							$y1 = $params[($ck - 2)] + $yoffset;
23611							$xa = ($x + (2 * $x1)) / 3;
23612							$ya = ($y + (2 * $y1)) / 3;
23613							$x = $params[($ck - 1)] + $xoffset;
23614							$y = $params[($ck)] + $yoffset;
23615							$xb = ($x + (2 * $x1)) / 3;
23616							$yb = ($y + (2 * $y1)) / 3;
23617							$this->_outCurve($xa, $ya, $xb, $yb, $x, $y);
23618							$xmin = min($xmin, $x, $xa, $xb);
23619							$ymin = min($ymin, $y, $ya, $yb);
23620							$xmax = max($xmax, $x, $xa, $xb);
23621							$ymax = max($ymax, $y, $ya, $yb);
23622							if ($relcoord) {
23623								$xoffset = $x;
23624								$yoffset = $y;
23625							}
23626						}
23627					}
23628					break;
23629				}
23630				case 'T': { // shorthand/smooth quadratic Bezier curveto
23631					foreach ($params as $ck => $cp) {
23632						$params[$ck] = $cp;
23633						if (($ck % 2) != 0) {
23634							if (($key > 0) AND ((strtoupper($paths[($key - 1)][1]) == 'Q') OR (strtoupper($paths[($key - 1)][1]) == 'T'))) {
23635								$x1 = (2 * $x) - $x1;
23636								$y1 = (2 * $y) - $y1;
23637							} else {
23638								$x1 = $x;
23639								$y1 = $y;
23640							}
23641							// convert quadratic points to cubic points
23642							$xa = ($x + (2 * $x1)) / 3;
23643							$ya = ($y + (2 * $y1)) / 3;
23644							$x = $params[($ck - 1)] + $xoffset;
23645							$y = $params[($ck)] + $yoffset;
23646							$xb = ($x + (2 * $x1)) / 3;
23647							$yb = ($y + (2 * $y1)) / 3;
23648							$this->_outCurve($xa, $ya, $xb, $yb, $x, $y);
23649							$xmin = min($xmin, $x, $xa, $xb);
23650							$ymin = min($ymin, $y, $ya, $yb);
23651							$xmax = max($xmax, $x, $xa, $xb);
23652							$ymax = max($ymax, $y, $ya, $yb);
23653							if ($relcoord) {
23654								$xoffset = $x;
23655								$yoffset = $y;
23656							}
23657						}
23658					}
23659					break;
23660				}
23661				case 'A': { // elliptical arc
23662					foreach ($params as $ck => $cp) {
23663						$params[$ck] = $cp;
23664						if ((($ck + 1) % 7) == 0) {
23665							$x0 = $x;
23666							$y0 = $y;
23667							$rx = max(abs($params[($ck - 6)]), .000000001);
23668							$ry = max(abs($params[($ck - 5)]), .000000001);
23669							$ang = -$rawparams[($ck - 4)];
23670							$angle = deg2rad($ang);
23671							$fa = $rawparams[($ck - 3)]; // large-arc-flag
23672							$fs = $rawparams[($ck - 2)]; // sweep-flag
23673							$x = $params[($ck - 1)] + $xoffset;
23674							$y = $params[$ck] + $yoffset;
23675							if ((abs($x0 - $x) < $minlen) AND (abs($y0 - $y) < $minlen)) {
23676								// endpoints are almost identical
23677								$xmin = min($xmin, $x);
23678								$ymin = min($ymin, $y);
23679								$xmax = max($xmax, $x);
23680								$ymax = max($ymax, $y);
23681							} else {
23682								$cos_ang = cos($angle);
23683								$sin_ang = sin($angle);
23684								$a = (($x0 - $x) / 2);
23685								$b = (($y0 - $y) / 2);
23686								$xa = ($a * $cos_ang) - ($b * $sin_ang);
23687								$ya = ($a * $sin_ang) + ($b * $cos_ang);
23688								$rx2 = $rx * $rx;
23689								$ry2 = $ry * $ry;
23690								$xa2 = $xa * $xa;
23691								$ya2 = $ya * $ya;
23692								$delta = ($xa2 / $rx2) + ($ya2 / $ry2);
23693								if ($delta > 1) {
23694									$rx *= sqrt($delta);
23695									$ry *= sqrt($delta);
23696									$rx2 = $rx * $rx;
23697									$ry2 = $ry * $ry;
23698								}
23699								$numerator = (($rx2 * $ry2) - ($rx2 * $ya2) - ($ry2 * $xa2));
23700								if ($numerator < 0) {
23701									$root = 0;
23702								} else {
23703									$root = sqrt($numerator / (($rx2 * $ya2) + ($ry2 * $xa2)));
23704								}
23705								if ($fa == $fs){
23706									$root *= -1;
23707								}
23708								$cax = $root * (($rx * $ya) / $ry);
23709								$cay = -$root * (($ry * $xa) / $rx);
23710								// coordinates of ellipse center
23711								$cx = ($cax * $cos_ang) - ($cay * $sin_ang) + (($x0 + $x) / 2);
23712								$cy = ($cax * $sin_ang) + ($cay * $cos_ang) + (($y0 + $y) / 2);
23713								// get angles
23714								$angs = TCPDF_STATIC::getVectorsAngle(1, 0, (($xa - $cax) / $rx), (($cay - $ya) / $ry));
23715								$dang = TCPDF_STATIC::getVectorsAngle((($xa - $cax) / $rx), (($ya - $cay) / $ry), ((-$xa - $cax) / $rx), ((-$ya - $cay) / $ry));
23716								if (($fs == 0) AND ($dang > 0)) {
23717									$dang -= (2 * M_PI);
23718								} elseif (($fs == 1) AND ($dang < 0)) {
23719									$dang += (2 * M_PI);
23720								}
23721								$angf = $angs - $dang;
23722								if ((($fs == 0) AND ($angs > $angf)) OR (($fs == 1) AND ($angs < $angf))) {
23723									// reverse angles
23724									$tmp = $angs;
23725									$angs = $angf;
23726									$angf = $tmp;
23727								}
23728								$angs = round(rad2deg($angs), 6);
23729								$angf = round(rad2deg($angf), 6);
23730								// covent angles to positive values
23731								if (($angs < 0) AND ($angf < 0)) {
23732									$angs += 360;
23733									$angf += 360;
23734								}
23735								$pie = false;
23736								if (($key == 0) AND (isset($paths[($key + 1)][1])) AND (trim($paths[($key + 1)][1]) == 'z')) {
23737									$pie = true;
23738								}
23739								list($axmin, $aymin, $axmax, $aymax) = $this->_outellipticalarc($cx, $cy, $rx, $ry, $ang, $angs, $angf, $pie, 2, false, ($fs == 0), true);
23740								$xmin = min($xmin, $x, $axmin);
23741								$ymin = min($ymin, $y, $aymin);
23742								$xmax = max($xmax, $x, $axmax);
23743								$ymax = max($ymax, $y, $aymax);
23744							}
23745							if ($relcoord) {
23746								$xoffset = $x;
23747								$yoffset = $y;
23748							}
23749						}
23750					}
23751					break;
23752				}
23753				case 'Z': {
23754					$this->_out('h');
23755					$x = $x0 = $xinitial;
23756					$y = $y0 = $yinitial;
23757					break;
23758				}
23759			}
23760			$firstcmd = false;
23761		} // end foreach
23762		if (!empty($op)) {
23763			$this->_out($op);
23764		}
23765		return array($xmin, $ymin, ($xmax - $xmin), ($ymax - $ymin));
23766	}
23767
23768	/**
23769	 * Return the tag name without the namespace
23770	 * @param $name (string) Tag name
23771	 * @protected
23772	 */
23773	protected function removeTagNamespace($name) {
23774		if(strpos($name, ':') !== false) {
23775			$parts = explode(':', $name);
23776			return $parts[(sizeof($parts) - 1)];
23777		}
23778		return $name;
23779	}
23780
23781	/**
23782	 * Sets the opening SVG element handler function for the XML parser. (*** TO BE COMPLETED ***)
23783	 * @param $parser (resource) The first parameter, parser, is a reference to the XML parser calling the handler.
23784	 * @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.
23785	 * @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.
23786	 * @param $ctm (array) tranformation matrix for clipping mode (starting transformation matrix).
23787	 * @author Nicola Asuni
23788	 * @since 5.0.000 (2010-05-02)
23789	 * @protected
23790	 */
23791	protected function startSVGElementHandler($parser, $name, $attribs, $ctm=array()) {
23792		$name = $this->removeTagNamespace($name);
23793		// check if we are in clip mode
23794		if ($this->svgclipmode) {
23795			$this->svgclippaths[$this->svgclipid][] = array('name' => $name, 'attribs' => $attribs, 'tm' => $this->svgcliptm[$this->svgclipid]);
23796			return;
23797		}
23798		if ($this->svgdefsmode AND !in_array($name, array('clipPath', 'linearGradient', 'radialGradient', 'stop'))) {
23799			if (isset($attribs['id'])) {
23800				$attribs['child_elements'] = array();
23801				$this->svgdefs[$attribs['id']] = array('name' => $name, 'attribs' => $attribs);
23802				return;
23803			}
23804			if (end($this->svgdefs) !== FALSE) {
23805				$last_svgdefs_id = key($this->svgdefs);
23806				if (isset($this->svgdefs[$last_svgdefs_id]['attribs']['child_elements'])) {
23807					$attribs['id'] = 'DF_'.(count($this->svgdefs[$last_svgdefs_id]['attribs']['child_elements']) + 1);
23808					$this->svgdefs[$last_svgdefs_id]['attribs']['child_elements'][$attribs['id']] = array('name' => $name, 'attribs' => $attribs);
23809					return;
23810				}
23811			}
23812			return;
23813		}
23814		$clipping = false;
23815		if ($parser == 'clip-path') {
23816			// set clipping mode
23817			$clipping = true;
23818		}
23819		// get styling properties
23820		$prev_svgstyle = $this->svgstyles[max(0,(count($this->svgstyles) - 1))]; // previous style
23821		$svgstyle = $this->svgstyles[0]; // set default style
23822		if ($clipping AND !isset($attribs['fill']) AND (!isset($attribs['style']) OR (!preg_match('/[;\"\s]{1}fill[\s]*:[\s]*([^;\"]*)/si', $attribs['style'], $attrval)))) {
23823			// default fill attribute for clipping
23824			$attribs['fill'] = 'none';
23825		}
23826		if (isset($attribs['style']) AND !TCPDF_STATIC::empty_string($attribs['style']) AND ($attribs['style'][0] != ';')) {
23827			// fix style for regular expression
23828			$attribs['style'] = ';'.$attribs['style'];
23829		}
23830		foreach ($prev_svgstyle as $key => $val) {
23831			if (in_array($key, TCPDF_IMAGES::$svginheritprop)) {
23832				// inherit previous value
23833				$svgstyle[$key] = $val;
23834			}
23835			if (isset($attribs[$key]) AND !TCPDF_STATIC::empty_string($attribs[$key])) {
23836				// specific attribute settings
23837				if ($attribs[$key] == 'inherit') {
23838					$svgstyle[$key] = $val;
23839				} else {
23840					$svgstyle[$key] = $attribs[$key];
23841				}
23842			} elseif (isset($attribs['style']) AND !TCPDF_STATIC::empty_string($attribs['style'])) {
23843				// CSS style syntax
23844				$attrval = array();
23845				if (preg_match('/[;\"\s]{1}'.$key.'[\s]*:[\s]*([^;\"]*)/si', $attribs['style'], $attrval) AND isset($attrval[1])) {
23846					if ($attrval[1] == 'inherit') {
23847						$svgstyle[$key] = $val;
23848					} else {
23849						$svgstyle[$key] = $attrval[1];
23850					}
23851				}
23852			}
23853		}
23854		// transformation matrix
23855		if (!empty($ctm)) {
23856			$tm = $ctm;
23857		} else {
23858			$tm = array(1,0,0,1,0,0);
23859		}
23860		if (isset($attribs['transform']) AND !empty($attribs['transform'])) {
23861			$tm = TCPDF_STATIC::getTransformationMatrixProduct($tm, TCPDF_STATIC::getSVGTransformMatrix($attribs['transform']));
23862		}
23863		$svgstyle['transfmatrix'] = $tm;
23864		$invisible = false;
23865		if (($svgstyle['visibility'] == 'hidden') OR ($svgstyle['visibility'] == 'collapse') OR ($svgstyle['display'] == 'none')) {
23866			// the current graphics element is invisible (nothing is painted)
23867			$invisible = true;
23868		}
23869		// process tag
23870		switch($name) {
23871			case 'defs': {
23872				$this->svgdefsmode = true;
23873				break;
23874			}
23875			// clipPath
23876			case 'clipPath': {
23877				if ($invisible) {
23878					break;
23879				}
23880				$this->svgclipmode = true;
23881				if (!isset($attribs['id'])) {
23882					$attribs['id'] = 'CP_'.(count($this->svgcliptm) + 1);
23883				}
23884				$this->svgclipid = $attribs['id'];
23885				$this->svgclippaths[$this->svgclipid] = array();
23886				$this->svgcliptm[$this->svgclipid] = $tm;
23887				break;
23888			}
23889			case 'svg': {
23890				// start of SVG object
23891				if(++$this->svg_tag_depth <= 1) {
23892					break;
23893				}
23894				// inner SVG
23895				array_push($this->svgstyles, $svgstyle);
23896				$this->StartTransform();
23897				$svgX = (isset($attribs['x'])?$attribs['x']:0);
23898				$svgY = (isset($attribs['y'])?$attribs['y']:0);
23899				$svgW = (isset($attribs['width'])?$attribs['width']:0);
23900				$svgH = (isset($attribs['height'])?$attribs['height']:0);
23901				// set x, y position using transform matrix
23902				$tm = TCPDF_STATIC::getTransformationMatrixProduct($tm, array( 1, 0, 0, 1, $svgX, $svgY));
23903				$this->SVGTransform($tm);
23904				// set clipping for width and height
23905				$x = 0;
23906				$y = 0;
23907				$w = (isset($attribs['width'])?$this->getHTMLUnitToUnits($attribs['width'], 0, $this->svgunit, false):$this->w);
23908				$h = (isset($attribs['height'])?$this->getHTMLUnitToUnits($attribs['height'], 0, $this->svgunit, false):$this->h);
23909				// draw clipping rect
23910				$this->Rect($x, $y, $w, $h, 'CNZ', array(), array());
23911				// parse viewbox, calculate extra transformation matrix
23912				if (isset($attribs['viewBox'])) {
23913					$tmp = array();
23914					preg_match_all("/[0-9]+/", $attribs['viewBox'], $tmp);
23915					$tmp = $tmp[0];
23916					if (sizeof($tmp) == 4) {
23917						$vx = $tmp[0];
23918						$vy = $tmp[1];
23919						$vw = $tmp[2];
23920						$vh = $tmp[3];
23921						// get aspect ratio
23922						$tmp = array();
23923						$aspectX = 'xMid';
23924						$aspectY = 'YMid';
23925						$fit = 'meet';
23926						if (isset($attribs['preserveAspectRatio'])) {
23927							if($attribs['preserveAspectRatio'] == 'none') {
23928								$fit = 'none';
23929							} else {
23930								preg_match_all('/[a-zA-Z]+/', $attribs['preserveAspectRatio'], $tmp);
23931								$tmp = $tmp[0];
23932								if ((sizeof($tmp) == 2) AND (strlen($tmp[0]) == 8) AND (in_array($tmp[1], array('meet', 'slice', 'none')))) {
23933									$aspectX = substr($tmp[0], 0, 4);
23934									$aspectY = substr($tmp[0], 4, 4);
23935									$fit = $tmp[1];
23936								}
23937							}
23938						}
23939						$wr = ($svgW / $vw);
23940						$hr = ($svgH / $vh);
23941						$ax = $ay = 0;
23942						if ((($fit == 'meet') AND ($hr < $wr)) OR (($fit == 'slice') AND ($hr > $wr))) {
23943							if ($aspectX == 'xMax') {
23944								$ax = (($vw * ($wr / $hr)) - $vw);
23945							}
23946							if ($aspectX == 'xMid') {
23947								$ax = ((($vw * ($wr / $hr)) - $vw) / 2);
23948							}
23949							$wr = $hr;
23950						} elseif ((($fit == 'meet') AND ($hr > $wr)) OR (($fit == 'slice') AND ($hr < $wr))) {
23951							if ($aspectY == 'YMax') {
23952								$ay = (($vh * ($hr / $wr)) - $vh);
23953							}
23954							if ($aspectY == 'YMid') {
23955								$ay = ((($vh * ($hr / $wr)) - $vh) / 2);
23956							}
23957							$hr = $wr;
23958						}
23959						$newtm = array($wr, 0, 0, $hr, (($wr * ($ax - $vx)) - $svgX), (($hr * ($ay - $vy)) - $svgY));
23960						$tm = TCPDF_STATIC::getTransformationMatrixProduct($tm, $newtm);
23961						$this->SVGTransform($tm);
23962					}
23963				}
23964				$this->setSVGStyles($svgstyle, $prev_svgstyle);
23965				break;
23966			}
23967			case 'g': {
23968				// group together related graphics elements
23969				array_push($this->svgstyles, $svgstyle);
23970				$this->StartTransform();
23971				$x = (isset($attribs['x'])?$attribs['x']:0);
23972				$y = (isset($attribs['y'])?$attribs['y']:0);
23973				$w = 1;//(isset($attribs['width'])?$attribs['width']:1);
23974				$h = 1;//(isset($attribs['height'])?$attribs['height']:1);
23975				$tm = TCPDF_STATIC::getTransformationMatrixProduct($tm, array($w, 0, 0, $h, $x, $y));
23976				$this->SVGTransform($tm);
23977				$this->setSVGStyles($svgstyle, $prev_svgstyle);
23978				break;
23979			}
23980			case 'linearGradient': {
23981				if ($this->pdfa_mode) {
23982					break;
23983				}
23984				if (!isset($attribs['id'])) {
23985					$attribs['id'] = 'GR_'.(count($this->svggradients) + 1);
23986				}
23987				$this->svggradientid = $attribs['id'];
23988				$this->svggradients[$this->svggradientid] = array();
23989				$this->svggradients[$this->svggradientid]['type'] = 2;
23990				$this->svggradients[$this->svggradientid]['stops'] = array();
23991				if (isset($attribs['gradientUnits'])) {
23992					$this->svggradients[$this->svggradientid]['gradientUnits'] = $attribs['gradientUnits'];
23993				} else {
23994					$this->svggradients[$this->svggradientid]['gradientUnits'] = 'objectBoundingBox';
23995				}
23996				//$attribs['spreadMethod']
23997				if (((!isset($attribs['x1'])) AND (!isset($attribs['y1'])) AND (!isset($attribs['x2'])) AND (!isset($attribs['y2'])))
23998					OR ((isset($attribs['x1']) AND (substr($attribs['x1'], -1) == '%'))
23999						OR (isset($attribs['y1']) AND (substr($attribs['y1'], -1) == '%'))
24000						OR (isset($attribs['x2']) AND (substr($attribs['x2'], -1) == '%'))
24001						OR (isset($attribs['y2']) AND (substr($attribs['y2'], -1) == '%')))) {
24002					$this->svggradients[$this->svggradientid]['mode'] = 'percentage';
24003				} else {
24004					$this->svggradients[$this->svggradientid]['mode'] = 'measure';
24005				}
24006				$x1 = (isset($attribs['x1'])?$attribs['x1']:'0');
24007				$y1 = (isset($attribs['y1'])?$attribs['y1']:'0');
24008				$x2 = (isset($attribs['x2'])?$attribs['x2']:'100');
24009				$y2 = (isset($attribs['y2'])?$attribs['y2']:'0');
24010				if (isset($attribs['gradientTransform'])) {
24011					$this->svggradients[$this->svggradientid]['gradientTransform'] = TCPDF_STATIC::getSVGTransformMatrix($attribs['gradientTransform']);
24012				}
24013				$this->svggradients[$this->svggradientid]['coords'] = array($x1, $y1, $x2, $y2);
24014				if (isset($attribs['xlink:href']) AND !empty($attribs['xlink:href'])) {
24015					// gradient is defined on another place
24016					$this->svggradients[$this->svggradientid]['xref'] = substr($attribs['xlink:href'], 1);
24017				}
24018				break;
24019			}
24020			case 'radialGradient': {
24021				if ($this->pdfa_mode) {
24022					break;
24023				}
24024				if (!isset($attribs['id'])) {
24025					$attribs['id'] = 'GR_'.(count($this->svggradients) + 1);
24026				}
24027				$this->svggradientid = $attribs['id'];
24028				$this->svggradients[$this->svggradientid] = array();
24029				$this->svggradients[$this->svggradientid]['type'] = 3;
24030				$this->svggradients[$this->svggradientid]['stops'] = array();
24031				if (isset($attribs['gradientUnits'])) {
24032					$this->svggradients[$this->svggradientid]['gradientUnits'] = $attribs['gradientUnits'];
24033				} else {
24034					$this->svggradients[$this->svggradientid]['gradientUnits'] = 'objectBoundingBox';
24035				}
24036				//$attribs['spreadMethod']
24037				if (((!isset($attribs['cx'])) AND (!isset($attribs['cy'])))
24038					OR ((isset($attribs['cx']) AND (substr($attribs['cx'], -1) == '%'))
24039					OR (isset($attribs['cy']) AND (substr($attribs['cy'], -1) == '%')))) {
24040					$this->svggradients[$this->svggradientid]['mode'] = 'percentage';
24041				} elseif (isset($attribs['r']) AND is_numeric($attribs['r']) AND ($attribs['r']) <= 1) {
24042					$this->svggradients[$this->svggradientid]['mode'] = 'ratio';
24043				} else {
24044					$this->svggradients[$this->svggradientid]['mode'] = 'measure';
24045				}
24046				$cx = (isset($attribs['cx']) ? $attribs['cx'] : 0.5);
24047				$cy = (isset($attribs['cy']) ? $attribs['cy'] : 0.5);
24048				$fx = (isset($attribs['fx']) ? $attribs['fx'] : $cx);
24049				$fy = (isset($attribs['fy']) ? $attribs['fy'] : $cy);
24050				$r = (isset($attribs['r']) ? $attribs['r'] : 0.5);
24051				if (isset($attribs['gradientTransform'])) {
24052					$this->svggradients[$this->svggradientid]['gradientTransform'] = TCPDF_STATIC::getSVGTransformMatrix($attribs['gradientTransform']);
24053				}
24054				$this->svggradients[$this->svggradientid]['coords'] = array($cx, $cy, $fx, $fy, $r);
24055				if (isset($attribs['xlink:href']) AND !empty($attribs['xlink:href'])) {
24056					// gradient is defined on another place
24057					$this->svggradients[$this->svggradientid]['xref'] = substr($attribs['xlink:href'], 1);
24058				}
24059				break;
24060			}
24061			case 'stop': {
24062				// gradient stops
24063				if (substr($attribs['offset'], -1) == '%') {
24064					$offset = floatval(substr($attribs['offset'], 0, -1)) / 100;
24065				} else {
24066					$offset = floatval($attribs['offset']);
24067					if ($offset > 1) {
24068						$offset /= 100;
24069					}
24070				}
24071				$stop_color = isset($svgstyle['stop-color'])?TCPDF_COLORS::convertHTMLColorToDec($svgstyle['stop-color'], $this->spot_colors):'black';
24072				$opacity = isset($svgstyle['stop-opacity'])?$svgstyle['stop-opacity']:1;
24073				$this->svggradients[$this->svggradientid]['stops'][] = array('offset' => $offset, 'color' => $stop_color, 'opacity' => $opacity);
24074				break;
24075			}
24076			// paths
24077			case 'path': {
24078				if ($invisible) {
24079					break;
24080				}
24081				if (isset($attribs['d'])) {
24082					$d = trim($attribs['d']);
24083					if (!empty($d)) {
24084						$x = (isset($attribs['x'])?$attribs['x']:0);
24085						$y = (isset($attribs['y'])?$attribs['y']:0);
24086						$w = (isset($attribs['width'])?$attribs['width']:1);
24087						$h = (isset($attribs['height'])?$attribs['height']:1);
24088						$tm = TCPDF_STATIC::getTransformationMatrixProduct($tm, array($w, 0, 0, $h, $x, $y));
24089						if ($clipping) {
24090							$this->SVGTransform($tm);
24091							$this->SVGPath($d, 'CNZ');
24092						} else {
24093							$this->StartTransform();
24094							$this->SVGTransform($tm);
24095							$obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h, 'SVGPath', array($d, 'CNZ'));
24096							if (!empty($obstyle)) {
24097								$this->SVGPath($d, $obstyle);
24098							}
24099							$this->StopTransform();
24100						}
24101					}
24102				}
24103				break;
24104			}
24105			// shapes
24106			case 'rect': {
24107				if ($invisible) {
24108					break;
24109				}
24110				$x = (isset($attribs['x'])?$this->getHTMLUnitToUnits($attribs['x'], 0, $this->svgunit, false):0);
24111				$y = (isset($attribs['y'])?$this->getHTMLUnitToUnits($attribs['y'], 0, $this->svgunit, false):0);
24112				$w = (isset($attribs['width'])?$this->getHTMLUnitToUnits($attribs['width'], 0, $this->svgunit, false):0);
24113				$h = (isset($attribs['height'])?$this->getHTMLUnitToUnits($attribs['height'], 0, $this->svgunit, false):0);
24114				$rx = (isset($attribs['rx'])?$this->getHTMLUnitToUnits($attribs['rx'], 0, $this->svgunit, false):0);
24115				$ry = (isset($attribs['ry'])?$this->getHTMLUnitToUnits($attribs['ry'], 0, $this->svgunit, false):$rx);
24116				if ($clipping) {
24117					$this->SVGTransform($tm);
24118					$this->RoundedRectXY($x, $y, $w, $h, $rx, $ry, '1111', 'CNZ', array(), array());
24119				} else {
24120					$this->StartTransform();
24121					$this->SVGTransform($tm);
24122					$obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h, 'RoundedRectXY', array($x, $y, $w, $h, $rx, $ry, '1111', 'CNZ'));
24123					if (!empty($obstyle)) {
24124						$this->RoundedRectXY($x, $y, $w, $h, $rx, $ry, '1111', $obstyle, array(), array());
24125					}
24126					$this->StopTransform();
24127				}
24128				break;
24129			}
24130			case 'circle': {
24131				if ($invisible) {
24132					break;
24133				}
24134				$r = (isset($attribs['r']) ? $this->getHTMLUnitToUnits($attribs['r'], 0, $this->svgunit, false) : 0);
24135				$cx = (isset($attribs['cx']) ? $this->getHTMLUnitToUnits($attribs['cx'], 0, $this->svgunit, false) : (isset($attribs['x']) ? $this->getHTMLUnitToUnits($attribs['x'], 0, $this->svgunit, false) : 0));
24136				$cy = (isset($attribs['cy']) ? $this->getHTMLUnitToUnits($attribs['cy'], 0, $this->svgunit, false) : (isset($attribs['y']) ? $this->getHTMLUnitToUnits($attribs['y'], 0, $this->svgunit, false) : 0));
24137				$x = ($cx - $r);
24138				$y = ($cy - $r);
24139				$w = (2 * $r);
24140				$h = $w;
24141				if ($clipping) {
24142					$this->SVGTransform($tm);
24143					$this->Circle($cx, $cy, $r, 0, 360, 'CNZ', array(), array(), 8);
24144				} else {
24145					$this->StartTransform();
24146					$this->SVGTransform($tm);
24147					$obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h, 'Circle', array($cx, $cy, $r, 0, 360, 'CNZ'));
24148					if (!empty($obstyle)) {
24149						$this->Circle($cx, $cy, $r, 0, 360, $obstyle, array(), array(), 8);
24150					}
24151					$this->StopTransform();
24152				}
24153				break;
24154			}
24155			case 'ellipse': {
24156				if ($invisible) {
24157					break;
24158				}
24159				$rx = (isset($attribs['rx']) ? $this->getHTMLUnitToUnits($attribs['rx'], 0, $this->svgunit, false) : 0);
24160				$ry = (isset($attribs['ry']) ? $this->getHTMLUnitToUnits($attribs['ry'], 0, $this->svgunit, false) : 0);
24161				$cx = (isset($attribs['cx']) ? $this->getHTMLUnitToUnits($attribs['cx'], 0, $this->svgunit, false) : (isset($attribs['x']) ? $this->getHTMLUnitToUnits($attribs['x'], 0, $this->svgunit, false) : 0));
24162				$cy = (isset($attribs['cy']) ? $this->getHTMLUnitToUnits($attribs['cy'], 0, $this->svgunit, false) : (isset($attribs['y']) ? $this->getHTMLUnitToUnits($attribs['y'], 0, $this->svgunit, false) : 0));
24163				$x = ($cx - $rx);
24164				$y = ($cy - $ry);
24165				$w = (2 * $rx);
24166				$h = (2 * $ry);
24167				if ($clipping) {
24168					$this->SVGTransform($tm);
24169					$this->Ellipse($cx, $cy, $rx, $ry, 0, 0, 360, 'CNZ', array(), array(), 8);
24170				} else {
24171					$this->StartTransform();
24172					$this->SVGTransform($tm);
24173					$obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h, 'Ellipse', array($cx, $cy, $rx, $ry, 0, 0, 360, 'CNZ'));
24174					if (!empty($obstyle)) {
24175						$this->Ellipse($cx, $cy, $rx, $ry, 0, 0, 360, $obstyle, array(), array(), 8);
24176					}
24177					$this->StopTransform();
24178				}
24179				break;
24180			}
24181			case 'line': {
24182				if ($invisible) {
24183					break;
24184				}
24185				$x1 = (isset($attribs['x1'])?$this->getHTMLUnitToUnits($attribs['x1'], 0, $this->svgunit, false):0);
24186				$y1 = (isset($attribs['y1'])?$this->getHTMLUnitToUnits($attribs['y1'], 0, $this->svgunit, false):0);
24187				$x2 = (isset($attribs['x2'])?$this->getHTMLUnitToUnits($attribs['x2'], 0, $this->svgunit, false):0);
24188				$y2 = (isset($attribs['y2'])?$this->getHTMLUnitToUnits($attribs['y2'], 0, $this->svgunit, false):0);
24189				$x = $x1;
24190				$y = $y1;
24191				$w = abs($x2 - $x1);
24192				$h = abs($y2 - $y1);
24193				if (!$clipping) {
24194					$this->StartTransform();
24195					$this->SVGTransform($tm);
24196					$obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h, 'Line', array($x1, $y1, $x2, $y2));
24197					$this->Line($x1, $y1, $x2, $y2);
24198					$this->StopTransform();
24199				}
24200				break;
24201			}
24202			case 'polyline':
24203			case 'polygon': {
24204				if ($invisible) {
24205					break;
24206				}
24207				$points = (isset($attribs['points'])?$attribs['points']:'0 0');
24208				$points = trim($points);
24209				// note that point may use a complex syntax not covered here
24210				$points = preg_split('/[\,\s]+/si', $points);
24211				if (count($points) < 4) {
24212					break;
24213				}
24214				$p = array();
24215				$xmin = 2147483647;
24216				$xmax = 0;
24217				$ymin = 2147483647;
24218				$ymax = 0;
24219				foreach ($points as $key => $val) {
24220					$p[$key] = $this->getHTMLUnitToUnits($val, 0, $this->svgunit, false);
24221					if (($key % 2) == 0) {
24222						// X coordinate
24223						$xmin = min($xmin, $p[$key]);
24224						$xmax = max($xmax, $p[$key]);
24225					} else {
24226						// Y coordinate
24227						$ymin = min($ymin, $p[$key]);
24228						$ymax = max($ymax, $p[$key]);
24229					}
24230				}
24231				$x = $xmin;
24232				$y = $ymin;
24233				$w = ($xmax - $xmin);
24234				$h = ($ymax - $ymin);
24235				if ($name == 'polyline') {
24236					$this->StartTransform();
24237					$this->SVGTransform($tm);
24238					$obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h, 'PolyLine', array($p, 'CNZ'));
24239					if (!empty($obstyle)) {
24240						$this->PolyLine($p, $obstyle, array(), array());
24241					}
24242					$this->StopTransform();
24243				} else { // polygon
24244					if ($clipping) {
24245						$this->SVGTransform($tm);
24246						$this->Polygon($p, 'CNZ', array(), array(), true);
24247					} else {
24248						$this->StartTransform();
24249						$this->SVGTransform($tm);
24250						$obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h, 'Polygon', array($p, 'CNZ'));
24251						if (!empty($obstyle)) {
24252							$this->Polygon($p, $obstyle, array(), array(), true);
24253						}
24254						$this->StopTransform();
24255					}
24256				}
24257				break;
24258			}
24259			// image
24260			case 'image': {
24261				if ($invisible) {
24262					break;
24263				}
24264				if (!isset($attribs['xlink:href']) OR empty($attribs['xlink:href'])) {
24265					break;
24266				}
24267				$x = (isset($attribs['x'])?$this->getHTMLUnitToUnits($attribs['x'], 0, $this->svgunit, false):0);
24268				$y = (isset($attribs['y'])?$this->getHTMLUnitToUnits($attribs['y'], 0, $this->svgunit, false):0);
24269				$w = (isset($attribs['width'])?$this->getHTMLUnitToUnits($attribs['width'], 0, $this->svgunit, false):0);
24270				$h = (isset($attribs['height'])?$this->getHTMLUnitToUnits($attribs['height'], 0, $this->svgunit, false):0);
24271				$img = $attribs['xlink:href'];
24272				if (!$clipping) {
24273					$this->StartTransform();
24274					$this->SVGTransform($tm);
24275					$obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h);
24276					if (preg_match('/^data:image\/[^;]+;base64,/', $img, $m) > 0) {
24277						// embedded image encoded as base64
24278						$img = '@'.base64_decode(substr($img, strlen($m[0])));
24279					} else {
24280						// fix image path
24281						if (!TCPDF_STATIC::empty_string($this->svgdir) AND (($img[0] == '.') OR (basename($img) == $img))) {
24282							// replace relative path with full server path
24283							$img = $this->svgdir.'/'.$img;
24284						}
24285						if (($img[0] == '/') AND !empty($_SERVER['DOCUMENT_ROOT']) AND ($_SERVER['DOCUMENT_ROOT'] != '/')) {
24286							$findroot = strpos($img, $_SERVER['DOCUMENT_ROOT']);
24287							if (($findroot === false) OR ($findroot > 1)) {
24288								if (substr($_SERVER['DOCUMENT_ROOT'], -1) == '/') {
24289									$img = substr($_SERVER['DOCUMENT_ROOT'], 0, -1).$img;
24290								} else {
24291									$img = $_SERVER['DOCUMENT_ROOT'].$img;
24292								}
24293							}
24294						}
24295						$img = urldecode($img);
24296						$testscrtype = @parse_url($img);
24297						if (empty($testscrtype['query'])) {
24298							// convert URL to server path
24299							$img = str_replace(K_PATH_URL, K_PATH_MAIN, $img);
24300						} elseif (preg_match('|^https?://|', $img) !== 1) {
24301							// convert server path to URL
24302							$img = str_replace(K_PATH_MAIN, K_PATH_URL, $img);
24303						}
24304					}
24305					// get image type
24306					$imgtype = TCPDF_IMAGES::getImageFileType($img);
24307					if (($imgtype == 'eps') OR ($imgtype == 'ai')) {
24308						$this->ImageEps($img, $x, $y, $w, $h);
24309					} elseif ($imgtype == 'svg') {
24310						// store SVG vars
24311						$svggradients = $this->svggradients;
24312						$svggradientid = $this->svggradientid;
24313						$svgdefsmode = $this->svgdefsmode;
24314						$svgdefs = $this->svgdefs;
24315						$svgclipmode = $this->svgclipmode;
24316						$svgclippaths = $this->svgclippaths;
24317						$svgcliptm = $this->svgcliptm;
24318						$svgclipid = $this->svgclipid;
24319						$svgtext = $this->svgtext;
24320						$svgtextmode = $this->svgtextmode;
24321						$this->ImageSVG($img, $x, $y, $w, $h);
24322						// restore SVG vars
24323						$this->svggradients = $svggradients;
24324						$this->svggradientid = $svggradientid;
24325						$this->svgdefsmode = $svgdefsmode;
24326						$this->svgdefs = $svgdefs;
24327						$this->svgclipmode = $svgclipmode;
24328						$this->svgclippaths = $svgclippaths;
24329						$this->svgcliptm = $svgcliptm;
24330						$this->svgclipid = $svgclipid;
24331						$this->svgtext = $svgtext;
24332						$this->svgtextmode = $svgtextmode;
24333					} else {
24334						$this->Image($img, $x, $y, $w, $h);
24335					}
24336					$this->StopTransform();
24337				}
24338				break;
24339			}
24340			// text
24341			case 'text':
24342			case 'tspan': {
24343				if (isset($this->svgtextmode['text-anchor']) AND !empty($this->svgtext)) {
24344					// @TODO: unsupported feature
24345				}
24346				// only basic support - advanced features must be implemented
24347				$this->svgtextmode['invisible'] = $invisible;
24348				if ($invisible) {
24349					break;
24350				}
24351				array_push($this->svgstyles, $svgstyle);
24352				if (isset($attribs['x'])) {
24353					$x = $this->getHTMLUnitToUnits($attribs['x'], 0, $this->svgunit, false);
24354				} elseif ($name == 'tspan') {
24355					$x = $this->x;
24356				} else {
24357					$x = 0;
24358				}
24359				if (isset($attribs['dx'])) {
24360					$x += $this->getHTMLUnitToUnits($attribs['dx'], 0, $this->svgunit, false);
24361				}
24362				if (isset($attribs['y'])) {
24363					$y = $this->getHTMLUnitToUnits($attribs['y'], 0, $this->svgunit, false);
24364				} elseif ($name == 'tspan') {
24365					$y = $this->y;
24366				} else {
24367					$y = 0;
24368				}
24369				if (isset($attribs['dy'])) {
24370					$y += $this->getHTMLUnitToUnits($attribs['dy'], 0, $this->svgunit, false);
24371				}
24372				$svgstyle['text-color'] = $svgstyle['fill'];
24373				$this->svgtext = '';
24374				if (isset($svgstyle['text-anchor'])) {
24375					$this->svgtextmode['text-anchor'] = $svgstyle['text-anchor'];
24376				} else {
24377					$this->svgtextmode['text-anchor'] = 'start';
24378				}
24379				if (isset($svgstyle['direction'])) {
24380					if ($svgstyle['direction'] == 'rtl') {
24381						$this->svgtextmode['rtl'] = true;
24382					} else {
24383						$this->svgtextmode['rtl'] = false;
24384					}
24385				} else {
24386					$this->svgtextmode['rtl'] = false;
24387				}
24388				if (isset($svgstyle['stroke']) AND ($svgstyle['stroke'] != 'none') AND isset($svgstyle['stroke-width']) AND ($svgstyle['stroke-width'] > 0)) {
24389					$this->svgtextmode['stroke'] = $this->getHTMLUnitToUnits($svgstyle['stroke-width'], 0, $this->svgunit, false);
24390				} else {
24391					$this->svgtextmode['stroke'] = false;
24392				}
24393				$this->StartTransform();
24394				$this->SVGTransform($tm);
24395				$obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, 1, 1);
24396				$this->x = $x;
24397				$this->y = $y;
24398				break;
24399			}
24400			// use
24401			case 'use': {
24402				if (isset($attribs['xlink:href']) AND !empty($attribs['xlink:href'])) {
24403					$svgdefid = substr($attribs['xlink:href'], 1);
24404					if (isset($this->svgdefs[$svgdefid])) {
24405						$use = $this->svgdefs[$svgdefid];
24406						if (isset($attribs['xlink:href'])) {
24407							unset($attribs['xlink:href']);
24408						}
24409						if (isset($attribs['id'])) {
24410							unset($attribs['id']);
24411						}
24412						if (isset($use['attribs']['x']) AND isset($attribs['x'])) {
24413							$attribs['x'] += $use['attribs']['x'];
24414						}
24415						if (isset($use['attribs']['y']) AND isset($attribs['y'])) {
24416							$attribs['y'] += $use['attribs']['y'];
24417						}
24418						if (empty($attribs['style'])) {
24419							$attribs['style'] = '';
24420						}
24421						if (!empty($use['attribs']['style'])) {
24422							// merge styles
24423							$attribs['style'] = str_replace(';;',';',';'.$use['attribs']['style'].$attribs['style']);
24424						}
24425						$attribs = array_merge($use['attribs'], $attribs);
24426						$this->startSVGElementHandler($parser, $use['name'], $attribs);
24427						return;
24428					}
24429				}
24430				break;
24431			}
24432			default: {
24433				break;
24434			}
24435		} // end of switch
24436		// process child elements
24437		if (!empty($attribs['child_elements'])) {
24438			$child_elements = $attribs['child_elements'];
24439			unset($attribs['child_elements']);
24440			foreach($child_elements as $child_element) {
24441				if (empty($child_element['attribs']['closing_tag'])) {
24442					$this->startSVGElementHandler('child-tag', $child_element['name'], $child_element['attribs']);
24443				} else {
24444					if (isset($child_element['attribs']['content'])) {
24445						$this->svgtext = $child_element['attribs']['content'];
24446					}
24447					$this->endSVGElementHandler('child-tag', $child_element['name']);
24448				}
24449			}
24450		}
24451	}
24452
24453	/**
24454	 * Sets the closing SVG element handler function for the XML parser.
24455	 * @param $parser (resource) The first parameter, parser, is a reference to the XML parser calling the handler.
24456	 * @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.
24457	 * @author Nicola Asuni
24458	 * @since 5.0.000 (2010-05-02)
24459	 * @protected
24460	 */
24461	protected function endSVGElementHandler($parser, $name) {
24462		$name = $this->removeTagNamespace($name);
24463		if ($this->svgdefsmode AND !in_array($name, array('defs', 'clipPath', 'linearGradient', 'radialGradient', 'stop'))) {;
24464			if (end($this->svgdefs) !== FALSE) {
24465				$last_svgdefs_id = key($this->svgdefs);
24466				if (isset($this->svgdefs[$last_svgdefs_id]['attribs']['child_elements'])) {
24467					foreach($this->svgdefs[$last_svgdefs_id]['attribs']['child_elements'] as $child_element) {
24468						if (isset($child_element['attribs']['id']) AND ($child_element['name'] == $name)) {
24469							$this->svgdefs[$last_svgdefs_id]['attribs']['child_elements'][$child_element['attribs']['id'].'_CLOSE'] = array('name' => $name, 'attribs' => array('closing_tag' => TRUE, 'content' => $this->svgtext));
24470							return;
24471						}
24472					}
24473					if ($this->svgdefs[$last_svgdefs_id]['name'] == $name) {
24474						$this->svgdefs[$last_svgdefs_id]['attribs']['child_elements'][$last_svgdefs_id.'_CLOSE'] = array('name' => $name, 'attribs' => array('closing_tag' => TRUE, 'content' => $this->svgtext));
24475						return;
24476					}
24477				}
24478			}
24479			return;
24480		}
24481		switch($name) {
24482			case 'defs': {
24483				$this->svgdefsmode = false;
24484				break;
24485			}
24486			// clipPath
24487			case 'clipPath': {
24488				$this->svgclipmode = false;
24489				break;
24490			}
24491			case 'svg': {
24492				if (--$this->svg_tag_depth <= 0) {
24493					break;
24494				}
24495			}
24496			case 'g': {
24497				// ungroup: remove last style from array
24498				array_pop($this->svgstyles);
24499				$this->StopTransform();
24500				break;
24501			}
24502			case 'text':
24503			case 'tspan': {
24504				if ($this->svgtextmode['invisible']) {
24505					// This implementation must be fixed to following the rule:
24506					// 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.
24507					break;
24508				}
24509				// print text
24510				$text = $this->svgtext;
24511				//$text = $this->stringTrim($text);
24512				$textlen = $this->GetStringWidth($text);
24513				if ($this->svgtextmode['text-anchor'] != 'start') {
24514					// check if string is RTL text
24515					if ($this->svgtextmode['text-anchor'] == 'end') {
24516						if ($this->svgtextmode['rtl']) {
24517							$this->x += $textlen;
24518						} else {
24519							$this->x -= $textlen;
24520						}
24521					} elseif ($this->svgtextmode['text-anchor'] == 'middle') {
24522						if ($this->svgtextmode['rtl']) {
24523							$this->x += ($textlen / 2);
24524						} else {
24525							$this->x -= ($textlen / 2);
24526						}
24527					}
24528				}
24529				$textrendermode = $this->textrendermode;
24530				$textstrokewidth = $this->textstrokewidth;
24531				$this->setTextRenderingMode($this->svgtextmode['stroke'], true, false);
24532				if ($name == 'text') {
24533					// store current coordinates
24534					$tmpx = $this->x;
24535					$tmpy = $this->y;
24536				}
24537				// print the text
24538				$this->Cell($textlen, 0, $text, 0, 0, '', false, '', 0, false, 'L', 'T');
24539				if ($name == 'text') {
24540					// restore coordinates
24541					$this->x = $tmpx;
24542					$this->y = $tmpy;
24543				}
24544				// restore previous rendering mode
24545				$this->textrendermode = $textrendermode;
24546				$this->textstrokewidth = $textstrokewidth;
24547				$this->svgtext = '';
24548				$this->StopTransform();
24549				if (!$this->svgdefsmode) {
24550					array_pop($this->svgstyles);
24551				}
24552				break;
24553			}
24554			default: {
24555				break;
24556			}
24557		}
24558	}
24559
24560	/**
24561	 * Sets the character data handler function for the XML parser.
24562	 * @param $parser (resource) The first parameter, parser, is a reference to the XML parser calling the handler.
24563	 * @param $data (string) The second parameter, data, contains the character data as a string.
24564	 * @author Nicola Asuni
24565	 * @since 5.0.000 (2010-05-02)
24566	 * @protected
24567	 */
24568	protected function segSVGContentHandler($parser, $data) {
24569		$this->svgtext .= $data;
24570	}
24571
24572	// --- END SVG METHODS -----------------------------------------------------
24573
24574} // END OF TCPDF CLASS
24575
24576//============================================================+
24577// END OF FILE
24578//============================================================+
24579