2 //============================================================+
3 // File name : tcpdf.php
6 // Last Update : 2022-12-06
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-2022 Nicola Asuni - Tecnick.com LTD
12 // This file is part of TCPDF software library.
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.
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.
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>.
28 // See LICENSE.TXT file for more information.
29 // -------------------------------------------------------------------
32 // This is a PHP class for generating PDF documents without requiring external extensions.
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.
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;
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.
68 //============================================================+
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>
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>
104 * Tools to encode your unicode fonts are on fonts/utils directory.</p>
105 * @package com.tecnick.tcpdf
106 * @author Nicola Asuni
110 // TCPDF configuration
111 require_once(dirname(__FILE__
).'/tcpdf_autoconfig.php');
112 // TCPDF static font methods and data
113 require_once(dirname(__FILE__
).'/include/tcpdf_font_data.php');
114 // TCPDF static font methods and data
115 require_once(dirname(__FILE__
).'/include/tcpdf_fonts.php');
116 // TCPDF static color methods and data
117 require_once(dirname(__FILE__
).'/include/tcpdf_colors.php');
118 // TCPDF static image methods and data
119 require_once(dirname(__FILE__
).'/include/tcpdf_images.php');
120 // TCPDF static methods and data
121 require_once(dirname(__FILE__
).'/include/tcpdf_static.php');
123 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
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.
132 * @author Nicola Asuni - info@tecnick.com
133 * @IgnoreAnnotation("protected")
134 * @IgnoreAnnotation("public")
135 * @IgnoreAnnotation("pre")
139 // Protected properties
142 * Current page number.
148 * Current object number.
154 * Array of object offsets.
157 protected $offsets = array();
160 * Array of object IDs for each page.
163 protected $pageobjects = array();
166 * Buffer holding in-memory PDF.
172 * Array containing pages.
175 protected $pages = array();
178 * Current document state.
190 * Current page orientation (P = Portrait, L = Landscape).
193 protected $CurOrientation;
199 protected $pagedim = array();
202 * Scale factor (number of points in user unit).
208 * Width of page format in points.
214 * Height of page format in points.
220 * Current width of page in points.
226 * Current height of page in points.
232 * Current width of page in user unit.
238 * Current height of page in user unit.
256 * Cell left margin (used by regions).
262 * Cell right margin (used by regions).
280 * Array of cell internal paddings ('T' => top, 'R' => right, 'B' => bottom, 'L' => left).
281 * @since 5.9.000 (2010-10-03)
284 protected $cell_padding = array('T' => 0, 'R' => 0, 'B' => 0, 'L' => 0);
287 * Array of cell margins ('T' => top, 'R' => right, 'B' => bottom, 'L' => left).
288 * @since 5.9.000 (2010-10-04)
291 protected $cell_margin = array('T' => 0, 'R' => 0, 'B' => 0, 'L' => 0);
294 * Current horizontal position in user unit for cell positioning.
300 * Current vertical position in user unit for cell positioning.
306 * Height of last cell printed.
312 * Line width in user unit.
315 protected $LineWidth;
318 * Array of standard font names.
321 protected $CoreFonts;
324 * Array of used fonts.
327 protected $fonts = array();
330 * Array of font files.
333 protected $FontFiles = array();
336 * Array of encoding differences.
339 protected $diffs = array();
342 * Array of used images.
345 protected $images = array();
348 * Depth of the svg tag, to keep track if the svg tag is a subtag or the root tag.
351 protected $svg_tag_depth = 0;
354 * Array of Annotations in pages.
357 protected $PageAnnots = array();
360 * Array of internal links.
363 protected $links = array();
366 * Current font family.
369 protected $FontFamily;
372 * Current font style.
375 protected $FontStyle;
378 * Current font ascent (distance between font top and baseline).
380 * @since 2.8.000 (2007-03-29)
382 protected $FontAscent;
385 * Current font descent (distance between font bottom and baseline).
387 * @since 2.8.000 (2007-03-29)
389 protected $FontDescent;
395 protected $underline;
407 protected $CurrentFont;
410 * Current font size in points.
413 protected $FontSizePt;
416 * Current font size in user unit.
422 * Commands for drawing color.
425 protected $DrawColor;
428 * Commands for filling color.
431 protected $FillColor;
434 * Commands for text color.
437 protected $TextColor;
440 * Indicates whether fill and text colors are different.
443 protected $ColorFlag;
446 * Automatic page breaking.
449 protected $AutoPageBreak;
452 * Threshold used to trigger page breaks.
455 protected $PageBreakTrigger;
458 * Flag set when processing page header.
461 protected $InHeader = false;
464 * Flag set when processing page footer.
467 protected $InFooter = false;
476 * Layout display mode.
479 protected $LayoutMode;
482 * If true set the document information dictionary in Unicode.
485 protected $docinfounicode = true;
491 protected $title = '';
497 protected $subject = '';
503 protected $author = '';
509 protected $keywords = '';
515 protected $creator = '';
518 * Starting page number.
521 protected $starting_page_number = 1;
524 * The right-bottom (or left-bottom for RTL) corner X coordinate of last inserted image.
526 * @author Nicola Asuni
532 * The right-bottom corner Y coordinate of last inserted image.
534 * @author Nicola Asuni
540 * Adjusting factor to convert pixels to user units.
542 * @author Nicola Asuni
545 protected $imgscale = 1;
548 * Boolean flag set to true when the input text is unicode (require unicode fonts).
550 * @author Nicola Asuni
553 protected $isunicode = false;
560 protected $PDFVersion = '1.7';
563 * ID of the stored default header template (-1 = not set).
566 protected $header_xobjid = false;
569 * If true reset the Header Xobject template at each page
572 protected $header_xobj_autoreset = false;
575 * Minimum distance between header and top page margin.
578 protected $header_margin;
581 * Minimum distance between footer and bottom page margin.
584 protected $footer_margin;
587 * Original left margin value.
589 * @since 1.53.0.TC013
591 protected $original_lMargin;
594 * Original right margin value.
596 * @since 1.53.0.TC013
598 protected $original_rMargin;
601 * Default font used on page header.
603 * @var array<int,string|float|null>
604 * @phpstan-var array{0: string, 1: string, 2: float|null}
606 protected $header_font;
609 * Default font used on page footer.
611 * @var array<int,string|float|null>
612 * @phpstan-var array{0: string, 1: string, 2: float|null}
614 protected $footer_font;
617 * Language templates.
623 * Barcode to print on page footer (only if set).
626 protected $barcode = false;
629 * Boolean flag to print/hide page header.
632 protected $print_header = true;
635 * Boolean flag to print/hide page footer.
638 protected $print_footer = true;
644 protected $header_logo = '';
647 * Width of header image logo in user units.
650 protected $header_logo_width = 30;
653 * Title to be printed on default page header.
656 protected $header_title = '';
659 * String to print on page header after title.
662 protected $header_string = '';
665 * Color for header text (RGB array).
666 * @since 5.9.174 (2012-07-25)
669 * @phpstan-var array{0: int, 1: int, 2: int}
671 protected $header_text_color = array(0,0,0);
674 * Color for header line (RGB array).
675 * @since 5.9.174 (2012-07-25)
678 * @phpstan-var array{0: int, 1: int, 2: int}
680 protected $header_line_color = array(0,0,0);
683 * Color for footer text (RGB array).
684 * @since 5.9.174 (2012-07-25)
687 * @phpstan-var array{0: int, 1: int, 2: int}
689 protected $footer_text_color = array(0,0,0);
692 * Color for footer line (RGB array).
693 * @since 5.9.174 (2012-07-25)
696 * @phpstan-var array{0: int, 1: int, 2: int}
698 protected $footer_line_color = array(0,0,0);
701 * Text shadow data array.
702 * @since 5.9.174 (2012-07-25)
705 protected $txtshadow = array('enabled'=>false, 'depth_w'=>0, 'depth_h'=>0, 'color'=>false, 'opacity'=>1, 'blend_mode'=>'Normal');
708 * Default number of columns for html table.
711 protected $default_table_columns = 4;
713 // variables for html parser
716 * HTML PARSER: array to store current link and rendering styles.
719 protected $HREF = array();
722 * List of available fonts on filesystem.
725 protected $fontlist = array();
728 * Current foreground color.
734 * HTML PARSER: array of boolean values, true in case of ordered list (OL), false otherwise.
737 protected $listordered = array();
740 * HTML PARSER: array count list items on nested lists.
743 protected $listcount = array();
746 * HTML PARSER: current list nesting level.
749 protected $listnum = 0;
752 * HTML PARSER: indent amount for lists.
755 protected $listindent = 0;
758 * HTML PARSER: current list indententation level.
761 protected $listindentlevel = 0;
764 * Current background color.
770 * Temporary font size in points.
773 protected $tempfontsize = 10;
776 * Spacer string for LI tags.
779 protected $lispacer = '';
784 * @since 1.53.0.TC010
786 protected $encoding = 'UTF-8';
789 * Boolean flag to indicate if the document language is Right-To-Left.
793 protected $rtl = false;
796 * Boolean flag used to force RTL or LTR string direction.
800 protected $tmprtl = false;
802 // --- Variables used for document encryption:
805 * IBoolean flag indicating whether document is protected.
807 * @since 2.0.000 (2008-01-02)
809 protected $encrypted;
812 * Array containing encryption settings.
814 * @since 5.0.005 (2010-05-11)
816 protected $encryptdata = array();
819 * Last RC4 key encrypted (cached for optimisation).
821 * @since 2.0.000 (2008-01-02)
823 protected $last_enc_key;
826 * Last RC4 computed key.
828 * @since 2.0.000 (2008-01-02)
830 protected $last_enc_key_c;
833 * File ID (used on document trailer).
835 * @since 5.0.005 (2010-05-12)
842 * Outlines for bookmark.
844 * @since 2.1.002 (2008-02-12)
846 protected $outlines = array();
849 * Outline root for bookmark.
851 * @since 2.1.002 (2008-02-12)
853 protected $OutlineRoot;
855 // --- javascript and form ---
860 * @since 2.1.002 (2008-02-12)
862 protected $javascript = '';
865 * Javascript counter.
867 * @since 2.1.002 (2008-02-12)
874 * @since 2.8.000 (2008-03-19)
876 protected $linethrough;
879 * Array with additional document-wide usage rights for the document.
881 * @since 5.8.014 (2010-08-23)
883 protected $ur = array();
886 * DPI (Dot Per Inch) Document Resolution (do not change).
888 * @since 3.0.000 (2008-03-27)
893 * Array of page numbers were a new page group was started (the page numbers are the keys of the array).
895 * @since 3.0.000 (2008-03-27)
897 protected $newpagegroup = array();
900 * Array that contains the number of pages in each page group.
902 * @since 3.0.000 (2008-03-27)
904 protected $pagegroups = array();
907 * Current page group number.
909 * @since 3.0.000 (2008-03-27)
911 protected $currpagegroup = 0;
914 * Array of transparency objects and parameters.
916 * @since 3.0.000 (2008-03-27)
918 protected $extgstates;
921 * Set the default JPEG compression quality (1-100).
923 * @since 3.0.000 (2008-03-27)
925 protected $jpeg_quality;
928 * Default cell height ratio.
930 * @since 3.0.014 (2008-05-23)
933 protected $cell_height_ratio = K_CELL_HEIGHT_RATIO
;
936 * PDF viewer preferences.
938 * @since 3.1.000 (2008-06-09)
940 protected $viewer_preferences;
943 * A name object specifying how the document should be displayed when opened.
945 * @since 3.1.000 (2008-06-09)
950 * Array for storing gradient information.
952 * @since 3.1.000 (2008-06-09)
954 protected $gradients = array();
957 * Array used to store positions inside the pages buffer (keys are the page numbers).
959 * @since 3.2.000 (2008-06-26)
961 protected $intmrk = array();
964 * Array used to store positions inside the pages buffer (keys are the page numbers).
966 * @since 5.7.000 (2010-08-03)
968 protected $bordermrk = array();
971 * Array used to store page positions to track empty pages (keys are the page numbers).
973 * @since 5.8.007 (2010-08-18)
975 protected $emptypagemrk = array();
978 * Array used to store content positions inside the pages buffer (keys are the page numbers).
980 * @since 4.6.021 (2009-07-20)
982 protected $cntmrk = array();
985 * Array used to store footer positions of each page.
987 * @since 3.2.000 (2008-07-01)
989 protected $footerpos = array();
992 * Array used to store footer length of each page.
994 * @since 4.0.014 (2008-07-29)
996 protected $footerlen = array();
999 * Boolean flag to indicate if a new line is created.
1001 * @since 3.2.000 (2008-07-01)
1003 protected $newline = true;
1006 * End position of the latest inserted line.
1008 * @since 3.2.000 (2008-07-01)
1010 protected $endlinex = 0;
1013 * PDF string for width value of the last line.
1015 * @since 4.0.006 (2008-07-16)
1017 protected $linestyleWidth = '';
1020 * PDF string for CAP value of the last line.
1022 * @since 4.0.006 (2008-07-16)
1024 protected $linestyleCap = '0 J';
1027 * PDF string for join value of the last line.
1029 * @since 4.0.006 (2008-07-16)
1031 protected $linestyleJoin = '0 j';
1034 * PDF string for dash value of the last line.
1036 * @since 4.0.006 (2008-07-16)
1038 protected $linestyleDash = '[] 0 d';
1041 * Boolean flag to indicate if marked-content sequence is open.
1043 * @since 4.0.013 (2008-07-28)
1045 protected $openMarkedContent = false;
1048 * Count the latest inserted vertical spaces on HTML.
1050 * @since 4.0.021 (2008-08-24)
1052 protected $htmlvspace = 0;
1055 * Array of Spot colors.
1057 * @since 4.0.024 (2008-09-12)
1059 protected $spot_colors = array();
1062 * Symbol used for HTML unordered list items.
1064 * @since 4.0.028 (2008-09-26)
1066 protected $lisymbol = '';
1069 * String used to mark the beginning and end of EPS image blocks.
1071 * @since 4.1.000 (2008-10-18)
1073 protected $epsmarker = 'x#!#EPS#!#x';
1076 * Array of transformation matrix.
1078 * @since 4.2.000 (2008-10-29)
1080 protected $transfmatrix = array();
1083 * Current key for transformation matrix.
1085 * @since 4.8.005 (2009-09-17)
1087 protected $transfmatrix_key = 0;
1090 * Booklet mode for double-sided pages.
1092 * @since 4.2.000 (2008-10-29)
1094 protected $booklet = false;
1097 * Epsilon value used for float calculations.
1099 * @since 4.2.000 (2008-10-29)
1101 protected $feps = 0.005;
1104 * Array used for custom vertical spaces for HTML tags.
1106 * @since 4.2.001 (2008-10-30)
1108 protected $tagvspaces = array();
1111 * HTML PARSER: custom indent amount for lists. Negative value means disabled.
1113 * @since 4.2.007 (2008-11-12)
1115 protected $customlistindent = -1;
1118 * Boolean flag to indicate if the border of the cell sides that cross the page should be removed.
1120 * @since 4.2.010 (2008-11-14)
1122 protected $opencell = true;
1125 * Array of files to embedd.
1127 * @since 4.4.000 (2008-12-07)
1129 protected $embeddedfiles = array();
1132 * Boolean flag to indicate if we are inside a PRE tag.
1134 * @since 4.4.001 (2008-12-08)
1136 protected $premode = false;
1139 * Array used to store positions of graphics transformation blocks inside the page buffer.
1140 * keys are the page numbers
1142 * @since 4.4.002 (2008-12-09)
1144 protected $transfmrk = array();
1147 * Default color for html links.
1149 * @since 4.4.003 (2008-12-09)
1151 protected $htmlLinkColorArray = array(0, 0, 255);
1154 * Default font style to add to html links.
1156 * @since 4.4.003 (2008-12-09)
1158 protected $htmlLinkFontStyle = 'U';
1161 * Counts the number of pages.
1163 * @since 4.5.000 (2008-12-31)
1165 protected $numpages = 0;
1168 * Array containing page lengths in bytes.
1170 * @since 4.5.000 (2008-12-31)
1172 protected $pagelen = array();
1175 * Counts the number of pages.
1177 * @since 4.5.000 (2008-12-31)
1179 protected $numimages = 0;
1182 * Store the image keys.
1184 * @since 4.5.000 (2008-12-31)
1186 protected $imagekeys = array();
1189 * Length of the buffer in bytes.
1191 * @since 4.5.000 (2008-12-31)
1193 protected $bufferlen = 0;
1196 * Counts the number of fonts.
1198 * @since 4.5.000 (2009-01-02)
1200 protected $numfonts = 0;
1203 * Store the font keys.
1205 * @since 4.5.000 (2009-01-02)
1207 protected $fontkeys = array();
1210 * Store the font object IDs.
1212 * @since 4.8.001 (2009-09-09)
1214 protected $font_obj_ids = array();
1217 * Store the fage status (true when opened, false when closed).
1219 * @since 4.5.000 (2009-01-02)
1221 protected $pageopen = array();
1224 * Default monospace font.
1226 * @since 4.5.025 (2009-03-10)
1228 protected $default_monospaced_font = 'courier';
1231 * Cloned copy of the current class object.
1233 * @since 4.5.029 (2009-03-19)
1238 * Array used to store the lengths of cache files.
1240 * @since 4.5.029 (2009-03-19)
1242 protected $cache_file_length = array();
1245 * Table header content to be repeated on each new page.
1247 * @since 4.5.030 (2009-03-20)
1249 protected $thead = '';
1252 * Margins used for table header.
1254 * @since 4.5.030 (2009-03-20)
1256 protected $theadMargins = array();
1259 * Boolean flag to enable document digital signature.
1261 * @since 4.6.005 (2009-04-24)
1263 protected $sign = false;
1266 * Digital signature data.
1268 * @since 4.6.005 (2009-04-24)
1270 protected $signature_data = array();
1273 * Digital signature max length.
1275 * @since 4.6.005 (2009-04-24)
1277 protected $signature_max_length = 11742;
1280 * Data for digital signature appearance.
1282 * @since 5.3.011 (2010-06-16)
1284 protected $signature_appearance = array('page' => 1, 'rect' => '0 0 0 0');
1287 * Array of empty digital signature appearances.
1289 * @since 5.9.101 (2011-07-06)
1291 protected $empty_signature_appearance = array();
1294 * Boolean flag to enable document timestamping with TSA.
1296 * @since 6.0.085 (2014-06-19)
1298 protected $tsa_timestamp = false;
1301 * Timestamping data.
1303 * @since 6.0.085 (2014-06-19)
1305 protected $tsa_data = array();
1308 * Regular expression used to find blank characters (required for word-wrapping).
1310 * @since 4.6.006 (2009-04-28)
1312 protected $re_spaces = '/[^\S\xa0]/';
1315 * Array of $re_spaces parts.
1317 * @since 5.5.011 (2010-07-09)
1319 protected $re_space = array('p' => '[^\S\xa0]', 'm' => '');
1322 * Digital signature object ID.
1324 * @since 4.6.022 (2009-06-23)
1326 protected $sig_obj_id = 0;
1329 * ID of page objects.
1331 * @since 4.7.000 (2009-08-29)
1333 protected $page_obj_id = array();
1336 * List of form annotations IDs.
1338 * @since 4.8.000 (2009-09-07)
1340 protected $form_obj_id = array();
1343 * 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.
1345 * @since 4.8.000 (2009-09-07)
1347 protected $default_form_prop = array('lineWidth'=>1, 'borderStyle'=>'solid', 'fillColor'=>array(255, 255, 255), 'strokeColor'=>array(128, 128, 128));
1350 * Javascript objects array.
1352 * @since 4.8.000 (2009-09-07)
1354 protected $js_objects = array();
1357 * Current form action (used during XHTML rendering).
1359 * @since 4.8.000 (2009-09-07)
1361 protected $form_action = '';
1364 * Current form encryption type (used during XHTML rendering).
1366 * @since 4.8.000 (2009-09-07)
1368 protected $form_enctype = 'application/x-www-form-urlencoded';
1371 * Current method to submit forms.
1373 * @since 4.8.000 (2009-09-07)
1375 protected $form_mode = 'post';
1378 * List of fonts used on form fields (fontname => fontkey).
1380 * @since 4.8.001 (2009-09-09)
1382 protected $annotation_fonts = array();
1385 * List of radio buttons parent objects.
1387 * @since 4.8.001 (2009-09-09)
1389 protected $radiobutton_groups = array();
1392 * List of radio group objects IDs.
1394 * @since 4.8.001 (2009-09-09)
1396 protected $radio_groups = array();
1399 * Text indentation value (used for text-indent CSS attribute).
1401 * @since 4.8.006 (2009-09-23)
1403 protected $textindent = 0;
1406 * Store page number when startTransaction() is called.
1408 * @since 4.8.006 (2009-09-23)
1410 protected $start_transaction_page = 0;
1413 * Store Y position when startTransaction() is called.
1415 * @since 4.9.001 (2010-03-28)
1417 protected $start_transaction_y = 0;
1420 * True when we are printing the thead section on a new page.
1422 * @since 4.8.027 (2010-01-25)
1424 protected $inthead = false;
1427 * Array of column measures (width, space, starting Y position).
1429 * @since 4.9.001 (2010-03-28)
1431 protected $columns = array();
1436 * @since 4.9.001 (2010-03-28)
1438 protected $num_columns = 1;
1441 * Current column number.
1443 * @since 4.9.001 (2010-03-28)
1445 protected $current_column = 0;
1448 * Starting page for columns.
1450 * @since 4.9.001 (2010-03-28)
1452 protected $column_start_page = 0;
1455 * Maximum page and column selected.
1457 * @since 5.8.000 (2010-08-11)
1459 protected $maxselcol = array('page' => 0, 'column' => 0);
1462 * Array of: X difference between table cell x start and starting page margin, cellspacing, cellpadding.
1464 * @since 5.8.000 (2010-08-11)
1466 protected $colxshift = array('x' => 0, 's' => array('H' => 0, 'V' => 0), 'p' => array('L' => 0, 'T' => 0, 'R' => 0, 'B' => 0));
1469 * 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.
1471 * @since 4.9.008 (2010-04-03)
1473 protected $textrendermode = 0;
1476 * Text stroke width in doc units.
1478 * @since 4.9.008 (2010-04-03)
1480 protected $textstrokewidth = 0;
1483 * Current stroke color.
1485 * @since 4.9.008 (2010-04-03)
1487 protected $strokecolor;
1490 * Default unit of measure for document.
1492 * @since 5.0.000 (2010-04-22)
1494 protected $pdfunit = 'mm';
1497 * Boolean flag true when we are on TOC (Table Of Content) page.
1500 protected $tocpage = false;
1503 * Boolean flag: if true convert vector images (SVG, EPS) to raster image using GD or ImageMagick library.
1505 * @since 5.0.000 (2010-04-26)
1507 protected $rasterize_vector_images = false;
1510 * Boolean flag: if true enables font subsetting by default.
1512 * @since 5.3.002 (2010-06-07)
1514 protected $font_subsetting = true;
1517 * Array of default graphic settings.
1519 * @since 5.5.008 (2010-07-02)
1521 protected $default_graphic_vars = array();
1524 * Array of XObjects.
1526 * @since 5.8.014 (2010-08-23)
1528 protected $xobjects = array();
1531 * Boolean value true when we are inside an XObject.
1533 * @since 5.8.017 (2010-08-24)
1535 protected $inxobj = false;
1538 * Current XObject ID.
1540 * @since 5.8.017 (2010-08-24)
1542 protected $xobjid = '';
1545 * Percentage of character stretching.
1547 * @since 5.9.000 (2010-09-29)
1549 protected $font_stretching = 100;
1552 * Increases or decreases the space between characters in a text by the specified amount (tracking).
1554 * @since 5.9.000 (2010-09-29)
1556 protected $font_spacing = 0;
1559 * Array of no-write regions.
1560 * ('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)
1562 * @since 5.9.003 (2010-10-14)
1564 protected $page_regions = array();
1567 * Boolean value true when page region check is active.
1570 protected $check_page_regions = true;
1573 * Array of PDF layers data.
1575 * @since 5.9.102 (2011-07-13)
1577 protected $pdflayers = array();
1580 * A dictionary of names and corresponding destinations (Dests key on document Catalog).
1582 * @since 5.9.097 (2011-06-23)
1584 protected $dests = array();
1587 * Object ID for Named Destinations
1589 * @since 5.9.097 (2011-06-23)
1594 * Embedded Files Names
1596 * @since 5.9.204 (2013-01-23)
1598 protected $efnames = array();
1601 * Directory used for the last SVG image.
1603 * @since 5.0.000 (2010-05-05)
1605 protected $svgdir = '';
1608 * Deafult unit of measure for SVG.
1610 * @since 5.0.000 (2010-05-02)
1612 protected $svgunit = 'px';
1615 * Array of SVG gradients.
1617 * @since 5.0.000 (2010-05-02)
1619 protected $svggradients = array();
1622 * ID of last SVG gradient.
1624 * @since 5.0.000 (2010-05-02)
1626 protected $svggradientid = 0;
1629 * Boolean value true when in SVG defs group.
1631 * @since 5.0.000 (2010-05-02)
1633 protected $svgdefsmode = false;
1636 * Array of SVG defs.
1638 * @since 5.0.000 (2010-05-02)
1640 protected $svgdefs = array();
1643 * Boolean value true when in SVG clipPath tag.
1645 * @since 5.0.000 (2010-04-26)
1647 protected $svgclipmode = false;
1650 * Array of SVG clipPath commands.
1652 * @since 5.0.000 (2010-05-02)
1654 protected $svgclippaths = array();
1657 * Array of SVG clipPath tranformation matrix.
1659 * @since 5.8.022 (2010-08-31)
1661 protected $svgcliptm = array();
1664 * ID of last SVG clipPath.
1666 * @since 5.0.000 (2010-05-02)
1668 protected $svgclipid = 0;
1673 * @since 5.0.000 (2010-05-02)
1675 protected $svgtext = '';
1678 * SVG text properties.
1680 * @since 5.8.013 (2010-08-23)
1682 protected $svgtextmode = array();
1685 * Array of SVG properties.
1687 * @since 5.0.000 (2010-05-02)
1689 protected $svgstyles = array(array(
1690 'alignment-baseline' => 'auto',
1691 'baseline-shift' => 'baseline',
1693 'clip-path' => 'none',
1694 'clip-rule' => 'nonzero',
1696 'color-interpolation' => 'sRGB',
1697 'color-interpolation-filters' => 'linearRGB',
1698 'color-profile' => 'auto',
1699 'color-rendering' => 'auto',
1701 'direction' => 'ltr',
1702 'display' => 'inline',
1703 'dominant-baseline' => 'auto',
1704 'enable-background' => 'accumulate',
1706 'fill-opacity' => 1,
1707 'fill-rule' => 'nonzero',
1709 'flood-color' => 'black',
1710 'flood-opacity' => 1,
1712 'font-family' => 'helvetica',
1713 'font-size' => 'medium',
1714 'font-size-adjust' => 'none',
1715 'font-stretch' => 'normal',
1716 'font-style' => 'normal',
1717 'font-variant' => 'normal',
1718 'font-weight' => 'normal',
1719 'glyph-orientation-horizontal' => '0deg',
1720 'glyph-orientation-vertical' => 'auto',
1721 'image-rendering' => 'auto',
1722 'kerning' => 'auto',
1723 'letter-spacing' => 'normal',
1724 'lighting-color' => 'white',
1726 'marker-end' => 'none',
1727 'marker-mid' => 'none',
1728 'marker-start' => 'none',
1731 'overflow' => 'auto',
1732 'pointer-events' => 'visiblePainted',
1733 'shape-rendering' => 'auto',
1734 'stop-color' => 'black',
1735 'stop-opacity' => 1,
1737 'stroke-dasharray' => 'none',
1738 'stroke-dashoffset' => 0,
1739 'stroke-linecap' => 'butt',
1740 'stroke-linejoin' => 'miter',
1741 'stroke-miterlimit' => 4,
1742 'stroke-opacity' => 1,
1743 'stroke-width' => 1,
1744 'text-anchor' => 'start',
1745 'text-decoration' => 'none',
1746 'text-rendering' => 'auto',
1747 'unicode-bidi' => 'normal',
1748 'visibility' => 'visible',
1749 'word-spacing' => 'normal',
1750 'writing-mode' => 'lr-tb',
1751 'text-color' => 'black',
1752 'transfmatrix' => array(1, 0, 0, 1, 0, 0)
1756 * If true force sRGB color profile for all document.
1758 * @since 5.9.121 (2011-09-28)
1760 protected $force_srgb = false;
1763 * If true set the document to PDF/A mode.
1765 * @since 5.9.121 (2011-09-27)
1767 protected $pdfa_mode = false;
1770 * version of PDF/A mode (1 - 3).
1772 * @since 6.2.26 (2019-03-12)
1774 protected $pdfa_version = 1;
1777 * Document creation date-time
1779 * @since 5.9.152 (2012-03-22)
1781 protected $doc_creation_timestamp;
1784 * Document modification date-time
1786 * @since 5.9.152 (2012-03-22)
1788 protected $doc_modification_timestamp;
1793 * @since 5.9.128 (2011-10-06)
1795 protected $custom_xmp = '';
1798 * Custom XMP RDF data.
1800 * @since 6.3.0 (2019-09-19)
1802 protected $custom_xmp_rdf = '';
1805 * Overprint mode array.
1806 * (Check the "Entries in a Graphics State Parameter Dictionary" on PDF 32000-1:2008).
1808 * @since 5.9.152 (2012-03-23)
1809 * @var array<string,bool|int>
1811 protected $overprint = array('OP' => false, 'op' => false, 'OPM' => 0);
1815 * (Check the "Entries in a Graphics State Parameter Dictionary" on PDF 32000-1:2008).
1817 * @since 5.9.152 (2012-03-23)
1819 protected $alpha = array('CA' => 1, 'ca' => 1, 'BM' => '/Normal', 'AIS' => false);
1822 * Define the page boundaries boxes to be set on document.
1824 * @since 5.9.152 (2012-03-23)
1826 protected $page_boxes = array('MediaBox', 'CropBox', 'BleedBox', 'TrimBox', 'ArtBox');
1829 * If true print TCPDF meta link.
1831 * @since 5.9.152 (2012-03-23)
1833 protected $tcpdflink = true;
1836 * Cache array for computed GD gamma values.
1838 * @since 5.9.1632 (2012-06-05)
1840 protected $gdgammacache = array();
1843 * Cache array for file content
1846 * @since 6.3.5 (2020-09-28)
1848 protected $fileContentCache = array();
1851 * Whether to allow local file path in image html tags, when prefixed with file://
1855 * @since 6.4 (2020-07-23)
1857 protected $allowLocalFiles = false;
1859 //------------------------------------------------------------
1861 //------------------------------------------------------------
1864 * This is the class constructor.
1865 * It allows to set up the page format, the orientation and the measure unit used in all the methods (except for the font sizes).
1867 * @param string $orientation 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>
1868 * @param string $unit User measure unit. Possible values are:<ul><li>pt: point</li><li>mm: millimeter (default)</li><li>cm: centimeter</li><li>in: inch</li></ul><br />A point equals 1/72 of inch, that is to say about 0.35 mm (an inch being 2.54 cm). This is a very common unit in typography; font sizes are expressed in that unit.
1869 * @param mixed $format 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().
1870 * @param boolean $unicode TRUE means that the input text is unicode (default = true)
1871 * @param string $encoding Charset encoding (used only when converting back html entities); default is UTF-8.
1872 * @param boolean $diskcache DEPRECATED FEATURE
1873 * @param false|integer $pdfa If not false, set the document to PDF/A mode and the good version (1 or 3).
1875 * @see getPageSizeFromFormat(), setPageFormat()
1877 public function __construct($orientation='P', $unit='mm', $format='A4', $unicode=true, $encoding='UTF-8', $diskcache=false, $pdfa=false) {
1878 // set file ID for trailer
1879 $serformat = (is_array($format) ?
json_encode($format) : $format);
1880 $this->file_id
= md5(TCPDF_STATIC
::getRandomSeed('TCPDF'.$orientation.$unit.$serformat.$encoding));
1881 $this->font_obj_ids
= array();
1882 $this->page_obj_id
= array();
1883 $this->form_obj_id
= array();
1886 if ($pdfa != false) {
1887 $this->pdfa_mode
= true;
1888 $this->pdfa_version
= $pdfa; // 1 or 3
1890 $this->pdfa_mode
= false;
1892 $this->force_srgb
= false;
1893 // set language direction
1895 $this->tmprtl
= false;
1898 // initialization of properties
1899 $this->isunicode
= $unicode;
1901 $this->transfmrk
[0] = array();
1902 $this->pagedim
= array();
1905 $this->pages
= array();
1907 $this->fonts
= array();
1908 $this->FontFiles
= array();
1909 $this->diffs
= array();
1910 $this->images
= array();
1911 $this->links
= array();
1912 $this->gradients
= array();
1913 $this->InFooter
= false;
1915 $this->FontFamily
= defined('PDF_FONT_NAME_MAIN')?PDF_FONT_NAME_MAIN
:'helvetica';
1916 $this->FontStyle
= '';
1917 $this->FontSizePt
= 12;
1918 $this->underline
= false;
1919 $this->overline
= false;
1920 $this->linethrough
= false;
1921 $this->DrawColor
= '0 G';
1922 $this->FillColor
= '0 g';
1923 $this->TextColor
= '0 g';
1924 $this->ColorFlag
= false;
1925 $this->pdflayers
= array();
1926 // encryption values
1927 $this->encrypted
= false;
1928 $this->last_enc_key
= '';
1929 // standard Unicode fonts
1930 $this->CoreFonts
= array(
1931 'courier'=>'Courier',
1932 'courierB'=>'Courier-Bold',
1933 'courierI'=>'Courier-Oblique',
1934 'courierBI'=>'Courier-BoldOblique',
1935 'helvetica'=>'Helvetica',
1936 'helveticaB'=>'Helvetica-Bold',
1937 'helveticaI'=>'Helvetica-Oblique',
1938 'helveticaBI'=>'Helvetica-BoldOblique',
1939 'times'=>'Times-Roman',
1940 'timesB'=>'Times-Bold',
1941 'timesI'=>'Times-Italic',
1942 'timesBI'=>'Times-BoldItalic',
1944 'zapfdingbats'=>'ZapfDingbats'
1947 $this->setPageUnit($unit);
1948 // set page format and orientation
1949 $this->setPageFormat($format, $orientation);
1950 // page margins (1 cm)
1951 $margin = 28.35 / $this->k
;
1952 $this->setMargins($margin, $margin);
1953 $this->clMargin
= $this->lMargin
;
1954 $this->crMargin
= $this->rMargin
;
1955 // internal cell padding
1956 $cpadding = $margin / 10;
1957 $this->setCellPaddings($cpadding, 0, $cpadding, 0);
1959 $this->setCellMargins(0, 0, 0, 0);
1960 // line width (0.2 mm)
1961 $this->LineWidth
= 0.57 / $this->k
;
1962 $this->linestyleWidth
= sprintf('%F w', ($this->LineWidth
* $this->k
));
1963 $this->linestyleCap
= '0 J';
1964 $this->linestyleJoin
= '0 j';
1965 $this->linestyleDash
= '[] 0 d';
1966 // automatic page break
1967 $this->setAutoPageBreak(true, (2 * $margin));
1968 // full width display mode
1969 $this->setDisplayMode('fullwidth');
1971 $this->setCompression();
1972 // set default PDF version number
1973 $this->setPDFVersion();
1974 $this->tcpdflink
= true;
1975 $this->encoding
= $encoding;
1976 $this->HREF
= array();
1977 $this->getFontsList();
1978 $this->fgcolor
= array('R' => 0, 'G' => 0, 'B' => 0);
1979 $this->strokecolor
= array('R' => 0, 'G' => 0, 'B' => 0);
1980 $this->bgcolor
= array('R' => 255, 'G' => 255, 'B' => 255);
1981 $this->extgstates
= array();
1982 $this->setTextShadow();
1984 $this->sign
= false;
1985 $this->tsa_timestamp
= false;
1986 $this->tsa_data
= array();
1987 $this->signature_appearance
= array('page' => 1, 'rect' => '0 0 0 0', 'name' => 'Signature');
1988 $this->empty_signature_appearance
= array();
1990 $this->ur
['enabled'] = false;
1991 $this->ur
['document'] = '/FullSave';
1992 $this->ur
['annots'] = '/Create/Delete/Modify/Copy/Import/Export';
1993 $this->ur
['form'] = '/Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate';
1994 $this->ur
['signature'] = '/Modify';
1995 $this->ur
['ef'] = '/Create/Delete/Modify/Import';
1996 $this->ur
['formex'] = '';
1997 // set default JPEG quality
1998 $this->jpeg_quality
= 75;
1999 // initialize some settings
2000 TCPDF_FONTS
::utf8Bidi(array(), '', false, $this->isunicode
, $this->CurrentFont
);
2002 $this->setFont($this->FontFamily
, $this->FontStyle
, $this->FontSizePt
);
2003 $this->setHeaderFont(array($this->FontFamily
, $this->FontStyle
, $this->FontSizePt
));
2004 $this->setFooterFont(array($this->FontFamily
, $this->FontStyle
, $this->FontSizePt
));
2005 // check if PCRE Unicode support is enabled
2006 if ($this->isunicode
AND (@preg_match
('/\pL/u', 'a') == 1)) {
2007 // PCRE unicode support is turned ON
2008 // \s : any whitespace character
2009 // \p{Z} : any separator
2010 // \p{Lo} : Unicode letter or ideograph that does not have lowercase and uppercase variants. Is used to chunk chinese words.
2011 // \xa0 : Unicode Character 'NO-BREAK SPACE' (U+00A0)
2012 //$this->setSpacesRE('/(?!\xa0)[\s\p{Z}\p{Lo}]/u');
2013 $this->setSpacesRE('/(?!\xa0)[\s\p{Z}]/u');
2015 // PCRE unicode support is turned OFF
2016 $this->setSpacesRE('/[^\S\xa0]/');
2018 $this->default_form_prop
= array('lineWidth'=>1, 'borderStyle'=>'solid', 'fillColor'=>array(255, 255, 255), 'strokeColor'=>array(128, 128, 128));
2019 // set document creation and modification timestamp
2020 $this->doc_creation_timestamp
= time();
2021 $this->doc_modification_timestamp
= $this->doc_creation_timestamp
;
2022 // get default graphic vars
2023 $this->default_graphic_vars
= $this->getGraphicVars();
2024 $this->header_xobj_autoreset
= false;
2025 $this->custom_xmp
= '';
2026 $this->custom_xmp_rdf
= '';
2030 * Default destructor.
2032 * @since 1.53.0.TC016
2034 public function __destruct() {
2036 $this->_destroy(true);
2040 * Set the units of measure for the document.
2041 * @param string $unit User measure unit. Possible values are:<ul><li>pt: point</li><li>mm: millimeter (default)</li><li>cm: centimeter</li><li>in: inch</li></ul><br />A point equals 1/72 of inch, that is to say about 0.35 mm (an inch being 2.54 cm). This is a very common unit in typography; font sizes are expressed in that unit.
2043 * @since 3.0.015 (2008-06-06)
2045 public function setPageUnit($unit) {
2046 $unit = strtolower($unit);
2057 $this->k
= $this->dpi
/ 25.4;
2062 $this->k
= $this->dpi
/ 2.54;
2067 $this->k
= $this->dpi
;
2072 $this->Error('Incorrect unit: '.$unit);
2076 $this->pdfunit
= $unit;
2077 if (isset($this->CurOrientation
)) {
2078 $this->setPageOrientation($this->CurOrientation
);
2083 * Change the format of the current page
2084 * @param mixed $format 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>
2085 * <li>['format'] = page format name (one of the above);</li>
2086 * <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>
2087 * <li>['PZ'] : The page's preferred zoom (magnification) factor.</li>
2088 * <li>['MediaBox'] : the boundaries of the physical medium on which the page shall be displayed or printed:</li>
2089 * <li>['MediaBox']['llx'] : lower-left x coordinate</li>
2090 * <li>['MediaBox']['lly'] : lower-left y coordinate</li>
2091 * <li>['MediaBox']['urx'] : upper-right x coordinate</li>
2092 * <li>['MediaBox']['ury'] : upper-right y coordinate</li>
2093 * <li>['CropBox'] : the visible region of default user space:</li>
2094 * <li>['CropBox']['llx'] : lower-left x coordinate</li>
2095 * <li>['CropBox']['lly'] : lower-left y coordinate</li>
2096 * <li>['CropBox']['urx'] : upper-right x coordinate</li>
2097 * <li>['CropBox']['ury'] : upper-right y coordinate</li>
2098 * <li>['BleedBox'] : the region to which the contents of the page shall be clipped when output in a production environment:</li>
2099 * <li>['BleedBox']['llx'] : lower-left x coordinate</li>
2100 * <li>['BleedBox']['lly'] : lower-left y coordinate</li>
2101 * <li>['BleedBox']['urx'] : upper-right x coordinate</li>
2102 * <li>['BleedBox']['ury'] : upper-right y coordinate</li>
2103 * <li>['TrimBox'] : the intended dimensions of the finished page after trimming:</li>
2104 * <li>['TrimBox']['llx'] : lower-left x coordinate</li>
2105 * <li>['TrimBox']['lly'] : lower-left y coordinate</li>
2106 * <li>['TrimBox']['urx'] : upper-right x coordinate</li>
2107 * <li>['TrimBox']['ury'] : upper-right y coordinate</li>
2108 * <li>['ArtBox'] : the extent of the page's meaningful content:</li>
2109 * <li>['ArtBox']['llx'] : lower-left x coordinate</li>
2110 * <li>['ArtBox']['lly'] : lower-left y coordinate</li>
2111 * <li>['ArtBox']['urx'] : upper-right x coordinate</li>
2112 * <li>['ArtBox']['ury'] : upper-right y coordinate</li>
2113 * <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>
2114 * <li>['BoxColorInfo'][BOXTYPE]['C'] : an array of three numbers in the range 0-255, representing the components in the DeviceRGB colour space.</li>
2115 * <li>['BoxColorInfo'][BOXTYPE]['W'] : the guideline width in default user units</li>
2116 * <li>['BoxColorInfo'][BOXTYPE]['S'] : the guideline style: S = Solid; D = Dashed</li>
2117 * <li>['BoxColorInfo'][BOXTYPE]['D'] : dash array defining a pattern of dashes and gaps to be used in drawing dashed guidelines</li>
2118 * <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>
2119 * <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>
2120 * <li>['trans']['S'] : transition style : Split, Blinds, Box, Wipe, Dissolve, Glitter, R, Fly, Push, Cover, Uncover, Fade</li>
2121 * <li>['trans']['D'] : The duration of the transition effect, in seconds.</li>
2122 * <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>
2123 * <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>
2124 * <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>
2125 * <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>
2126 * <li>['trans']['B'] : (Fly transition style only) If true, the area that shall be flown in is rectangular and opaque. Default: false.</li>
2128 * @param string $orientation page orientation. Possible values are (case insensitive):<ul>
2129 * <li>P or Portrait (default)</li>
2130 * <li>L or Landscape</li>
2131 * <li>'' (empty string) for automatic orientation</li>
2134 * @since 3.0.015 (2008-06-06)
2135 * @see getPageSizeFromFormat()
2137 protected function setPageFormat($format, $orientation='P') {
2138 if (!empty($format) AND isset($this->pagedim
[$this->page
])) {
2139 // remove inherited values
2140 unset($this->pagedim
[$this->page
]);
2142 if (is_string($format)) {
2143 // get page measures from format name
2144 $pf = TCPDF_STATIC
::getPageSizeFromFormat($format);
2145 $this->fwPt
= $pf[0];
2146 $this->fhPt
= $pf[1];
2148 // the boundaries of the physical medium on which the page shall be displayed or printed
2149 if (isset($format['MediaBox'])) {
2150 $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
);
2151 $this->fwPt
= (($format['MediaBox']['urx'] - $format['MediaBox']['llx']) * $this->k
);
2152 $this->fhPt
= (($format['MediaBox']['ury'] - $format['MediaBox']['lly']) * $this->k
);
2154 if (isset($format[0]) AND is_numeric($format[0]) AND isset($format[1]) AND is_numeric($format[1])) {
2155 $pf = array(($format[0] * $this->k
), ($format[1] * $this->k
));
2157 if (!isset($format['format'])) {
2159 $format['format'] = 'A4';
2161 $pf = TCPDF_STATIC
::getPageSizeFromFormat($format['format']);
2163 $this->fwPt
= $pf[0];
2164 $this->fhPt
= $pf[1];
2165 $this->pagedim
= TCPDF_STATIC
::setPageBoxes($this->page
, 'MediaBox', 0, 0, $this->fwPt
, $this->fhPt
, true, $this->k
, $this->pagedim
);
2167 // the visible region of default user space
2168 if (isset($format['CropBox'])) {
2169 $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
);
2171 // the region to which the contents of the page shall be clipped when output in a production environment
2172 if (isset($format['BleedBox'])) {
2173 $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
);
2175 // the intended dimensions of the finished page after trimming
2176 if (isset($format['TrimBox'])) {
2177 $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
);
2179 // the page's meaningful content (including potential white space)
2180 if (isset($format['ArtBox'])) {
2181 $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
);
2183 // specify the colours and other visual characteristics that should be used in displaying guidelines on the screen for the various page boundaries
2184 if (isset($format['BoxColorInfo'])) {
2185 $this->pagedim
[$this->page
]['BoxColorInfo'] = $format['BoxColorInfo'];
2187 if (isset($format['Rotate']) AND (($format['Rotate'] %
90) == 0)) {
2188 // The number of degrees by which the page shall be rotated clockwise when displayed or printed. The value shall be a multiple of 90.
2189 $this->pagedim
[$this->page
]['Rotate'] = intval($format['Rotate']);
2191 if (isset($format['PZ'])) {
2192 // The page's preferred zoom (magnification) factor
2193 $this->pagedim
[$this->page
]['PZ'] = floatval($format['PZ']);
2195 if (isset($format['trans'])) {
2196 // The style and duration of the visual transition to use when moving from another page to the given page during a presentation
2197 if (isset($format['trans']['Dur'])) {
2198 // The page's display duration
2199 $this->pagedim
[$this->page
]['trans']['Dur'] = floatval($format['trans']['Dur']);
2201 $stansition_styles = array('Split', 'Blinds', 'Box', 'Wipe', 'Dissolve', 'Glitter', 'R', 'Fly', 'Push', 'Cover', 'Uncover', 'Fade');
2202 if (isset($format['trans']['S']) AND in_array($format['trans']['S'], $stansition_styles)) {
2203 // The transition style that shall be used when moving to this page from another during a presentation
2204 $this->pagedim
[$this->page
]['trans']['S'] = $format['trans']['S'];
2205 $valid_effect = array('Split', 'Blinds');
2206 $valid_vals = array('H', 'V');
2207 if (isset($format['trans']['Dm']) AND in_array($format['trans']['S'], $valid_effect) AND in_array($format['trans']['Dm'], $valid_vals)) {
2208 $this->pagedim
[$this->page
]['trans']['Dm'] = $format['trans']['Dm'];
2210 $valid_effect = array('Split', 'Box', 'Fly');
2211 $valid_vals = array('I', 'O');
2212 if (isset($format['trans']['M']) AND in_array($format['trans']['S'], $valid_effect) AND in_array($format['trans']['M'], $valid_vals)) {
2213 $this->pagedim
[$this->page
]['trans']['M'] = $format['trans']['M'];
2215 $valid_effect = array('Wipe', 'Glitter', 'Fly', 'Cover', 'Uncover', 'Push');
2216 if (isset($format['trans']['Di']) AND in_array($format['trans']['S'], $valid_effect)) {
2217 if (((($format['trans']['Di'] == 90) OR ($format['trans']['Di'] == 180)) AND ($format['trans']['S'] == 'Wipe'))
2218 OR (($format['trans']['Di'] == 315) AND ($format['trans']['S'] == 'Glitter'))
2219 OR (($format['trans']['Di'] == 0) OR ($format['trans']['Di'] == 270))) {
2220 $this->pagedim
[$this->page
]['trans']['Di'] = intval($format['trans']['Di']);
2223 if (isset($format['trans']['SS']) AND ($format['trans']['S'] == 'Fly')) {
2224 $this->pagedim
[$this->page
]['trans']['SS'] = floatval($format['trans']['SS']);
2226 if (isset($format['trans']['B']) AND ($format['trans']['B'] === true) AND ($format['trans']['S'] == 'Fly')) {
2227 $this->pagedim
[$this->page
]['trans']['B'] = 'true';
2230 $this->pagedim
[$this->page
]['trans']['S'] = 'R';
2232 if (isset($format['trans']['D'])) {
2233 // The duration of the transition effect, in seconds
2234 $this->pagedim
[$this->page
]['trans']['D'] = floatval($format['trans']['D']);
2236 $this->pagedim
[$this->page
]['trans']['D'] = 1;
2240 $this->setPageOrientation($orientation);
2244 * Set page orientation.
2245 * @param string $orientation 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>
2246 * @param boolean|null $autopagebreak Boolean indicating if auto-page-break mode should be on or off.
2247 * @param float|null $bottommargin bottom margin of the page.
2249 * @since 3.0.015 (2008-06-06)
2251 public function setPageOrientation($orientation, $autopagebreak=null, $bottommargin=null) {
2252 if (!isset($this->pagedim
[$this->page
]['MediaBox'])) {
2253 // the boundaries of the physical medium on which the page shall be displayed or printed
2254 $this->pagedim
= TCPDF_STATIC
::setPageBoxes($this->page
, 'MediaBox', 0, 0, $this->fwPt
, $this->fhPt
, true, $this->k
, $this->pagedim
);
2256 if (!isset($this->pagedim
[$this->page
]['CropBox'])) {
2257 // the visible region of default user space
2258 $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
);
2260 if (!isset($this->pagedim
[$this->page
]['BleedBox'])) {
2261 // the region to which the contents of the page shall be clipped when output in a production environment
2262 $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
);
2264 if (!isset($this->pagedim
[$this->page
]['TrimBox'])) {
2265 // the intended dimensions of the finished page after trimming
2266 $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
);
2268 if (!isset($this->pagedim
[$this->page
]['ArtBox'])) {
2269 // the page's meaningful content (including potential white space)
2270 $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
);
2272 if (!isset($this->pagedim
[$this->page
]['Rotate'])) {
2273 // The number of degrees by which the page shall be rotated clockwise when displayed or printed. The value shall be a multiple of 90.
2274 $this->pagedim
[$this->page
]['Rotate'] = 0;
2276 if (!isset($this->pagedim
[$this->page
]['PZ'])) {
2277 // The page's preferred zoom (magnification) factor
2278 $this->pagedim
[$this->page
]['PZ'] = 1;
2280 if ($this->fwPt
> $this->fhPt
) {
2282 $default_orientation = 'L';
2285 $default_orientation = 'P';
2287 $valid_orientations = array('P', 'L');
2288 if (empty($orientation)) {
2289 $orientation = $default_orientation;
2291 $orientation = strtoupper($orientation[0]);
2293 if (in_array($orientation, $valid_orientations) AND ($orientation != $default_orientation)) {
2294 $this->CurOrientation
= $orientation;
2295 $this->wPt
= $this->fhPt
;
2296 $this->hPt
= $this->fwPt
;
2298 $this->CurOrientation
= $default_orientation;
2299 $this->wPt
= $this->fwPt
;
2300 $this->hPt
= $this->fhPt
;
2302 if ((abs($this->pagedim
[$this->page
]['MediaBox']['urx'] - $this->hPt
) < $this->feps
) AND (abs($this->pagedim
[$this->page
]['MediaBox']['ury'] - $this->wPt
) < $this->feps
)){
2303 // swap X and Y coordinates (change page orientation)
2304 $this->pagedim
= TCPDF_STATIC
::swapPageBoxCoordinates($this->page
, $this->pagedim
);
2306 $this->w
= ($this->wPt
/ $this->k
);
2307 $this->h
= ($this->hPt
/ $this->k
);
2308 if (TCPDF_STATIC
::empty_string($autopagebreak)) {
2309 if (isset($this->AutoPageBreak
)) {
2310 $autopagebreak = $this->AutoPageBreak
;
2312 $autopagebreak = true;
2315 if (TCPDF_STATIC
::empty_string($bottommargin)) {
2316 if (isset($this->bMargin
)) {
2317 $bottommargin = $this->bMargin
;
2319 // default value = 2 cm
2320 $bottommargin = 2 * 28.35 / $this->k
;
2323 $this->setAutoPageBreak($autopagebreak, $bottommargin);
2324 // store page dimensions
2325 $this->pagedim
[$this->page
]['w'] = $this->wPt
;
2326 $this->pagedim
[$this->page
]['h'] = $this->hPt
;
2327 $this->pagedim
[$this->page
]['wk'] = $this->w
;
2328 $this->pagedim
[$this->page
]['hk'] = $this->h
;
2329 $this->pagedim
[$this->page
]['tm'] = $this->tMargin
;
2330 $this->pagedim
[$this->page
]['bm'] = $bottommargin;
2331 $this->pagedim
[$this->page
]['lm'] = $this->lMargin
;
2332 $this->pagedim
[$this->page
]['rm'] = $this->rMargin
;
2333 $this->pagedim
[$this->page
]['pb'] = $autopagebreak;
2334 $this->pagedim
[$this->page
]['or'] = $this->CurOrientation
;
2335 $this->pagedim
[$this->page
]['olm'] = $this->original_lMargin
;
2336 $this->pagedim
[$this->page
]['orm'] = $this->original_rMargin
;
2340 * Set regular expression to detect withespaces or word separators.
2341 * The pattern delimiter must be the forward-slash character "/".
2342 * Some example patterns are:
2344 * Non-Unicode or missing PCRE unicode support: "/[^\S\xa0]/"
2345 * Unicode and PCRE unicode support: "/(?!\xa0)[\s\p{Z}]/u"
2346 * Unicode and PCRE unicode support in Chinese mode: "/(?!\xa0)[\s\p{Z}\p{Lo}]/u"
2347 * if PCRE unicode support is turned ON ("\P" is the negate class of "\p"):
2348 * \s : any whitespace character
2349 * \p{Z} : any separator
2350 * \p{Lo} : Unicode letter or ideograph that does not have lowercase and uppercase variants. Is used to chunk chinese words.
2351 * \xa0 : Unicode Character 'NO-BREAK SPACE' (U+00A0)
2353 * @param string $re regular expression (leave empty for default).
2355 * @since 4.6.016 (2009-06-15)
2357 public function setSpacesRE($re='/[^\S\xa0]/') {
2358 $this->re_spaces
= $re;
2359 $re_parts = explode('/', $re);
2360 // get pattern parts
2361 $this->re_space
= array();
2362 if (isset($re_parts[1]) AND !empty($re_parts[1])) {
2363 $this->re_space
['p'] = $re_parts[1];
2365 $this->re_space
['p'] = '[\s]';
2367 // set pattern modifiers
2368 if (isset($re_parts[2]) AND !empty($re_parts[2])) {
2369 $this->re_space
['m'] = $re_parts[2];
2371 $this->re_space
['m'] = '';
2376 * Enable or disable Right-To-Left language mode
2377 * @param boolean $enable if true enable Right-To-Left language mode.
2378 * @param boolean $resetx if true reset the X position on direction change.
2380 * @since 2.0.000 (2008-01-03)
2382 public function setRTL($enable, $resetx=true) {
2383 $enable = $enable ?
true : false;
2384 $resetx = ($resetx AND ($enable != $this->rtl
));
2385 $this->rtl
= $enable;
2386 $this->tmprtl
= false;
2393 * Return the RTL status
2396 * @since 4.0.012 (2008-07-24)
2398 public function getRTL() {
2403 * Force temporary RTL language direction
2404 * @param false|string $mode can be false, 'L' for LTR or 'R' for RTL
2406 * @since 2.1.000 (2008-01-09)
2408 public function setTempRTL($mode) {
2410 switch (strtoupper($mode)) {
2431 $this->tmprtl
= $newmode;
2435 * Return the current temporary RTL status
2438 * @since 4.8.014 (2009-11-04)
2440 public function isRTLTextDir() {
2441 return ($this->rtl
OR ($this->tmprtl
== 'R'));
2445 * Set the last cell height.
2446 * @param float $h cell height.
2447 * @author Nicola Asuni
2449 * @since 1.53.0.TC034
2451 public function setLastH($h) {
2456 * Return the cell height
2457 * @param int $fontsize Font size in internal units
2458 * @param boolean $padding If true add cell padding
2462 public function getCellHeight($fontsize, $padding=TRUE) {
2463 $height = ($fontsize * $this->cell_height_ratio
);
2465 $height +
= ($this->cell_padding
['T'] +
$this->cell_padding
['B']);
2467 return round($height, 6);
2471 * Reset the last cell height.
2473 * @since 5.9.000 (2010-10-03)
2475 public function resetLastH() {
2476 $this->lasth
= $this->getCellHeight($this->FontSize
);
2480 * Get the last cell height.
2481 * @return float last cell height
2483 * @since 4.0.017 (2008-08-05)
2485 public function getLastH() {
2486 return $this->lasth
;
2490 * Set the adjusting factor to convert pixels to user units.
2491 * @param float $scale adjusting factor to convert pixels to user units.
2492 * @author Nicola Asuni
2496 public function setImageScale($scale) {
2497 $this->imgscale
= $scale;
2501 * Returns the adjusting factor to convert pixels to user units.
2502 * @return float adjusting factor to convert pixels to user units.
2503 * @author Nicola Asuni
2507 public function getImageScale() {
2508 return $this->imgscale
;
2512 * Returns an array of page dimensions:
2513 * <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>
2514 * @param int|null $pagenum page number (empty = current page)
2515 * @return array of page dimensions.
2516 * @author Nicola Asuni
2518 * @since 4.5.027 (2009-03-16)
2520 public function getPageDimensions($pagenum=null) {
2521 if (empty($pagenum)) {
2522 $pagenum = $this->page
;
2524 return $this->pagedim
[$pagenum];
2528 * Returns the page width in units.
2529 * @param int|null $pagenum page number (empty = current page)
2530 * @return int|float page width.
2531 * @author Nicola Asuni
2534 * @see getPageDimensions()
2536 public function getPageWidth($pagenum=null) {
2537 if (empty($pagenum)) {
2540 return $this->pagedim
[$pagenum]['w'];
2544 * Returns the page height in units.
2545 * @param int|null $pagenum page number (empty = current page)
2546 * @return int|float page height.
2547 * @author Nicola Asuni
2550 * @see getPageDimensions()
2552 public function getPageHeight($pagenum=null) {
2553 if (empty($pagenum)) {
2556 return $this->pagedim
[$pagenum]['h'];
2560 * Returns the page break margin.
2561 * @param int|null $pagenum page number (empty = current page)
2562 * @return int|float page break margin.
2563 * @author Nicola Asuni
2566 * @see getPageDimensions()
2568 public function getBreakMargin($pagenum=null) {
2569 if (empty($pagenum)) {
2570 return $this->bMargin
;
2572 return $this->pagedim
[$pagenum]['bm'];
2576 * Returns the scale factor (number of points in user unit).
2577 * @return int scale factor.
2578 * @author Nicola Asuni
2582 public function getScaleFactor() {
2587 * Defines the left, top and right margins.
2588 * @param int|float $left Left margin.
2589 * @param int|float $top Top margin.
2590 * @param int|float|null $right Right margin. Default value is the left one.
2591 * @param boolean $keepmargins if true overwrites the default page margins
2594 * @see SetLeftMargin(), SetTopMargin(), SetRightMargin(), SetAutoPageBreak()
2596 public function setMargins($left, $top, $right=null, $keepmargins=false) {
2597 //Set left, top and right margins
2598 $this->lMargin
= $left;
2599 $this->tMargin
= $top;
2600 if ($right == -1 OR $right === null) {
2603 $this->rMargin
= $right;
2605 // overwrite original values
2606 $this->original_lMargin
= $this->lMargin
;
2607 $this->original_rMargin
= $this->rMargin
;
2612 * 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.
2613 * @param int|float $margin The margin.
2616 * @see SetTopMargin(), SetRightMargin(), SetAutoPageBreak(), SetMargins()
2618 public function setLeftMargin($margin) {
2620 $this->lMargin
= $margin;
2621 if (($this->page
> 0) AND ($this->x
< $margin)) {
2627 * Defines the top margin. The method can be called before creating the first page.
2628 * @param int|float $margin The margin.
2631 * @see SetLeftMargin(), SetRightMargin(), SetAutoPageBreak(), SetMargins()
2633 public function setTopMargin($margin) {
2635 $this->tMargin
= $margin;
2636 if (($this->page
> 0) AND ($this->y
< $margin)) {
2642 * Defines the right margin. The method can be called before creating the first page.
2643 * @param int|float $margin The margin.
2646 * @see SetLeftMargin(), SetTopMargin(), SetAutoPageBreak(), SetMargins()
2648 public function setRightMargin($margin) {
2649 $this->rMargin
= $margin;
2650 if (($this->page
> 0) AND ($this->x
> ($this->w
- $margin))) {
2651 $this->x
= $this->w
- $margin;
2656 * Set the same internal Cell padding for top, right, bottom, left-
2657 * @param int|float $pad internal padding.
2659 * @since 2.1.000 (2008-01-09)
2660 * @see getCellPaddings(), setCellPaddings()
2662 public function setCellPadding($pad) {
2664 $this->cell_padding
['L'] = $pad;
2665 $this->cell_padding
['T'] = $pad;
2666 $this->cell_padding
['R'] = $pad;
2667 $this->cell_padding
['B'] = $pad;
2672 * Set the internal Cell paddings.
2673 * @param int|float|null $left left padding
2674 * @param int|float|null $top top padding
2675 * @param int|float|null $right right padding
2676 * @param int|float|null $bottom bottom padding
2678 * @since 5.9.000 (2010-10-03)
2679 * @see getCellPaddings(), SetCellPadding()
2681 public function setCellPaddings($left=null, $top=null, $right=null, $bottom=null) {
2682 if (!TCPDF_STATIC
::empty_string($left) AND ($left >= 0)) {
2683 $this->cell_padding
['L'] = $left;
2685 if (!TCPDF_STATIC
::empty_string($top) AND ($top >= 0)) {
2686 $this->cell_padding
['T'] = $top;
2688 if (!TCPDF_STATIC
::empty_string($right) AND ($right >= 0)) {
2689 $this->cell_padding
['R'] = $right;
2691 if (!TCPDF_STATIC
::empty_string($bottom) AND ($bottom >= 0)) {
2692 $this->cell_padding
['B'] = $bottom;
2697 * Get the internal Cell padding array.
2698 * @return array of padding values
2700 * @since 5.9.000 (2010-10-03)
2701 * @see setCellPaddings(), SetCellPadding()
2703 public function getCellPaddings() {
2704 return $this->cell_padding
;
2708 * Set the internal Cell margins.
2709 * @param int|float|null $left left margin
2710 * @param int|float|null $top top margin
2711 * @param int|float|null $right right margin
2712 * @param int|float|null $bottom bottom margin
2714 * @since 5.9.000 (2010-10-03)
2715 * @see getCellMargins()
2717 public function setCellMargins($left=null, $top=null, $right=null, $bottom=null) {
2718 if (!TCPDF_STATIC
::empty_string($left) AND ($left >= 0)) {
2719 $this->cell_margin
['L'] = $left;
2721 if (!TCPDF_STATIC
::empty_string($top) AND ($top >= 0)) {
2722 $this->cell_margin
['T'] = $top;
2724 if (!TCPDF_STATIC
::empty_string($right) AND ($right >= 0)) {
2725 $this->cell_margin
['R'] = $right;
2727 if (!TCPDF_STATIC
::empty_string($bottom) AND ($bottom >= 0)) {
2728 $this->cell_margin
['B'] = $bottom;
2733 * Get the internal Cell margin array.
2734 * @return array of margin values
2736 * @since 5.9.000 (2010-10-03)
2737 * @see setCellMargins()
2739 public function getCellMargins() {
2740 return $this->cell_margin
;
2744 * Adjust the internal Cell padding array to take account of the line width.
2745 * @param string|array|int|bool $brd 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)))
2746 * @return void|array array of adjustments
2748 * @since 5.9.000 (2010-10-03)
2750 protected function adjustCellPadding($brd=0) {
2754 if (is_string($brd)) {
2755 // convert string to array
2756 $slen = strlen($brd);
2758 for ($i = 0; $i < $slen; ++
$i) {
2759 $newbrd[$brd[$i]] = true;
2765 ||
(is_numeric($brd) && ((int)$brd > 0))
2767 $brd = array('LRTB' => true);
2769 if (!is_array($brd)) {
2772 // store current cell padding
2773 $cp = $this->cell_padding
;
2774 // select border mode
2775 if (isset($brd['mode'])) {
2776 $mode = $brd['mode'];
2777 unset($brd['mode']);
2782 foreach ($brd as $border => $style) {
2783 $line_width = $this->LineWidth
;
2784 if (is_array($style) && isset($style['width'])) {
2786 $line_width = $style['width'];
2788 $adj = 0; // line width inside the cell
2800 $adj = ($line_width / 2);
2804 // correct internal cell padding if required to avoid overlap between text and lines
2806 is_numeric($this->cell_padding
['T'])
2807 && ($this->cell_padding
['T'] < $adj)
2808 && (strpos($border, 'T') !== false)
2810 $this->cell_padding
['T'] = $adj;
2813 is_numeric($this->cell_padding
['R'])
2814 && ($this->cell_padding
['R'] < $adj)
2815 && (strpos($border, 'R') !== false)
2817 $this->cell_padding
['R'] = $adj;
2820 is_numeric($this->cell_padding
['B'])
2821 && ($this->cell_padding
['B'] < $adj)
2822 && (strpos($border, 'B') !== false)
2824 $this->cell_padding
['B'] = $adj;
2827 is_numeric($this->cell_padding
['L'])
2828 && ($this->cell_padding
['L'] < $adj)
2829 && (strpos($border, 'L') !== false)
2831 $this->cell_padding
['L'] = $adj;
2837 'T' => ($this->cell_padding
['T'] - $cp['T']),
2838 'R' => ($this->cell_padding
['R'] - $cp['R']),
2839 'B' => ($this->cell_padding
['B'] - $cp['B']),
2840 'L' => ($this->cell_padding
['L'] - $cp['L']),
2845 * 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.
2846 * @param boolean $auto Boolean indicating if mode should be on or off.
2847 * @param float $margin Distance from the bottom of the page.
2850 * @see Cell(), MultiCell(), AcceptPageBreak()
2852 public function setAutoPageBreak($auto, $margin=0) {
2853 $this->AutoPageBreak
= $auto ?
true : false;
2854 $this->bMargin
= $margin;
2855 $this->PageBreakTrigger
= $this->h
- $margin;
2859 * Return the auto-page-break mode (true or false).
2860 * @return bool auto-page-break mode
2864 public function getAutoPageBreak() {
2865 return $this->AutoPageBreak
;
2869 * Defines the way the document is to be displayed by the viewer.
2870 * @param mixed $zoom The zoom to use. It can be one of the following string values or a number indicating the zooming factor to use. <ul><li>fullpage: displays the entire page on screen </li><li>fullwidth: uses maximum width of window</li><li>real: uses real size (equivalent to 100% zoom)</li><li>default: uses viewer default mode</li></ul>
2871 * @param string $layout The page layout. Possible values are:<ul><li>SinglePage Display one page at a time</li><li>OneColumn Display the pages in one column</li><li>TwoColumnLeft Display the pages in two columns, with odd-numbered pages on the left</li><li>TwoColumnRight Display the pages in two columns, with odd-numbered pages on the right</li><li>TwoPageLeft (PDF 1.5) Display the pages two at a time, with odd-numbered pages on the left</li><li>TwoPageRight (PDF 1.5) Display the pages two at a time, with odd-numbered pages on the right</li></ul>
2872 * @param string $mode A name object specifying how the document should be displayed when opened:<ul><li>UseNone Neither document outline nor thumbnail images visible</li><li>UseOutlines Document outline visible</li><li>UseThumbs Thumbnail images visible</li><li>FullScreen Full-screen mode, with no menu bar, window controls, or any other window visible</li><li>UseOC (PDF 1.5) Optional content group panel visible</li><li>UseAttachments (PDF 1.6) Attachments panel visible</li></ul>
2876 public function setDisplayMode($zoom, $layout='SinglePage', $mode='UseNone') {
2877 if (($zoom == 'fullpage') OR ($zoom == 'fullwidth') OR ($zoom == 'real') OR ($zoom == 'default') OR (!is_string($zoom))) {
2878 $this->ZoomMode
= $zoom;
2880 $this->Error('Incorrect zoom display mode: '.$zoom);
2882 $this->LayoutMode
= TCPDF_STATIC
::getPageLayoutMode($layout);
2883 $this->PageMode
= TCPDF_STATIC
::getPageMode($mode);
2887 * 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.
2888 * Note: the Zlib extension is required for this feature. If not present, compression will be turned off.
2889 * @param boolean $compress Boolean indicating if compression must be enabled.
2893 public function setCompression($compress=true) {
2894 $this->compress
= false;
2895 if (function_exists('gzcompress')) {
2897 if ( !$this->pdfa_mode
) {
2898 $this->compress
= true;
2905 * Set flag to force sRGB_IEC61966-2.1 black scaled ICC color profile for the whole document.
2906 * @param boolean $mode If true force sRGB output intent.
2908 * @since 5.9.121 (2011-09-28)
2910 public function setSRGBmode($mode=false) {
2911 $this->force_srgb
= $mode ?
true : false;
2915 * Turn on/off Unicode mode for document information dictionary (meta tags).
2916 * This has effect only when unicode mode is set to false.
2917 * @param boolean $unicode if true set the meta information in Unicode
2918 * @since 5.9.027 (2010-12-01)
2921 public function setDocInfoUnicode($unicode=true) {
2922 $this->docinfounicode
= $unicode ?
true : false;
2926 * Defines the title of the document.
2927 * @param string $title The title.
2930 * @see SetAuthor(), SetCreator(), SetKeywords(), SetSubject()
2932 public function setTitle($title) {
2933 $this->title
= $title;
2937 * Defines the subject of the document.
2938 * @param string $subject The subject.
2941 * @see SetAuthor(), SetCreator(), SetKeywords(), SetTitle()
2943 public function setSubject($subject) {
2944 $this->subject
= $subject;
2948 * Defines the author of the document.
2949 * @param string $author The name of the author.
2952 * @see SetCreator(), SetKeywords(), SetSubject(), SetTitle()
2954 public function setAuthor($author) {
2955 $this->author
= $author;
2959 * Associates keywords with the document, generally in the form 'keyword1 keyword2 ...'.
2960 * @param string $keywords The list of keywords.
2963 * @see SetAuthor(), SetCreator(), SetSubject(), SetTitle()
2965 public function setKeywords($keywords) {
2966 $this->keywords
= $keywords;
2970 * Defines the creator of the document. This is typically the name of the application that generates the PDF.
2971 * @param string $creator The name of the creator.
2974 * @see SetAuthor(), SetKeywords(), SetSubject(), SetTitle()
2976 public function setCreator($creator) {
2977 $this->creator
= $creator;
2981 * Whether to allow local file path in image html tags, when prefixed with file://
2983 * @param bool $allowLocalFiles true, when local files should be allowed. Otherwise false.
2987 public function setAllowLocalFiles($allowLocalFiles) {
2988 $this->allowLocalFiles
= (bool) $allowLocalFiles;
2993 * Throw an exception or print an error message and die if the K_TCPDF_PARSER_THROW_EXCEPTION_ERROR constant is set to true.
2994 * @param string $msg The error message
2998 public function Error($msg) {
2999 // unset all class variables
3000 $this->_destroy(true);
3001 if (defined('K_TCPDF_THROW_EXCEPTION_ERROR') AND !K_TCPDF_THROW_EXCEPTION_ERROR
) {
3002 die('<strong>TCPDF ERROR: </strong>'.$msg);
3004 throw new Exception('TCPDF ERROR: '.$msg);
3009 * This method begins the generation of the PDF document.
3010 * It is not necessary to call it explicitly because AddPage() does it automatically.
3011 * Note: no page is created by this method
3014 * @see AddPage(), Close()
3016 public function Open() {
3021 * Terminates the PDF document.
3022 * It is not necessary to call this method explicitly because Output() does it automatically.
3023 * If the document contains no page, AddPage() is called to prevent from getting an invalid document.
3026 * @see Open(), Output()
3028 public function Close() {
3029 if ($this->state
== 3) {
3032 if ($this->page
== 0) {
3036 if ($this->tcpdflink
) {
3037 // save current graphic settings
3038 $gvars = $this->getGraphicVars();
3039 $this->setEqualColumns();
3040 $this->lastpage(true);
3041 $this->setAutoPageBreak(false);
3043 $this->y
= $this->h
- (1 / $this->k
);
3045 $this->_outSaveGraphicsState();
3046 $font = defined('PDF_FONT_NAME_MAIN')?PDF_FONT_NAME_MAIN
:'helvetica';
3047 $this->setFont($font, '', 1);
3048 $this->setTextRenderingMode(0, false, false);
3049 $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";
3050 $lnk = "\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x74\x63\x70\x64\x66\x2e\x6f\x72\x67";
3051 $this->Cell(0, 0, $msg, 0, 0, 'L', 0, $lnk, 0, false, 'D', 'B');
3052 $this->_outRestoreGraphicsState();
3053 // restore graphic settings
3054 $this->setGraphicVars($gvars);
3060 // unset all class variables (except critical ones)
3061 $this->_destroy(false);
3065 * Move pointer at the specified document page and update page dimensions.
3066 * @param int $pnum page number (1 ... numpages)
3067 * @param boolean $resetmargins if true reset left, right, top margins and Y position.
3069 * @since 2.1.000 (2008-01-07)
3070 * @see getPage(), lastpage(), getNumPages()
3072 public function setPage($pnum, $resetmargins=false) {
3073 if (($pnum == $this->page
) AND ($this->state
== 2)) {
3076 if (($pnum > 0) AND ($pnum <= $this->numpages
)) {
3078 // save current graphic settings
3079 //$gvars = $this->getGraphicVars();
3080 $oldpage = $this->page
;
3081 $this->page
= $pnum;
3082 $this->wPt
= $this->pagedim
[$this->page
]['w'];
3083 $this->hPt
= $this->pagedim
[$this->page
]['h'];
3084 $this->w
= $this->pagedim
[$this->page
]['wk'];
3085 $this->h
= $this->pagedim
[$this->page
]['hk'];
3086 $this->tMargin
= $this->pagedim
[$this->page
]['tm'];
3087 $this->bMargin
= $this->pagedim
[$this->page
]['bm'];
3088 $this->original_lMargin
= $this->pagedim
[$this->page
]['olm'];
3089 $this->original_rMargin
= $this->pagedim
[$this->page
]['orm'];
3090 $this->AutoPageBreak
= $this->pagedim
[$this->page
]['pb'];
3091 $this->CurOrientation
= $this->pagedim
[$this->page
]['or'];
3092 $this->setAutoPageBreak($this->AutoPageBreak
, $this->bMargin
);
3093 // restore graphic settings
3094 //$this->setGraphicVars($gvars);
3095 if ($resetmargins) {
3096 $this->lMargin
= $this->pagedim
[$this->page
]['olm'];
3097 $this->rMargin
= $this->pagedim
[$this->page
]['orm'];
3098 $this->setY($this->tMargin
);
3100 // account for booklet mode
3101 if ($this->pagedim
[$this->page
]['olm'] != $this->pagedim
[$oldpage]['olm']) {
3102 $deltam = $this->pagedim
[$this->page
]['olm'] - $this->pagedim
[$this->page
]['orm'];
3103 $this->lMargin +
= $deltam;
3104 $this->rMargin
-= $deltam;
3108 $this->Error('Wrong page number on setPage() function: '.$pnum);
3113 * Reset pointer to the last document page.
3114 * @param boolean $resetmargins if true reset left, right, top margins and Y position.
3116 * @since 2.0.000 (2008-01-04)
3117 * @see setPage(), getPage(), getNumPages()
3119 public function lastPage($resetmargins=false) {
3120 $this->setPage($this->getNumPages(), $resetmargins);
3124 * Get current document page number.
3125 * @return int page number
3127 * @since 2.1.000 (2008-01-07)
3128 * @see setPage(), lastpage(), getNumPages()
3130 public function getPage() {
3135 * Get the total number of insered pages.
3136 * @return int number of pages
3138 * @since 2.1.000 (2008-01-07)
3139 * @see setPage(), getPage(), lastpage()
3141 public function getNumPages() {
3142 return $this->numpages
;
3146 * Adds a new TOC (Table Of Content) page to the document.
3147 * @param string $orientation page orientation.
3148 * @param mixed $format 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().
3149 * @param boolean $keepmargins if true overwrites the default page margins with the current margins
3151 * @since 5.0.001 (2010-05-06)
3152 * @see AddPage(), startPage(), endPage(), endTOCPage()
3154 public function addTOCPage($orientation='', $format='', $keepmargins=false) {
3155 $this->AddPage($orientation, $format, $keepmargins, true);
3159 * Terminate the current TOC (Table Of Content) page
3161 * @since 5.0.001 (2010-05-06)
3162 * @see AddPage(), startPage(), endPage(), addTOCPage()
3164 public function endTOCPage() {
3165 $this->endPage(true);
3169 * 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).
3170 * The origin of the coordinate system is at the top-left corner (or top-right for RTL) and increasing ordinates go downwards.
3171 * @param string $orientation page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
3172 * @param mixed $format 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().
3173 * @param boolean $keepmargins if true overwrites the default page margins with the current margins
3174 * @param boolean $tocpage if true set the tocpage state to true (the added page will be used to display Table Of Content).
3177 * @see startPage(), endPage(), addTOCPage(), endTOCPage(), getPageSizeFromFormat(), setPageFormat()
3179 public function AddPage($orientation='', $format='', $keepmargins=false, $tocpage=false) {
3180 if ($this->inxobj
) {
3181 // we are inside an XObject template
3184 if (!isset($this->original_lMargin
) OR $keepmargins) {
3185 $this->original_lMargin
= $this->lMargin
;
3187 if (!isset($this->original_rMargin
) OR $keepmargins) {
3188 $this->original_rMargin
= $this->rMargin
;
3190 // terminate previous page
3193 $this->startPage($orientation, $format, $tocpage);
3197 * Terminate the current page
3198 * @param boolean $tocpage if true set the tocpage state to false (end the page used to display Table Of Content).
3200 * @since 4.2.010 (2008-11-14)
3201 * @see AddPage(), startPage(), addTOCPage(), endTOCPage()
3203 public function endPage($tocpage=false) {
3204 // check if page is already closed
3205 if (($this->page
== 0) OR ($this->numpages
> $this->page
) OR (!$this->pageopen
[$this->page
])) {
3208 // print page footer
3212 // mark page as closed
3213 $this->pageopen
[$this->page
] = false;
3215 $this->tocpage
= false;
3220 * Starts a new page to the document. The page must be closed using the endPage() function.
3221 * The origin of the coordinate system is at the top-left corner and increasing ordinates go downwards.
3222 * @param string $orientation page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
3223 * @param mixed $format 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().
3224 * @param boolean $tocpage if true the page is designated to contain the Table-Of-Content.
3225 * @since 4.2.010 (2008-11-14)
3226 * @see AddPage(), endPage(), addTOCPage(), endTOCPage(), getPageSizeFromFormat(), setPageFormat()
3229 public function startPage($orientation='', $format='', $tocpage=false) {
3231 $this->tocpage
= true;
3233 // move page numbers of documents to be attached
3234 if ($this->tocpage
) {
3235 // move reference to unexistent pages (used for page attachments)
3237 $tmpoutlines = $this->outlines
;
3238 foreach ($tmpoutlines as $key => $outline) {
3239 if (!$outline['f'] AND ($outline['p'] > $this->numpages
)) {
3240 $this->outlines
[$key]['p'] = ($outline['p'] +
1);
3244 $tmpdests = $this->dests
;
3245 foreach ($tmpdests as $key => $dest) {
3246 if (!$dest['f'] AND ($dest['p'] > $this->numpages
)) {
3247 $this->dests
[$key]['p'] = ($dest['p'] +
1);
3251 $tmplinks = $this->links
;
3252 foreach ($tmplinks as $key => $link) {
3253 if (!$link['f'] AND ($link['p'] > $this->numpages
)) {
3254 $this->links
[$key]['p'] = ($link['p'] +
1);
3258 if ($this->numpages
> $this->page
) {
3259 // this page has been already added
3260 $this->setPage($this->page +
1);
3261 $this->setY($this->tMargin
);
3265 if ($this->state
== 0) {
3269 $this->swapMargins($this->booklet
);
3270 // save current graphic settings
3271 $gvars = $this->getGraphicVars();
3273 $this->_beginpage($orientation, $format);
3274 // mark page as open
3275 $this->pageopen
[$this->page
] = true;
3276 // restore graphic settings
3277 $this->setGraphicVars($gvars);
3279 $this->setPageMark();
3280 // print page header
3282 // restore graphic settings
3283 $this->setGraphicVars($gvars);
3285 $this->setPageMark();
3286 // print table header (if any)
3287 $this->setTableHeader();
3288 // set mark for empty page check
3289 $this->emptypagemrk
[$this->page
]= $this->pagelen
[$this->page
];
3293 * Set start-writing mark on current page stream used to put borders and fills.
3294 * Borders and fills are always created after content and inserted on the position marked by this method.
3295 * This function must be called after calling Image() function for a background image.
3296 * Background images must be always inserted before calling Multicell() or WriteHTMLCell() or WriteHTML() functions.
3298 * @since 4.0.016 (2008-07-30)
3300 public function setPageMark() {
3301 $this->intmrk
[$this->page
] = $this->pagelen
[$this->page
];
3302 $this->bordermrk
[$this->page
] = $this->intmrk
[$this->page
];
3303 $this->setContentMark();
3307 * Set start-writing mark on selected page.
3308 * Borders and fills are always created after content and inserted on the position marked by this method.
3309 * @param int $page page number (default is the current page)
3311 * @since 4.6.021 (2009-07-20)
3313 protected function setContentMark($page=0) {
3315 $page = $this->page
;
3317 if (isset($this->footerlen
[$page])) {
3318 $this->cntmrk
[$page] = $this->pagelen
[$page] - $this->footerlen
[$page];
3320 $this->cntmrk
[$page] = $this->pagelen
[$page];
3326 * @param string $ln header image logo
3327 * @param int $lw header image logo width in mm
3328 * @param string $ht string to print as title on document header
3329 * @param string $hs string to print on document header
3330 * @param int[] $tc RGB array color for text.
3331 * @param int[] $lc RGB array color for line.
3334 public function setHeaderData($ln='', $lw=0, $ht='', $hs='', $tc=array(0,0,0), $lc=array(0,0,0)) {
3335 $this->header_logo
= $ln;
3336 $this->header_logo_width
= $lw;
3337 $this->header_title
= $ht;
3338 $this->header_string
= $hs;
3339 $this->header_text_color
= $tc;
3340 $this->header_line_color
= $lc;
3345 * @param int[] $tc RGB array color for text.
3346 * @param int[] $lc RGB array color for line.
3349 public function setFooterData($tc=array(0,0,0), $lc=array(0,0,0)) {
3350 $this->footer_text_color
= $tc;
3351 $this->footer_line_color
= $lc;
3355 * Returns header data:
3356 * <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>
3357 * @return array<string,mixed>
3359 * @since 4.0.012 (2008-07-24)
3361 public function getHeaderData() {
3363 $ret['logo'] = $this->header_logo
;
3364 $ret['logo_width'] = $this->header_logo_width
;
3365 $ret['title'] = $this->header_title
;
3366 $ret['string'] = $this->header_string
;
3367 $ret['text_color'] = $this->header_text_color
;
3368 $ret['line_color'] = $this->header_line_color
;
3373 * Set header margin.
3374 * (minimum distance between header and top page margin)
3375 * @param int $hm distance in user units
3378 public function setHeaderMargin($hm=10) {
3379 $this->header_margin
= $hm;
3383 * Returns header margin in user units.
3385 * @since 4.0.012 (2008-07-24)
3388 public function getHeaderMargin() {
3389 return $this->header_margin
;
3393 * Set footer margin.
3394 * (minimum distance between footer and bottom page margin)
3395 * @param int $fm distance in user units
3398 public function setFooterMargin($fm=10) {
3399 $this->footer_margin
= $fm;
3403 * Returns footer margin in user units.
3405 * @since 4.0.012 (2008-07-24)
3408 public function getFooterMargin() {
3409 return $this->footer_margin
;
3412 * Set a flag to print page header.
3413 * @param boolean $val set to true to print the page header (default), false otherwise.
3416 public function setPrintHeader($val=true) {
3417 $this->print_header
= $val ?
true : false;
3421 * Set a flag to print page footer.
3422 * @param boolean $val set to true to print the page footer (default), false otherwise.
3425 public function setPrintFooter($val=true) {
3426 $this->print_footer
= $val ?
true : false;
3430 * Return the right-bottom (or left-bottom for RTL) corner X coordinate of last inserted image
3434 public function getImageRBX() {
3435 return $this->img_rb_x
;
3439 * Return the right-bottom (or left-bottom for RTL) corner Y coordinate of last inserted image
3443 public function getImageRBY() {
3444 return $this->img_rb_y
;
3448 * Reset the xobject template used by Header() method.
3451 public function resetHeaderTemplate() {
3452 $this->header_xobjid
= false;
3456 * Set a flag to automatically reset the xobject template used by Header() method at each page.
3457 * @param boolean $val set to true to reset Header xobject template at each page, false otherwise.
3460 public function setHeaderTemplateAutoreset($val=true) {
3461 $this->header_xobj_autoreset
= $val ?
true : false;
3465 * This method is used to render the page header.
3466 * It is automatically called by AddPage() and could be overwritten in your own inherited class.
3469 public function Header() {
3470 if ($this->header_xobjid
=== false) {
3471 // start a new XObject Template
3472 $this->header_xobjid
= $this->startTemplate($this->w
, $this->tMargin
);
3473 $headerfont = $this->getHeaderFont();
3474 $headerdata = $this->getHeaderData();
3475 $this->y
= $this->header_margin
;
3477 $this->x
= $this->w
- $this->original_rMargin
;
3479 $this->x
= $this->original_lMargin
;
3481 if (($headerdata['logo']) AND ($headerdata['logo'] != K_BLANK_IMAGE
)) {
3482 $imgtype = TCPDF_IMAGES
::getImageFileType(K_PATH_IMAGES
.$headerdata['logo']);
3483 if (($imgtype == 'eps') OR ($imgtype == 'ai')) {
3484 $this->ImageEps(K_PATH_IMAGES
.$headerdata['logo'], '', '', $headerdata['logo_width']);
3485 } elseif ($imgtype == 'svg') {
3486 $this->ImageSVG(K_PATH_IMAGES
.$headerdata['logo'], '', '', $headerdata['logo_width']);
3488 $this->Image(K_PATH_IMAGES
.$headerdata['logo'], '', '', $headerdata['logo_width']);
3490 $imgy = $this->getImageRBY();
3494 $cell_height = $this->getCellHeight($headerfont[2] / $this->k
);
3495 // set starting margin for text data cell
3496 if ($this->getRTL()) {
3497 $header_x = $this->original_rMargin +
($headerdata['logo_width'] * 1.1);
3499 $header_x = $this->original_lMargin +
($headerdata['logo_width'] * 1.1);
3501 $cw = $this->w
- $this->original_lMargin
- $this->original_rMargin
- ($headerdata['logo_width'] * 1.1);
3502 $this->setTextColorArray($this->header_text_color
);
3504 $this->setFont($headerfont[0], 'B', $headerfont[2] +
1);
3505 $this->setX($header_x);
3506 $this->Cell($cw, $cell_height, $headerdata['title'], 0, 1, '', 0, '', 0);
3508 $this->setFont($headerfont[0], $headerfont[1], $headerfont[2]);
3509 $this->setX($header_x);
3510 $this->MultiCell($cw, $cell_height, $headerdata['string'], 0, '', 0, 1, '', '', true, 0, false, true, 0, 'T', false);
3511 // print an ending header line
3512 $this->setLineStyle(array('width' => 0.85 / $this->k
, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => $headerdata['line_color']));
3513 $this->setY((2.835 / $this->k
) +
max($imgy, $this->y
));
3515 $this->setX($this->original_rMargin
);
3517 $this->setX($this->original_lMargin
);
3519 $this->Cell(($this->w
- $this->original_lMargin
- $this->original_rMargin
), 0, '', 'T', 0, 'C');
3520 $this->endTemplate();
3522 // print header template
3525 if (!$this->header_xobj_autoreset
AND $this->booklet
AND (($this->page %
2) == 0)) {
3526 // adjust margins for booklet mode
3527 $dx = ($this->original_lMargin
- $this->original_rMargin
);
3530 $x = $this->w +
$dx;
3534 $this->printTemplate($this->header_xobjid
, $x, 0, 0, 0, '', '', false);
3535 if ($this->header_xobj_autoreset
) {
3536 // reset header xobject template at each page
3537 $this->header_xobjid
= false;
3542 * This method is used to render the page footer.
3543 * It is automatically called by AddPage() and could be overwritten in your own inherited class.
3546 public function Footer() {
3548 $this->setTextColorArray($this->footer_text_color
);
3549 //set style for cell border
3550 $line_width = (0.85 / $this->k
);
3551 $this->setLineStyle(array('width' => $line_width, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => $this->footer_line_color
));
3552 //print document barcode
3553 $barcode = $this->getBarcode();
3554 if (!empty($barcode)) {
3555 $this->Ln($line_width);
3556 $barcode_width = round(($this->w
- $this->original_lMargin
- $this->original_rMargin
) / 3);
3558 'position' => $this->rtl?
'R':'L',
3559 'align' => $this->rtl?
'R':'L',
3562 'cellfitalign' => '',
3565 'fgcolor' => array(0,0,0),
3569 $this->write1DBarcode($barcode, 'C128', '', $cur_y +
$line_width, '', (($this->footer_margin
/ 3) - $line_width), 0.3, $style, '');
3571 $w_page = isset($this->l
['w_page']) ?
$this->l
['w_page'].' ' : '';
3572 if (empty($this->pagegroups
)) {
3573 $pagenumtxt = $w_page.$this->getAliasNumPage().' / '.$this->getAliasNbPages();
3575 $pagenumtxt = $w_page.$this->getPageNumGroupAlias().' / '.$this->getPageGroupAlias();
3577 $this->setY($cur_y);
3579 if ($this->getRTL()) {
3580 $this->setX($this->original_rMargin
);
3581 $this->Cell(0, 0, $pagenumtxt, 'T', 0, 'L');
3583 $this->setX($this->original_lMargin
);
3584 $this->Cell(0, 0, $this->getAliasRightShift().$pagenumtxt, 'T', 0, 'R');
3589 * This method is used to render the page header.
3591 * @since 4.0.012 (2008-07-24)
3593 protected function setHeader() {
3594 if (!$this->print_header
OR ($this->state
!= 2)) {
3597 $this->InHeader
= true;
3598 $this->setGraphicVars($this->default_graphic_vars
);
3599 $temp_thead = $this->thead
;
3600 $temp_theadMargins = $this->theadMargins
;
3601 $lasth = $this->lasth
;
3602 $newline = $this->newline
;
3603 $this->_outSaveGraphicsState();
3604 $this->rMargin
= $this->original_rMargin
;
3605 $this->lMargin
= $this->original_lMargin
;
3606 $this->setCellPadding(0);
3607 //set current position
3609 $this->setXY($this->original_rMargin
, $this->header_margin
);
3611 $this->setXY($this->original_lMargin
, $this->header_margin
);
3613 $this->setFont($this->header_font
[0], $this->header_font
[1], $this->header_font
[2]);
3617 $this->setXY($this->original_rMargin
, $this->tMargin
);
3619 $this->setXY($this->original_lMargin
, $this->tMargin
);
3621 $this->_outRestoreGraphicsState();
3622 $this->lasth
= $lasth;
3623 $this->thead
= $temp_thead;
3624 $this->theadMargins
= $temp_theadMargins;
3625 $this->newline
= $newline;
3626 $this->InHeader
= false;
3630 * This method is used to render the page footer.
3632 * @since 4.0.012 (2008-07-24)
3634 protected function setFooter() {
3635 if ($this->state
!= 2) {
3638 $this->InFooter
= true;
3639 // save current graphic settings
3640 $gvars = $this->getGraphicVars();
3642 $this->footerpos
[$this->page
] = $this->pagelen
[$this->page
];
3644 if ($this->print_footer
) {
3645 $this->setGraphicVars($this->default_graphic_vars
);
3646 $this->current_column
= 0;
3647 $this->num_columns
= 1;
3648 $temp_thead = $this->thead
;
3649 $temp_theadMargins = $this->theadMargins
;
3650 $lasth = $this->lasth
;
3651 $this->_outSaveGraphicsState();
3652 $this->rMargin
= $this->original_rMargin
;
3653 $this->lMargin
= $this->original_lMargin
;
3654 $this->setCellPadding(0);
3655 //set current position
3656 $footer_y = $this->h
- $this->footer_margin
;
3658 $this->setXY($this->original_rMargin
, $footer_y);
3660 $this->setXY($this->original_lMargin
, $footer_y);
3662 $this->setFont($this->footer_font
[0], $this->footer_font
[1], $this->footer_font
[2]);
3666 $this->setXY($this->original_rMargin
, $this->tMargin
);
3668 $this->setXY($this->original_lMargin
, $this->tMargin
);
3670 $this->_outRestoreGraphicsState();
3671 $this->lasth
= $lasth;
3672 $this->thead
= $temp_thead;
3673 $this->theadMargins
= $temp_theadMargins;
3675 // restore graphic settings
3676 $this->setGraphicVars($gvars);
3677 $this->current_column
= $gvars['current_column'];
3678 $this->num_columns
= $gvars['num_columns'];
3679 // calculate footer length
3680 $this->footerlen
[$this->page
] = $this->pagelen
[$this->page
] - $this->footerpos
[$this->page
] +
1;
3681 $this->InFooter
= false;
3685 * Check if we are on the page body (excluding page header and footer).
3686 * @return bool true if we are not in page header nor in page footer, false otherwise.
3688 * @since 5.9.091 (2011-06-15)
3690 protected function inPageBody() {
3691 return (($this->InHeader
=== false) AND ($this->InFooter
=== false));
3695 * This method is used to render the table header on new page (if any).
3697 * @since 4.5.030 (2009-03-25)
3699 protected function setTableHeader() {
3700 if ($this->num_columns
> 1) {
3701 // multi column mode
3704 if (isset($this->theadMargins
['top'])) {
3705 // restore the original top-margin
3706 $this->tMargin
= $this->theadMargins
['top'];
3707 $this->pagedim
[$this->page
]['tm'] = $this->tMargin
;
3708 $this->y
= $this->tMargin
;
3710 if (!TCPDF_STATIC
::empty_string($this->thead
) AND (!$this->inthead
)) {
3712 $prev_lMargin = $this->lMargin
;
3713 $prev_rMargin = $this->rMargin
;
3714 $prev_cell_padding = $this->cell_padding
;
3715 $this->lMargin
= $this->theadMargins
['lmargin'] +
($this->pagedim
[$this->page
]['olm'] - $this->pagedim
[$this->theadMargins
['page']]['olm']);
3716 $this->rMargin
= $this->theadMargins
['rmargin'] +
($this->pagedim
[$this->page
]['orm'] - $this->pagedim
[$this->theadMargins
['page']]['orm']);
3717 $this->cell_padding
= $this->theadMargins
['cell_padding'];
3719 $this->x
= $this->w
- $this->rMargin
;
3721 $this->x
= $this->lMargin
;
3723 // account for special "cell" mode
3724 if ($this->theadMargins
['cell']) {
3726 $this->x
-= $this->cell_padding
['R'];
3728 $this->x +
= $this->cell_padding
['L'];
3731 $gvars = $this->getGraphicVars();
3732 if (!empty($this->theadMargins
['gvars'])) {
3733 // set the correct graphic style
3734 $this->setGraphicVars($this->theadMargins
['gvars']);
3735 $this->rMargin
= $gvars['rMargin'];
3736 $this->lMargin
= $gvars['lMargin'];
3738 // print table header
3739 $this->writeHTML($this->thead
, false, false, false, false, '');
3740 $this->setGraphicVars($gvars);
3741 // set new top margin to skip the table headers
3742 if (!isset($this->theadMargins
['top'])) {
3743 $this->theadMargins
['top'] = $this->tMargin
;
3745 // store end of header position
3746 if (!isset($this->columns
[0]['th'])) {
3747 $this->columns
[0]['th'] = array();
3749 $this->columns
[0]['th']['\''.$this->page
.'\''] = $this->y
;
3750 $this->tMargin
= $this->y
;
3751 $this->pagedim
[$this->page
]['tm'] = $this->tMargin
;
3753 $this->lMargin
= $prev_lMargin;
3754 $this->rMargin
= $prev_rMargin;
3755 $this->cell_padding
= $prev_cell_padding;
3760 * Returns the current page number.
3761 * @return int page number
3764 * @see getAliasNbPages()
3766 public function PageNo() {
3771 * Returns the array of spot colors.
3772 * @return array Spot colors array.
3774 * @since 6.0.038 (2013-09-30)
3776 public function getAllSpotColors() {
3777 return $this->spot_colors
;
3781 * Defines a new spot color.
3782 * It can be expressed in RGB components or gray scale.
3783 * The method can be called before the first page is created and the value is retained from page to page.
3784 * @param string $name Full name of the spot color.
3785 * @param float $c Cyan color for CMYK. Value between 0 and 100.
3786 * @param float $m Magenta color for CMYK. Value between 0 and 100.
3787 * @param float $y Yellow color for CMYK. Value between 0 and 100.
3788 * @param float $k Key (Black) color for CMYK. Value between 0 and 100.
3790 * @since 4.0.024 (2008-09-12)
3791 * @see SetDrawSpotColor(), SetFillSpotColor(), SetTextSpotColor()
3793 public function AddSpotColor($name, $c, $m, $y, $k) {
3794 if (!isset($this->spot_colors
[$name])) {
3795 $i = (1 +
count($this->spot_colors
));
3796 $this->spot_colors
[$name] = array('C' => $c, 'M' => $m, 'Y' => $y, 'K' => $k, 'name' => $name, 'i' => $i);
3801 * Set the spot color for the specified type ('draw', 'fill', 'text').
3802 * @param string $type Type of object affected by this color: ('draw', 'fill', 'text').
3803 * @param string $name Name of the spot color.
3804 * @param float $tint Intensity of the color (from 0 to 100 ; 100 = full intensity by default).
3805 * @return string PDF color command.
3807 * @since 5.9.125 (2011-10-03)
3809 public function setSpotColor($type, $name, $tint=100) {
3810 $spotcolor = TCPDF_COLORS
::getSpotColor($name, $this->spot_colors
);
3811 if ($spotcolor === false) {
3812 $this->Error('Undefined spot color: '.$name.', you must add it using the AddSpotColor() method.');
3814 $tint = (max(0, min(100, $tint)) / 100);
3815 $pdfcolor = sprintf('/CS%d ', $this->spot_colors
[$name]['i']);
3818 $pdfcolor .= sprintf('CS %F SCN', $tint);
3819 $this->DrawColor
= $pdfcolor;
3820 $this->strokecolor
= $spotcolor;
3824 $pdfcolor .= sprintf('cs %F scn', $tint);
3825 $this->FillColor
= $pdfcolor;
3826 $this->bgcolor
= $spotcolor;
3830 $pdfcolor .= sprintf('cs %F scn', $tint);
3831 $this->TextColor
= $pdfcolor;
3832 $this->fgcolor
= $spotcolor;
3836 $this->ColorFlag
= ($this->FillColor
!= $this->TextColor
);
3837 if ($this->state
== 2) {
3838 $this->_out($pdfcolor);
3840 if ($this->inxobj
) {
3841 // we are inside an XObject template
3842 $this->xobjects
[$this->xobjid
]['spot_colors'][$name] = $this->spot_colors
[$name];
3848 * Defines the spot color used for all drawing operations (lines, rectangles and cell borders).
3849 * @param string $name Name of the spot color.
3850 * @param float $tint Intensity of the color (from 0 to 100 ; 100 = full intensity by default).
3852 * @since 4.0.024 (2008-09-12)
3853 * @see AddSpotColor(), SetFillSpotColor(), SetTextSpotColor()
3855 public function setDrawSpotColor($name, $tint=100) {
3856 $this->setSpotColor('draw', $name, $tint);
3860 * Defines the spot color used for all filling operations (filled rectangles and cell backgrounds).
3861 * @param string $name Name of the spot color.
3862 * @param float $tint Intensity of the color (from 0 to 100 ; 100 = full intensity by default).
3864 * @since 4.0.024 (2008-09-12)
3865 * @see AddSpotColor(), SetDrawSpotColor(), SetTextSpotColor()
3867 public function setFillSpotColor($name, $tint=100) {
3868 $this->setSpotColor('fill', $name, $tint);
3872 * Defines the spot color used for text.
3873 * @param string $name Name of the spot color.
3874 * @param int $tint Intensity of the color (from 0 to 100 ; 100 = full intensity by default).
3876 * @since 4.0.024 (2008-09-12)
3877 * @see AddSpotColor(), SetDrawSpotColor(), SetFillSpotColor()
3879 public function setTextSpotColor($name, $tint=100) {
3880 $this->setSpotColor('text', $name, $tint);
3884 * Set the color array for the specified type ('draw', 'fill', 'text').
3885 * It can be expressed in RGB, CMYK or GRAY SCALE components.
3886 * The method can be called before the first page is created and the value is retained from page to page.
3887 * @param string $type Type of object affected by this color: ('draw', 'fill', 'text').
3888 * @param array $color Array of colors (1=gray, 3=RGB, 4=CMYK or 5=spotcolor=CMYK+name values).
3889 * @param boolean $ret If true do not send the PDF command.
3890 * @return string The PDF command or empty string.
3892 * @since 3.1.000 (2008-06-11)
3894 public function setColorArray($type, $color, $ret=false) {
3895 if (is_array($color)) {
3896 $color = array_values($color);
3897 // component: grey, RGB red or CMYK cyan
3898 $c = isset($color[0]) ?
$color[0] : -1;
3899 // component: RGB green or CMYK magenta
3900 $m = isset($color[1]) ?
$color[1] : -1;
3901 // component: RGB blue or CMYK yellow
3902 $y = isset($color[2]) ?
$color[2] : -1;
3903 // component: CMYK black
3904 $k = isset($color[3]) ?
$color[3] : -1;
3906 $name = isset($color[4]) ?
$color[4] : '';
3908 return $this->setColor($type, $c, $m, $y, $k, $ret, $name);
3915 * Defines the color used for all drawing operations (lines, rectangles and cell borders).
3916 * It can be expressed in RGB, CMYK or GRAY SCALE components.
3917 * The method can be called before the first page is created and the value is retained from page to page.
3918 * @param array $color Array of colors (1, 3 or 4 values).
3919 * @param boolean $ret If true do not send the PDF command.
3920 * @return string the PDF command
3922 * @since 3.1.000 (2008-06-11)
3923 * @see SetDrawColor()
3925 public function setDrawColorArray($color, $ret=false) {
3926 return $this->setColorArray('draw', $color, $ret);
3930 * Defines the color used for all filling operations (filled rectangles and cell backgrounds).
3931 * It can be expressed in RGB, CMYK or GRAY SCALE components.
3932 * The method can be called before the first page is created and the value is retained from page to page.
3933 * @param array $color Array of colors (1, 3 or 4 values).
3934 * @param boolean $ret If true do not send the PDF command.
3936 * @since 3.1.000 (2008-6-11)
3937 * @see SetFillColor()
3939 public function setFillColorArray($color, $ret=false) {
3940 return $this->setColorArray('fill', $color, $ret);
3944 * Defines the color used for text. It can be expressed in RGB components or gray scale.
3945 * The method can be called before the first page is created and the value is retained from page to page.
3946 * @param array $color Array of colors (1, 3 or 4 values).
3947 * @param boolean $ret If true do not send the PDF command.
3949 * @since 3.1.000 (2008-6-11)
3950 * @see SetFillColor()
3952 public function setTextColorArray($color, $ret=false) {
3953 return $this->setColorArray('text', $color, $ret);
3957 * Defines the color used by the specified type ('draw', 'fill', 'text').
3958 * @param string $type Type of object affected by this color: ('draw', 'fill', 'text').
3959 * @param float $col1 GRAY level for single color, or Red color for RGB (0-255), or CYAN color for CMYK (0-100).
3960 * @param float $col2 GREEN color for RGB (0-255), or MAGENTA color for CMYK (0-100).
3961 * @param float $col3 BLUE color for RGB (0-255), or YELLOW color for CMYK (0-100).
3962 * @param float $col4 KEY (BLACK) color for CMYK (0-100).
3963 * @param boolean $ret If true do not send the command.
3964 * @param string $name spot color name (if any)
3965 * @return string The PDF command or empty string.
3967 * @since 5.9.125 (2011-10-03)
3969 public function setColor($type, $col1=0, $col2=-1, $col3=-1, $col4=-1, $ret=false, $name='') {
3970 // set default values
3971 if (!is_numeric($col1)) {
3974 if (!is_numeric($col2)) {
3977 if (!is_numeric($col3)) {
3980 if (!is_numeric($col4)) {
3983 // set color by case
3985 if (($col2 == -1) AND ($col3 == -1) AND ($col4 == -1)) {
3987 $col1 = max(0, min(255, $col1));
3988 $intcolor = array('G' => $col1);
3989 $pdfcolor = sprintf('%F ', ($col1 / 255));
3991 } elseif ($col4 == -1) {
3993 $col1 = max(0, min(255, $col1));
3994 $col2 = max(0, min(255, $col2));
3995 $col3 = max(0, min(255, $col3));
3996 $intcolor = array('R' => $col1, 'G' => $col2, 'B' => $col3);
3997 $pdfcolor = sprintf('%F %F %F ', ($col1 / 255), ($col2 / 255), ($col3 / 255));
4000 $col1 = max(0, min(100, $col1));
4001 $col2 = max(0, min(100, $col2));
4002 $col3 = max(0, min(100, $col3));
4003 $col4 = max(0, min(100, $col4));
4006 $intcolor = array('C' => $col1, 'M' => $col2, 'Y' => $col3, 'K' => $col4);
4007 $pdfcolor = sprintf('%F %F %F %F ', ($col1 / 100), ($col2 / 100), ($col3 / 100), ($col4 / 100));
4011 $intcolor = array('C' => $col1, 'M' => $col2, 'Y' => $col3, 'K' => $col4, 'name' => $name);
4012 $this->AddSpotColor($name, $col1, $col2, $col3, $col4);
4013 $pdfcolor = $this->setSpotColor($type, $name, 100);
4018 $pdfcolor .= strtoupper($suffix);
4019 $this->DrawColor
= $pdfcolor;
4020 $this->strokecolor
= $intcolor;
4024 $pdfcolor .= $suffix;
4025 $this->FillColor
= $pdfcolor;
4026 $this->bgcolor
= $intcolor;
4030 $pdfcolor .= $suffix;
4031 $this->TextColor
= $pdfcolor;
4032 $this->fgcolor
= $intcolor;
4036 $this->ColorFlag
= ($this->FillColor
!= $this->TextColor
);
4037 if (($type != 'text') AND ($this->state
== 2) AND $type !== 0) {
4039 $this->_out($pdfcolor);
4047 * 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.
4048 * @param float $col1 GRAY level for single color, or Red color for RGB (0-255), or CYAN color for CMYK (0-100).
4049 * @param float $col2 GREEN color for RGB (0-255), or MAGENTA color for CMYK (0-100).
4050 * @param float $col3 BLUE color for RGB (0-255), or YELLOW color for CMYK (0-100).
4051 * @param float $col4 KEY (BLACK) color for CMYK (0-100).
4052 * @param boolean $ret If true do not send the command.
4053 * @param string $name spot color name (if any)
4054 * @return string the PDF command
4057 * @see SetDrawColorArray(), SetFillColor(), SetTextColor(), Line(), Rect(), Cell(), MultiCell()
4059 public function setDrawColor($col1=0, $col2=-1, $col3=-1, $col4=-1, $ret=false, $name='') {
4060 return $this->setColor('draw', $col1, $col2, $col3, $col4, $ret, $name);
4064 * 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.
4065 * @param float $col1 GRAY level for single color, or Red color for RGB (0-255), or CYAN color for CMYK (0-100).
4066 * @param float $col2 GREEN color for RGB (0-255), or MAGENTA color for CMYK (0-100).
4067 * @param float $col3 BLUE color for RGB (0-255), or YELLOW color for CMYK (0-100).
4068 * @param float $col4 KEY (BLACK) color for CMYK (0-100).
4069 * @param boolean $ret If true do not send the command.
4070 * @param string $name Spot color name (if any).
4071 * @return string The PDF command.
4074 * @see SetFillColorArray(), SetDrawColor(), SetTextColor(), Rect(), Cell(), MultiCell()
4076 public function setFillColor($col1=0, $col2=-1, $col3=-1, $col4=-1, $ret=false, $name='') {
4077 return $this->setColor('fill', $col1, $col2, $col3, $col4, $ret, $name);
4081 * 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.
4082 * @param float $col1 GRAY level for single color, or Red color for RGB (0-255), or CYAN color for CMYK (0-100).
4083 * @param float $col2 GREEN color for RGB (0-255), or MAGENTA color for CMYK (0-100).
4084 * @param float $col3 BLUE color for RGB (0-255), or YELLOW color for CMYK (0-100).
4085 * @param float $col4 KEY (BLACK) color for CMYK (0-100).
4086 * @param boolean $ret If true do not send the command.
4087 * @param string $name Spot color name (if any).
4088 * @return string Empty string.
4091 * @see SetTextColorArray(), SetDrawColor(), SetFillColor(), Text(), Cell(), MultiCell()
4093 public function setTextColor($col1=0, $col2=-1, $col3=-1, $col4=-1, $ret=false, $name='') {
4094 return $this->setColor('text', $col1, $col2, $col3, $col4, $ret, $name);
4098 * Returns the length of a string in user unit. A font must be selected.<br>
4099 * @param string $s The string whose length is to be computed
4100 * @param string $fontname Family font. It can be either a name defined by AddFont() or one of the standard families. It is also possible to pass an empty string, in that case, the current family is retained.
4101 * @param string $fontstyle Font style. Possible values are (case insensitive):<ul><li>empty string: regular</li><li>B: bold</li><li>I: italic</li><li>U: underline</li><li>D: line-through</li><li>O: overline</li></ul> or any combination. The default value is regular.
4102 * @param float $fontsize Font size in points. The default value is the current size.
4103 * @param boolean $getarray if true returns an array of characters widths, if false returns the total length.
4104 * @return float[]|float total string length or array of characted widths
4105 * @author Nicola Asuni
4109 public function GetStringWidth($s, $fontname='', $fontstyle='', $fontsize=0, $getarray=false) {
4110 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);
4114 * Returns the string length of an array of chars in user unit or an array of characters widths. A font must be selected.<br>
4115 * @param array $sa The array of chars whose total length is to be computed
4116 * @param string $fontname Family font. It can be either a name defined by AddFont() or one of the standard families. It is also possible to pass an empty string, in that case, the current family is retained.
4117 * @param string $fontstyle Font style. Possible values are (case insensitive):<ul><li>empty string: regular</li><li>B: bold</li><li>I: italic</li><li>U: underline</li><li>D: line through</li><li>O: overline</li></ul> or any combination. The default value is regular.
4118 * @param float $fontsize Font size in points. The default value is the current size.
4119 * @param boolean $getarray if true returns an array of characters widths, if false returns the total length.
4120 * @return float[]|float total string length or array of characted widths
4121 * @author Nicola Asuni
4123 * @since 2.4.000 (2008-03-06)
4125 public function GetArrStringWidth($sa, $fontname='', $fontstyle='', $fontsize=0, $getarray=false) {
4126 // store current values
4127 if (!TCPDF_STATIC
::empty_string($fontname)) {
4128 $prev_FontFamily = $this->FontFamily
;
4129 $prev_FontStyle = $this->FontStyle
;
4130 $prev_FontSizePt = $this->FontSizePt
;
4131 $this->setFont($fontname, $fontstyle, $fontsize, '', 'default', false);
4133 // convert UTF-8 array to Latin1 if required
4134 if ($this->isunicode
AND (!$this->isUnicodeFont())) {
4135 $sa = TCPDF_FONTS
::UTF8ArrToLatin1Arr($sa);
4137 $w = 0; // total width
4138 $wa = array(); // array of characters widths
4139 foreach ($sa as $ck => $char) {
4141 $cw = $this->GetCharWidth($char, isset($sa[($ck +
1)]));
4145 // restore previous values
4146 if (!TCPDF_STATIC
::empty_string($fontname)) {
4147 $this->setFont($prev_FontFamily, $prev_FontStyle, $prev_FontSizePt, '', 'default', false);
4156 * Returns the length of the char in user unit for the current font considering current stretching and spacing (tracking).
4157 * @param int $char The char code whose length is to be returned
4158 * @param boolean $notlast If false ignore the font-spacing.
4159 * @return float char width
4160 * @author Nicola Asuni
4162 * @since 2.4.000 (2008-03-06)
4164 public function GetCharWidth($char, $notlast=true) {
4166 $chw = $this->getRawCharWidth($char);
4167 if (($this->font_spacing
< 0) OR (($this->font_spacing
> 0) AND $notlast)) {
4168 // increase/decrease font spacing
4169 $chw +
= $this->font_spacing
;
4171 if ($this->font_stretching
!= 100) {
4172 // fixed stretching mode
4173 $chw *= ($this->font_stretching
/ 100);
4179 * Returns the length of the char in user unit for the current font.
4180 * @param int $char The char code whose length is to be returned
4181 * @return float char width
4182 * @author Nicola Asuni
4184 * @since 5.9.000 (2010-09-28)
4186 public function getRawCharWidth($char) {
4188 // SHY character will not be printed
4191 if (isset($this->CurrentFont
['cw'][intval($char)])) {
4192 $w = $this->CurrentFont
['cw'][intval($char)];
4193 } elseif (isset($this->CurrentFont
['dw'])) {
4195 $w = $this->CurrentFont
['dw'];
4196 } elseif (isset($this->CurrentFont
['cw'][32])) {
4198 $w = $this->CurrentFont
['cw'][32];
4202 return $this->getAbsFontMeasure($w);
4206 * Returns the numbero of characters in a string.
4207 * @param string $s The input string.
4208 * @return int number of characters
4210 * @since 2.0.0001 (2008-01-07)
4212 public function GetNumChars($s) {
4213 if ($this->isUnicodeFont()) {
4214 return count(TCPDF_FONTS
::UTF8StringToArray($s, $this->isunicode
, $this->CurrentFont
));
4220 * Fill the list of available fonts ($this->fontlist).
4222 * @since 4.0.013 (2008-07-28)
4224 protected function getFontsList() {
4225 if (($fontsdir = opendir(TCPDF_FONTS
::_getfontpath())) !== false) {
4226 while (($file = readdir($fontsdir)) !== false) {
4227 if (substr($file, -4) == '.php') {
4228 array_push($this->fontlist
, strtolower(basename($file, '.php')));
4231 closedir($fontsdir);
4236 * Imports a TrueType, Type1, core, or CID0 font and makes it available.
4237 * It is necessary to generate a font definition file first (read /fonts/utils/README.TXT).
4238 * 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.
4239 * @param string $family Font family. The name can be chosen arbitrarily. If it is a standard family name, it will override the corresponding font.
4240 * @param string $style Font style. Possible values are (case insensitive):<ul><li>empty string: regular (default)</li><li>B: bold</li><li>I: italic</li><li>BI or IB: bold italic</li></ul>
4241 * @param string $fontfile The font definition file. By default, the name is built from the family and style, in lower case with no spaces.
4242 * @return array|false array containing the font data, or false in case of error.
4243 * @param mixed $subset 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.
4246 * @see SetFont(), setFontSubsetting()
4248 public function AddFont($family, $style='', $fontfile='', $subset='default') {
4249 if ($subset === 'default') {
4250 $subset = $this->font_subsetting
;
4252 if ($this->pdfa_mode
) {
4255 if (TCPDF_STATIC
::empty_string($family)) {
4256 if (!TCPDF_STATIC
::empty_string($this->FontFamily
)) {
4257 $family = $this->FontFamily
;
4259 $this->Error('Empty font family');
4262 // move embedded styles on $style
4263 if (substr($family, -1) == 'I') {
4265 $family = substr($family, 0, -1);
4267 if (substr($family, -1) == 'B') {
4269 $family = substr($family, 0, -1);
4271 // normalize family name
4272 $family = strtolower($family);
4273 if ((!$this->isunicode
) AND ($family == 'arial')) {
4274 $family = 'helvetica';
4276 if (($family == 'symbol') OR ($family == 'zapfdingbats')) {
4279 if ($this->pdfa_mode
AND (isset($this->CoreFonts
[$family]))) {
4280 // all fonts must be embedded
4281 $family = 'pdfa'.$family;
4283 $tempstyle = strtoupper($style === null ?
'' : $style);
4286 if (strpos($tempstyle, 'U') !== false) {
4287 $this->underline
= true;
4289 $this->underline
= false;
4291 // line-through (deleted)
4292 if (strpos($tempstyle, 'D') !== false) {
4293 $this->linethrough
= true;
4295 $this->linethrough
= false;
4298 if (strpos($tempstyle, 'O') !== false) {
4299 $this->overline
= true;
4301 $this->overline
= false;
4304 if (strpos($tempstyle, 'B') !== false) {
4308 if (strpos($tempstyle, 'I') !== false) {
4312 $fontkey = $family.$style;
4313 $font_style = $style.($this->underline ?
'U' : '').($this->linethrough ?
'D' : '').($this->overline ?
'O' : '');
4314 $fontdata = array('fontkey' => $fontkey, 'family' => $family, 'style' => $font_style);
4315 // check if the font has been already added
4316 $fb = $this->getFontBuffer($fontkey);
4317 if ($fb !== false) {
4318 if ($this->inxobj
) {
4319 // we are inside an XObject template
4320 $this->xobjects
[$this->xobjid
]['fonts'][$fontkey] = $fb['i'];
4324 // get specified font directory (if any)
4326 if (!TCPDF_STATIC
::empty_string($fontfile)) {
4327 $fontdir = dirname($fontfile);
4328 if (TCPDF_STATIC
::empty_string($fontdir) OR ($fontdir == '.')) {
4334 // true when the font style variation is missing
4335 $missing_style = false;
4336 // search and include font file
4337 if (TCPDF_STATIC
::empty_string($fontfile) OR (!@TCPDF_STATIC
::file_exists($fontfile))) {
4338 // build a standard filenames for specified font
4339 $tmp_fontfile = str_replace(' ', '', $family).strtolower($style).'.php';
4340 $fontfile = TCPDF_FONTS
::getFontFullPath($tmp_fontfile, $fontdir);
4341 if (TCPDF_STATIC
::empty_string($fontfile)) {
4342 $missing_style = true;
4343 // try to remove the style part
4344 $tmp_fontfile = str_replace(' ', '', $family).'.php';
4345 $fontfile = TCPDF_FONTS
::getFontFullPath($tmp_fontfile, $fontdir);
4348 // include font file
4349 if (!TCPDF_STATIC
::empty_string($fontfile) AND (@TCPDF_STATIC
::file_exists($fontfile))) {
4368 $this->Error('Could not include font definition file: '.$family.'');
4370 // check font parameters
4371 if ((!isset($type)) OR (!isset($cw))) {
4372 $this->Error('The font definition file has a bad format: '.$fontfile.'');
4374 // SET default parameters
4375 if (!isset($file) OR TCPDF_STATIC
::empty_string($file)) {
4378 if (!isset($enc) OR TCPDF_STATIC
::empty_string($enc)) {
4381 if (!isset($cidinfo) OR TCPDF_STATIC
::empty_string($cidinfo)) {
4382 $cidinfo = array('Registry'=>'Adobe', 'Ordering'=>'Identity', 'Supplement'=>0);
4383 $cidinfo['uni2cid'] = array();
4385 if (!isset($ctg) OR TCPDF_STATIC
::empty_string($ctg)) {
4388 if (!isset($desc) OR TCPDF_STATIC
::empty_string($desc)) {
4391 if (!isset($up) OR TCPDF_STATIC
::empty_string($up)) {
4394 if (!isset($ut) OR TCPDF_STATIC
::empty_string($ut)) {
4397 if (!isset($cw) OR TCPDF_STATIC
::empty_string($cw)) {
4400 if (!isset($dw) OR TCPDF_STATIC
::empty_string($dw)) {
4401 // set default width
4402 if (isset($desc['MissingWidth']) AND ($desc['MissingWidth'] > 0)) {
4403 $dw = $desc['MissingWidth'];
4404 } elseif (isset($cw[32])) {
4411 if ($type == 'core') {
4412 $name = $this->CoreFonts
[$fontkey];
4414 } elseif (($type == 'TrueType') OR ($type == 'Type1')) {
4416 } elseif ($type == 'TrueTypeUnicode') {
4417 $enc = 'Identity-H';
4418 } elseif ($type == 'cidfont0') {
4419 if ($this->pdfa_mode
) {
4420 $this->Error('All fonts must be embedded in PDF/A mode!');
4423 $this->Error('Unknow font type: '.$type.'');
4425 // set name if unset
4426 if (!isset($name) OR empty($name)) {
4429 // create artificial font style variations if missing (only works with non-embedded fonts)
4430 if (($type != 'core') AND $missing_style) {
4432 $styles = array('' => '', 'B' => ',Bold', 'I' => ',Italic', 'BI' => ',BoldItalic');
4433 $name .= $styles[$bistyle];
4435 if (strpos($bistyle, 'B') !== false) {
4436 if (isset($desc['StemV'])) {
4437 // from normal to bold
4438 $desc['StemV'] = round($desc['StemV'] * 1.75);
4441 $desc['StemV'] = 123;
4444 // artificial italic
4445 if (strpos($bistyle, 'I') !== false) {
4446 if (isset($desc['ItalicAngle'])) {
4447 $desc['ItalicAngle'] -= 11;
4449 $desc['ItalicAngle'] = -11;
4451 if (isset($desc['Flags'])) {
4452 $desc['Flags'] |
= 64; //bit 7
4454 $desc['Flags'] = 64;
4458 // check if the array of characters bounding boxes is defined
4459 if (!isset($cbbox)) {
4462 // initialize subsetchars
4463 $subsetchars = array_fill(0, 255, true);
4464 $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));
4465 if ($this->inxobj
) {
4466 // we are inside an XObject template
4467 $this->xobjects
[$this->xobjid
]['fonts'][$fontkey] = $this->numfonts
;
4469 if (isset($diff) AND (!empty($diff))) {
4470 //Search existing encodings
4472 $nb = count($this->diffs
);
4473 for ($i=1; $i <= $nb; ++
$i) {
4474 if ($this->diffs
[$i] == $diff) {
4481 $this->diffs
[$d] = $diff;
4483 $this->setFontSubBuffer($fontkey, 'diff', $d);
4485 if (!TCPDF_STATIC
::empty_string($file)) {
4486 if (!isset($this->FontFiles
[$file])) {
4487 if ((strcasecmp($type,'TrueType') == 0) OR (strcasecmp($type, 'TrueTypeUnicode') == 0)) {
4488 $this->FontFiles
[$file] = array('length1' => $originalsize, 'fontdir' => $fontdir, 'subset' => $subset, 'fontkeys' => array($fontkey));
4489 } elseif ($type != 'core') {
4490 $this->FontFiles
[$file] = array('length1' => $size1, 'length2' => $size2, 'fontdir' => $fontdir, 'subset' => $subset, 'fontkeys' => array($fontkey));
4493 // update fontkeys that are sharing this font file
4494 $this->FontFiles
[$file]['subset'] = ($this->FontFiles
[$file]['subset'] AND $subset);
4495 if (!in_array($fontkey, $this->FontFiles
[$file]['fontkeys'])) {
4496 $this->FontFiles
[$file]['fontkeys'][] = $fontkey;
4504 * Sets the font used to print character strings.
4505 * The font can be either a standard one or a font added via the AddFont() method. Standard fonts use Windows encoding cp1252 (Western Europe).
4506 * The method can be called before the first page is created and the font is retained from page to page.
4507 * If you just wish to change the current font size, it is simpler to call SetFontSize().
4508 * 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 />
4509 * @param string $family Family font. It can be either a name defined by AddFont() or one of the standard Type1 families (case insensitive):<ul><li>times (Times-Roman)</li><li>timesb (Times-Bold)</li><li>timesi (Times-Italic)</li><li>timesbi (Times-BoldItalic)</li><li>helvetica (Helvetica)</li><li>helveticab (Helvetica-Bold)</li><li>helveticai (Helvetica-Oblique)</li><li>helveticabi (Helvetica-BoldOblique)</li><li>courier (Courier)</li><li>courierb (Courier-Bold)</li><li>courieri (Courier-Oblique)</li><li>courierbi (Courier-BoldOblique)</li><li>symbol (Symbol)</li><li>zapfdingbats (ZapfDingbats)</li></ul> It is also possible to pass an empty string. In that case, the current family is retained.
4510 * @param string $style Font style. Possible values are (case insensitive):<ul><li>empty string: regular</li><li>B: bold</li><li>I: italic</li><li>U: underline</li><li>D: line 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.
4511 * @param float|null $size Font size in points. The default value is the current size. If no size has been specified since the beginning of the document, the value taken is 12
4512 * @param string $fontfile The font definition file. By default, the name is built from the family and style, in lower case with no spaces.
4513 * @param mixed $subset 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.
4514 * @param boolean $out if true output the font size command, otherwise only set the font properties.
4515 * @author Nicola Asuni
4518 * @see AddFont(), SetFontSize()
4520 public function setFont($family, $style='', $size=null, $fontfile='', $subset='default', $out=true) {
4521 //Select a font; size given in points
4522 if ($size === null) {
4523 $size = $this->FontSizePt
;
4528 // try to add font (if not already added)
4529 $fontdata = $this->AddFont($family, $style, $fontfile, $subset);
4530 $this->FontFamily
= $fontdata['family'];
4531 $this->FontStyle
= $fontdata['style'];
4532 if (isset($this->CurrentFont
['fontkey']) AND isset($this->CurrentFont
['subsetchars'])) {
4533 // save subset chars of the previous font
4534 $this->setFontSubBuffer($this->CurrentFont
['fontkey'], 'subsetchars', $this->CurrentFont
['subsetchars']);
4536 $this->CurrentFont
= $this->getFontBuffer($fontdata['fontkey']);
4537 $this->setFontSize($size, $out);
4541 * Defines the size of the current font.
4542 * @param float $size The font size in points.
4543 * @param boolean $out if true output the font size command, otherwise only set the font properties.
4548 public function setFontSize($size, $out=true) {
4549 $size = (float)$size;
4550 // font size in points
4551 $this->FontSizePt
= $size;
4552 // font size in user units
4553 $this->FontSize
= $size / $this->k
;
4554 // calculate some font metrics
4555 if (isset($this->CurrentFont
['desc']['FontBBox'])) {
4556 $bbox = explode(' ', substr($this->CurrentFont
['desc']['FontBBox'], 1, -1));
4557 $font_height = ((intval($bbox[3]) - intval($bbox[1])) * $size / 1000);
4559 $font_height = $size * 1.219;
4561 if (isset($this->CurrentFont
['desc']['Ascent']) AND ($this->CurrentFont
['desc']['Ascent'] > 0)) {
4562 $font_ascent = ($this->CurrentFont
['desc']['Ascent'] * $size / 1000);
4564 if (isset($this->CurrentFont
['desc']['Descent']) AND ($this->CurrentFont
['desc']['Descent'] <= 0)) {
4565 $font_descent = (- $this->CurrentFont
['desc']['Descent'] * $size / 1000);
4567 if (!isset($font_ascent) AND !isset($font_descent)) {
4569 $font_ascent = 0.76 * $font_height;
4570 $font_descent = $font_height - $font_ascent;
4571 } elseif (!isset($font_descent)) {
4572 $font_descent = $font_height - $font_ascent;
4573 } elseif (!isset($font_ascent)) {
4574 $font_ascent = $font_height - $font_descent;
4576 $this->FontAscent
= ($font_ascent / $this->k
);
4577 $this->FontDescent
= ($font_descent / $this->k
);
4578 if ($out AND ($this->page
> 0) AND (isset($this->CurrentFont
['i'])) AND ($this->state
== 2)) {
4579 $this->_out(sprintf('BT /F%d %F Tf ET', $this->CurrentFont
['i'], $this->FontSizePt
));
4584 * Returns the bounding box of the current font in user units.
4587 * @since 5.9.152 (2012-03-23)
4589 public function getFontBBox() {
4591 if (isset($this->CurrentFont
['desc']['FontBBox'])) {
4592 $tmpbbox = explode(' ', substr($this->CurrentFont
['desc']['FontBBox'], 1, -1));
4593 $fbbox = array_map(array($this,'getAbsFontMeasure'), $tmpbbox);
4596 if (isset($this->CurrentFont
['desc']['MaxWidth'])) {
4597 $maxw = $this->getAbsFontMeasure(intval($this->CurrentFont
['desc']['MaxWidth']));
4600 if (isset($this->CurrentFont
['desc']['MissingWidth'])) {
4601 $maxw = max($maxw, $this->CurrentFont
['desc']['MissingWidth']);
4603 if (isset($this->CurrentFont
['desc']['AvgWidth'])) {
4604 $maxw = max($maxw, $this->CurrentFont
['desc']['AvgWidth']);
4606 if (isset($this->CurrentFont
['dw'])) {
4607 $maxw = max($maxw, $this->CurrentFont
['dw']);
4609 foreach ($this->CurrentFont
['cw'] as $char => $w) {
4610 $maxw = max($maxw, $w);
4615 $maxw = $this->getAbsFontMeasure($maxw);
4617 $fbbox = array(0, (0 - $this->FontDescent
), $maxw, $this->FontAscent
);
4623 * Convert a relative font measure into absolute value.
4624 * @param int $s Font measure.
4625 * @return float Absolute measure.
4626 * @since 5.9.186 (2012-09-13)
4628 public function getAbsFontMeasure($s) {
4629 return ($s * $this->FontSize
/ 1000);
4633 * Returns the glyph bounding box of the specified character in the current font in user units.
4634 * @param int $char Input character code.
4635 * @return false|array array(xMin, yMin, xMax, yMax) or FALSE if not defined.
4636 * @since 5.9.186 (2012-09-13)
4638 public function getCharBBox($char) {
4640 if (isset($this->CurrentFont
['cw'][$c])) {
4641 // glyph is defined ... use zero width & height for glyphs without outlines
4642 $result = array(0,0,0,0);
4643 if (isset($this->CurrentFont
['cbbox'][$c])) {
4644 $result = $this->CurrentFont
['cbbox'][$c];
4646 return array_map(array($this,'getAbsFontMeasure'), $result);
4652 * Return the font descent value
4653 * @param string $font font name
4654 * @param string $style font style
4655 * @param float $size The size (in points)
4656 * @return int font descent
4658 * @author Nicola Asuni
4659 * @since 4.9.003 (2010-03-30)
4661 public function getFontDescent($font, $style='', $size=0) {
4662 $fontdata = $this->AddFont($font, $style);
4663 $fontinfo = $this->getFontBuffer($fontdata['fontkey']);
4664 if (isset($fontinfo['desc']['Descent']) AND ($fontinfo['desc']['Descent'] <= 0)) {
4665 $descent = (- $fontinfo['desc']['Descent'] * $size / 1000);
4667 $descent = (1.219 * 0.24 * $size);
4669 return ($descent / $this->k
);
4673 * Return the font ascent value.
4674 * @param string $font font name
4675 * @param string $style font style
4676 * @param float $size The size (in points)
4677 * @return int font ascent
4679 * @author Nicola Asuni
4680 * @since 4.9.003 (2010-03-30)
4682 public function getFontAscent($font, $style='', $size=0) {
4683 $fontdata = $this->AddFont($font, $style);
4684 $fontinfo = $this->getFontBuffer($fontdata['fontkey']);
4685 if (isset($fontinfo['desc']['Ascent']) AND ($fontinfo['desc']['Ascent'] > 0)) {
4686 $ascent = ($fontinfo['desc']['Ascent'] * $size / 1000);
4688 $ascent = 1.219 * 0.76 * $size;
4690 return ($ascent / $this->k
);
4694 * Return true in the character is present in the specified font.
4695 * @param mixed $char Character to check (integer value or string)
4696 * @param string $font Font name (family name).
4697 * @param string $style Font style.
4698 * @return bool true if the char is defined, false otherwise.
4700 * @since 5.9.153 (2012-03-28)
4702 public function isCharDefined($char, $font='', $style='') {
4703 if (is_string($char)) {
4704 // get character code
4705 $char = TCPDF_FONTS
::UTF8StringToArray($char, $this->isunicode
, $this->CurrentFont
);
4708 if (TCPDF_STATIC
::empty_string($font)) {
4709 if (TCPDF_STATIC
::empty_string($style)) {
4710 return (isset($this->CurrentFont
['cw'][intval($char)]));
4712 $font = $this->FontFamily
;
4714 $fontdata = $this->AddFont($font, $style);
4715 $fontinfo = $this->getFontBuffer($fontdata['fontkey']);
4716 return (isset($fontinfo['cw'][intval($char)]));
4720 * Replace missing font characters on selected font with specified substitutions.
4721 * @param string $text Text to process.
4722 * @param string $font Font name (family name).
4723 * @param string $style Font style.
4724 * @param array $subs 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.
4725 * @return string Processed text.
4727 * @since 5.9.153 (2012-03-28)
4729 public function replaceMissingChars($text, $font='', $style='', $subs=array()) {
4733 if (TCPDF_STATIC
::empty_string($font)) {
4734 $font = $this->FontFamily
;
4736 $fontdata = $this->AddFont($font, $style);
4737 $fontinfo = $this->getFontBuffer($fontdata['fontkey']);
4738 $uniarr = TCPDF_FONTS
::UTF8StringToArray($text, $this->isunicode
, $this->CurrentFont
);
4739 foreach ($uniarr as $k => $chr) {
4740 if (!isset($fontinfo['cw'][$chr])) {
4741 // this character is missing on the selected font
4742 if (isset($subs[$chr])) {
4743 // we have available substitutions
4744 if (is_array($subs[$chr])) {
4745 foreach($subs[$chr] as $s) {
4746 if (isset($fontinfo['cw'][$s])) {
4751 } elseif (isset($fontinfo['cw'][$subs[$chr]])) {
4752 $uniarr[$k] = $subs[$chr];
4757 return TCPDF_FONTS
::UniArrSubString(TCPDF_FONTS
::UTF8ArrayToUniArray($uniarr, $this->isunicode
));
4761 * Defines the default monospaced font.
4762 * @param string $font Font name.
4766 public function setDefaultMonospacedFont($font) {
4767 $this->default_monospaced_font
= $font;
4771 * 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 />
4772 * The identifier can then be passed to Cell(), Write(), Image() or Link(). The destination is defined with SetLink().
4775 * @see Cell(), Write(), Image(), Link(), SetLink()
4777 public function AddLink() {
4778 // create a new internal link
4779 $n = count($this->links
) +
1;
4780 $this->links
[$n] = array('p' => 0, 'y' => 0, 'f' => false);
4785 * Defines the page and position a link points to.
4786 * @param int $link The link identifier returned by AddLink()
4787 * @param float $y Ordinate of target position; -1 indicates the current position. The default value is 0 (top of page)
4788 * @param int|string $page 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.
4793 public function setLink($link, $y=0, $page=-1) {
4795 if (!empty($page) AND (substr($page, 0, 1) == '*')) {
4796 $page = intval(substr($page, 1));
4797 // this page number will not be changed when moving/add/deleting pages
4801 $page = $this->page
;
4806 $this->links
[$link] = array('p' => $page, 'y' => $y, 'f' => $fixed);
4810 * Puts a link on a rectangular area of the page.
4811 * 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.
4812 * @param float $x Abscissa of the upper-left corner of the rectangle
4813 * @param float $y Ordinate of the upper-left corner of the rectangle
4814 * @param float $w Width of the rectangle
4815 * @param float $h Height of the rectangle
4816 * @param mixed $link URL or identifier returned by AddLink()
4817 * @param int $spaces number of spaces on the text to link
4820 * @see AddLink(), Annotation(), Cell(), Write(), Image()
4822 public function Link($x, $y, $w, $h, $link, $spaces=0) {
4823 $this->Annotation($x, $y, $w, $h, $link, array('Subtype'=>'Link'), $spaces);
4827 * Puts a markup annotation on a rectangular area of the page.
4828 * !!!!THE ANNOTATION SUPPORT IS NOT YET FULLY IMPLEMENTED !!!!
4829 * @param float $x Abscissa of the upper-left corner of the rectangle
4830 * @param float $y Ordinate of the upper-left corner of the rectangle
4831 * @param float $w Width of the rectangle
4832 * @param float $h Height of the rectangle
4833 * @param string $text annotation text or alternate content
4834 * @param array $opt array of options (see section 8.4 of PDF reference 1.7).
4835 * @param int $spaces number of spaces on the text to link
4837 * @since 4.0.018 (2008-08-06)
4839 public function Annotation($x, $y, $w, $h, $text, $opt=array('Subtype'=>'Text'), $spaces=0) {
4840 if ($this->inxobj
) {
4841 // store parameters for later use on template
4842 $this->xobjects
[$this->xobjid
]['annotations'][] = array('x' => $x, 'y' => $y, 'w' => $w, 'h' => $h, 'text' => $text, 'opt' => $opt, 'spaces' => $spaces);
4851 // check page for no-write regions and adapt page margins if necessary
4852 list($x, $y) = $this->checkPageRegions($h, $x, $y);
4853 // recalculate coordinates to account for graphic transformations
4854 if (isset($this->transfmatrix
) AND !empty($this->transfmatrix
)) {
4855 for ($i=$this->transfmatrix_key
; $i > 0; --$i) {
4856 $maxid = count($this->transfmatrix
[$i]) - 1;
4857 for ($j=$maxid; $j >= 0; --$j) {
4858 $ctm = $this->transfmatrix
[$i][$j];
4859 if (isset($ctm['a'])) {
4861 $y = ($this->h
- $y) * $this->k
;
4867 $x1 = ($ctm['a'] * $xt) +
($ctm['c'] * $yt) +
$ctm['e'];
4868 $y1 = ($ctm['b'] * $xt) +
($ctm['d'] * $yt) +
$ctm['f'];
4872 $x2 = ($ctm['a'] * $xt) +
($ctm['c'] * $yt) +
$ctm['e'];
4873 $y2 = ($ctm['b'] * $xt) +
($ctm['d'] * $yt) +
$ctm['f'];
4877 $x3 = ($ctm['a'] * $xt) +
($ctm['c'] * $yt) +
$ctm['e'];
4878 $y3 = ($ctm['b'] * $xt) +
($ctm['d'] * $yt) +
$ctm['f'];
4882 $x4 = ($ctm['a'] * $xt) +
($ctm['c'] * $yt) +
$ctm['e'];
4883 $y4 = ($ctm['b'] * $xt) +
($ctm['d'] * $yt) +
$ctm['f'];
4884 // new coordinates (rectangle area)
4885 $x = min($x1, $x2, $x3, $x4);
4886 $y = max($y1, $y2, $y3, $y4);
4887 $w = (max($x1, $x2, $x3, $x4) - $x) / $this->k
;
4888 $h = ($y - min($y1, $y2, $y3, $y4)) / $this->k
;
4890 $y = $this->h
- ($y / $this->k
);
4895 if ($this->page
<= 0) {
4898 $page = $this->page
;
4900 if (!isset($this->PageAnnots
[$page])) {
4901 $this->PageAnnots
[$page] = array();
4903 $this->PageAnnots
[$page][] = array('n' => ++
$this->n
, 'x' => $x, 'y' => $y, 'w' => $w, 'h' => $h, 'txt' => $text, 'opt' => $opt, 'numspaces' => $spaces);
4904 if (!$this->pdfa_mode ||
($this->pdfa_mode
&& $this->pdfa_version
== 3)) {
4905 if ((($opt['Subtype'] == 'FileAttachment') OR ($opt['Subtype'] == 'Sound')) AND (!TCPDF_STATIC
::empty_string($opt['FS']))
4906 AND (@TCPDF_STATIC
::file_exists($opt['FS']) OR TCPDF_STATIC
::isValidURL($opt['FS']))
4907 AND (!isset($this->embeddedfiles
[basename($opt['FS'])]))) {
4908 $this->embeddedfiles
[basename($opt['FS'])] = array('f' => ++
$this->n
, 'n' => ++
$this->n
, 'file' => $opt['FS']);
4911 // Add widgets annotation's icons
4912 if (isset($opt['mk']['i']) AND @TCPDF_STATIC
::file_exists($opt['mk']['i'])) {
4913 $this->Image($opt['mk']['i'], '', '', 10, 10, '', '', '', false, 300, '', false, false, 0, false, true);
4915 if (isset($opt['mk']['ri']) AND @TCPDF_STATIC
::file_exists($opt['mk']['ri'])) {
4916 $this->Image($opt['mk']['ri'], '', '', 0, 0, '', '', '', false, 300, '', false, false, 0, false, true);
4918 if (isset($opt['mk']['ix']) AND @TCPDF_STATIC
::file_exists($opt['mk']['ix'])) {
4919 $this->Image($opt['mk']['ix'], '', '', 0, 0, '', '', '', false, 300, '', false, false, 0, false, true);
4924 * Embedd the attached files.
4925 * @since 4.4.000 (2008-12-07)
4929 protected function _putEmbeddedFiles() {
4930 if ($this->pdfa_mode
&& $this->pdfa_version
!= 3) {
4931 // embedded files are not allowed in PDF/A mode version 1 and 2
4934 reset($this->embeddedfiles
);
4935 foreach ($this->embeddedfiles
as $filename => $filedata) {
4936 $data = $this->getCachedFileContents($filedata['file']);
4937 if ($data !== FALSE) {
4938 $rawsize = strlen($data);
4941 $this->efnames
[$filename] = $filedata['f'].' 0 R';
4942 // embedded file specification object
4943 $out = $this->_getobj($filedata['f'])."\n";
4944 $out .= '<</Type /Filespec /F '.$this->_datastring($filename, $filedata['f']);
4945 $out .= ' /UF '.$this->_datastring($filename, $filedata['f']);
4946 $out .= ' /AFRelationship /Source';
4947 $out .= ' /EF <</F '.$filedata['n'].' 0 R>> >>';
4948 $out .= "\n".'endobj';
4950 // embedded file object
4952 if ($this->compress
) {
4953 $data = gzcompress($data);
4954 $filter = ' /Filter /FlateDecode';
4957 if ($this->pdfa_version
== 3) {
4958 $filter = ' /Subtype /text#2Fxml';
4961 $stream = $this->_getrawstream($data, $filedata['n']);
4962 $out = $this->_getobj($filedata['n'])."\n";
4963 $out .= '<< /Type /EmbeddedFile'.$filter.' /Length '.strlen($stream).' /Params <</Size '.$rawsize.'>> >>';
4964 $out .= ' stream'."\n".$stream."\n".'endstream';
4965 $out .= "\n".'endobj';
4973 * Prints a text cell at the specified position.
4974 * This method allows to place a string precisely on the page.
4975 * @param float $x Abscissa of the cell origin
4976 * @param float $y Ordinate of the cell origin
4977 * @param string $txt String to print
4978 * @param int $fstroke outline size in user units (0 = disable)
4979 * @param boolean $fclip if true activate clipping mode (you must call StartTransform() before this function and StopTransform() to stop the clipping tranformation).
4980 * @param boolean $ffill if true fills the text
4981 * @param mixed $border 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)))
4982 * @param int $ln Indicates where the current position should go after the call. Possible values are:<ul><li>0: to the right (or left for RTL languages)</li><li>1: to the beginning of the next line</li><li>2: below</li></ul>Putting 1 is equivalent to putting 0 and calling Ln() just after. Default value: 0.
4983 * @param string $align Allows to center or align the text. Possible values are:<ul><li>L or empty string: left align (default value)</li><li>C: center</li><li>R: right align</li><li>J: justify</li></ul>
4984 * @param boolean $fill Indicates if the cell background must be painted (true) or transparent (false).
4985 * @param mixed $link URL or identifier returned by AddLink().
4986 * @param int $stretch 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.
4987 * @param boolean $ignore_min_height if true ignore automatic minimum height value.
4988 * @param string $calign 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>
4989 * @param string $valign text vertical alignment inside the cell. Possible values are:<ul><li>T : top</li><li>C : center</li><li>B : bottom</li></ul>
4990 * @param boolean $rtloff if true uses the page top-left corner as origin of axis for $x and $y initial position.
4993 * @see Cell(), Write(), MultiCell(), WriteHTML(), WriteHTMLCell()
4995 public function Text($x, $y, $txt, $fstroke=0, $fclip=false, $ffill=true, $border=0, $ln=0, $align='', $fill=false, $link='', $stretch=0, $ignore_min_height=false, $calign='T', $valign='M', $rtloff=false) {
4996 $textrendermode = $this->textrendermode
;
4997 $textstrokewidth = $this->textstrokewidth
;
4998 $this->setTextRenderingMode($fstroke, $ffill, $fclip);
4999 $this->setXY($x, $y, $rtloff);
5000 $this->Cell(0, 0, $txt, $border, $ln, $align, $fill, $link, $stretch, $ignore_min_height, $calign, $valign);
5001 // restore previous rendering mode
5002 $this->textrendermode
= $textrendermode;
5003 $this->textstrokewidth
= $textstrokewidth;
5007 * Whenever a page break condition is met, the method is called, and the break is issued or not depending on the returned value.
5008 * The default implementation returns a value according to the mode selected by SetAutoPageBreak().<br />
5009 * This method is called automatically and should not be called directly by the application.
5013 * @see SetAutoPageBreak()
5015 public function AcceptPageBreak() {
5016 if ($this->num_columns
> 1) {
5017 // multi column mode
5018 if ($this->current_column
< ($this->num_columns
- 1)) {
5019 // go to next column
5020 $this->selectColumn($this->current_column +
1);
5021 } elseif ($this->AutoPageBreak
) {
5025 $this->selectColumn(0);
5027 // avoid page breaking from checkPageBreak()
5030 return $this->AutoPageBreak
;
5034 * Add page if needed.
5035 * @param float $h Cell height. Default value: 0.
5036 * @param float|null $y starting y position, leave empty for current position.
5037 * @param bool $addpage if true add a page, otherwise only return the true/false state
5038 * @return bool true in case of page break, false otherwise.
5039 * @since 3.2.000 (2008-07-01)
5042 protected function checkPageBreak($h=0, $y=null, $addpage=true) {
5043 if (TCPDF_STATIC
::empty_string($y)) {
5046 $current_page = $this->page
;
5047 if ((($y +
$h) > $this->PageBreakTrigger
) AND ($this->inPageBody()) AND ($this->AcceptPageBreak())) {
5049 //Automatic page break
5051 $this->AddPage($this->CurOrientation
);
5052 $this->y
= $this->tMargin
;
5053 $oldpage = $this->page
- 1;
5055 if ($this->pagedim
[$this->page
]['orm'] != $this->pagedim
[$oldpage]['orm']) {
5056 $this->x
= $x - ($this->pagedim
[$this->page
]['orm'] - $this->pagedim
[$oldpage]['orm']);
5061 if ($this->pagedim
[$this->page
]['olm'] != $this->pagedim
[$oldpage]['olm']) {
5062 $this->x
= $x +
($this->pagedim
[$this->page
]['olm'] - $this->pagedim
[$oldpage]['olm']);
5070 if ($current_page != $this->page
) {
5071 // account for columns mode
5078 * 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 />
5079 * If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting.
5080 * @param float $w Cell width. If 0, the cell extends up to the right margin.
5081 * @param float $h Cell height. Default value: 0.
5082 * @param string $txt String to print. Default value: empty string.
5083 * @param mixed $border 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)))
5084 * @param int $ln Indicates where the current position should go after the call. Possible values are:<ul><li>0: to the right (or left for RTL languages)</li><li>1: to the beginning of the next line</li><li>2: below</li></ul> Putting 1 is equivalent to putting 0 and calling Ln() just after. Default value: 0.
5085 * @param string $align Allows to center or align the text. Possible values are:<ul><li>L or empty string: left align (default value)</li><li>C: center</li><li>R: right align</li><li>J: justify</li></ul>
5086 * @param boolean $fill Indicates if the cell background must be painted (true) or transparent (false).
5087 * @param mixed $link URL or identifier returned by AddLink().
5088 * @param int $stretch 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.
5089 * @param boolean $ignore_min_height if true ignore automatic minimum height value.
5090 * @param string $calign 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>
5091 * @param string $valign text vertical alignment inside the cell. Possible values are:<ul><li>T : top</li><li>C : center</li><li>B : bottom</li></ul>
5094 * @see SetFont(), SetDrawColor(), SetFillColor(), SetTextColor(), SetLineWidth(), AddLink(), Ln(), MultiCell(), Write(), SetAutoPageBreak()
5096 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') {
5097 $prev_cell_margin = $this->cell_margin
;
5098 $prev_cell_padding = $this->cell_padding
;
5099 $this->adjustCellPadding($border);
5100 if (!$ignore_min_height) {
5101 $min_cell_height = $this->getCellHeight($this->FontSize
);
5102 if ($h < $min_cell_height) {
5103 $h = $min_cell_height;
5106 $this->checkPageBreak($h +
$this->cell_margin
['T'] +
$this->cell_margin
['B']);
5107 // apply text shadow if enabled
5108 if ($this->txtshadow
['enabled']) {
5112 $bc = $this->bgcolor
;
5113 $fc = $this->fgcolor
;
5114 $sc = $this->strokecolor
;
5115 $alpha = $this->alpha
;
5117 $this->x +
= $this->txtshadow
['depth_w'];
5118 $this->y +
= $this->txtshadow
['depth_h'];
5119 $this->setFillColorArray($this->txtshadow
['color']);
5120 $this->setTextColorArray($this->txtshadow
['color']);
5121 $this->setDrawColorArray($this->txtshadow
['color']);
5122 if ($this->txtshadow
['opacity'] != $alpha['CA']) {
5123 $this->setAlpha($this->txtshadow
['opacity'], $this->txtshadow
['blend_mode']);
5125 if ($this->state
== 2) {
5126 $this->_out($this->getCellCode($w, $h, $txt, $border, $ln, $align, $fill, $link, $stretch, true, $calign, $valign));
5131 $this->setFillColorArray($bc);
5132 $this->setTextColorArray($fc);
5133 $this->setDrawColorArray($sc);
5134 if ($this->txtshadow
['opacity'] != $alpha['CA']) {
5135 $this->setAlpha($alpha['CA'], $alpha['BM'], $alpha['ca'], $alpha['AIS']);
5138 if ($this->state
== 2) {
5139 $this->_out($this->getCellCode($w, $h, $txt, $border, $ln, $align, $fill, $link, $stretch, true, $calign, $valign));
5141 $this->cell_padding
= $prev_cell_padding;
5142 $this->cell_margin
= $prev_cell_margin;
5146 * 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 />
5147 * If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting.
5148 * @param float $w Cell width. If 0, the cell extends up to the right margin.
5149 * @param float $h Cell height. Default value: 0.
5150 * @param string $txt String to print. Default value: empty string.
5151 * @param mixed $border 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)))
5152 * @param int $ln Indicates where the current position should go after the call. Possible values are:<ul><li>0: to the right (or left for RTL languages)</li><li>1: to the beginning of the next line</li><li>2: below</li></ul>Putting 1 is equivalent to putting 0 and calling Ln() just after. Default value: 0.
5153 * @param string $align Allows to center or align the text. Possible values are:<ul><li>L or empty string: left align (default value)</li><li>C: center</li><li>R: right align</li><li>J: justify</li></ul>
5154 * @param boolean $fill Indicates if the cell background must be painted (true) or transparent (false).
5155 * @param mixed $link URL or identifier returned by AddLink().
5156 * @param int $stretch 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.
5157 * @param boolean $ignore_min_height if true ignore automatic minimum height value.
5158 * @param string $calign 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>
5159 * @param string $valign text vertical alignment inside the cell. Possible values are:<ul><li>T : top</li><li>M : middle</li><li>B : bottom</li></ul>
5160 * @return string containing cell code
5165 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') {
5166 // replace 'NO-BREAK SPACE' (U+00A0) character with a simple space
5167 $txt = is_null($txt) ?
'' : $txt;
5168 $txt = str_replace(TCPDF_FONTS
::unichr(160, $this->isunicode
), ' ', $txt);
5169 $prev_cell_margin = $this->cell_margin
;
5170 $prev_cell_padding = $this->cell_padding
;
5171 $txt = TCPDF_STATIC
::removeSHY($txt, $this->isunicode
);
5172 $rs = ''; //string to be returned
5173 $this->adjustCellPadding($border);
5174 if (!$ignore_min_height) {
5175 $min_cell_height = $this->getCellHeight($this->FontSize
);
5176 if ($h < $min_cell_height) {
5177 $h = $min_cell_height;
5181 // check page for no-write regions and adapt page margins if necessary
5182 list($this->x
, $this->y
) = $this->checkPageRegions($h, $this->x
, $this->y
);
5184 $x = $this->x
- $this->cell_margin
['R'];
5186 $x = $this->x +
$this->cell_margin
['L'];
5188 $y = $this->y +
$this->cell_margin
['T'];
5189 $prev_font_stretching = $this->font_stretching
;
5190 $prev_font_spacing = $this->font_spacing
;
5191 // cell vertical alignment
5198 $y -= $this->cell_padding
['T'];
5203 $y -= ($h - $this->cell_padding
['B'] - $this->FontAscent
- $this->FontDescent
);
5210 $y -= (($h - $this->FontAscent
- $this->FontDescent
) / 2);
5221 $y -= ($this->cell_padding
['T'] +
$this->FontAscent
);
5226 $y -= ($h - $this->cell_padding
['B'] - $this->FontDescent
);
5233 $y -= (($h +
$this->FontAscent
- $this->FontDescent
) / 2);
5244 $y -= ($this->cell_padding
['T'] +
$this->FontAscent +
$this->FontDescent
);
5249 $y -= ($h - $this->cell_padding
['B']);
5256 $y -= (($h +
$this->FontAscent +
$this->FontDescent
) / 2);
5279 // text vertical alignment
5283 $yt = $y +
$this->cell_padding
['T'];
5288 $yt = $y +
$h - $this->cell_padding
['B'] - $this->FontAscent
- $this->FontDescent
;
5295 $yt = $y +
(($h - $this->FontAscent
- $this->FontDescent
) / 2);
5299 $basefonty = $yt +
$this->FontAscent
;
5300 if (TCPDF_STATIC
::empty_string($w) OR ($w <= 0)) {
5302 $w = $x - $this->lMargin
;
5304 $w = $this->w
- $this->rMargin
- $x;
5309 if (is_string($border) AND (strlen($border) == 4)) {
5313 if ($fill OR ($border == 1)) {
5315 $op = ($border == 1) ?
'B' : 'f';
5320 $xk = (($x - $w) * $k);
5324 $s .= sprintf('%F %F %F %F re %s ', $xk, (($this->h
- $y) * $k), ($w * $k), (-$h * $k), $op);
5327 $s .= $this->getCellBorder($x, $y, $w, $h, $border);
5330 if ($this->isunicode
) {
5331 if (($this->CurrentFont
['type'] == 'core') OR ($this->CurrentFont
['type'] == 'TrueType') OR ($this->CurrentFont
['type'] == 'Type1')) {
5332 $txt2 = TCPDF_FONTS
::UTF8ToLatin1($txt2, $this->isunicode
, $this->CurrentFont
);
5334 $unicode = TCPDF_FONTS
::UTF8StringToArray($txt, $this->isunicode
, $this->CurrentFont
); // array of UTF-8 unicode values
5335 $unicode = TCPDF_FONTS
::utf8Bidi($unicode, '', $this->tmprtl
, $this->isunicode
, $this->CurrentFont
);
5336 // replace thai chars (if any)
5337 if (defined('K_THAI_TOPCHARS') AND (K_THAI_TOPCHARS
== true)) {
5339 $numchars = count($unicode);
5340 // po pla, for far, for fan
5341 $longtail = array(0x0e1b, 0x0e1d, 0x0e1f);
5342 // do chada, to patak
5343 $lowtail = array(0x0e0e, 0x0e0f);
5344 // mai hun arkad, sara i, sara ii, sara ue, sara uee
5345 $upvowel = array(0x0e31, 0x0e34, 0x0e35, 0x0e36, 0x0e37);
5346 // mai ek, mai tho, mai tri, mai chattawa, karan
5347 $tonemark = array(0x0e48, 0x0e49, 0x0e4a, 0x0e4b, 0x0e4c);
5348 // sara u, sara uu, pinthu
5349 $lowvowel = array(0x0e38, 0x0e39, 0x0e3a);
5351 for ($i = 0; $i < $numchars; $i++
) {
5352 if (($unicode[$i] >= 0x0e00) && ($unicode[$i] <= 0x0e5b)) {
5353 $ch0 = $unicode[$i];
5354 $ch1 = ($i > 0) ?
$unicode[($i - 1)] : 0;
5355 $ch2 = ($i > 1) ?
$unicode[($i - 2)] : 0;
5356 $chn = ($i < ($numchars - 1)) ?
$unicode[($i +
1)] : 0;
5357 if (in_array($ch0, $tonemark)) {
5358 if ($chn == 0x0e33) {
5360 if (in_array($ch1, $longtail)) {
5361 // tonemark at upper left
5362 $output[] = $this->replaceChar($ch0, (0xf713 +
$ch0 - 0x0e48));
5364 // tonemark at upper right (normal position)
5367 } elseif (in_array($ch1, $longtail) OR (in_array($ch2, $longtail) AND in_array($ch1, $lowvowel))) {
5368 // tonemark at lower left
5369 $output[] = $this->replaceChar($ch0, (0xf705 +
$ch0 - 0x0e48));
5370 } elseif (in_array($ch1, $upvowel)) {
5371 if (in_array($ch2, $longtail)) {
5372 // tonemark at upper left
5373 $output[] = $this->replaceChar($ch0, (0xf713 +
$ch0 - 0x0e48));
5375 // tonemark at upper right (normal position)
5379 // tonemark at lower right
5380 $output[] = $this->replaceChar($ch0, (0xf70a +
$ch0 - 0x0e48));
5382 } elseif (($ch0 == 0x0e33) AND (in_array($ch1, $longtail) OR (in_array($ch2, $longtail) AND in_array($ch1, $tonemark)))) {
5383 // add lower left nikhahit and sara aa
5384 if ($this->isCharDefined(0xf711) AND $this->isCharDefined(0x0e32)) {
5386 $this->CurrentFont
['subsetchars'][0xf711] = true;
5388 $this->CurrentFont
['subsetchars'][0x0e32] = true;
5392 } elseif (in_array($ch1, $longtail)) {
5393 if ($ch0 == 0x0e31) {
5394 // lower left mai hun arkad
5395 $output[] = $this->replaceChar($ch0, 0xf710);
5396 } elseif (in_array($ch0, $upvowel)) {
5398 $output[] = $this->replaceChar($ch0, (0xf701 +
$ch0 - 0x0e34));
5399 } elseif ($ch0 == 0x0e47) {
5400 // lower left mai tai koo
5401 $output[] = $this->replaceChar($ch0, 0xf712);
5406 } elseif (in_array($ch1, $lowtail) AND in_array($ch0, $lowvowel)) {
5408 $output[] = $this->replaceChar($ch0, (0xf718 +
$ch0 - 0x0e38));
5409 } elseif (($ch0 == 0x0e0d) AND in_array($chn, $lowvowel)) {
5410 // yo ying without lower part
5411 $output[] = $this->replaceChar($ch0, 0xf70f);
5412 } elseif (($ch0 == 0x0e10) AND in_array($chn, $lowvowel)) {
5413 // tho santan without lower part
5414 $output[] = $this->replaceChar($ch0, 0xf700);
5419 // non-thai character
5420 $output[] = $unicode[$i];
5424 // update font subsetchars
5425 $this->setFontSubBuffer($this->CurrentFont
['fontkey'], 'subsetchars', $this->CurrentFont
['subsetchars']);
5426 } // end of K_THAI_TOPCHARS
5427 $txt2 = TCPDF_FONTS
::arrUTF8ToUTF16BE($unicode, false);
5430 $txt2 = TCPDF_STATIC
::_escape($txt2);
5431 // get current text width (considering general font stretching and spacing)
5432 $txwidth = $this->GetStringWidth($txt);
5434 // check for stretch mode
5436 // calculate ratio between cell width and text width
5440 $ratio = (($w - $this->cell_padding
['L'] - $this->cell_padding
['R']) / $width);
5442 // check if stretching is required
5443 if (($ratio < 1) OR (($ratio > 1) AND (($stretch %
2) == 0))) {
5444 // the text will be stretched to fit cell width
5446 // set new character spacing
5447 $this->font_spacing +
= ($w - $this->cell_padding
['L'] - $this->cell_padding
['R'] - $width) / (max(($this->GetNumChars($txt) - 1), 1) * ($this->font_stretching
/ 100));
5449 // set new horizontal stretching
5450 $this->font_stretching
*= $ratio;
5452 // recalculate text width (the text fills the entire cell)
5453 $width = $w - $this->cell_padding
['L'] - $this->cell_padding
['R'];
5458 if ($this->font_stretching
!= 100) {
5459 // apply font stretching
5460 $rs .= sprintf('BT %F Tz ET ', $this->font_stretching
);
5462 if ($this->font_spacing
!= 0) {
5463 // increase/decrease font spacing
5464 $rs .= sprintf('BT %F Tc ET ', ($this->font_spacing
* $this->k
));
5466 if ($this->ColorFlag
AND ($this->textrendermode
< 4)) {
5467 $s .= 'q '.$this->TextColor
.' ';
5470 $s .= sprintf('BT %d Tr %F w ET ', $this->textrendermode
, ($this->textstrokewidth
* $this->k
));
5471 // count number of spaces
5472 $ns = substr_count($txt, chr(32));
5475 if (($align == 'J') AND ($ns > 0)) {
5476 if ($this->isUnicodeFont()) {
5477 // get string width without spaces
5478 $width = $this->GetStringWidth(str_replace(' ', '', $txt));
5479 // calculate average space width
5480 $spacewidth = -1000 * ($w - $width - $this->cell_padding
['L'] - $this->cell_padding
['R']) / ($ns?
$ns:1) / ($this->FontSize?
$this->FontSize
:1);
5481 if ($this->font_stretching
!= 100) {
5482 // word spacing is affected by stretching
5483 $spacewidth /= ($this->font_stretching
/ 100);
5485 // set word position to be used with TJ operator
5486 $txt2 = str_replace(chr(0).chr(32), ') '.sprintf('%F', $spacewidth).' (', $txt2);
5487 $unicode_justification = true;
5492 $spacewidth = (($w - $width - $this->cell_padding
['L'] - $this->cell_padding
['R']) / ($ns?
$ns:1)) * $this->k
;
5493 if ($this->font_stretching
!= 100) {
5494 // word spacing (Tw) is affected by stretching
5495 $spacewidth /= ($this->font_stretching
/ 100);
5498 $rs .= sprintf('BT %F Tw ET ', $spacewidth);
5500 $width = $w - $this->cell_padding
['L'] - $this->cell_padding
['R'];
5502 // replace carriage return characters
5503 $txt2 = str_replace("\r", ' ', $txt2);
5506 $dx = ($w - $width) / 2;
5511 $dx = $this->cell_padding
['R'];
5513 $dx = $w - $width - $this->cell_padding
['R'];
5519 $dx = $w - $width - $this->cell_padding
['L'];
5521 $dx = $this->cell_padding
['L'];
5528 $dx = $this->cell_padding
['R'];
5530 $dx = $this->cell_padding
['L'];
5536 $xdx = $x - $dx - $width;
5542 $s .= sprintf('BT %F %F Td [(%s)] TJ ET', $xdk, (($this->h
- $basefonty) * $k), $txt2);
5543 if (isset($uniblock)) { // @phpstan-ignore-line
5544 // print overlapping characters as separate string
5545 $xshift = 0; // horizontal shift
5546 $ty = (($this->h
- $basefonty +
(0.2 * $this->FontSize
)) * $k);
5547 $spw = (($w - $txwidth - $this->cell_padding
['L'] - $this->cell_padding
['R']) / ($ns?
$ns:1));
5548 foreach ($uniblock as $uk => $uniarr) { // @phpstan-ignore-line
5549 if (($uk %
2) == 0) {
5551 if ($spacewidth != 0) {
5552 // justification shift
5553 $xshift +
= (count(array_keys($uniarr, 32)) * $spw);
5555 $xshift +
= $this->GetArrStringWidth($uniarr); // + shift justification
5557 // character to print
5558 $topchr = TCPDF_FONTS
::arrUTF8ToUTF16BE($uniarr, false);
5559 $topchr = TCPDF_STATIC
::_escape($topchr);
5560 $s .= sprintf(' BT %F %F Td [(%s)] TJ ET', ($xdk +
($xshift * $k)), $ty, $topchr);
5564 if ($this->underline
) {
5565 $s .= ' '.$this->_dounderlinew($xdx, $basefonty, $width);
5567 if ($this->linethrough
) {
5568 $s .= ' '.$this->_dolinethroughw($xdx, $basefonty, $width);
5570 if ($this->overline
) {
5571 $s .= ' '.$this->_dooverlinew($xdx, $basefonty, $width);
5573 if ($this->ColorFlag
AND ($this->textrendermode
< 4)) {
5577 $this->Link($xdx, $yt, $width, ($this->FontAscent +
$this->FontDescent
), $link, $ns);
5584 if ($this->font_spacing
!= 0) {
5585 // reset font spacing mode
5586 $rs .= ' BT 0 Tc ET';
5588 if ($this->font_stretching
!= 100) {
5589 // reset font stretching mode
5590 $rs .= ' BT 100 Tz ET';
5593 // reset word spacing
5594 if (!$this->isUnicodeFont() AND ($align == 'J')) {
5595 $rs .= ' BT 0 Tw ET';
5597 // reset stretching and spacing
5598 $this->font_stretching
= $prev_font_stretching;
5599 $this->font_spacing
= $prev_font_spacing;
5602 //Go to the beginning of the next line
5603 $this->y
= $y +
$h +
$this->cell_margin
['B'];
5606 $this->x
= $this->w
- $this->rMargin
;
5608 $this->x
= $this->lMargin
;
5612 // go left or right by case
5614 $this->x
= $x - $w - $this->cell_margin
['L'];
5616 $this->x
= $x +
$w +
$this->cell_margin
['R'];
5619 $gstyles = ''.$this->linestyleWidth
.' '.$this->linestyleCap
.' '.$this->linestyleJoin
.' '.$this->linestyleDash
.' '.$this->DrawColor
.' '.$this->FillColor
."\n";
5621 $this->cell_padding
= $prev_cell_padding;
5622 $this->cell_margin
= $prev_cell_margin;
5627 * Replace a char if is defined on the current font.
5628 * @param int $oldchar Integer code (unicode) of the character to replace.
5629 * @param int $newchar Integer code (unicode) of the new character.
5630 * @return int the replaced char or the old char in case the new char i not defined
5632 * @since 5.9.167 (2012-06-22)
5634 protected function replaceChar($oldchar, $newchar) {
5635 if ($this->isCharDefined($newchar)) {
5636 // add the new char on the subset list
5637 $this->CurrentFont
['subsetchars'][$newchar] = true;
5638 // return the new character
5641 // return the old char
5646 * Returns the code to draw the cell border
5647 * @param float $x X coordinate.
5648 * @param float $y Y coordinate.
5649 * @param float $w Cell width.
5650 * @param float $h Cell height.
5651 * @param string|array|int $brd 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)))
5652 * @return string containing cell border code
5654 * @see SetLineStyle()
5655 * @since 5.7.000 (2010-08-02)
5657 protected function getCellBorder($x, $y, $w, $h, $brd) {
5658 $s = ''; // string to be returned
5663 $brd = array('LRTB' => true);
5665 // calculate coordinates for border
5668 $xeL = ($x - $w) * $k;
5672 $xeR = ($x +
$w) * $k;
5674 $yeL = (($this->h
- ($y +
$h)) * $k);
5675 $yeT = (($this->h
- $y) * $k);
5680 if (is_string($brd)) {
5681 // convert string to array
5682 $slen = strlen($brd);
5684 for ($i = 0; $i < $slen; ++
$i) {
5685 $newbrd[$brd[$i]] = array('cap' => 'square', 'join' => 'miter');
5689 if (isset($brd['mode'])) {
5690 $mode = $brd['mode'];
5691 unset($brd['mode']);
5695 foreach ($brd as $border => $style) {
5696 if (is_array($style) AND !empty($style)) {
5697 // apply border style
5698 $prev_style = $this->linestyleWidth
.' '.$this->linestyleCap
.' '.$this->linestyleJoin
.' '.$this->linestyleDash
.' '.$this->DrawColor
.' ';
5699 $s .= $this->setLineStyle($style, true)."\n";
5703 $off = (($this->LineWidth
/ 2) * $k);
5712 $w +
= $this->LineWidth
;
5713 $h +
= $this->LineWidth
;
5717 $off = ($this->LineWidth
/ 2) * $k;
5726 $w -= $this->LineWidth
;
5727 $h -= $this->LineWidth
;
5743 // draw borders by case
5744 if (strlen($border) == 4) {
5745 $s .= sprintf('%F %F %F %F re S ', $xT, $yT, ($w * $k), (-$h * $k));
5746 } elseif (strlen($border) == 3) {
5747 if (strpos($border,'B') === false) { // LTR
5748 $s .= sprintf('%F %F m ', $xL, $yL);
5749 $s .= sprintf('%F %F l ', $xT, $yT);
5750 $s .= sprintf('%F %F l ', $xR, $yR);
5751 $s .= sprintf('%F %F l ', $xB, $yB);
5753 } elseif (strpos($border,'L') === false) { // TRB
5754 $s .= sprintf('%F %F m ', $xT, $yT);
5755 $s .= sprintf('%F %F l ', $xR, $yR);
5756 $s .= sprintf('%F %F l ', $xB, $yB);
5757 $s .= sprintf('%F %F l ', $xL, $yL);
5759 } elseif (strpos($border,'T') === false) { // RBL
5760 $s .= sprintf('%F %F m ', $xR, $yR);
5761 $s .= sprintf('%F %F l ', $xB, $yB);
5762 $s .= sprintf('%F %F l ', $xL, $yL);
5763 $s .= sprintf('%F %F l ', $xT, $yT);
5765 } elseif (strpos($border,'R') === false) { // BLT
5766 $s .= sprintf('%F %F m ', $xB, $yB);
5767 $s .= sprintf('%F %F l ', $xL, $yL);
5768 $s .= sprintf('%F %F l ', $xT, $yT);
5769 $s .= sprintf('%F %F l ', $xR, $yR);
5772 } elseif (strlen($border) == 2) {
5773 if ((strpos($border,'L') !== false) AND (strpos($border,'T') !== false)) { // LT
5774 $s .= sprintf('%F %F m ', $xL, $yL);
5775 $s .= sprintf('%F %F l ', $xT, $yT);
5776 $s .= sprintf('%F %F l ', $xR, $yR);
5778 } elseif ((strpos($border,'T') !== false) AND (strpos($border,'R') !== false)) { // TR
5779 $s .= sprintf('%F %F m ', $xT, $yT);
5780 $s .= sprintf('%F %F l ', $xR, $yR);
5781 $s .= sprintf('%F %F l ', $xB, $yB);
5783 } elseif ((strpos($border,'R') !== false) AND (strpos($border,'B') !== false)) { // RB
5784 $s .= sprintf('%F %F m ', $xR, $yR);
5785 $s .= sprintf('%F %F l ', $xB, $yB);
5786 $s .= sprintf('%F %F l ', $xL, $yL);
5788 } elseif ((strpos($border,'B') !== false) AND (strpos($border,'L') !== false)) { // BL
5789 $s .= sprintf('%F %F m ', $xB, $yB);
5790 $s .= sprintf('%F %F l ', $xL, $yL);
5791 $s .= sprintf('%F %F l ', $xT, $yT);
5793 } elseif ((strpos($border,'L') !== false) AND (strpos($border,'R') !== false)) { // LR
5794 $s .= sprintf('%F %F m ', $xL, $yL);
5795 $s .= sprintf('%F %F l ', $xT, $yT);
5797 $s .= sprintf('%F %F m ', $xR, $yR);
5798 $s .= sprintf('%F %F l ', $xB, $yB);
5800 } elseif ((strpos($border,'T') !== false) AND (strpos($border,'B') !== false)) { // TB
5801 $s .= sprintf('%F %F m ', $xT, $yT);
5802 $s .= sprintf('%F %F l ', $xR, $yR);
5804 $s .= sprintf('%F %F m ', $xB, $yB);
5805 $s .= sprintf('%F %F l ', $xL, $yL);
5808 } else { // strlen($border) == 1
5809 if (strpos($border,'L') !== false) { // L
5810 $s .= sprintf('%F %F m ', $xL, $yL);
5811 $s .= sprintf('%F %F l ', $xT, $yT);
5813 } elseif (strpos($border,'T') !== false) { // T
5814 $s .= sprintf('%F %F m ', $xT, $yT);
5815 $s .= sprintf('%F %F l ', $xR, $yR);
5817 } elseif (strpos($border,'R') !== false) { // R
5818 $s .= sprintf('%F %F m ', $xR, $yR);
5819 $s .= sprintf('%F %F l ', $xB, $yB);
5821 } elseif (strpos($border,'B') !== false) { // B
5822 $s .= sprintf('%F %F m ', $xB, $yB);
5823 $s .= sprintf('%F %F l ', $xL, $yL);
5827 if (is_array($style) AND !empty($style)) {
5828 // reset border style to previous value
5829 $s .= "\n".$this->linestyleWidth
.' '.$this->linestyleCap
.' '.$this->linestyleJoin
.' '.$this->linestyleDash
.' '.$this->DrawColor
."\n";
5836 * This method allows printing text with line breaks.
5837 * 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 />
5838 * Text can be aligned, centered or justified. The cell block can be framed and the background painted.
5839 * @param float $w Width of cells. If 0, they extend up to the right margin of the page.
5840 * @param float $h Cell minimum height. The cell extends automatically if needed.
5841 * @param string $txt String to print
5842 * @param mixed $border 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)))
5843 * @param string $align Allows to center or align the text. Possible values are:<ul><li>L or empty string: left align</li><li>C: center</li><li>R: right align</li><li>J: justification (default value when $ishtml=false)</li></ul>
5844 * @param boolean $fill Indicates if the cell background must be painted (true) or transparent (false).
5845 * @param int $ln Indicates where the current position should go after the call. Possible values are:<ul><li>0: to the right</li><li>1: to the beginning of the next line [DEFAULT]</li><li>2: below</li></ul>
5846 * @param float|null $x x position in user units
5847 * @param float|null $y y position in user units
5848 * @param boolean $reseth if true reset the last cell height (default true).
5849 * @param int $stretch 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.
5850 * @param boolean $ishtml 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.
5851 * @param boolean $autopadding if true, uses internal padding and automatically adjust it to account for line width.
5852 * @param float $maxh 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.
5853 * @param string $valign 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.
5854 * @param boolean $fitcell 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.
5855 * @return int Return the number of cells or 1 for html mode.
5858 * @see SetFont(), SetDrawColor(), SetFillColor(), SetTextColor(), SetLineWidth(), Cell(), Write(), SetAutoPageBreak()
5860 public function MultiCell($w, $h, $txt, $border=0, $align='J', $fill=false, $ln=1, $x=null, $y=null, $reseth=true, $stretch=0, $ishtml=false, $autopadding=true, $maxh=0, $valign='T', $fitcell=false) {
5861 $prev_cell_margin = $this->cell_margin
;
5862 $prev_cell_padding = $this->cell_padding
;
5863 // adjust internal padding
5864 $this->adjustCellPadding($border);
5865 $mc_padding = $this->cell_padding
;
5866 $mc_margin = $this->cell_margin
;
5867 $this->cell_padding
['T'] = 0;
5868 $this->cell_padding
['B'] = 0;
5869 $this->setCellMargins(0, 0, 0, 0);
5870 if (TCPDF_STATIC
::empty_string($this->lasth
) OR $reseth) {
5872 $this->resetLastH();
5874 if (!TCPDF_STATIC
::empty_string($y)) {
5875 $this->setY($y); // set y in order to convert negative y values to positive ones
5879 if (($h > 0) AND $this->inPageBody() AND (($y +
$h +
$mc_margin['T'] +
$mc_margin['B']) > $this->PageBreakTrigger
)) {
5880 // spit cell in more pages/columns
5881 $newh = ($this->PageBreakTrigger
- $y);
5882 $resth = ($h - $newh); // cell to be printed on the next page/column
5885 // get current page number
5886 $startpage = $this->page
;
5887 // get current column
5888 $startcolumn = $this->current_column
;
5889 if (!TCPDF_STATIC
::empty_string($x)) {
5894 // check page for no-write regions and adapt page margins if necessary
5895 list($x, $y) = $this->checkPageRegions(0, $x, $y);
5897 $oy = $y +
$mc_margin['T'];
5899 $ox = ($this->w
- $x - $mc_margin['R']);
5901 $ox = ($x +
$mc_margin['L']);
5906 if (TCPDF_STATIC
::empty_string($w) OR ($w <= 0)) {
5908 $w = ($this->x
- $this->lMargin
- $mc_margin['L']);
5910 $w = ($this->w
- $this->x
- $this->rMargin
- $mc_margin['R']);
5913 // store original margin values
5914 $lMargin = $this->lMargin
;
5915 $rMargin = $this->rMargin
;
5917 $this->rMargin
= ($this->w
- $this->x
);
5918 $this->lMargin
= ($this->x
- $w);
5920 $this->lMargin
= ($this->x
);
5921 $this->rMargin
= ($this->w
- $this->x
- $w);
5923 $this->clMargin
= $this->lMargin
;
5924 $this->crMargin
= $this->rMargin
;
5927 $this->y +
= $mc_padding['T'];
5929 if ($ishtml) { // ******* Write HTML text
5930 $this->writeHTML($txt, true, false, $reseth, true, $align);
5932 } else { // ******* Write simple text
5933 $prev_FontSizePt = $this->FontSizePt
;
5935 // ajust height values
5936 $tobottom = ($this->h
- $this->y
- $this->bMargin
- $this->cell_padding
['T'] - $this->cell_padding
['B']);
5937 $h = $maxh = max(min($h, $tobottom), min($maxh, $tobottom));
5939 // vertical alignment
5942 $text_height = $this->getStringHeight($w, $txt, $reseth, $autopadding, $mc_padding, $border);
5943 if ($fitcell AND ($text_height > $maxh) AND ($this->FontSizePt
> 1)) {
5944 // try to reduce font size to fit text on cell (use a quick search algorithm)
5946 $fmax = $this->FontSizePt
;
5947 $diff_epsilon = (1 / $this->k
); // one point (min resolution)
5948 $maxit = (2 * min(100, max(10, intval($fmax)))); // max number of iterations
5949 while ($maxit >= 0) {
5950 $fmid = (($fmax +
$fmin) / 2);
5951 $this->setFontSize($fmid, false);
5952 $this->resetLastH();
5953 $text_height = $this->getStringHeight($w, $txt, $reseth, $autopadding, $mc_padding, $border);
5954 $diff = ($maxh - $text_height);
5956 if ($diff <= $diff_epsilon) {
5966 // premature exit, we get the minimum font value to fit the cell
5967 $this->setFontSize($fmin);
5968 $this->resetLastH();
5969 $text_height = $this->getStringHeight($w, $txt, $reseth, $autopadding, $mc_padding, $border);
5971 $this->setFontSize($fmid);
5972 $this->resetLastH();
5975 if ($text_height < $maxh) {
5976 if ($valign == 'M') {
5977 // text vertically centered
5978 $this->y +
= (($maxh - $text_height) / 2);
5979 } elseif ($valign == 'B') {
5980 // text vertically aligned on bottom
5981 $this->y +
= ($maxh - $text_height);
5985 $nl = $this->Write($this->lasth
, $txt, '', 0, $align, true, $stretch, false, true, $maxh, 0, $mc_margin);
5987 // restore font size
5988 $this->setFontSize($prev_FontSizePt);
5992 // add bottom padding
5993 $this->y +
= $mc_padding['B'];
5995 // Get end-of-text Y position
5996 $currentY = $this->y
;
5997 // get latest page number
5998 $endpage = $this->page
;
6000 $skip = ($endpage - $startpage);
6002 while ($tmpresth > 0) {
6004 // add a page (or trig AcceptPageBreak() for multicolumn mode)
6005 $this->checkPageBreak($this->PageBreakTrigger +
1);
6007 if ($this->num_columns
> 1) {
6008 $tmpresth -= ($this->h
- $this->y
- $this->bMargin
);
6010 $tmpresth -= ($this->h
- $this->tMargin
- $this->bMargin
);
6014 $currentY = $this->y
;
6015 $endpage = $this->page
;
6017 // get latest column
6018 $endcolumn = $this->current_column
;
6019 if ($this->num_columns
== 0) {
6020 $this->num_columns
= 1;
6022 // disable page regions check
6023 $check_page_regions = $this->check_page_regions
;
6024 $this->check_page_regions
= false;
6026 $border_start = TCPDF_STATIC
::getBorderMode($border, $position='start', $this->opencell
);
6027 $border_end = TCPDF_STATIC
::getBorderMode($border, $position='end', $this->opencell
);
6028 $border_middle = TCPDF_STATIC
::getBorderMode($border, $position='middle', $this->opencell
);
6029 // design borders around HTML cells.
6030 for ($page = $startpage; $page <= $endpage; ++
$page) { // for each page
6032 $this->setPage($page);
6033 if ($this->num_columns
< 2) {
6034 // single-column mode
6036 $this->y
= $this->tMargin
;
6038 // account for margin changes
6039 if ($page > $startpage) {
6040 if (($this->rtl
) AND ($this->pagedim
[$page]['orm'] != $this->pagedim
[$startpage]['orm'])) {
6041 $this->x
-= ($this->pagedim
[$page]['orm'] - $this->pagedim
[$startpage]['orm']);
6042 } elseif ((!$this->rtl
) AND ($this->pagedim
[$page]['olm'] != $this->pagedim
[$startpage]['olm'])) {
6043 $this->x +
= ($this->pagedim
[$page]['olm'] - $this->pagedim
[$startpage]['olm']);
6046 if ($startpage == $endpage) {
6048 for ($column = $startcolumn; $column <= $endcolumn; ++
$column) { // for each column
6049 if ($column != $this->current_column
) {
6050 $this->selectColumn($column);
6053 $this->x
-= $mc_margin['R'];
6055 $this->x +
= $mc_margin['L'];
6057 if ($startcolumn == $endcolumn) { // single column
6059 $h = max($h, ($currentY - $oy));
6061 } elseif ($column == $startcolumn) { // first column
6062 $cborder = $border_start;
6064 $h = $this->h
- $this->y
- $this->bMargin
;
6065 } elseif ($column == $endcolumn) { // end column
6066 $cborder = $border_end;
6067 $h = $currentY - $this->y
;
6071 } else { // middle column
6072 $cborder = $border_middle;
6073 $h = $this->h
- $this->y
- $this->bMargin
;
6076 $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
6077 } // end for each column
6078 } elseif ($page == $startpage) { // first page
6079 for ($column = $startcolumn; $column < $this->num_columns
; ++
$column) { // for each column
6080 if ($column != $this->current_column
) {
6081 $this->selectColumn($column);
6084 $this->x
-= $mc_margin['R'];
6086 $this->x +
= $mc_margin['L'];
6088 if ($column == $startcolumn) { // first column
6089 $cborder = $border_start;
6091 $h = $this->h
- $this->y
- $this->bMargin
;
6092 } else { // middle column
6093 $cborder = $border_middle;
6094 $h = $this->h
- $this->y
- $this->bMargin
;
6097 $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
6098 } // end for each column
6099 } elseif ($page == $endpage) { // last page
6100 for ($column = 0; $column <= $endcolumn; ++
$column) { // for each column
6101 if ($column != $this->current_column
) {
6102 $this->selectColumn($column);
6105 $this->x
-= $mc_margin['R'];
6107 $this->x +
= $mc_margin['L'];
6109 if ($column == $endcolumn) {
6111 $cborder = $border_end;
6112 $h = $currentY - $this->y
;
6118 $cborder = $border_middle;
6119 $h = $this->h
- $this->y
- $this->bMargin
;
6122 $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
6123 } // end for each column
6124 } else { // middle page
6125 for ($column = 0; $column < $this->num_columns
; ++
$column) { // for each column
6126 $this->selectColumn($column);
6128 $this->x
-= $mc_margin['R'];
6130 $this->x +
= $mc_margin['L'];
6132 $cborder = $border_middle;
6133 $h = $this->h
- $this->y
- $this->bMargin
;
6135 $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
6136 } // end for each column
6138 if ($cborder OR $fill) {
6139 $offsetlen = strlen($ccode);
6140 // draw border and fill
6141 if ($this->inxobj
) {
6142 // we are inside an XObject template
6143 if (end($this->xobjects
[$this->xobjid
]['transfmrk']) !== false) {
6144 $pagemarkkey = key($this->xobjects
[$this->xobjid
]['transfmrk']);
6145 $pagemark = $this->xobjects
[$this->xobjid
]['transfmrk'][$pagemarkkey];
6146 $this->xobjects
[$this->xobjid
]['transfmrk'][$pagemarkkey] +
= $offsetlen;
6148 $pagemark = $this->xobjects
[$this->xobjid
]['intmrk'];
6149 $this->xobjects
[$this->xobjid
]['intmrk'] +
= $offsetlen;
6151 $pagebuff = $this->xobjects
[$this->xobjid
]['outdata'];
6152 $pstart = substr($pagebuff, 0, $pagemark);
6153 $pend = substr($pagebuff, $pagemark);
6154 $this->xobjects
[$this->xobjid
]['outdata'] = $pstart.$ccode.$pend;
6156 if (end($this->transfmrk
[$this->page
]) !== false) {
6157 $pagemarkkey = key($this->transfmrk
[$this->page
]);
6158 $pagemark = $this->transfmrk
[$this->page
][$pagemarkkey];
6159 $this->transfmrk
[$this->page
][$pagemarkkey] +
= $offsetlen;
6160 } elseif ($this->InFooter
) {
6161 $pagemark = $this->footerpos
[$this->page
];
6162 $this->footerpos
[$this->page
] +
= $offsetlen;
6164 $pagemark = $this->intmrk
[$this->page
];
6165 $this->intmrk
[$this->page
] +
= $offsetlen;
6167 $pagebuff = $this->getPageBuffer($this->page
);
6168 $pstart = substr($pagebuff, 0, $pagemark);
6169 $pend = substr($pagebuff, $pagemark);
6170 $this->setPageBuffer($this->page
, $pstart.$ccode.$pend);
6173 } // end for each page
6174 // restore page regions check
6175 $this->check_page_regions
= $check_page_regions;
6176 // Get end-of-cell Y position
6177 $currentY = $this->GetY();
6178 // restore previous values
6179 if ($this->num_columns
> 1) {
6180 $this->selectColumn();
6182 // restore original margins
6183 $this->lMargin
= $lMargin;
6184 $this->rMargin
= $rMargin;
6185 if ($this->page
> $startpage) {
6186 // check for margin variations between pages (i.e. booklet mode)
6187 $dl = ($this->pagedim
[$this->page
]['olm'] - $this->pagedim
[$startpage]['olm']);
6188 $dr = ($this->pagedim
[$this->page
]['orm'] - $this->pagedim
[$startpage]['orm']);
6189 if (($dl != 0) OR ($dr != 0)) {
6190 $this->lMargin +
= $dl;
6191 $this->rMargin +
= $dr;
6196 //Go to the beginning of the next line
6197 $this->setY($currentY +
$mc_margin['B']);
6199 $this->setX($x +
$w +
$mc_margin['L'] +
$mc_margin['R']);
6202 // go left or right by case
6203 $this->setPage($startpage);
6205 $this->setX($x +
$w +
$mc_margin['L'] +
$mc_margin['R']);
6207 $this->setContentMark();
6208 $this->cell_padding
= $prev_cell_padding;
6209 $this->cell_margin
= $prev_cell_margin;
6210 $this->clMargin
= $this->lMargin
;
6211 $this->crMargin
= $this->rMargin
;
6216 * This method return the estimated number of lines for print a simple text string using Multicell() method.
6217 * @param string $txt String for calculating his height
6218 * @param float $w Width of cells. If 0, they extend up to the right margin of the page.
6219 * @param boolean $reseth if true reset the last cell height (default false).
6220 * @param boolean $autopadding if true, uses internal padding and automatically adjust it to account for line width (default true).
6221 * @param array|null $cellpadding Internal cell padding, if empty uses default cell padding.
6222 * @param mixed $border 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)))
6223 * @return float Return the minimal height needed for multicell method for printing the $txt param.
6224 * @author Alexander Escalona Fern\E1ndez, Nicola Asuni
6228 public function getNumLines($txt, $w=0, $reseth=false, $autopadding=true, $cellpadding=null, $border=0) {
6229 if ($txt === NULL) {
6236 // adjust internal padding
6237 $prev_cell_padding = $this->cell_padding
;
6238 $prev_lasth = $this->lasth
;
6239 if (is_array($cellpadding)) {
6240 $this->cell_padding
= $cellpadding;
6242 $this->adjustCellPadding($border);
6243 if (TCPDF_STATIC
::empty_string($w) OR ($w <= 0)) {
6245 $w = $this->x
- $this->lMargin
;
6247 $w = $this->w
- $this->rMargin
- $this->x
;
6250 $wmax = $w - $this->cell_padding
['L'] - $this->cell_padding
['R'];
6253 $this->resetLastH();
6257 $chars = TCPDF_FONTS
::utf8Bidi(TCPDF_FONTS
::UTF8StringToArray($txt, $this->isunicode
, $this->CurrentFont
), $txt, $this->tmprtl
, $this->isunicode
, $this->CurrentFont
);
6258 $charsWidth = $this->GetArrStringWidth($chars, '', '', 0, true);
6259 $length = count($chars);
6260 $lastSeparator = -1;
6261 for ($i = 0; $i < $length; ++
$i) {
6263 $charWidth = $charsWidth[$i];
6266 OR preg_match($this->re_spaces
, TCPDF_FONTS
::unichr($c, $this->isunicode
))
6268 AND ($i > 0) AND ($i < ($length - 1))
6269 AND @preg_match
('/[\p{L}]/'.$this->re_space
['m'], TCPDF_FONTS
::unichr($chars[($i - 1)], $this->isunicode
))
6270 AND @preg_match
('/[\p{L}]/'.$this->re_space
['m'], TCPDF_FONTS
::unichr($chars[($i +
1)], $this->isunicode
))
6274 $lastSeparator = $i;
6276 if ((($sum +
$charWidth) > $wmax) OR ($c == 10)) {
6279 $lastSeparator = -1;
6281 } elseif ($lastSeparator != -1) {
6282 $i = $lastSeparator;
6283 $lastSeparator = -1;
6292 if ($chars[($length - 1)] == 10) {
6295 $this->cell_padding
= $prev_cell_padding;
6296 $this->lasth
= $prev_lasth;
6301 * This method return the estimated height needed for printing a simple text string using the Multicell() method.
6302 * Generally, if you want to know the exact height for a block of content you can use the following alternative technique:
6304 * // store current object
6305 * $pdf->startTransaction();
6306 * // store starting values
6307 * $start_y = $pdf->GetY();
6308 * $start_page = $pdf->getPage();
6309 * // call your printing functions with your parameters
6310 * // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
6311 * $pdf->MultiCell($w=0, $h=0, $txt, $border=1, $align='L', $fill=false, $ln=1, $x=null, $y=null, $reseth=true, $stretch=0, $ishtml=false, $autopadding=true, $maxh=0);
6312 * // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
6314 * $end_y = $pdf->GetY();
6315 * $end_page = $pdf->getPage();
6316 * // calculate height
6318 * if ($end_page == $start_page) {
6319 * $height = $end_y - $start_y;
6321 * for ($page=$start_page; $page <= $end_page; ++$page) {
6322 * $this->setPage($page);
6323 * if ($page == $start_page) {
6325 * $height += $this->h - $start_y - $this->bMargin;
6326 * } elseif ($page == $end_page) {
6328 * $height += $end_y - $this->tMargin;
6330 * $height += $this->h - $this->tMargin - $this->bMargin;
6334 * // restore previous object
6335 * $pdf = $pdf->rollbackTransaction();
6337 * @param float $w Width of cells. If 0, they extend up to the right margin of the page.
6338 * @param string $txt String for calculating his height
6339 * @param boolean $reseth if true reset the last cell height (default false).
6340 * @param boolean $autopadding if true, uses internal padding and automatically adjust it to account for line width (default true).
6341 * @param array|null $cellpadding Internal cell padding, if empty uses default cell padding.
6342 * @param mixed $border 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)))
6343 * @return float Return the minimal height needed for multicell method for printing the $txt param.
6344 * @author Nicola Asuni, Alexander Escalona Fern\E1ndez
6347 public function getStringHeight($w, $txt, $reseth=false, $autopadding=true, $cellpadding=null, $border=0) {
6348 // adjust internal padding
6349 $prev_cell_padding = $this->cell_padding
;
6350 $prev_lasth = $this->lasth
;
6351 if (is_array($cellpadding)) {
6352 $this->cell_padding
= $cellpadding;
6354 $this->adjustCellPadding($border);
6355 $lines = $this->getNumLines($txt, $w, $reseth, $autopadding, $cellpadding, $border);
6356 $height = $this->getCellHeight(($lines * $this->FontSize
), $autopadding);
6357 $this->cell_padding
= $prev_cell_padding;
6358 $this->lasth
= $prev_lasth;
6363 * This method prints text from the current position.<br />
6364 * @param float $h Line height
6365 * @param string $txt String to print
6366 * @param mixed $link URL or identifier returned by AddLink()
6367 * @param boolean $fill Indicates if the cell background must be painted (true) or transparent (false).
6368 * @param string $align Allows to center or align the text. Possible values are:<ul><li>L or empty string: left align (default value)</li><li>C: center</li><li>R: right align</li><li>J: justify</li></ul>
6369 * @param boolean $ln if true set cursor at the bottom of the line, otherwise set cursor at the top of the line.
6370 * @param int $stretch 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.
6371 * @param boolean $firstline if true prints only the first line and return the remaining string.
6372 * @param boolean $firstblock if true the string is the starting of a line.
6373 * @param float $maxh maximum height. It should be >= $h and less then remaining space to the bottom of the page, or 0 for disable this feature.
6374 * @param float $wadj first line width will be reduced by this amount (used in HTML mode).
6375 * @param array|null $margin margin array of the parent container
6376 * @return mixed Return the number of cells or the remaining string if $firstline = true.
6380 public function Write($h, $txt, $link='', $fill=false, $align='', $ln=false, $stretch=0, $firstline=false, $firstblock=false, $maxh=0, $wadj=0, $margin=null) {
6381 // check page for no-write regions and adapt page margins if necessary
6382 list($this->x
, $this->y
) = $this->checkPageRegions($h, $this->x
, $this->y
);
6383 if (strlen($txt) == 0) {
6387 if (!is_array($margin)) {
6388 // set default margins
6389 $margin = $this->cell_margin
;
6391 // remove carriage returns
6392 $s = str_replace("\r", '', $txt);
6393 // check if string contains arabic text
6394 if (preg_match(TCPDF_FONT_DATA
::$uni_RE_PATTERN_ARABIC, $s)) {
6399 // check if string contains RTL text
6400 if ($arabic OR ($this->tmprtl
== 'R') OR preg_match(TCPDF_FONT_DATA
::$uni_RE_PATTERN_RTL, $s)) {
6406 $chrwidth = $this->GetCharWidth(46); // dot character
6407 // get array of unicode values
6408 $chars = TCPDF_FONTS
::UTF8StringToArray($s, $this->isunicode
, $this->CurrentFont
);
6409 // calculate maximum width for a single character on string
6410 $chrw = $this->GetArrStringWidth($chars, '', '', 0, true);
6411 array_walk($chrw, array($this, 'getRawCharWidth'));
6412 $maxchwidth = max($chrw);
6413 // get array of chars
6414 $uchars = TCPDF_FONTS
::UTF8ArrayToUniArray($chars, $this->isunicode
);
6415 // get the number of characters
6416 $nb = count($chars);
6417 // replacement for SHY character (minus symbol)
6418 $shy_replacement = 45;
6419 $shy_replacement_char = TCPDF_FONTS
::unichr($shy_replacement, $this->isunicode
);
6420 // widht for SHY replacement
6421 $shy_replacement_width = $this->GetCharWidth($shy_replacement);
6423 $pw = $w = $this->w
- $this->lMargin
- $this->rMargin
;
6424 // calculate remaining line width ($w)
6426 $w = $this->x
- $this->lMargin
;
6428 $w = $this->w
- $this->rMargin
- $this->x
;
6431 $wmax = ($w - $wadj);
6433 $wmax -= ($this->cell_padding
['L'] +
$this->cell_padding
['R']);
6435 if ((!$firstline) AND (($chrwidth > $wmax) OR ($maxchwidth > $wmax))) {
6436 // the maximum width character do not fit on column
6439 // minimum row height
6440 $row_height = max($h, $this->getCellHeight($this->FontSize
));
6442 $maxy = $this->y +
$maxh - max($row_height, $h);
6443 $start_page = $this->page
;
6444 $i = 0; // character position
6445 $j = 0; // current starting position
6446 $sep = -1; // position of the last blank space
6447 $prevsep = $sep; // previous separator
6448 $shy = false; // true if the last blank is a soft hypen (SHY)
6449 $prevshy = $shy; // previous shy mode
6450 $l = 0; // current string length
6451 $nl = 0; //number of lines
6453 $pc = 0; // previous character
6454 // for each character
6456 if (($maxh > 0) AND ($this->y
> $maxy) ) {
6459 //Get the current character
6461 if ($c == 10) { // 10 = "\n" = new line
6462 //Explicit line break
6463 if ($align == 'J') {
6472 $tmpstr = TCPDF_FONTS
::UniArrSubString($uchars, $j, $i);
6475 $tmparr = array_slice($chars, $j, ($i - $j));
6477 $tmparr = TCPDF_FONTS
::utf8Bidi($tmparr, $tmpstr, $this->tmprtl
, $this->isunicode
, $this->CurrentFont
);
6479 $linew = $this->GetArrStringWidth($tmparr);
6482 $this->endlinex
= $startx - $linew;
6484 $this->endlinex
= $startx +
$linew;
6487 $tmpcellpadding = $this->cell_padding
;
6489 $this->setCellPadding(0);
6492 if ($firstblock AND $this->isRTLTextDir()) {
6493 $tmpstr = $this->stringRightTrim($tmpstr);
6495 // Skip newlines at the beginning of a page or column
6496 if (!empty($tmpstr) OR ($this->y
< ($this->PageBreakTrigger
- $row_height))) {
6497 $this->Cell($w, $h, $tmpstr, 0, 1, $talign, $fill, $link, $stretch);
6501 $this->cell_padding
= $tmpcellpadding;
6502 return (TCPDF_FONTS
::UniArrSubString($uchars, $i));
6510 // account for margin changes
6511 if ((($this->y +
$this->lasth
) > $this->PageBreakTrigger
) AND ($this->inPageBody())) {
6512 if ($this->AcceptPageBreak())
6515 $this->x
-= $margin['R'];
6517 $this->x +
= $margin['L'];
6519 $this->lMargin +
= $margin['L'];
6520 $this->rMargin +
= $margin['R'];
6523 $w = $this->getRemainingWidth();
6524 $wmax = ($w - $this->cell_padding
['L'] - $this->cell_padding
['R']);
6526 // 160 is the non-breaking space.
6527 // 173 is SHY (Soft Hypen).
6528 // \p{Z} or \p{Separator}: any kind of Unicode whitespace or invisible separator.
6529 // \p{Lo} or \p{Other_Letter}: a Unicode letter or ideograph that does not have lowercase and uppercase variants.
6530 // \p{Lo} is needed because Chinese characters are packed next to each other without spaces in between.
6533 OR preg_match($this->re_spaces
, TCPDF_FONTS
::unichr($c, $this->isunicode
))
6535 AND ($i < ($nb - 1))
6536 AND @preg_match
('/[\p{L}]/'.$this->re_space
['m'], TCPDF_FONTS
::unichr($pc, $this->isunicode
))
6537 AND @preg_match
('/[\p{L}]/'.$this->re_space
['m'], TCPDF_FONTS
::unichr($chars[($i +
1)], $this->isunicode
))
6541 // update last blank space position
6544 // check if is a SHY
6545 if (($c == 173) OR ($c == 45)) {
6549 $tmp_shy_replacement_width = 0;
6550 $tmp_shy_replacement_char = '';
6552 $tmp_shy_replacement_width = $shy_replacement_width;
6553 $tmp_shy_replacement_char = $shy_replacement_char;
6559 // update string length
6560 if ($this->isUnicodeFont() AND ($arabic)) {
6561 // with bidirectional algorithm some chars may be changed affecting the line length
6562 // *** very slow ***
6563 $l = $this->GetArrStringWidth(TCPDF_FONTS
::utf8Bidi(array_slice($chars, $j, ($i - $j)), '', $this->tmprtl
, $this->isunicode
, $this->CurrentFont
));
6565 $l +
= $this->GetCharWidth($c, ($i+
1 < $nb));
6567 if (($l > $wmax) OR (($c == 173) AND (($l +
$tmp_shy_replacement_width) >= $wmax))) {
6568 if (($c == 173) AND (($l +
$tmp_shy_replacement_width) > $wmax)) {
6572 // we have reached the end of column
6574 // check if the line was already started
6575 if (($this->rtl
AND ($this->x
<= ($this->w
- $this->rMargin
- $this->cell_padding
['R'] - $margin['R'] - $chrwidth)))
6576 OR ((!$this->rtl
) AND ($this->x
>= ($this->lMargin +
$this->cell_padding
['L'] +
$margin['L'] +
$chrwidth)))) {
6577 // print a void cell and go to next line
6578 $this->Cell($w, $h, '', 0, 1);
6581 return (TCPDF_FONTS
::UniArrSubString($uchars, $j));
6584 // truncate the word because do not fit on column
6585 $tmpstr = TCPDF_FONTS
::UniArrSubString($uchars, $j, $i);
6588 $tmparr = array_slice($chars, $j, ($i - $j));
6590 $tmparr = TCPDF_FONTS
::utf8Bidi($tmparr, $tmpstr, $this->tmprtl
, $this->isunicode
, $this->CurrentFont
);
6592 $linew = $this->GetArrStringWidth($tmparr);
6595 $this->endlinex
= $startx - $linew;
6597 $this->endlinex
= $startx +
$linew;
6600 $tmpcellpadding = $this->cell_padding
;
6602 $this->setCellPadding(0);
6605 if ($firstblock AND $this->isRTLTextDir()) {
6606 $tmpstr = $this->stringRightTrim($tmpstr);
6608 $this->Cell($w, $h, $tmpstr, 0, 1, $align, $fill, $link, $stretch);
6611 $this->cell_padding
= $tmpcellpadding;
6612 return (TCPDF_FONTS
::UniArrSubString($uchars, $i));
6619 if ($this->rtl
AND (!$firstblock) AND ($sep < $i)) {
6624 // check the length of the next string
6625 $strrest = TCPDF_FONTS
::UniArrSubString($uchars, ($sep +
$endspace));
6626 $nextstr = TCPDF_STATIC
::pregSplit('/'.$this->re_space
['p'].'/', $this->re_space
['m'], $this->stringTrim($strrest));
6627 if (isset($nextstr[0]) AND ($this->GetStringWidth($nextstr[0]) > $pw)) {
6628 // truncate the word because do not fit on a full page width
6629 $tmpstr = TCPDF_FONTS
::UniArrSubString($uchars, $j, $i);
6632 $tmparr = array_slice($chars, $j, ($i - $j));
6634 $tmparr = TCPDF_FONTS
::utf8Bidi($tmparr, $tmpstr, $this->tmprtl
, $this->isunicode
, $this->CurrentFont
);
6636 $linew = $this->GetArrStringWidth($tmparr);
6639 $this->endlinex
= ($startx - $linew);
6641 $this->endlinex
= ($startx +
$linew);
6644 $tmpcellpadding = $this->cell_padding
;
6646 $this->setCellPadding(0);
6649 if ($firstblock AND $this->isRTLTextDir()) {
6650 $tmpstr = $this->stringRightTrim($tmpstr);
6652 $this->Cell($w, $h, $tmpstr, 0, 1, $align, $fill, $link, $stretch);
6655 $this->cell_padding
= $tmpcellpadding;
6656 return (TCPDF_FONTS
::UniArrSubString($uchars, $i));
6663 // add hypen (minus symbol) at the end of the line
6664 $shy_width = $tmp_shy_replacement_width;
6666 $shy_char_left = $tmp_shy_replacement_char;
6667 $shy_char_right = '';
6669 $shy_char_left = '';
6670 $shy_char_right = $tmp_shy_replacement_char;
6674 $shy_char_left = '';
6675 $shy_char_right = '';
6677 $tmpstr = TCPDF_FONTS
::UniArrSubString($uchars, $j, ($sep +
$endspace));
6680 $tmparr = array_slice($chars, $j, (($sep +
$endspace) - $j));
6682 $tmparr = TCPDF_FONTS
::utf8Bidi($tmparr, $tmpstr, $this->tmprtl
, $this->isunicode
, $this->CurrentFont
);
6684 $linew = $this->GetArrStringWidth($tmparr);
6687 $this->endlinex
= $startx - $linew - $shy_width;
6689 $this->endlinex
= $startx +
$linew +
$shy_width;
6692 $tmpcellpadding = $this->cell_padding
;
6694 $this->setCellPadding(0);
6698 if ($firstblock AND $this->isRTLTextDir()) {
6699 $tmpstr = $this->stringRightTrim($tmpstr);
6701 $this->Cell($w, $h, $shy_char_left.$tmpstr.$shy_char_right, 0, 1, $align, $fill, $link, $stretch);
6704 if ($chars[$sep] == 45) {
6707 // return the remaining text
6708 $this->cell_padding
= $tmpcellpadding;
6709 return (TCPDF_FONTS
::UniArrSubString($uchars, ($sep +
$endspace)));
6717 // account for margin changes
6718 if ((($this->y +
$this->lasth
) > $this->PageBreakTrigger
) AND ($this->inPageBody())) {
6719 if ($this->AcceptPageBreak())
6722 $this->x
-= $margin['R'];
6724 $this->x +
= $margin['L'];
6726 $this->lMargin +
= $margin['L'];
6727 $this->rMargin +
= $margin['R'];
6730 $w = $this->getRemainingWidth();
6731 $wmax = $w - $this->cell_padding
['L'] - $this->cell_padding
['R'];
6740 // save last character
6743 } // end while i < nb
6744 // print last substring (if any)
6768 $tmpstr = TCPDF_FONTS
::UniArrSubString($uchars, $j, $nb);
6771 $tmparr = array_slice($chars, $j, ($nb - $j));
6773 $tmparr = TCPDF_FONTS
::utf8Bidi($tmparr, $tmpstr, $this->tmprtl
, $this->isunicode
, $this->CurrentFont
);
6775 $linew = $this->GetArrStringWidth($tmparr);
6778 $this->endlinex
= $startx - $linew;
6780 $this->endlinex
= $startx +
$linew;
6783 $tmpcellpadding = $this->cell_padding
;
6785 $this->setCellPadding(0);
6788 if ($firstblock AND $this->isRTLTextDir()) {
6789 $tmpstr = $this->stringRightTrim($tmpstr);
6791 $this->Cell($w, $h, $tmpstr, 0, $ln, $align, $fill, $link, $stretch);
6794 $this->cell_padding
= $tmpcellpadding;
6795 return (TCPDF_FONTS
::UniArrSubString($uchars, $nb));
6806 * Returns the remaining width between the current position and margins.
6807 * @return float Return the remaining width
6810 protected function getRemainingWidth() {
6811 list($this->x
, $this->y
) = $this->checkPageRegions(0, $this->x
, $this->y
);
6813 return ($this->x
- $this->lMargin
);
6815 return ($this->w
- $this->rMargin
- $this->x
);
6820 * Set the block dimensions accounting for page breaks and page/column fitting
6821 * @param float $w width
6822 * @param float $h height
6823 * @param float $x X coordinate
6824 * @param float $y Y coodiante
6825 * @param boolean $fitonpage if true the block is resized to not exceed page dimensions.
6826 * @return array array($w, $h, $x, $y)
6828 * @since 5.5.009 (2010-07-05)
6830 protected function fitBlock($w, $h, $x, $y, $fitonpage=false) {
6832 // set maximum width
6833 $w = ($this->w
- $this->lMargin
- $this->rMargin
);
6839 // set maximum height
6840 $h = ($this->PageBreakTrigger
- $this->tMargin
);
6845 // resize the block to be vertically contained on a single page or single column
6846 if ($fitonpage OR $this->AutoPageBreak
) {
6847 $ratio_wh = ($w / $h);
6848 if ($h > ($this->PageBreakTrigger
- $this->tMargin
)) {
6849 $h = $this->PageBreakTrigger
- $this->tMargin
;
6850 $w = ($h * $ratio_wh);
6852 // resize the block to be horizontally contained on a single page or single column
6854 $maxw = ($this->w
- $this->lMargin
- $this->rMargin
);
6857 $h = ($w / $ratio_wh);
6861 // Check whether we need a new page or new column first as this does not fit
6864 if ($this->checkPageBreak($h, $y) OR ($this->y
< $prev_y)) {
6867 $x +
= ($prev_x - $this->x
);
6869 $x +
= ($this->x
- $prev_x);
6871 $this->newline
= true;
6873 // resize the block to be contained on the remaining available page or column space
6875 $ratio_wh = ($w / $h);
6876 if (($y +
$h) > $this->PageBreakTrigger
) {
6877 $h = $this->PageBreakTrigger
- $y;
6878 $w = ($h * $ratio_wh);
6880 if ((!$this->rtl
) AND (($x +
$w) > ($this->w
- $this->rMargin
))) {
6881 $w = $this->w
- $this->rMargin
- $x;
6882 $h = ($w / $ratio_wh);
6883 } elseif (($this->rtl
) AND (($x - $w) < ($this->lMargin
))) {
6884 $w = $x - $this->lMargin
;
6885 $h = ($w / $ratio_wh);
6888 return array($w, $h, $x, $y);
6892 * Puts an image in the page.
6893 * The upper-left corner must be given.
6894 * The dimensions can be specified in different ways:<ul>
6895 * <li>explicit width and height (expressed in user unit)</li>
6896 * <li>one explicit dimension, the other being calculated automatically in order to keep the original proportions</li>
6897 * <li>no explicit dimension, in which case the image is put at 72 dpi</li></ul>
6898 * 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;
6899 * The format can be specified explicitly or inferred from the file extension.<br />
6900 * It is possible to put a link on the image.<br />
6901 * Remark: if an image is used several times, only one copy will be embedded in the file.<br />
6902 * @param string $file 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').
6903 * @param float|null $x Abscissa of the upper-left corner (LTR) or upper-right corner (RTL).
6904 * @param float|null $y Ordinate of the upper-left corner (LTR) or upper-right corner (RTL).
6905 * @param float $w Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
6906 * @param float $h Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
6907 * @param string $type Image format. Possible values are (case insensitive): JPEG and PNG (whitout GD library) and all images supported by GD: GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM;. If not specified, the type is inferred from the file extension.
6908 * @param mixed $link URL or identifier returned by AddLink().
6909 * @param string $align Indicates the alignment of the pointer next to image insertion relative to image height. The value can be:<ul><li>T: top-right for LTR or top-left for RTL</li><li>M: middle-right for LTR or middle-left for RTL</li><li>B: bottom-right for LTR or bottom-left for RTL</li><li>N: next line</li></ul>
6910 * @param mixed $resize 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).
6911 * @param int $dpi dot-per-inch resolution used on resize
6912 * @param string $palign Allows to center or align the image on the current line. Possible values are:<ul><li>L : left align</li><li>C : center</li><li>R : right align</li><li>'' : empty string : left for LTR or right for RTL</li></ul>
6913 * @param boolean $ismask true if this image is a mask, false otherwise
6914 * @param mixed $imgmask image object returned by this function or false
6915 * @param mixed $border 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)))
6916 * @param mixed $fitbox 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).
6917 * @param boolean $hidden If true do not display the image.
6918 * @param boolean $fitonpage If true the image is resized to not exceed page dimensions.
6919 * @param boolean $alt If true the image will be added as alternative and not directly printed (the ID of the image will be returned).
6920 * @param array $altimgs 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.
6921 * @return mixed|false image information
6925 public function Image($file, $x=null, $y=null, $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()) {
6926 if ($this->state
!= 2) {
6929 if (TCPDF_STATIC
::empty_string($x)) {
6932 if (TCPDF_STATIC
::empty_string($y)) {
6935 // check page for no-write regions and adapt page margins if necessary
6936 list($x, $y) = $this->checkPageRegions($h, $x, $y);
6937 $exurl = ''; // external streams
6940 // Make sure the file variable is not empty or null because accessing $file[0] later
6941 // results in error when running PHP 7.4
6945 // check if we are passing an image as file or string
6946 if ($file[0] === '@') {
6947 // image from string
6948 $imgdata = substr($file, 1);
6949 } else { // image file
6950 if ($file[0] === '*') {
6951 // image as external stream
6952 $file = substr($file, 1);
6955 // check if file exist and it is valid
6956 if (!@$this->fileExists($file)) {
6959 if (false !== $info = $this->getImageBuffer($file)) {
6960 $imsize = array($info['w'], $info['h']);
6961 } elseif (($imsize = @getimagesize
($file)) === FALSE && strpos($file, '__tcpdf_'.$this->file_id
.'_img') === FALSE){
6962 $imgdata = $this->getCachedFileContents($file);
6965 if (!empty($imgdata)) {
6966 // copy image to cache
6967 $original_file = $file;
6968 $file = TCPDF_STATIC
::getObjFilename('img', $this->file_id
);
6969 $fp = TCPDF_STATIC
::fopenLocal($file, 'w');
6971 $this->Error('Unable to write file: '.$file);
6973 fwrite($fp, $imgdata);
6976 $imsize = @getimagesize
($file);
6977 if ($imsize === FALSE) {
6979 $file = $original_file;
6982 if ($imsize === FALSE) {
6983 if (($w > 0) AND ($h > 0)) {
6984 // get measures from specified data
6985 $pw = $this->getHTMLUnitToUnits($w, 0, $this->pdfunit
, true) * $this->imgscale
* $this->k
;
6986 $ph = $this->getHTMLUnitToUnits($h, 0, $this->pdfunit
, true) * $this->imgscale
* $this->k
;
6987 $imsize = array($pw, $ph);
6989 $this->Error('[Image] Unable to get the size of the image: '.$file);
6993 $filehash = md5($file);
6994 // get original image width and height in pixels
6995 list($pixw, $pixh) = $imsize;
6996 // calculate image width and height on document
6997 if (($w <= 0) AND ($h <= 0)) {
6998 // convert image size to document unit
6999 $w = $this->pixelsToUnits($pixw);
7000 $h = $this->pixelsToUnits($pixh);
7001 } elseif ($w <= 0) {
7002 $w = $h * $pixw / $pixh;
7003 } elseif ($h <= 0) {
7004 $h = $w * $pixh / $pixw;
7005 } elseif (($fitbox !== false) AND ($w > 0) AND ($h > 0)) {
7006 if (strlen($fitbox) !== 2) {
7007 // set default alignment
7010 // scale image dimensions proportionally to fit within the ($w, $h) box
7011 if ((($w * $pixh) / ($h * $pixw)) < 1) {
7012 // store current height
7014 // calculate new height
7015 $h = $w * $pixh / $pixw;
7016 // height difference
7017 $hdiff = ($oldh - $h);
7018 // vertical alignment
7019 switch (strtoupper($fitbox[1])) {
7033 // store current width
7035 // calculate new width
7036 $w = $h * $pixw / $pixh;
7038 $wdiff = ($oldw - $w);
7039 // horizontal alignment
7040 switch (strtoupper($fitbox[0])) {
7064 // fit the image on available space
7065 list($w, $h, $x, $y) = $this->fitBlock($w, $h, $x, $y, $fitonpage);
7066 // calculate new minimum dimensions in pixels
7067 $neww = round($w * $this->k
* $dpi / $this->dpi
);
7068 $newh = round($h * $this->k
* $dpi / $this->dpi
);
7069 // check if resize is necessary (resize is used only to reduce the image)
7070 $newsize = ($neww * $newh);
7071 $pixsize = ($pixw * $pixh);
7072 if (intval($resize) == 2) {
7074 } elseif ($newsize >= $pixsize) {
7077 // check if image has been already added on document
7079 if (in_array($file, $this->imagekeys
)) {
7081 // get existing image data
7082 $info = $this->getImageBuffer($file);
7083 if (strpos($file, '__tcpdf_'.$this->file_id
.'_imgmask_') === FALSE) {
7084 // check if the newer image is larger
7085 $oldsize = ($info['w'] * $info['h']);
7086 if ((($oldsize < $newsize) AND ($resize)) OR (($oldsize < $pixsize) AND (!$resize))) {
7090 } elseif (($ismask === false) AND ($imgmask === false) AND (strpos($file, '__tcpdf_'.$this->file_id
.'_imgmask_') === FALSE)) {
7091 // create temp image file (without alpha channel)
7092 $tempfile_plain = K_PATH_CACHE
.'__tcpdf_'.$this->file_id
.'_imgmask_plain_'.$filehash;
7093 // create temp alpha file
7094 $tempfile_alpha = K_PATH_CACHE
.'__tcpdf_'.$this->file_id
.'_imgmask_alpha_'.$filehash;
7095 // check for cached images
7096 if (in_array($tempfile_plain, $this->imagekeys
)) {
7097 // get existing image data
7098 $info = $this->getImageBuffer($tempfile_plain);
7099 // check if the newer image is larger
7100 $oldsize = ($info['w'] * $info['h']);
7101 if ((($oldsize < $newsize) AND ($resize)) OR (($oldsize < $pixsize) AND (!$resize))) {
7106 $imgmask = $this->Image($tempfile_alpha, $x, $y, $w, $h, 'PNG', '', '', $resize, $dpi, '', true, false);
7107 // embed image, masked with previously embedded mask
7108 return $this->Image($tempfile_plain, $x, $y, $w, $h, $type, $link, $align, $resize, $dpi, $palign, false, $imgmask);
7113 //First use of image, get info
7114 $type = strtolower($type);
7116 $type = TCPDF_IMAGES
::getImageFileType($file, $imsize);
7117 } elseif ($type == 'jpg') {
7120 // Specific image handlers (defined on TCPDF_IMAGES CLASS)
7121 $mtd = '_parse'.$type;
7122 // GD image handler function
7123 $gdfunction = 'imagecreatefrom'.$type;
7125 if ((method_exists('TCPDF_IMAGES', $mtd)) AND (!($resize AND (function_exists($gdfunction) OR extension_loaded('imagick'))))) {
7126 // TCPDF image functions
7127 $info = TCPDF_IMAGES
::$mtd($file);
7128 if (($ismask === false) AND ($imgmask === false) AND (strpos($file, '__tcpdf_'.$this->file_id
.'_imgmask_') === FALSE)
7129 AND (($info === 'pngalpha') OR (isset($info['trns']) AND !empty($info['trns'])))) {
7130 return $this->ImagePngAlpha($file, $x, $y, $pixw, $pixh, $w, $h, 'PNG', $link, $align, $resize, $dpi, $palign, $filehash);
7133 if (($info === false) AND function_exists($gdfunction)) {
7136 $img = $gdfunction($file);
7137 if ($img !== false) {
7139 $imgr = imagecreatetruecolor($neww, $newh);
7140 if (($type == 'gif') OR ($type == 'png')) {
7141 $imgr = TCPDF_IMAGES
::setGDImageTransparency($imgr, $img);
7143 imagecopyresampled($imgr, $img, 0, 0, 0, 0, $neww, $newh, $pixw, $pixh);
7146 if (($type == 'gif') OR ($type == 'png')) {
7147 $info = TCPDF_IMAGES
::_toPNG($img, TCPDF_STATIC
::getObjFilename('img', $this->file_id
));
7149 $info = TCPDF_IMAGES
::_toJPEG($img, $this->jpeg_quality
, TCPDF_STATIC
::getObjFilename('img', $this->file_id
));
7152 } catch(Exception
$e) {
7156 if (($info === false) AND extension_loaded('imagick')) {
7158 // ImageMagick library
7159 $img = new Imagick();
7160 if ($type == 'svg') {
7161 if ($file[0] === '@') {
7162 // image from string
7163 $svgimg = substr($file, 1);
7165 // get SVG file content
7166 $svgimg = $this->getCachedFileContents($file);
7168 if ($svgimg !== FALSE) {
7169 // get width and height
7171 if (preg_match('/<svg([^\>]*)>/si', $svgimg, $regs)) {
7174 if (preg_match('/[\s]+width[\s]*=[\s]*"([^"]*)"/si', $svgtag, $tmp)) {
7175 $ow = $this->getHTMLUnitToUnits($tmp[1], 1, $this->svgunit
, false);
7176 $owu = sprintf('%F', ($ow * $dpi / 72)).$this->pdfunit
;
7177 $svgtag = preg_replace('/[\s]+width[\s]*=[\s]*"[^"]*"/si', ' width="'.$owu.'"', $svgtag, 1);
7182 if (preg_match('/[\s]+height[\s]*=[\s]*"([^"]*)"/si', $svgtag, $tmp)) {
7183 $oh = $this->getHTMLUnitToUnits($tmp[1], 1, $this->svgunit
, false);
7184 $ohu = sprintf('%F', ($oh * $dpi / 72)).$this->pdfunit
;
7185 $svgtag = preg_replace('/[\s]+height[\s]*=[\s]*"[^"]*"/si', ' height="'.$ohu.'"', $svgtag, 1);
7190 if (!preg_match('/[\s]+viewBox[\s]*=[\s]*"[\s]*([0-9\.]+)[\s]+([0-9\.]+)[\s]+([0-9\.]+)[\s]+([0-9\.]+)[\s]*"/si', $svgtag, $tmp)) {
7191 $vbw = ($ow * $this->imgscale
* $this->k
);
7192 $vbh = ($oh * $this->imgscale
* $this->k
);
7193 $vbox = sprintf(' viewBox="0 0 %F %F" ', $vbw, $vbh);
7194 $svgtag = $vbox.$svgtag;
7196 $svgimg = preg_replace('/<svg([^\>]*)>/si', '<svg'.$svgtag.'>', $svgimg, 1);
7198 $img->readImageBlob($svgimg);
7201 $img->readImage($file);
7204 $img->resizeImage($neww, $newh, 10, 1, false);
7206 $img->setCompressionQuality($this->jpeg_quality
);
7207 $img->setImageFormat('jpeg');
7208 $tempname = TCPDF_STATIC
::getObjFilename('img', $this->file_id
);
7209 $img->writeImage($tempname);
7210 $info = TCPDF_IMAGES
::_parsejpeg($tempname);
7213 } catch(Exception
$e) {
7217 if ($info === false) {
7218 // unable to process image
7223 $info['cs'] = 'DeviceGray';
7225 if ($imgmask !== false) {
7226 $info['masked'] = $imgmask;
7228 if (!empty($exurl)) {
7229 $info['exurl'] = $exurl;
7231 // array of alternative images
7232 $info['altimgs'] = $altimgs;
7233 // add image to document
7234 $info['i'] = $this->setImageBuffer($file, $info);
7237 $this->img_rb_x
= $x +
$w;
7238 $this->img_rb_y
= $y +
$h;
7241 if ($palign == 'L') {
7242 $ximg = $this->lMargin
;
7243 } elseif ($palign == 'C') {
7244 $ximg = ($this->w +
$this->lMargin
- $this->rMargin
- $w) / 2;
7245 } elseif ($palign == 'R') {
7246 $ximg = $this->w
- $this->rMargin
- $w;
7248 $ximg = $this->rtl ?
$x - $w : $x;
7251 if ($ismask OR $hidden) {
7252 // image is not displayed
7255 $xkimg = $ximg * $this->k
;
7257 // only non-alternative immages will be set
7258 $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']));
7260 if (!empty($border)) {
7268 $this->Cell($w, $h, '', $border, 0, '', 0, '', 0, true);
7273 $this->Link($ximg, $y, $w, $h, $link, 0);
7275 // set pointer to align the next text/objects
7279 $this->x
= $this->img_rb_x
;
7283 $this->y
= $y +
round($h/2);
7284 $this->x
= $this->img_rb_x
;
7288 $this->y
= $this->img_rb_y
;
7289 $this->x
= $this->img_rb_x
;
7293 $this->setY($this->img_rb_y
);
7300 $this->endlinex
= $this->img_rb_x
;
7301 if ($this->inxobj
) {
7302 // we are inside an XObject template
7303 $this->xobjects
[$this->xobjid
]['images'][] = $info['i'];
7309 * Extract info from a PNG image with alpha channel using the Imagick or GD library.
7310 * @param string $file Name of the file containing the image.
7311 * @param float $x Abscissa of the upper-left corner.
7312 * @param float $y Ordinate of the upper-left corner.
7313 * @param float $wpx Original width of the image in pixels.
7314 * @param float $hpx original height of the image in pixels.
7315 * @param float $w Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
7316 * @param float $h Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
7317 * @param string $type Image format. Possible values are (case insensitive): JPEG and PNG (whitout GD library) and all images supported by GD: GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM;. If not specified, the type is inferred from the file extension.
7318 * @param mixed $link URL or identifier returned by AddLink().
7319 * @param string $align Indicates the alignment of the pointer next to image insertion relative to image height. The value can be:<ul><li>T: top-right for LTR or top-left for RTL</li><li>M: middle-right for LTR or middle-left for RTL</li><li>B: bottom-right for LTR or bottom-left for RTL</li><li>N: next line</li></ul>
7320 * @param boolean $resize If true resize (reduce) the image to fit $w and $h (requires GD library).
7321 * @param int $dpi dot-per-inch resolution used on resize
7322 * @param string $palign Allows to center or align the image on the current line. Possible values are:<ul><li>L : left align</li><li>C : center</li><li>R : right align</li><li>'' : empty string : left for LTR or right for RTL</li></ul>
7323 * @param string $filehash File hash used to build unique file names.
7324 * @author Nicola Asuni
7326 * @since 4.3.007 (2008-12-04)
7329 protected function ImagePngAlpha($file, $x, $y, $wpx, $hpx, $w, $h, $type, $link, $align, $resize, $dpi, $palign, $filehash='') {
7330 // create temp images
7331 if (empty($filehash)) {
7332 $filehash = md5($file);
7334 // create temp image file (without alpha channel)
7335 $tempfile_plain = K_PATH_CACHE
.'__tcpdf_'.$this->file_id
.'_imgmask_plain_'.$filehash;
7336 // create temp alpha file
7337 $tempfile_alpha = K_PATH_CACHE
.'__tcpdf_'.$this->file_id
.'_imgmask_alpha_'.$filehash;
7340 // ImageMagick extension
7341 if (($parsed === false) AND extension_loaded('imagick')) {
7343 // ImageMagick library
7344 $img = new Imagick();
7345 $img->readImage($file);
7346 // clone image object
7347 $imga = TCPDF_STATIC
::objclone($img);
7348 // extract alpha channel
7349 if (method_exists($img, 'setImageAlphaChannel') AND defined('Imagick::ALPHACHANNEL_EXTRACT')) {
7350 $img->setImageAlphaChannel(Imagick
::ALPHACHANNEL_EXTRACT
);
7352 $img->separateImageChannel(8); // 8 = (imagick::CHANNEL_ALPHA | imagick::CHANNEL_OPACITY | imagick::CHANNEL_MATTE);
7353 $img->negateImage(true);
7355 $img->setImageFormat('png');
7356 $img->writeImage($tempfile_alpha);
7357 // remove alpha channel
7358 if (method_exists($imga, 'setImageMatte')) {
7359 $imga->setImageMatte(false);
7361 $imga->separateImageChannel(39); // 39 = (imagick::CHANNEL_ALL & ~(imagick::CHANNEL_ALPHA | imagick::CHANNEL_OPACITY | imagick::CHANNEL_MATTE));
7363 $imga->setImageFormat('png');
7364 $imga->writeImage($tempfile_plain);
7366 } catch (Exception
$e) {
7367 // Imagemagick fails, try with GD
7368 $parse_error = 'Imagick library error: '.$e->getMessage();
7372 if (($parsed === false) AND function_exists('imagecreatefrompng')) {
7375 $img = imagecreatefrompng($file);
7376 $imgalpha = imagecreate($wpx, $hpx);
7377 // generate gray scale palette (0 -> 255)
7378 for ($c = 0; $c < 256; ++
$c) {
7379 ImageColorAllocate($imgalpha, $c, $c, $c);
7381 // extract alpha channel
7382 for ($xpx = 0; $xpx < $wpx; ++
$xpx) {
7383 for ($ypx = 0; $ypx < $hpx; ++
$ypx) {
7384 $color = imagecolorat($img, $xpx, $ypx);
7385 // get and correct gamma color
7386 $alpha = $this->getGDgamma($img, $color);
7387 imagesetpixel($imgalpha, (int) $xpx, (int) $ypx, (int) $alpha);
7390 imagepng($imgalpha, $tempfile_alpha);
7391 imagedestroy($imgalpha);
7392 // extract image without alpha channel
7393 $imgplain = imagecreatetruecolor($wpx, $hpx);
7394 imagecopy($imgplain, $img, 0, 0, 0, 0, $wpx, $hpx);
7395 imagepng($imgplain, $tempfile_plain);
7396 imagedestroy($imgplain);
7398 } catch (Exception
$e) {
7400 $parse_error = 'GD library error: '.$e->getMessage();
7403 if ($parsed === false) {
7404 if (empty($parse_error)) {
7405 $this->Error('TCPDF requires the Imagick or GD extension to handle PNG images with alpha channel.');
7407 $this->Error($parse_error);
7411 $imgmask = $this->Image($tempfile_alpha, $x, $y, $w, $h, 'PNG', '', '', $resize, $dpi, '', true, false);
7412 // embed image, masked with previously embedded mask
7413 $this->Image($tempfile_plain, $x, $y, $w, $h, $type, $link, $align, $resize, $dpi, $palign, false, $imgmask);
7417 * Get the GD-corrected PNG gamma value from alpha color
7418 * @param resource $img GD image Resource ID.
7419 * @param int $c alpha color
7421 * @since 4.3.007 (2008-12-04)
7423 protected function getGDgamma($img, $c) {
7424 if (!isset($this->gdgammacache
['#'.$c])) {
7425 $colors = imagecolorsforindex($img, $c);
7426 // GD alpha is only 7 bit (0 -> 127)
7427 $this->gdgammacache
['#'.$c] = (int) (((127 - $colors['alpha']) / 127) * 255);
7429 $this->gdgammacache
['#'.$c] = (int) (pow(($this->gdgammacache
['#'.$c] / 255), 2.2) * 255);
7430 // store the latest values on cache to improve performances
7431 if (count($this->gdgammacache
) > 8) {
7432 // remove one element from the cache array
7433 array_shift($this->gdgammacache
);
7436 return $this->gdgammacache
['#'.$c];
7440 * Performs a line break.
7441 * The current abscissa goes back to the left margin and the ordinate increases by the amount passed in parameter.
7442 * @param float|null $h The height of the break. By default, the value equals the height of the last printed cell.
7443 * @param boolean $cell if true add the current left (or right o for RTL) padding to the X coordinate
7448 public function Ln($h=null, $cell=false) {
7449 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'])) {
7450 // revove vertical space from the top of the column
7455 $cellpadding = $this->cell_padding
['R'];
7457 $cellpadding = $this->cell_padding
['L'];
7463 $this->x
= $this->w
- $this->rMargin
- $cellpadding;
7465 $this->x
= $this->lMargin +
$cellpadding;
7467 if (TCPDF_STATIC
::empty_string($h)) {
7471 $this->newline
= true;
7475 * Returns the relative X value of current position.
7476 * The value is relative to the left border for LTR languages and to the right border for RTL languages.
7480 * @see SetX(), GetY(), SetY()
7482 public function GetX() {
7485 return ($this->w
- $this->x
);
7492 * Returns the absolute X value of current position.
7496 * @see SetX(), GetY(), SetY()
7498 public function GetAbsX() {
7503 * Returns the ordinate of the current position.
7507 * @see SetY(), GetX(), SetX()
7509 public function GetY() {
7514 * Defines the abscissa of the current position.
7515 * If the passed value is negative, it is relative to the right of the page (or left if language is RTL).
7516 * @param float $x The value of the abscissa in user units.
7517 * @param boolean $rtloff if true always uses the page top-left corner as origin of axis.
7520 * @see GetX(), GetY(), SetY(), SetXY()
7522 public function setX($x, $rtloff=false) {
7524 if (!$rtloff AND $this->rtl
) {
7526 $this->x
= $this->w
- $x;
7534 $this->x
= $this->w +
$x;
7540 if ($this->x
> $this->w
) {
7541 $this->x
= $this->w
;
7546 * Moves the current abscissa back to the left margin and sets the ordinate.
7547 * If the passed value is negative, it is relative to the bottom of the page.
7548 * @param float $y The value of the ordinate in user units.
7549 * @param bool $resetx if true (default) reset the X position.
7550 * @param boolean $rtloff if true always uses the page top-left corner as origin of axis.
7553 * @see GetX(), GetY(), SetY(), SetXY()
7555 public function setY($y, $resetx=true, $rtloff=false) {
7559 if (!$rtloff AND $this->rtl
) {
7560 $this->x
= $this->w
- $this->rMargin
;
7562 $this->x
= $this->lMargin
;
7568 $this->y
= $this->h +
$y;
7573 if ($this->y
> $this->h
) {
7574 $this->y
= $this->h
;
7579 * Defines the abscissa and ordinate of the current position.
7580 * If the passed values are negative, they are relative respectively to the right and bottom of the page.
7581 * @param float $x The value of the abscissa.
7582 * @param float $y The value of the ordinate.
7583 * @param boolean $rtloff if true always uses the page top-left corner as origin of axis.
7586 * @see SetX(), SetY()
7588 public function setXY($x, $y, $rtloff=false) {
7589 $this->setY($y, false, $rtloff);
7590 $this->setX($x, $rtloff);
7594 * Set the absolute X coordinate of the current pointer.
7595 * @param float $x The value of the abscissa in user units.
7597 * @since 5.9.186 (2012-09-13)
7598 * @see setAbsX(), setAbsY(), SetAbsXY()
7600 public function setAbsX($x) {
7601 $this->x
= floatval($x);
7605 * Set the absolute Y coordinate of the current pointer.
7606 * @param float $y (float) The value of the ordinate in user units.
7608 * @since 5.9.186 (2012-09-13)
7609 * @see setAbsX(), setAbsY(), SetAbsXY()
7611 public function setAbsY($y) {
7612 $this->y
= floatval($y);
7616 * Set the absolute X and Y coordinates of the current pointer.
7617 * @param float $x The value of the abscissa in user units.
7618 * @param float $y (float) The value of the ordinate in user units.
7620 * @since 5.9.186 (2012-09-13)
7621 * @see setAbsX(), setAbsY(), SetAbsXY()
7623 public function setAbsXY($x, $y) {
7629 * Send the document to a given destination: string, local file or browser.
7630 * In the last case, the plug-in may be used (if present) or a download ("Save as" dialog box) may be forced.<br />
7631 * The method first calls Close() if necessary to terminate the document.
7632 * @param string $name The name of the file when saved
7633 * @param string $dest Destination where to send the document. It can take one of the following values:<ul><li>I: send the file inline to the browser (default). The plug-in is used if available. The name given by name is used when one selects the "Save as" option on the link generating the PDF.</li><li>D: send to the browser and force a file download with the name given by name.</li><li>F: save to a local 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>
7639 public function Output($name='doc.pdf', $dest='I') {
7640 //Output PDF to some destination
7641 //Finish document if necessary
7642 if ($this->state
< 3) {
7645 //Normalize parameters
7646 if (is_bool($dest)) {
7647 $dest = $dest ?
'D' : 'F';
7649 $dest = strtoupper($dest);
7652 // *** apply digital signature to the document ***
7653 // get the document content
7654 $pdfdoc = $this->getBuffer();
7655 // remove last newline
7656 $pdfdoc = substr($pdfdoc, 0, -1);
7657 // remove filler space
7658 $byterange_string_len = strlen(TCPDF_STATIC
::$byterange_string);
7659 // define the ByteRange
7660 $byte_range = array();
7662 $byte_range[1] = strpos($pdfdoc, TCPDF_STATIC
::$byterange_string) +
$byterange_string_len +
10;
7663 $byte_range[2] = $byte_range[1] +
$this->signature_max_length +
2;
7664 $byte_range[3] = strlen($pdfdoc) - $byte_range[2];
7665 $pdfdoc = substr($pdfdoc, 0, $byte_range[1]).substr($pdfdoc, $byte_range[2]);
7666 // replace the ByteRange
7667 $byterange = sprintf('/ByteRange[0 %u %u %u]', $byte_range[1], $byte_range[2], $byte_range[3]);
7668 $byterange .= str_repeat(' ', ($byterange_string_len - strlen($byterange)));
7669 $pdfdoc = str_replace(TCPDF_STATIC
::$byterange_string, $byterange, $pdfdoc);
7670 // write the document to a temporary folder
7671 $tempdoc = TCPDF_STATIC
::getObjFilename('doc', $this->file_id
);
7672 $f = TCPDF_STATIC
::fopenLocal($tempdoc, 'wb');
7674 $this->Error('Unable to create temporary file: '.$tempdoc);
7676 $pdfdoc_length = strlen($pdfdoc);
7677 fwrite($f, $pdfdoc, $pdfdoc_length);
7679 // get digital signature via openssl library
7680 $tempsign = TCPDF_STATIC
::getObjFilename('sig', $this->file_id
);
7681 if (empty($this->signature_data
['extracerts'])) {
7682 openssl_pkcs7_sign($tempdoc, $tempsign, $this->signature_data
['signcert'], array($this->signature_data
['privkey'], $this->signature_data
['password']), array(), PKCS7_BINARY | PKCS7_DETACHED
);
7684 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']);
7687 $signature = file_get_contents($tempsign);
7688 // extract signature
7689 $signature = substr($signature, $pdfdoc_length);
7690 $signature = substr($signature, (strpos($signature, "%%EOF\n\n------") +
13));
7691 $tmparr = explode("\n\n", $signature);
7692 $signature = $tmparr[1];
7694 $signature = base64_decode(trim($signature));
7695 // add TSA timestamp to signature
7696 $signature = $this->applyTSA($signature);
7697 // convert signature to hex
7698 $signature = current(unpack('H*', $signature));
7699 $signature = str_pad($signature, $this->signature_max_length
, '0');
7700 // Add signature to the document
7701 $this->buffer
= substr($pdfdoc, 0, $byte_range[1]).'<'.$signature.'>'.substr($pdfdoc, $byte_range[1]);
7702 $this->bufferlen
= strlen($this->buffer
);
7706 // Send PDF to the standard output
7707 if (ob_get_contents()) {
7708 $this->Error('Some data has already been output, can\'t send PDF file');
7710 if (php_sapi_name() != 'cli') {
7711 // send output to a browser
7712 header('Content-Type: application/pdf');
7713 if (headers_sent()) {
7714 $this->Error('Some data has already been output to browser, can\'t send PDF file');
7716 header('Cache-Control: private, must-revalidate, post-check=0, pre-check=0, max-age=1');
7717 //header('Cache-Control: public, must-revalidate, max-age=0'); // HTTP/1.1
7718 header('Pragma: public');
7719 header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
7720 header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
7721 header('Content-Disposition: inline; filename="' . rawurlencode(basename($name)) . '"; ' .
7722 'filename*=UTF-8\'\'' . rawurlencode(basename($name)));
7723 TCPDF_STATIC
::sendOutputData($this->getBuffer(), $this->bufferlen
);
7725 echo $this->getBuffer();
7730 // download PDF as file
7731 if (ob_get_contents()) {
7732 $this->Error('Some data has already been output, can\'t send PDF file');
7734 header('Content-Description: File Transfer');
7735 if (headers_sent()) {
7736 $this->Error('Some data has already been output to browser, can\'t send PDF file');
7738 header('Cache-Control: private, must-revalidate, post-check=0, pre-check=0, max-age=1');
7739 //header('Cache-Control: public, must-revalidate, max-age=0'); // HTTP/1.1
7740 header('Pragma: public');
7741 header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
7742 header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
7743 // force download dialog
7744 if (strpos(php_sapi_name(), 'cgi') === false) {
7745 header('Content-Type: application/force-download');
7746 header('Content-Type: application/octet-stream', false);
7747 header('Content-Type: application/download', false);
7748 header('Content-Type: application/pdf', false);
7750 header('Content-Type: application/pdf');
7752 // use the Content-Disposition header to supply a recommended filename
7753 header('Content-Disposition: attachment; filename="' . rawurlencode(basename($name)) . '"; ' .
7754 'filename*=UTF-8\'\'' . rawurlencode(basename($name)));
7755 header('Content-Transfer-Encoding: binary');
7756 TCPDF_STATIC
::sendOutputData($this->getBuffer(), $this->bufferlen
);
7762 // save PDF to a local file
7763 $f = TCPDF_STATIC
::fopenLocal($name, 'wb');
7765 $this->Error('Unable to create output file: '.$name);
7767 fwrite($f, $this->getBuffer(), $this->bufferlen
);
7769 if ($dest == 'FI') {
7770 // send headers to browser
7771 header('Content-Type: application/pdf');
7772 header('Cache-Control: private, must-revalidate, post-check=0, pre-check=0, max-age=1');
7773 //header('Cache-Control: public, must-revalidate, max-age=0'); // HTTP/1.1
7774 header('Pragma: public');
7775 header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
7776 header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
7777 header('Content-Disposition: inline; filename="'.basename($name).'"');
7778 TCPDF_STATIC
::sendOutputData(file_get_contents($name), filesize($name));
7779 } elseif ($dest == 'FD') {
7780 // send headers to browser
7781 if (ob_get_contents()) {
7782 $this->Error('Some data has already been output, can\'t send PDF file');
7784 header('Content-Description: File Transfer');
7785 if (headers_sent()) {
7786 $this->Error('Some data has already been output to browser, can\'t send PDF file');
7788 header('Cache-Control: private, must-revalidate, post-check=0, pre-check=0, max-age=1');
7789 header('Pragma: public');
7790 header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
7791 header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
7792 // force download dialog
7793 if (strpos(php_sapi_name(), 'cgi') === false) {
7794 header('Content-Type: application/force-download');
7795 header('Content-Type: application/octet-stream', false);
7796 header('Content-Type: application/download', false);
7797 header('Content-Type: application/pdf', false);
7799 header('Content-Type: application/pdf');
7801 // use the Content-Disposition header to supply a recommended filename
7802 header('Content-Disposition: attachment; filename="'.basename($name).'"');
7803 header('Content-Transfer-Encoding: binary');
7804 TCPDF_STATIC
::sendOutputData(file_get_contents($name), filesize($name));
7809 // return PDF as base64 mime multi-part email attachment (RFC 2045)
7810 $retval = 'Content-Type: application/pdf;'."\r\n";
7811 $retval .= ' name="'.$name.'"'."\r\n";
7812 $retval .= 'Content-Transfer-Encoding: base64'."\r\n";
7813 $retval .= 'Content-Disposition: attachment;'."\r\n";
7814 $retval .= ' filename="'.$name.'"'."\r\n\r\n";
7815 $retval .= chunk_split(base64_encode($this->getBuffer()), 76, "\r\n");
7819 // returns PDF as a string
7820 return $this->getBuffer();
7823 $this->Error('Incorrect output destination: '.$dest);
7829 protected static $cleaned_ids = array();
7831 * Unset all class variables except the following critical variables.
7832 * @param boolean $destroyall if true destroys all class variables, otherwise preserves critical variables.
7833 * @param boolean $preserve_objcopy if true preserves the objcopy variable
7835 * @since 4.5.016 (2009-02-24)
7837 public function _destroy($destroyall=false, $preserve_objcopy=false) {
7838 if (isset(self
::$cleaned_ids[$this->file_id
])) {
7839 $destroyall = false;
7841 if ($destroyall AND !$preserve_objcopy && isset($this->file_id
)) {
7842 self
::$cleaned_ids[$this->file_id
] = true;
7843 // remove all temporary files
7844 if ($handle = @opendir
(K_PATH_CACHE
)) {
7845 while ( false !== ( $file_name = readdir( $handle ) ) ) {
7846 if (strpos($file_name, '__tcpdf_'.$this->file_id
.'_') === 0) {
7847 unlink(K_PATH_CACHE
.$file_name);
7852 if (isset($this->imagekeys
)) {
7853 foreach($this->imagekeys
as $file) {
7854 if (strpos($file, K_PATH_CACHE
) === 0 && TCPDF_STATIC
::file_exists($file)) {
7869 'signature_max_length',
7874 foreach (array_keys(get_object_vars($this)) as $val) {
7875 if ($destroyall OR !in_array($val, $preserve)) {
7876 if ((!$preserve_objcopy OR ($val != 'objcopy')) AND ($val != 'file_id') AND isset($this->$val)) {
7884 * Check for locale-related bug
7887 protected function _dochecks() {
7888 //Check for locale-related bug
7890 $this->Error('Don\'t alter the locale before including class file');
7892 //Check for decimal separator
7893 if (sprintf('%.1F', 1.0) != '1.0') {
7894 setlocale(LC_NUMERIC
, 'C');
7899 * Return an array containing variations for the basic page number alias.
7900 * @param string $a Base alias.
7901 * @return array of page number aliases
7904 protected function getInternalPageNumberAliases($a= '') {
7906 // build array of Unicode + ASCII variants (the order is important)
7907 $alias = array('u' => array(), 'a' => array());
7909 $alias['u'][] = TCPDF_STATIC
::_escape($u);
7910 if ($this->isunicode
) {
7911 $alias['u'][] = TCPDF_STATIC
::_escape(TCPDF_FONTS
::UTF8ToLatin1($u, $this->isunicode
, $this->CurrentFont
));
7912 $alias['u'][] = TCPDF_STATIC
::_escape(TCPDF_FONTS
::utf8StrRev($u, false, $this->tmprtl
, $this->isunicode
, $this->CurrentFont
));
7913 $alias['a'][] = TCPDF_STATIC
::_escape(TCPDF_FONTS
::UTF8ToLatin1($a, $this->isunicode
, $this->CurrentFont
));
7914 $alias['a'][] = TCPDF_STATIC
::_escape(TCPDF_FONTS
::utf8StrRev($a, false, $this->tmprtl
, $this->isunicode
, $this->CurrentFont
));
7916 $alias['a'][] = TCPDF_STATIC
::_escape($a);
7921 * Return an array containing all internal page aliases.
7922 * @return array of page number aliases
7925 protected function getAllInternalPageNumberAliases() {
7926 $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);
7928 foreach($basic_alias as $k => $a) {
7929 $pnalias[$k] = $this->getInternalPageNumberAliases($a);
7935 * Replace right shift page number aliases with spaces to correct right alignment.
7936 * This works perfectly only when using monospaced fonts.
7937 * @param string $page Page content.
7938 * @param array $aliases Array of page aliases.
7939 * @param int $diff initial difference to add.
7940 * @return string replaced page content.
7943 protected function replaceRightShiftPageNumAliases($page, $aliases, $diff) {
7944 foreach ($aliases as $type => $alias) {
7945 foreach ($alias as $a) {
7946 // find position of compensation factor
7947 $startnum = (strpos($a, ':') +
1);
7948 $a = substr($a, 0, $startnum);
7949 if (($pos = strpos($page, $a)) !== false) {
7951 $endnum = strpos($page, '}', $pos);
7952 // string to be replaced
7953 $aa = substr($page, $pos, ($endnum - $pos +
1));
7954 // get compensation factor
7955 $ratio = substr($page, ($pos +
$startnum), ($endnum - $pos - $startnum));
7956 $ratio = preg_replace('/[^0-9\.]/', '', $ratio);
7957 $ratio = floatval($ratio);
7959 $chrdiff = floor(($diff +
12) * $ratio);
7960 $shift = str_repeat(' ', $chrdiff);
7961 $shift = TCPDF_FONTS
::UTF8ToUTF16BE($shift, false, $this->isunicode
, $this->CurrentFont
);
7963 $chrdiff = floor(($diff +
11) * $ratio);
7964 $shift = str_repeat(' ', $chrdiff);
7966 $page = str_replace($aa, $shift, $page);
7974 * Set page boxes to be included on page descriptions.
7975 * @param array $boxes Array of page boxes to set on document: ('MediaBox', 'CropBox', 'BleedBox', 'TrimBox', 'ArtBox').
7978 protected function setPageBoxTypes($boxes) {
7979 $this->page_boxes
= array();
7980 foreach ($boxes as $box) {
7981 if (in_array($box, TCPDF_STATIC
::$pageboxes)) {
7982 $this->page_boxes
[] = $box;
7988 * Output pages (and replace page number aliases).
7991 protected function _putpages() {
7992 $filter = ($this->compress
) ?
'/Filter /FlateDecode ' : '';
7993 // get internal aliases for page numbers
7994 $pnalias = $this->getAllInternalPageNumberAliases();
7995 $num_pages = $this->numpages
;
7996 $ptpa = TCPDF_STATIC
::formatPageNumber(($this->starting_page_number +
$num_pages - 1));
7997 $ptpu = TCPDF_FONTS
::UTF8ToUTF16BE($ptpa, false, $this->isunicode
, $this->CurrentFont
);
7998 $ptp_num_chars = $this->GetNumChars($ptpa);
8004 for ($n = 1; $n <= $num_pages; ++
$n) {
8006 $temppage = $this->getPageBuffer($n);
8007 $pagelen = strlen($temppage);
8008 // set replacements for total pages number
8009 $pnpa = TCPDF_STATIC
::formatPageNumber(($this->starting_page_number +
$n - 1));
8010 $pnpu = TCPDF_FONTS
::UTF8ToUTF16BE($pnpa, false, $this->isunicode
, $this->CurrentFont
);
8011 $pnp_num_chars = $this->GetNumChars($pnpa);
8012 $pdiff = 0; // difference used for right shift alignment of page numbers
8013 $gdiff = 0; // difference used for right shift alignment of page group numbers
8014 if (!empty($this->pagegroups
)) {
8015 if (isset($this->newpagegroup
[$n])) {
8018 $ptga = TCPDF_STATIC
::formatPageNumber($this->pagegroups
[$groupnum]);
8019 $ptgu = TCPDF_FONTS
::UTF8ToUTF16BE($ptga, false, $this->isunicode
, $this->CurrentFont
);
8020 $ptg_num_chars = $this->GetNumChars($ptga);
8023 $pnga = TCPDF_STATIC
::formatPageNumber($pagegroupnum);
8024 $pngu = TCPDF_FONTS
::UTF8ToUTF16BE($pnga, false, $this->isunicode
, $this->CurrentFont
);
8025 $png_num_chars = $this->GetNumChars($pnga);
8026 // replace page numbers
8028 $replace[] = array($ptgu, $ptg_num_chars, 9, $pnalias[2]['u']);
8029 $replace[] = array($ptga, $ptg_num_chars, 7, $pnalias[2]['a']);
8030 $replace[] = array($pngu, $png_num_chars, 9, $pnalias[3]['u']);
8031 $replace[] = array($pnga, $png_num_chars, 7, $pnalias[3]['a']);
8032 list($temppage, $gdiff) = TCPDF_STATIC
::replacePageNumAliases($temppage, $replace, $gdiff);
8034 // replace page numbers
8036 $replace[] = array($ptpu, $ptp_num_chars, 9, $pnalias[0]['u']);
8037 $replace[] = array($ptpa, $ptp_num_chars, 7, $pnalias[0]['a']);
8038 $replace[] = array($pnpu, $pnp_num_chars, 9, $pnalias[1]['u']);
8039 $replace[] = array($pnpa, $pnp_num_chars, 7, $pnalias[1]['a']);
8040 list($temppage, $pdiff) = TCPDF_STATIC
::replacePageNumAliases($temppage, $replace, $pdiff);
8041 // replace right shift alias
8042 $temppage = $this->replaceRightShiftPageNumAliases($temppage, $pnalias[4], max($pdiff, $gdiff));
8043 // replace EPS marker
8044 $temppage = str_replace($this->epsmarker
, '', $temppage);
8046 $this->page_obj_id
[$n] = $this->_newobj();
8048 $out .= ' /Type /Page';
8049 $out .= ' /Parent 1 0 R';
8050 if (empty($this->signature_data
['approval']) OR ($this->signature_data
['approval'] != 'A')) {
8051 $out .= ' /LastModified '.$this->_datestring(0, $this->doc_modification_timestamp
);
8053 $out .= ' /Resources 2 0 R';
8054 foreach ($this->page_boxes
as $box) {
8056 $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']);
8058 if (isset($this->pagedim
[$n]['BoxColorInfo']) AND !empty($this->pagedim
[$n]['BoxColorInfo'])) {
8059 $out .= ' /BoxColorInfo <<';
8060 foreach ($this->page_boxes
as $box) {
8061 if (isset($this->pagedim
[$n]['BoxColorInfo'][$box])) {
8062 $out .= ' /'.$box.' <<';
8063 if (isset($this->pagedim
[$n]['BoxColorInfo'][$box]['C'])) {
8064 $color = $this->pagedim
[$n]['BoxColorInfo'][$box]['C'];
8066 $out .= sprintf(' %F %F %F', ($color[0] / 255), ($color[1] / 255), ($color[2] / 255));
8069 if (isset($this->pagedim
[$n]['BoxColorInfo'][$box]['W'])) {
8070 $out .= ' /W '.($this->pagedim
[$n]['BoxColorInfo'][$box]['W'] * $this->k
);
8072 if (isset($this->pagedim
[$n]['BoxColorInfo'][$box]['S'])) {
8073 $out .= ' /S /'.$this->pagedim
[$n]['BoxColorInfo'][$box]['S'];
8075 if (isset($this->pagedim
[$n]['BoxColorInfo'][$box]['D'])) {
8076 $dashes = $this->pagedim
[$n]['BoxColorInfo'][$box]['D'];
8078 foreach ($dashes as $dash) {
8079 $out .= sprintf(' %F', ($dash * $this->k
));
8088 $out .= ' /Contents '.($this->n +
1).' 0 R';
8089 $out .= ' /Rotate '.$this->pagedim
[$n]['Rotate'];
8090 if (!$this->pdfa_mode ||
$this->pdfa_version
>= 2) {
8091 $out .= ' /Group << /Type /Group /S /Transparency /CS /DeviceRGB >>';
8093 if (isset($this->pagedim
[$n]['trans']) AND !empty($this->pagedim
[$n]['trans'])) {
8095 if (isset($this->pagedim
[$n]['trans']['Dur'])) {
8096 $out .= ' /Dur '.$this->pagedim
[$n]['trans']['Dur'];
8098 $out .= ' /Trans <<';
8099 $out .= ' /Type /Trans';
8100 if (isset($this->pagedim
[$n]['trans']['S'])) {
8101 $out .= ' /S /'.$this->pagedim
[$n]['trans']['S'];
8103 if (isset($this->pagedim
[$n]['trans']['D'])) {
8104 $out .= ' /D '.$this->pagedim
[$n]['trans']['D'];
8106 if (isset($this->pagedim
[$n]['trans']['Dm'])) {
8107 $out .= ' /Dm /'.$this->pagedim
[$n]['trans']['Dm'];
8109 if (isset($this->pagedim
[$n]['trans']['M'])) {
8110 $out .= ' /M /'.$this->pagedim
[$n]['trans']['M'];
8112 if (isset($this->pagedim
[$n]['trans']['Di'])) {
8113 $out .= ' /Di '.$this->pagedim
[$n]['trans']['Di'];
8115 if (isset($this->pagedim
[$n]['trans']['SS'])) {
8116 $out .= ' /SS '.$this->pagedim
[$n]['trans']['SS'];
8118 if (isset($this->pagedim
[$n]['trans']['B'])) {
8119 $out .= ' /B '.$this->pagedim
[$n]['trans']['B'];
8123 $out .= $this->_getannotsrefs($n);
8124 $out .= ' /PZ '.$this->pagedim
[$n]['PZ'];
8126 $out .= "\n".'endobj';
8129 $p = ($this->compress
) ?
gzcompress($temppage) : $temppage;
8131 $p = $this->_getrawstream($p);
8132 $this->_out('<<'.$filter.'/Length '.strlen($p).'>> stream'."\n".$p."\n".'endstream'."\n".'endobj');
8135 $out = $this->_getobj(1)."\n";
8136 $out .= '<< /Type /Pages /Kids [';
8137 foreach($this->page_obj_id
as $page_obj) {
8138 $out .= ' '.$page_obj.' 0 R';
8140 $out .= ' ] /Count '.$num_pages.' >>';
8141 $out .= "\n".'endobj';
8146 * Get references to page annotations.
8147 * @param int $n page number
8150 * @author Nicola Asuni
8151 * @since 5.0.010 (2010-05-17)
8153 protected function _getannotsrefs($n) {
8154 if (!(isset($this->PageAnnots
[$n]) OR ($this->sign
AND isset($this->signature_data
['cert_type'])))) {
8157 $out = ' /Annots [';
8158 if (isset($this->PageAnnots
[$n])) {
8159 foreach ($this->PageAnnots
[$n] as $key => $val) {
8160 if (!in_array($val['n'], $this->radio_groups
)) {
8161 $out .= ' '.$val['n'].' 0 R';
8164 // add radiobutton groups
8165 if (isset($this->radiobutton_groups
[$n])) {
8166 foreach ($this->radiobutton_groups
[$n] as $key => $data) {
8167 if (isset($data['n'])) {
8168 $out .= ' '.$data['n'].' 0 R';
8173 if ($this->sign
AND ($n == $this->signature_appearance
['page']) AND isset($this->signature_data
['cert_type'])) {
8174 // set reference for signature object
8175 $out .= ' '.$this->sig_obj_id
.' 0 R';
8177 if (!empty($this->empty_signature_appearance
)) {
8178 foreach ($this->empty_signature_appearance
as $esa) {
8179 if ($esa['page'] == $n) {
8180 // set reference for empty signature objects
8181 $out .= ' '.$esa['objid'].' 0 R';
8190 * Output annotations objects for all pages.
8191 * !!! THIS METHOD IS NOT YET COMPLETED !!!
8192 * See section 12.5 of PDF 32000_2008 reference.
8194 * @author Nicola Asuni
8195 * @since 4.0.018 (2008-08-06)
8197 protected function _putannotsobjs() {
8198 // reset object counter
8199 for ($n=1; $n <= $this->numpages
; ++
$n) {
8200 if (isset($this->PageAnnots
[$n])) {
8201 // set page annotations
8202 foreach ($this->PageAnnots
[$n] as $key => $pl) {
8203 $annot_obj_id = $this->PageAnnots
[$n][$key]['n'];
8204 // create annotation object for grouping radiobuttons
8205 if (isset($this->radiobutton_groups
[$n][$pl['txt']]) AND is_array($this->radiobutton_groups
[$n][$pl['txt']])) {
8206 $radio_button_obj_id = $this->radiobutton_groups
[$n][$pl['txt']]['n'];
8208 $annots .= ' /Type /Annot';
8209 $annots .= ' /Subtype /Widget';
8210 $annots .= ' /Rect [0 0 0 0]';
8211 if ($this->radiobutton_groups
[$n][$pl['txt']]['#readonly#']) {
8213 $annots .= ' /F 68';
8214 $annots .= ' /Ff 49153';
8216 $annots .= ' /F 4'; // default print for PDF/A
8217 $annots .= ' /Ff 49152';
8219 $annots .= ' /T '.$this->_datastring($pl['txt'], $radio_button_obj_id);
8220 if (isset($pl['opt']['tu']) AND is_string($pl['opt']['tu'])) {
8221 $annots .= ' /TU '.$this->_datastring($pl['opt']['tu'], $radio_button_obj_id);
8223 $annots .= ' /FT /Btn';
8224 $annots .= ' /Kids [';
8226 foreach ($this->radiobutton_groups
[$n][$pl['txt']] as $key => $data) {
8227 if (isset($data['kid'])) {
8228 $annots .= ' '.$data['kid'].' 0 R';
8229 if ($data['def'] !== 'Off') {
8230 $defval = $data['def'];
8235 if (!empty($defval)) {
8236 $annots .= ' /V /'.$defval;
8239 $this->_out($this->_getobj($radio_button_obj_id)."\n".$annots."\n".'endobj');
8240 $this->form_obj_id
[] = $radio_button_obj_id;
8241 // store object id to be used on Parent entry of Kids
8242 $this->radiobutton_groups
[$n][$pl['txt']] = $radio_button_obj_id;
8245 $pl['opt'] = array_change_key_case($pl['opt'], CASE_LOWER
);
8246 $a = $pl['x'] * $this->k
;
8247 $b = $this->pagedim
[$n]['h'] - (($pl['y'] +
$pl['h']) * $this->k
);
8248 $c = $pl['w'] * $this->k
;
8249 $d = $pl['h'] * $this->k
;
8250 $rect = sprintf('%F %F %F %F', $a, $b, $a+
$c, $b+
$d);
8251 // create new annotation object
8252 $annots = '<</Type /Annot';
8253 $annots .= ' /Subtype /'.$pl['opt']['subtype'];
8254 $annots .= ' /Rect ['.$rect.']';
8255 $ft = array('Btn', 'Tx', 'Ch', 'Sig');
8256 if (isset($pl['opt']['ft']) AND in_array($pl['opt']['ft'], $ft)) {
8257 $annots .= ' /FT /'.$pl['opt']['ft'];
8260 if ($pl['opt']['subtype'] !== 'Link') {
8261 $annots .= ' /Contents '.$this->_textstring($pl['txt'], $annot_obj_id);
8263 $annots .= ' /P '.$this->page_obj_id
[$n].' 0 R';
8264 $annots .= ' /NM '.$this->_datastring(sprintf('%04u-%04u', $n, $key), $annot_obj_id);
8265 $annots .= ' /M '.$this->_datestring($annot_obj_id, $this->doc_modification_timestamp
);
8266 if (isset($pl['opt']['f'])) {
8268 if (is_array($pl['opt']['f'])) {
8269 foreach ($pl['opt']['f'] as $f) {
8270 switch (strtolower($f)) {
8303 case 'togglenoview': {
8307 case 'lockedcontents': {
8317 $fval = intval($pl['opt']['f']);
8322 if ($this->pdfa_mode
) {
8323 // force print flag for PDF/A mode
8326 $annots .= ' /F '.intval($fval);
8327 if (isset($pl['opt']['as']) AND is_string($pl['opt']['as'])) {
8328 $annots .= ' /AS /'.$pl['opt']['as'];
8330 if (isset($pl['opt']['ap'])) {
8331 // appearance stream
8332 $annots .= ' /AP <<';
8333 if (is_array($pl['opt']['ap'])) {
8334 foreach ($pl['opt']['ap'] as $apmode => $apdef) {
8335 // $apmode can be: n = normal; r = rollover; d = down;
8336 $annots .= ' /'.strtoupper($apmode);
8337 if (is_array($apdef)) {
8339 foreach ($apdef as $apstate => $stream) {
8340 // reference to XObject that define the appearance for this mode-state
8341 $apsobjid = $this->_putAPXObject($c, $d, $stream);
8342 $annots .= ' /'.$apstate.' '.$apsobjid.' 0 R';
8346 // reference to XObject that define the appearance for this mode
8347 $apsobjid = $this->_putAPXObject($c, $d, $apdef);
8348 $annots .= ' '.$apsobjid.' 0 R';
8352 $annots .= $pl['opt']['ap'];
8356 if (isset($pl['opt']['bs']) AND (is_array($pl['opt']['bs']))) {
8357 $annots .= ' /BS <<';
8358 $annots .= ' /Type /Border';
8359 if (isset($pl['opt']['bs']['w'])) {
8360 $annots .= ' /W '.intval($pl['opt']['bs']['w']);
8362 $bstyles = array('S', 'D', 'B', 'I', 'U');
8363 if (isset($pl['opt']['bs']['s']) AND in_array($pl['opt']['bs']['s'], $bstyles)) {
8364 $annots .= ' /S /'.$pl['opt']['bs']['s'];
8366 if (isset($pl['opt']['bs']['d']) AND (is_array($pl['opt']['bs']['d']))) {
8368 foreach ($pl['opt']['bs']['d'] as $cord) {
8369 $annots .= ' '.intval($cord);
8375 $annots .= ' /Border [';
8376 if (isset($pl['opt']['border']) AND (count($pl['opt']['border']) >= 3)) {
8377 $annots .= intval($pl['opt']['border'][0]).' ';
8378 $annots .= intval($pl['opt']['border'][1]).' ';
8379 $annots .= intval($pl['opt']['border'][2]);
8380 if (isset($pl['opt']['border'][3]) AND is_array($pl['opt']['border'][3])) {
8382 foreach ($pl['opt']['border'][3] as $dash) {
8383 $annots .= intval($dash).' ';
8392 if (isset($pl['opt']['be']) AND (is_array($pl['opt']['be']))) {
8393 $annots .= ' /BE <<';
8394 $bstyles = array('S', 'C');
8395 if (isset($pl['opt']['be']['s']) AND in_array($pl['opt']['be']['s'], $bstyles)) {
8396 $annots .= ' /S /'.$pl['opt']['bs']['s'];
8398 $annots .= ' /S /S';
8400 if (isset($pl['opt']['be']['i']) AND ($pl['opt']['be']['i'] >= 0) AND ($pl['opt']['be']['i'] <= 2)) {
8401 $annots .= ' /I '.sprintf(' %F', $pl['opt']['be']['i']);
8405 if (isset($pl['opt']['c']) AND (is_array($pl['opt']['c'])) AND !empty($pl['opt']['c'])) {
8406 $annots .= ' /C '.TCPDF_COLORS
::getColorStringFromArray($pl['opt']['c']);
8408 //$annots .= ' /StructParent ';
8409 //$annots .= ' /OC ';
8410 $markups = array('text', 'freetext', 'line', 'square', 'circle', 'polygon', 'polyline', 'highlight', 'underline', 'squiggly', 'strikeout', 'stamp', 'caret', 'ink', 'fileattachment', 'sound');
8411 if (in_array(strtolower($pl['opt']['subtype']), $markups)) {
8412 // this is a markup type
8413 if (isset($pl['opt']['t']) AND is_string($pl['opt']['t'])) {
8414 $annots .= ' /T '.$this->_textstring($pl['opt']['t'], $annot_obj_id);
8416 //$annots .= ' /Popup ';
8417 if (isset($pl['opt']['ca'])) {
8418 $annots .= ' /CA '.sprintf('%F', floatval($pl['opt']['ca']));
8420 if (isset($pl['opt']['rc'])) {
8421 $annots .= ' /RC '.$this->_textstring($pl['opt']['rc'], $annot_obj_id);
8423 $annots .= ' /CreationDate '.$this->_datestring($annot_obj_id, $this->doc_creation_timestamp
);
8424 //$annots .= ' /IRT ';
8425 if (isset($pl['opt']['subj'])) {
8426 $annots .= ' /Subj '.$this->_textstring($pl['opt']['subj'], $annot_obj_id);
8428 //$annots .= ' /RT ';
8429 //$annots .= ' /IT ';
8430 //$annots .= ' /ExData ';
8432 $lineendings = array('Square', 'Circle', 'Diamond', 'OpenArrow', 'ClosedArrow', 'None', 'Butt', 'ROpenArrow', 'RClosedArrow', 'Slash');
8434 switch (strtolower($pl['opt']['subtype'])) {
8436 if (isset($pl['opt']['open'])) {
8437 $annots .= ' /Open '. (strtolower($pl['opt']['open']) == 'true' ?
'true' : 'false');
8439 $iconsapp = array('Comment', 'Help', 'Insert', 'Key', 'NewParagraph', 'Note', 'Paragraph');
8440 if (isset($pl['opt']['name']) AND in_array($pl['opt']['name'], $iconsapp)) {
8441 $annots .= ' /Name /'.$pl['opt']['name'];
8443 $annots .= ' /Name /Note';
8445 $hasStateModel = isset($pl['opt']['statemodel']);
8446 $hasState = isset($pl['opt']['state']);
8447 $statemodels = array('Marked', 'Review');
8448 if (!$hasStateModel && !$hasState) {
8451 if ($hasStateModel AND in_array($pl['opt']['statemodel'], $statemodels)) {
8452 $annots .= ' /StateModel /'.$pl['opt']['statemodel'];
8454 $pl['opt']['statemodel'] = 'Marked';
8455 $annots .= ' /StateModel /'.$pl['opt']['statemodel'];
8457 if ($pl['opt']['statemodel'] == 'Marked') {
8458 $states = array('Accepted', 'Unmarked');
8460 $states = array('Accepted', 'Rejected', 'Cancelled', 'Completed', 'None');
8462 if ($hasState AND in_array($pl['opt']['state'], $states)) {
8463 $annots .= ' /State /'.$pl['opt']['state'];
8465 if ($pl['opt']['statemodel'] == 'Marked') {
8466 $annots .= ' /State /Unmarked';
8468 $annots .= ' /State /None';
8474 if (is_string($pl['txt']) && !empty($pl['txt'])) {
8475 if ($pl['txt'][0] == '#') {
8476 // internal destination
8477 $annots .= ' /A <</S /GoTo /D /'.TCPDF_STATIC
::encodeNameObject(substr($pl['txt'], 1)).'>>';
8478 } elseif ($pl['txt'][0] == '%') {
8479 // embedded PDF file
8480 $filename = basename(substr($pl['txt'], 1));
8481 $annots .= ' /A << /S /GoToE /D [0 /Fit] /NewWindow true /T << /R /C /P '.($n - 1).' /A '.$this->embeddedfiles
[$filename]['a'].' >> >>';
8482 } elseif ($pl['txt'][0] == '*') {
8483 // embedded generic file
8484 $filename = basename(substr($pl['txt'], 1));
8485 $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});';
8486 $annots .= ' /A << /S /JavaScript /JS '.$this->_textstring($jsa, $annot_obj_id).'>>';
8488 $parsedUrl = parse_url($pl['txt']);
8489 if (empty($parsedUrl['scheme']) AND (!empty($parsedUrl['path']) && strtolower(substr($parsedUrl['path'], -4)) == '.pdf')) {
8490 // relative link to a PDF file
8491 $dest = '[0 /Fit]'; // default page 0
8492 if (!empty($parsedUrl['fragment'])) {
8493 // check for named destination
8494 $tmp = explode('=', $parsedUrl['fragment']);
8495 $dest = '('.((count($tmp) == 2) ?
$tmp[1] : $tmp[0]).')';
8497 $annots .= ' /A <</S /GoToR /D '.$dest.' /F '.$this->_datastring($this->unhtmlentities($parsedUrl['path']), $annot_obj_id).' /NewWindow true>>';
8499 // external URI link
8500 $annots .= ' /A <</S /URI /URI '.$this->_datastring($this->unhtmlentities($pl['txt']), $annot_obj_id).'>>';
8503 } elseif (isset($this->links
[$pl['txt']])) {
8505 $l = $this->links
[$pl['txt']];
8506 if (isset($this->page_obj_id
[($l['p'])])) {
8507 $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
)));
8510 $hmodes = array('N', 'I', 'O', 'P');
8511 if (isset($pl['opt']['h']) AND in_array($pl['opt']['h'], $hmodes)) {
8512 $annots .= ' /H /'.$pl['opt']['h'];
8514 $annots .= ' /H /I';
8516 //$annots .= ' /PA ';
8517 //$annots .= ' /Quadpoints ';
8521 if (isset($pl['opt']['da']) AND !empty($pl['opt']['da'])) {
8522 $annots .= ' /DA ('.$pl['opt']['da'].')';
8524 if (isset($pl['opt']['q']) AND ($pl['opt']['q'] >= 0) AND ($pl['opt']['q'] <= 2)) {
8525 $annots .= ' /Q '.intval($pl['opt']['q']);
8527 if (isset($pl['opt']['rc'])) {
8528 $annots .= ' /RC '.$this->_textstring($pl['opt']['rc'], $annot_obj_id);
8530 if (isset($pl['opt']['ds'])) {
8531 $annots .= ' /DS '.$this->_textstring($pl['opt']['ds'], $annot_obj_id);
8533 if (isset($pl['opt']['cl']) AND is_array($pl['opt']['cl'])) {
8534 $annots .= ' /CL [';
8535 foreach ($pl['opt']['cl'] as $cl) {
8536 $annots .= sprintf('%F ', $cl * $this->k
);
8540 $tfit = array('FreeText', 'FreeTextCallout', 'FreeTextTypeWriter');
8541 if (isset($pl['opt']['it']) AND in_array($pl['opt']['it'], $tfit)) {
8542 $annots .= ' /IT /'.$pl['opt']['it'];
8544 if (isset($pl['opt']['rd']) AND is_array($pl['opt']['rd'])) {
8545 $l = $pl['opt']['rd'][0] * $this->k
;
8546 $r = $pl['opt']['rd'][1] * $this->k
;
8547 $t = $pl['opt']['rd'][2] * $this->k
;
8548 $b = $pl['opt']['rd'][3] * $this->k
;
8549 $annots .= ' /RD ['.sprintf('%F %F %F %F', $l, $r, $t, $b).']';
8551 if (isset($pl['opt']['le']) AND in_array($pl['opt']['le'], $lineendings)) {
8552 $annots .= ' /LE /'.$pl['opt']['le'];
8595 case 'fileattachment': {
8596 if ($this->pdfa_mode
&& $this->pdfa_version
!= 3) {
8597 // embedded files are not allowed in PDF/A mode version 1 and 2
8600 if (!isset($pl['opt']['fs'])) {
8603 $filename = basename($pl['opt']['fs']);
8604 if (isset($this->embeddedfiles
[$filename]['f'])) {
8605 $annots .= ' /FS '.$this->embeddedfiles
[$filename]['f'].' 0 R';
8606 $iconsapp = array('Graph', 'Paperclip', 'PushPin', 'Tag');
8607 if (isset($pl['opt']['name']) AND in_array($pl['opt']['name'], $iconsapp)) {
8608 $annots .= ' /Name /'.$pl['opt']['name'];
8610 $annots .= ' /Name /PushPin';
8612 // index (zero-based) of the annotation in the Annots array of this page
8613 $this->embeddedfiles
[$filename]['a'] = $key;
8618 if (!isset($pl['opt']['fs'])) {
8621 $filename = basename($pl['opt']['fs']);
8622 if (isset($this->embeddedfiles
[$filename]['f'])) {
8623 // ... TO BE COMPLETED ...
8624 // /R /C /B /E /CO /CP
8625 $annots .= ' /Sound '.$this->embeddedfiles
[$filename]['f'].' 0 R';
8626 $iconsapp = array('Speaker', 'Mic');
8627 if (isset($pl['opt']['name']) AND in_array($pl['opt']['name'], $iconsapp)) {
8628 $annots .= ' /Name /'.$pl['opt']['name'];
8630 $annots .= ' /Name /Speaker';
8639 $hmode = array('N', 'I', 'O', 'P', 'T');
8640 if (isset($pl['opt']['h']) AND in_array($pl['opt']['h'], $hmode)) {
8641 $annots .= ' /H /'.$pl['opt']['h'];
8643 if (isset($pl['opt']['mk']) AND (is_array($pl['opt']['mk'])) AND !empty($pl['opt']['mk'])) {
8644 $annots .= ' /MK <<';
8645 if (isset($pl['opt']['mk']['r'])) {
8646 $annots .= ' /R '.$pl['opt']['mk']['r'];
8648 if (isset($pl['opt']['mk']['bc']) AND (is_array($pl['opt']['mk']['bc']))) {
8649 $annots .= ' /BC '.TCPDF_COLORS
::getColorStringFromArray($pl['opt']['mk']['bc']);
8651 if (isset($pl['opt']['mk']['bg']) AND (is_array($pl['opt']['mk']['bg']))) {
8652 $annots .= ' /BG '.TCPDF_COLORS
::getColorStringFromArray($pl['opt']['mk']['bg']);
8654 if (isset($pl['opt']['mk']['ca'])) {
8655 $annots .= ' /CA '.$pl['opt']['mk']['ca'];
8657 if (isset($pl['opt']['mk']['rc'])) {
8658 $annots .= ' /RC '.$pl['opt']['mk']['rc'];
8660 if (isset($pl['opt']['mk']['ac'])) {
8661 $annots .= ' /AC '.$pl['opt']['mk']['ac'];
8663 if (isset($pl['opt']['mk']['i'])) {
8664 $info = $this->getImageBuffer($pl['opt']['mk']['i']);
8665 if ($info !== false) {
8666 $annots .= ' /I '.$info['n'].' 0 R';
8669 if (isset($pl['opt']['mk']['ri'])) {
8670 $info = $this->getImageBuffer($pl['opt']['mk']['ri']);
8671 if ($info !== false) {
8672 $annots .= ' /RI '.$info['n'].' 0 R';
8675 if (isset($pl['opt']['mk']['ix'])) {
8676 $info = $this->getImageBuffer($pl['opt']['mk']['ix']);
8677 if ($info !== false) {
8678 $annots .= ' /IX '.$info['n'].' 0 R';
8681 if (isset($pl['opt']['mk']['if']) AND (is_array($pl['opt']['mk']['if'])) AND !empty($pl['opt']['mk']['if'])) {
8682 $annots .= ' /IF <<';
8683 $if_sw = array('A', 'B', 'S', 'N');
8684 if (isset($pl['opt']['mk']['if']['sw']) AND in_array($pl['opt']['mk']['if']['sw'], $if_sw)) {
8685 $annots .= ' /SW /'.$pl['opt']['mk']['if']['sw'];
8687 $if_s = array('A', 'P');
8688 if (isset($pl['opt']['mk']['if']['s']) AND in_array($pl['opt']['mk']['if']['s'], $if_s)) {
8689 $annots .= ' /S /'.$pl['opt']['mk']['if']['s'];
8691 if (isset($pl['opt']['mk']['if']['a']) AND (is_array($pl['opt']['mk']['if']['a'])) AND !empty($pl['opt']['mk']['if']['a'])) {
8692 $annots .= sprintf(' /A [%F %F]', $pl['opt']['mk']['if']['a'][0], $pl['opt']['mk']['if']['a'][1]);
8694 if (isset($pl['opt']['mk']['if']['fb']) AND ($pl['opt']['mk']['if']['fb'])) {
8695 $annots .= ' /FB true';
8699 if (isset($pl['opt']['mk']['tp']) AND ($pl['opt']['mk']['tp'] >= 0) AND ($pl['opt']['mk']['tp'] <= 6)) {
8700 $annots .= ' /TP '.intval($pl['opt']['mk']['tp']);
8704 // --- Entries for field dictionaries ---
8705 if (isset($this->radiobutton_groups
[$n][$pl['txt']])) {
8707 $annots .= ' /Parent '.$this->radiobutton_groups
[$n][$pl['txt']].' 0 R';
8709 if (isset($pl['opt']['t']) AND is_string($pl['opt']['t'])) {
8710 $annots .= ' /T '.$this->_datastring($pl['opt']['t'], $annot_obj_id);
8712 if (isset($pl['opt']['tu']) AND is_string($pl['opt']['tu'])) {
8713 $annots .= ' /TU '.$this->_datastring($pl['opt']['tu'], $annot_obj_id);
8715 if (isset($pl['opt']['tm']) AND is_string($pl['opt']['tm'])) {
8716 $annots .= ' /TM '.$this->_datastring($pl['opt']['tm'], $annot_obj_id);
8718 if (isset($pl['opt']['ff'])) {
8719 if (is_array($pl['opt']['ff'])) {
8720 // array of bit settings
8722 foreach($pl['opt']['ff'] as $val) {
8723 $flag +
= 1 << ($val - 1);
8726 $flag = intval($pl['opt']['ff']);
8728 $annots .= ' /Ff '.$flag;
8730 if (isset($pl['opt']['maxlen'])) {
8731 $annots .= ' /MaxLen '.intval($pl['opt']['maxlen']);
8733 if (isset($pl['opt']['v'])) {
8735 if (is_array($pl['opt']['v'])) {
8736 foreach ($pl['opt']['v'] AS $optval) {
8737 if (is_float($optval)) {
8738 $optval = sprintf('%F', $optval);
8740 $annots .= ' '.$optval;
8743 $annots .= ' '.$this->_textstring($pl['opt']['v'], $annot_obj_id);
8746 if (isset($pl['opt']['dv'])) {
8748 if (is_array($pl['opt']['dv'])) {
8749 foreach ($pl['opt']['dv'] AS $optval) {
8750 if (is_float($optval)) {
8751 $optval = sprintf('%F', $optval);
8753 $annots .= ' '.$optval;
8756 $annots .= ' '.$this->_textstring($pl['opt']['dv'], $annot_obj_id);
8759 if (isset($pl['opt']['rv'])) {
8761 if (is_array($pl['opt']['rv'])) {
8762 foreach ($pl['opt']['rv'] AS $optval) {
8763 if (is_float($optval)) {
8764 $optval = sprintf('%F', $optval);
8766 $annots .= ' '.$optval;
8769 $annots .= ' '.$this->_textstring($pl['opt']['rv'], $annot_obj_id);
8772 if (isset($pl['opt']['a']) AND !empty($pl['opt']['a'])) {
8773 $annots .= ' /A << '.$pl['opt']['a'].' >>';
8775 if (isset($pl['opt']['aa']) AND !empty($pl['opt']['aa'])) {
8776 $annots .= ' /AA << '.$pl['opt']['aa'].' >>';
8778 if (isset($pl['opt']['da']) AND !empty($pl['opt']['da'])) {
8779 $annots .= ' /DA ('.$pl['opt']['da'].')';
8781 if (isset($pl['opt']['q']) AND ($pl['opt']['q'] >= 0) AND ($pl['opt']['q'] <= 2)) {
8782 $annots .= ' /Q '.intval($pl['opt']['q']);
8784 if (isset($pl['opt']['opt']) AND (is_array($pl['opt']['opt'])) AND !empty($pl['opt']['opt'])) {
8785 $annots .= ' /Opt [';
8786 foreach($pl['opt']['opt'] AS $copt) {
8787 if (is_array($copt)) {
8788 $annots .= ' ['.$this->_textstring($copt[0], $annot_obj_id).' '.$this->_textstring($copt[1], $annot_obj_id).']';
8790 $annots .= ' '.$this->_textstring($copt, $annot_obj_id);
8795 if (isset($pl['opt']['ti'])) {
8796 $annots .= ' /TI '.intval($pl['opt']['ti']);
8798 if (isset($pl['opt']['i']) AND (is_array($pl['opt']['i'])) AND !empty($pl['opt']['i'])) {
8800 foreach($pl['opt']['i'] AS $copt) {
8801 $annots .= intval($copt).' ';
8810 case 'printermark': {
8827 // create new annotation object
8828 $this->_out($this->_getobj($annot_obj_id)."\n".$annots."\n".'endobj');
8829 if ($formfield AND !isset($this->radiobutton_groups
[$n][$pl['txt']])) {
8830 // store reference of form object
8831 $this->form_obj_id
[] = $annot_obj_id;
8835 } // end for each page
8839 * Put appearance streams XObject used to define annotation's appearance states.
8840 * @param int $w annotation width
8841 * @param int $h annotation height
8842 * @param string $stream appearance stream
8843 * @return int object ID
8845 * @since 4.8.001 (2009-09-09)
8847 protected function _putAPXObject($w=0, $h=0, $stream='') {
8848 $stream = trim($stream);
8849 $out = $this->_getobj()."\n";
8850 $this->xobjects
['AX'.$this->n
] = array('n' => $this->n
);
8852 $out .= ' /Type /XObject';
8853 $out .= ' /Subtype /Form';
8854 $out .= ' /FormType 1';
8855 if ($this->compress
) {
8856 $stream = gzcompress($stream);
8857 $out .= ' /Filter /FlateDecode';
8859 $rect = sprintf('%F %F', $w, $h);
8860 $out .= ' /BBox [0 0 '.$rect.']';
8861 $out .= ' /Matrix [1 0 0 1 0 0]';
8862 $out .= ' /Resources 2 0 R';
8863 $stream = $this->_getrawstream($stream);
8864 $out .= ' /Length '.strlen($stream);
8866 $out .= ' stream'."\n".$stream."\n".'endstream';
8867 $out .= "\n".'endobj';
8874 * @author Nicola Asuni
8877 protected function _putfonts() {
8879 foreach ($this->diffs
as $diff) {
8882 $this->_out('<< /Type /Encoding /BaseEncoding /WinAnsiEncoding /Differences ['.$diff.'] >>'."\n".'endobj');
8884 foreach ($this->FontFiles
as $file => $info) {
8885 // search and get font file to embedd
8886 $fontfile = TCPDF_FONTS
::getFontFullPath($file, $info['fontdir']);
8887 if (!TCPDF_STATIC
::empty_string($fontfile)) {
8888 $font = file_get_contents($fontfile);
8889 $compressed = (substr($file, -2) == '.z');
8890 if ((!$compressed) AND (isset($info['length2']))) {
8891 $header = (ord($font[0]) == 128);
8893 // strip first binary header
8894 $font = substr($font, 6);
8896 if ($header AND (ord($font[$info['length1']]) == 128)) {
8897 // strip second binary header
8898 $font = substr($font, 0, $info['length1']).substr($font, ($info['length1'] +
6));
8900 } elseif ($info['subset'] AND ((!$compressed) OR ($compressed AND function_exists('gzcompress')))) {
8903 $font = gzuncompress($font);
8905 // merge subset characters
8906 $subsetchars = array(); // used chars
8907 foreach ($info['fontkeys'] as $fontkey) {
8908 $fontinfo = $this->getFontBuffer($fontkey);
8909 $subsetchars +
= $fontinfo['subsetchars'];
8911 // rebuild a font subset
8912 $font = TCPDF_FONTS
::_getTrueTypeFontSubset($font, $subsetchars);
8913 // calculate new font length
8914 $info['length1'] = strlen($font);
8917 $font = gzcompress($font);
8921 $this->FontFiles
[$file]['n'] = $this->n
;
8922 $stream = $this->_getrawstream($font);
8923 $out = '<< /Length '.strlen($stream);
8925 $out .= ' /Filter /FlateDecode';
8927 $out .= ' /Length1 '.$info['length1'];
8928 if (isset($info['length2'])) {
8929 $out .= ' /Length2 '.$info['length2'].' /Length3 0';
8932 $out .= ' stream'."\n".$stream."\n".'endstream';
8933 $out .= "\n".'endobj';
8937 foreach ($this->fontkeys
as $k) {
8939 $font = $this->getFontBuffer($k);
8940 $type = $font['type'];
8941 $name = $font['name'];
8942 if ($type == 'core') {
8943 // standard core font
8944 $out = $this->_getobj($this->font_obj_ids
[$k])."\n";
8945 $out .= '<</Type /Font';
8946 $out .= ' /Subtype /Type1';
8947 $out .= ' /BaseFont /'.$name;
8948 $out .= ' /Name /F'.$font['i'];
8949 if ((strtolower($name) != 'symbol') AND (strtolower($name) != 'zapfdingbats')) {
8950 $out .= ' /Encoding /WinAnsiEncoding';
8952 if ($k == 'helvetica') {
8953 // add default font for annotations
8954 $this->annotation_fonts
[$k] = $font['i'];
8957 $out .= "\n".'endobj';
8959 } elseif (($type == 'Type1') OR ($type == 'TrueType')) {
8960 // additional Type1 or TrueType font
8961 $out = $this->_getobj($this->font_obj_ids
[$k])."\n";
8962 $out .= '<</Type /Font';
8963 $out .= ' /Subtype /'.$type;
8964 $out .= ' /BaseFont /'.$name;
8965 $out .= ' /Name /F'.$font['i'];
8966 $out .= ' /FirstChar 32 /LastChar 255';
8967 $out .= ' /Widths '.($this->n +
1).' 0 R';
8968 $out .= ' /FontDescriptor '.($this->n +
2).' 0 R';
8970 if (isset($font['diff'])) {
8971 $out .= ' /Encoding '.($nf +
$font['diff']).' 0 R';
8973 $out .= ' /Encoding /WinAnsiEncoding';
8977 $out .= "\n".'endobj';
8982 for ($i = 32; $i < 256; ++
$i) {
8983 if (isset($font['cw'][$i])) {
8984 $s .= $font['cw'][$i].' ';
8986 $s .= $font['dw'].' ';
8990 $s .= "\n".'endobj';
8994 $s = '<</Type /FontDescriptor /FontName /'.$name;
8995 foreach ($font['desc'] as $fdk => $fdv) {
8996 if (is_float($fdv)) {
8997 $fdv = sprintf('%F', $fdv);
8999 $s .= ' /'.$fdk.' '.$fdv.'';
9001 if (!TCPDF_STATIC
::empty_string($font['file'])) {
9002 $s .= ' /FontFile'.($type == 'Type1' ?
'' : '2').' '.$this->FontFiles
[$font['file']]['n'].' 0 R';
9005 $s .= "\n".'endobj';
9009 $mtd = '_put'.strtolower($type);
9010 if (!method_exists($this, $mtd)) {
9011 $this->Error('Unsupported font type: '.$type);
9019 * Adds unicode fonts.<br>
9020 * Based on PDF Reference 1.3 (section 5)
9021 * @param array $font font data
9023 * @author Nicola Asuni
9024 * @since 1.52.0.TC005 (2005-01-05)
9026 protected function _puttruetypeunicode($font) {
9028 if ($font['subset']) {
9029 // change name for font subsetting
9030 $subtag = sprintf('%06u', $font['i']);
9031 $subtag = strtr($subtag, '0123456789', 'ABCDEFGHIJ');
9032 $fontname .= $subtag.'+';
9034 $fontname .= $font['name'];
9036 // A composite font composed of other fonts, organized hierarchically
9037 $out = $this->_getobj($this->font_obj_ids
[$font['fontkey']])."\n";
9038 $out .= '<< /Type /Font';
9039 $out .= ' /Subtype /Type0';
9040 $out .= ' /BaseFont /'.$fontname;
9041 $out .= ' /Name /F'.$font['i'];
9042 $out .= ' /Encoding /'.$font['enc'];
9043 $out .= ' /ToUnicode '.($this->n +
1).' 0 R';
9044 $out .= ' /DescendantFonts ['.($this->n +
2).' 0 R]';
9046 $out .= "\n".'endobj';
9048 // ToUnicode map for Identity-H
9049 $stream = TCPDF_FONT_DATA
::$uni_identity_h;
9052 $stream = ($this->compress
) ?
gzcompress($stream) : $stream;
9053 $filter = ($this->compress
) ?
'/Filter /FlateDecode ' : '';
9054 $stream = $this->_getrawstream($stream);
9055 $this->_out('<<'.$filter.'/Length '.strlen($stream).'>> stream'."\n".$stream."\n".'endstream'."\n".'endobj');
9057 // A CIDFont whose glyph descriptions are based on TrueType font technology
9058 $oid = $this->_newobj();
9059 $out = '<< /Type /Font';
9060 $out .= ' /Subtype /CIDFontType2';
9061 $out .= ' /BaseFont /'.$fontname;
9062 // A dictionary containing entries that define the character collection of the CIDFont.
9063 $cidinfo = '/Registry '.$this->_datastring($font['cidinfo']['Registry'], $oid);
9064 $cidinfo .= ' /Ordering '.$this->_datastring($font['cidinfo']['Ordering'], $oid);
9065 $cidinfo .= ' /Supplement '.$font['cidinfo']['Supplement'];
9066 $out .= ' /CIDSystemInfo << '.$cidinfo.' >>';
9067 $out .= ' /FontDescriptor '.($this->n +
1).' 0 R';
9068 $out .= ' /DW '.$font['dw']; // default width
9069 $out .= "\n".TCPDF_FONTS
::_putfontwidths($font, 0);
9070 if (isset($font['ctg']) AND (!TCPDF_STATIC
::empty_string($font['ctg']))) {
9071 $out .= "\n".'/CIDToGIDMap '.($this->n +
2).' 0 R';
9074 $out .= "\n".'endobj';
9077 // A font descriptor describing the CIDFont default metrics other than its glyph widths
9079 $out = '<< /Type /FontDescriptor';
9080 $out .= ' /FontName /'.$fontname;
9081 foreach ($font['desc'] as $key => $value) {
9082 if (is_float($value)) {
9083 $value = sprintf('%F', $value);
9085 $out .= ' /'.$key.' '.$value;
9088 if (!TCPDF_STATIC
::empty_string($font['file'])) {
9089 // A stream containing a TrueType font
9090 $out .= ' /FontFile2 '.$this->FontFiles
[$font['file']]['n'].' 0 R';
9091 $fontdir = $this->FontFiles
[$font['file']]['fontdir'];
9094 $out .= "\n".'endobj';
9096 if (isset($font['ctg']) AND (!TCPDF_STATIC
::empty_string($font['ctg']))) {
9098 // Embed CIDToGIDMap
9099 // A specification of the mapping from CIDs to glyph indices
9100 // search and get CTG font file to embedd
9101 $ctgfile = strtolower($font['ctg']);
9102 // search and get ctg font file to embedd
9103 $fontfile = TCPDF_FONTS
::getFontFullPath($ctgfile, $fontdir);
9104 if (TCPDF_STATIC
::empty_string($fontfile)) {
9105 $this->Error('Font file not found: '.$ctgfile);
9107 $stream = $this->_getrawstream(file_get_contents($fontfile));
9108 $out = '<< /Length '.strlen($stream).'';
9109 if (substr($fontfile, -2) == '.z') { // check file extension
9110 // Decompresses data encoded using the public-domain
9111 // zlib/deflate compression method, reproducing the
9112 // original text or binary data
9113 $out .= ' /Filter /FlateDecode';
9116 $out .= ' stream'."\n".$stream."\n".'endstream';
9117 $out .= "\n".'endobj';
9123 * Output CID-0 fonts.
9124 * A Type 0 CIDFont contains glyph descriptions based on the Adobe Type 1 font format
9125 * @param array $font font data
9127 * @author Andrew Whitehead, Nicola Asuni, Yukihiro Nakadaira
9128 * @since 3.2.000 (2008-06-23)
9130 protected function _putcidfont0($font) {
9132 if (!isset($font['cw'][1])) {
9135 if (isset($font['cidinfo']['uni2cid'])) {
9136 // convert unicode to cid.
9137 $uni2cid = $font['cidinfo']['uni2cid'];
9139 foreach ($font['cw'] as $uni => $width) {
9140 if (isset($uni2cid[$uni])) {
9141 $cw[($uni2cid[$uni] +
$cidoffset)] = $width;
9142 } elseif ($uni < 256) {
9144 } // else unknown character
9146 $font = array_merge($font, array('cw' => $cw));
9148 $name = $font['name'];
9149 $enc = $font['enc'];
9151 $longname = $name.'-'.$enc;
9155 $out = $this->_getobj($this->font_obj_ids
[$font['fontkey']])."\n";
9156 $out .= '<</Type /Font';
9157 $out .= ' /Subtype /Type0';
9158 $out .= ' /BaseFont /'.$longname;
9159 $out .= ' /Name /F'.$font['i'];
9161 $out .= ' /Encoding /'.$enc;
9163 $out .= ' /DescendantFonts ['.($this->n +
1).' 0 R]';
9165 $out .= "\n".'endobj';
9167 $oid = $this->_newobj();
9168 $out = '<</Type /Font';
9169 $out .= ' /Subtype /CIDFontType0';
9170 $out .= ' /BaseFont /'.$name;
9171 $cidinfo = '/Registry '.$this->_datastring($font['cidinfo']['Registry'], $oid);
9172 $cidinfo .= ' /Ordering '.$this->_datastring($font['cidinfo']['Ordering'], $oid);
9173 $cidinfo .= ' /Supplement '.$font['cidinfo']['Supplement'];
9174 $out .= ' /CIDSystemInfo <<'.$cidinfo.'>>';
9175 $out .= ' /FontDescriptor '.($this->n +
1).' 0 R';
9176 $out .= ' /DW '.$font['dw'];
9177 $out .= "\n".TCPDF_FONTS
::_putfontwidths($font, $cidoffset);
9179 $out .= "\n".'endobj';
9182 $s = '<</Type /FontDescriptor /FontName /'.$name;
9183 foreach ($font['desc'] as $k => $v) {
9184 if ($k != 'Style') {
9186 $v = sprintf('%F', $v);
9188 $s .= ' /'.$k.' '.$v.'';
9192 $s .= "\n".'endobj';
9200 protected function _putimages() {
9201 $filter = ($this->compress
) ?
'/Filter /FlateDecode ' : '';
9202 foreach ($this->imagekeys
as $file) {
9203 $info = $this->getImageBuffer($file);
9204 // set object for alternate images array
9206 if ((!$this->pdfa_mode
) AND isset($info['altimgs']) AND !empty($info['altimgs'])) {
9207 $altoid = $this->_newobj();
9209 foreach ($info['altimgs'] as $altimage) {
9210 if (isset($this->xobjects
['I'.$altimage[0]]['n'])) {
9211 $out .= ' << /Image '.$this->xobjects
['I'.$altimage[0]]['n'].' 0 R';
9212 $out .= ' /DefaultForPrinting';
9213 if ($altimage[1] === true) {
9222 $out .= "\n".'endobj';
9226 $oid = $this->_newobj();
9227 $this->xobjects
['I'.$info['i']] = array('n' => $oid);
9228 $this->setImageSubBuffer($file, 'n', $this->n
);
9229 $out = '<</Type /XObject';
9230 $out .= ' /Subtype /Image';
9231 $out .= ' /Width '.$info['w'];
9232 $out .= ' /Height '.$info['h'];
9233 if (array_key_exists('masked', $info)) {
9234 $out .= ' /SMask '.($this->n
- 1).' 0 R';
9238 if (isset($info['icc']) AND ($info['icc'] !== false)) {
9241 $out .= ' /ColorSpace [/ICCBased '.($this->n +
1).' 0 R]';
9242 } elseif ($info['cs'] == 'Indexed') {
9243 // Indexed Colour Space
9244 $out .= ' /ColorSpace [/Indexed /DeviceRGB '.((strlen($info['pal']) / 3) - 1).' '.($this->n +
1).' 0 R]';
9246 // Device Colour Space
9247 $out .= ' /ColorSpace /'.$info['cs'];
9249 if ($info['cs'] == 'DeviceCMYK') {
9250 $out .= ' /Decode [1 0 1 0 1 0 1 0]';
9252 $out .= ' /BitsPerComponent '.$info['bpc'];
9254 // reference to alternate images dictionary
9255 $out .= ' /Alternates '.$altoid.' 0 R';
9257 if (isset($info['exurl']) AND !empty($info['exurl'])) {
9259 $out .= ' /Length 0';
9260 $out .= ' /F << /FS /URL /F '.$this->_datastring($info['exurl'], $oid).' >>';
9261 if (isset($info['f'])) {
9262 $out .= ' /FFilter /'.$info['f'];
9265 $out .= ' stream'."\n".'endstream';
9267 if (isset($info['f'])) {
9268 $out .= ' /Filter /'.$info['f'];
9270 if (isset($info['parms'])) {
9271 $out .= ' '.$info['parms'];
9273 if (isset($info['trns']) AND is_array($info['trns'])) {
9275 $count_info = count($info['trns']);
9276 if ($info['cs'] == 'Indexed') {
9277 $maxval =(pow(2, $info['bpc']) - 1);
9278 for ($i = 0; $i < $count_info; ++
$i) {
9279 if (($info['trns'][$i] != 0) AND ($info['trns'][$i] != $maxval)) {
9280 // this is not a binary type mask @TODO: create a SMask
9283 } elseif (empty($trns) AND ($info['trns'][$i] == 0)) {
9284 // store the first fully transparent value
9285 $trns .= $i.' '.$i.' ';
9290 for ($i = 0; $i < $count_info; ++
$i) {
9291 if ($info['trns'][$i] == 0) {
9292 $trns .= $info['trns'][$i].' '.$info['trns'][$i].' ';
9296 // Colour Key Masking
9297 if (!empty($trns)) {
9298 $out .= ' /Mask ['.$trns.']';
9301 $stream = $this->_getrawstream($info['data']);
9302 $out .= ' /Length '.strlen($stream).' >>';
9303 $out .= ' stream'."\n".$stream."\n".'endstream';
9305 $out .= "\n".'endobj';
9308 // ICC colour profile
9310 $icc = ($this->compress
) ?
gzcompress($info['icc']) : $info['icc'];
9311 $icc = $this->_getrawstream($icc);
9312 $this->_out('<</N '.$info['ch'].' /Alternate /'.$info['cs'].' '.$filter.'/Length '.strlen($icc).'>> stream'."\n".$icc."\n".'endstream'."\n".'endobj');
9313 } elseif ($info['cs'] == 'Indexed') {
9316 $pal = ($this->compress
) ?
gzcompress($info['pal']) : $info['pal'];
9317 $pal = $this->_getrawstream($pal);
9318 $this->_out('<<'.$filter.'/Length '.strlen($pal).'>> stream'."\n".$pal."\n".'endstream'."\n".'endobj');
9324 * Output Form XObjects Templates.
9325 * @author Nicola Asuni
9326 * @since 5.8.017 (2010-08-24)
9328 * @see startTemplate(), endTemplate(), printTemplate()
9330 protected function _putxobjects() {
9331 foreach ($this->xobjects
as $key => $data) {
9332 if (isset($data['outdata'])) {
9333 $stream = str_replace($this->epsmarker
, '', trim($data['outdata']));
9334 $out = $this->_getobj($data['n'])."\n";
9336 $out .= ' /Type /XObject';
9337 $out .= ' /Subtype /Form';
9338 $out .= ' /FormType 1';
9339 if ($this->compress
) {
9340 $stream = gzcompress($stream);
9341 $out .= ' /Filter /FlateDecode';
9343 $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
));
9344 $out .= ' /Matrix [1 0 0 1 0 0]';
9345 $out .= ' /Resources <<';
9346 $out .= ' /ProcSet [/PDF /Text /ImageB /ImageC /ImageI]';
9347 if (!$this->pdfa_mode ||
$this->pdfa_version
>= 2) {
9349 if (isset($data['extgstates']) AND !empty($data['extgstates'])) {
9350 $out .= ' /ExtGState <<';
9351 foreach ($data['extgstates'] as $k => $extgstate) {
9352 if (isset($this->extgstates
[$k]['name'])) {
9353 $out .= ' /'.$this->extgstates
[$k]['name'];
9357 $out .= ' '.$this->extgstates
[$k]['n'].' 0 R';
9361 if (isset($data['gradients']) AND !empty($data['gradients'])) {
9364 foreach ($data['gradients'] as $id => $grad) {
9365 // gradient patterns
9366 $gp .= ' /p'.$id.' '.$this->gradients
[$id]['pattern'].' 0 R';
9367 // gradient shadings
9368 $gs .= ' /Sh'.$id.' '.$this->gradients
[$id]['id'].' 0 R';
9370 $out .= ' /Pattern <<'.$gp.' >>';
9371 $out .= ' /Shading <<'.$gs.' >>';
9375 if (isset($data['spot_colors']) AND !empty($data['spot_colors'])) {
9376 $out .= ' /ColorSpace <<';
9377 foreach ($data['spot_colors'] as $name => $color) {
9378 $out .= ' /CS'.$color['i'].' '.$this->spot_colors
[$name]['n'].' 0 R';
9383 if (!empty($data['fonts'])) {
9384 $out .= ' /Font <<';
9385 foreach ($data['fonts'] as $fontkey => $fontid) {
9386 $out .= ' /F'.$fontid.' '.$this->font_obj_ids
[$fontkey].' 0 R';
9390 // images or nested xobjects
9391 if (!empty($data['images']) OR !empty($data['xobjects'])) {
9392 $out .= ' /XObject <<';
9393 foreach ($data['images'] as $imgid) {
9394 $out .= ' /I'.$imgid.' '.$this->xobjects
['I'.$imgid]['n'].' 0 R';
9396 foreach ($data['xobjects'] as $sub_id => $sub_objid) {
9397 $out .= ' /'.$sub_id.' '.$sub_objid['n'].' 0 R';
9401 $out .= ' >>'; //end resources
9402 if (isset($data['group']) AND ($data['group'] !== false)) {
9403 // set transparency group
9404 $out .= ' /Group << /Type /Group /S /Transparency';
9405 if (is_array($data['group'])) {
9406 if (isset($data['group']['CS']) AND !empty($data['group']['CS'])) {
9407 $out .= ' /CS /'.$data['group']['CS'];
9409 if (isset($data['group']['I'])) {
9410 $out .= ' /I /'.($data['group']['I']===true?
'true':'false');
9412 if (isset($data['group']['K'])) {
9413 $out .= ' /K /'.($data['group']['K']===true?
'true':'false');
9418 $stream = $this->_getrawstream($stream, $data['n']);
9419 $out .= ' /Length '.strlen($stream);
9421 $out .= ' stream'."\n".$stream."\n".'endstream';
9422 $out .= "\n".'endobj';
9429 * Output Spot Colors Resources.
9431 * @since 4.0.024 (2008-09-12)
9433 protected function _putspotcolors() {
9434 foreach ($this->spot_colors
as $name => $color) {
9436 $this->spot_colors
[$name]['n'] = $this->n
;
9437 $out = '[/Separation /'.str_replace(' ', '#20', $name);
9438 $out .= ' /DeviceCMYK <<';
9439 $out .= ' /Range [0 1 0 1 0 1 0 1] /C0 [0 0 0 0]';
9440 $out .= ' '.sprintf('/C1 [%F %F %F %F] ', ($color['C'] / 100), ($color['M'] / 100), ($color['Y'] / 100), ($color['K'] / 100));
9441 $out .= ' /FunctionType 2 /Domain [0 1] /N 1>>]';
9442 $out .= "\n".'endobj';
9448 * Return XObjects Dictionary.
9449 * @return string XObjects dictionary
9451 * @since 5.8.014 (2010-08-23)
9453 protected function _getxobjectdict() {
9455 foreach ($this->xobjects
as $id => $objid) {
9456 $out .= ' /'.$id.' '.$objid['n'].' 0 R';
9462 * Output Resources Dictionary.
9465 protected function _putresourcedict() {
9466 $out = $this->_getobj(2)."\n";
9467 $out .= '<< /ProcSet [/PDF /Text /ImageB /ImageC /ImageI]';
9468 $out .= ' /Font <<';
9469 foreach ($this->fontkeys
as $fontkey) {
9470 $font = $this->getFontBuffer($fontkey);
9471 $out .= ' /F'.$font['i'].' '.$font['n'].' 0 R';
9474 $out .= ' /XObject <<';
9475 $out .= $this->_getxobjectdict();
9478 if (!empty($this->pdflayers
)) {
9479 $out .= ' /Properties <<';
9480 foreach ($this->pdflayers
as $layer) {
9481 $out .= ' /'.$layer['layer'].' '.$layer['objid'].' 0 R';
9485 if (!$this->pdfa_mode ||
$this->pdfa_version
>= 2) {
9487 if (isset($this->extgstates
) AND !empty($this->extgstates
)) {
9488 $out .= ' /ExtGState <<';
9489 foreach ($this->extgstates
as $k => $extgstate) {
9490 if (isset($extgstate['name'])) {
9491 $out .= ' /'.$extgstate['name'];
9495 $out .= ' '.$extgstate['n'].' 0 R';
9499 if (isset($this->gradients
) AND !empty($this->gradients
)) {
9502 foreach ($this->gradients
as $id => $grad) {
9503 // gradient patterns
9504 $gp .= ' /p'.$id.' '.$grad['pattern'].' 0 R';
9505 // gradient shadings
9506 $gs .= ' /Sh'.$id.' '.$grad['id'].' 0 R';
9508 $out .= ' /Pattern <<'.$gp.' >>';
9509 $out .= ' /Shading <<'.$gs.' >>';
9513 if (isset($this->spot_colors
) AND !empty($this->spot_colors
)) {
9514 $out .= ' /ColorSpace <<';
9515 foreach ($this->spot_colors
as $color) {
9516 $out .= ' /CS'.$color['i'].' '.$color['n'].' 0 R';
9521 $out .= "\n".'endobj';
9529 protected function _putresources() {
9530 $this->_putextgstates();
9533 $this->_putimages();
9534 $this->_putspotcolors();
9535 $this->_putshaders();
9536 $this->_putxobjects();
9537 $this->_putresourcedict();
9539 $this->_putEmbeddedFiles();
9540 $this->_putannotsobjs();
9541 $this->_putjavascript();
9542 $this->_putbookmarks();
9543 $this->_putencryption();
9547 * Adds some Metadata information (Document Information Dictionary)
9548 * (see Chapter 14.3.3 Document Information Dictionary of PDF32000_2008.pdf Reference)
9549 * @return int object id
9552 protected function _putinfo() {
9553 $oid = $this->_newobj();
9555 // store current isunicode value
9556 $prev_isunicode = $this->isunicode
;
9557 if ($this->docinfounicode
) {
9558 $this->isunicode
= true;
9560 if (!TCPDF_STATIC
::empty_string($this->title
)) {
9561 // The document's title.
9562 $out .= ' /Title '.$this->_textstring($this->title
, $oid);
9564 if (!TCPDF_STATIC
::empty_string($this->author
)) {
9565 // The name of the person who created the document.
9566 $out .= ' /Author '.$this->_textstring($this->author
, $oid);
9568 if (!TCPDF_STATIC
::empty_string($this->subject
)) {
9569 // The subject of the document.
9570 $out .= ' /Subject '.$this->_textstring($this->subject
, $oid);
9572 if (!TCPDF_STATIC
::empty_string($this->keywords
)) {
9573 // Keywords associated with the document.
9574 $out .= ' /Keywords '.$this->_textstring($this->keywords
, $oid);
9576 if (!TCPDF_STATIC
::empty_string($this->creator
)) {
9577 // 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.
9578 $out .= ' /Creator '.$this->_textstring($this->creator
, $oid);
9580 // restore previous isunicode value
9581 $this->isunicode
= $prev_isunicode;
9583 $out .= ' /Producer '.$this->_textstring(TCPDF_STATIC
::getTCPDFProducer(), $oid);
9584 // The date and time the document was created, in human-readable form
9585 $out .= ' /CreationDate '.$this->_datestring(0, $this->doc_creation_timestamp
);
9586 // The date and time the document was most recently modified, in human-readable form
9587 $out .= ' /ModDate '.$this->_datestring(0, $this->doc_modification_timestamp
);
9588 // A name object indicating whether the document has been modified to include trapping information
9589 $out .= ' /Trapped /False';
9591 $out .= "\n".'endobj';
9597 * Set additional XMP data to be added on the default XMP data just before the end of "x:xmpmeta" tag.
9598 * IMPORTANT: This data is added as-is without controls, so you have to validate your data before using this method!
9599 * @param string $xmp Custom XMP data.
9600 * @since 5.9.128 (2011-10-06)
9603 public function setExtraXMP($xmp) {
9604 $this->custom_xmp
= $xmp;
9608 * Set additional XMP data to be added on the default XMP data just before the end of "rdf:RDF" tag.
9609 * IMPORTANT: This data is added as-is without controls, so you have to validate your data before using this method!
9610 * @param string $xmp Custom XMP RDF data.
9611 * @since 6.3.0 (2019-09-19)
9614 public function setExtraXMPRDF($xmp) {
9615 $this->custom_xmp_rdf
= $xmp;
9619 * Put XMP data object and return ID.
9620 * @return int The object ID.
9621 * @since 5.9.121 (2011-09-28)
9624 protected function _putXMP() {
9625 $oid = $this->_newobj();
9626 // store current isunicode value
9627 $prev_isunicode = $this->isunicode
;
9628 $this->isunicode
= true;
9629 $prev_encrypted = $this->encrypted
;
9630 $this->encrypted
= false;
9632 $xmp = '<?xpacket begin="'.TCPDF_FONTS
::unichr(0xfeff, $this->isunicode
).'" id="W5M0MpCehiHzreSzNTczkc9d"?>'."\n";
9633 $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";
9634 $xmp .= "\t".'<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">'."\n";
9635 $xmp .= "\t\t".'<rdf:Description rdf:about="" xmlns:dc="http://purl.org/dc/elements/1.1/">'."\n";
9636 $xmp .= "\t\t\t".'<dc:format>application/pdf</dc:format>'."\n";
9637 $xmp .= "\t\t\t".'<dc:title>'."\n";
9638 $xmp .= "\t\t\t\t".'<rdf:Alt>'."\n";
9639 $xmp .= "\t\t\t\t\t".'<rdf:li xml:lang="x-default">'.TCPDF_STATIC
::_escapeXML($this->title
).'</rdf:li>'."\n";
9640 $xmp .= "\t\t\t\t".'</rdf:Alt>'."\n";
9641 $xmp .= "\t\t\t".'</dc:title>'."\n";
9642 $xmp .= "\t\t\t".'<dc:creator>'."\n";
9643 $xmp .= "\t\t\t\t".'<rdf:Seq>'."\n";
9644 $xmp .= "\t\t\t\t\t".'<rdf:li>'.TCPDF_STATIC
::_escapeXML($this->author
).'</rdf:li>'."\n";
9645 $xmp .= "\t\t\t\t".'</rdf:Seq>'."\n";
9646 $xmp .= "\t\t\t".'</dc:creator>'."\n";
9647 $xmp .= "\t\t\t".'<dc:description>'."\n";
9648 $xmp .= "\t\t\t\t".'<rdf:Alt>'."\n";
9649 $xmp .= "\t\t\t\t\t".'<rdf:li xml:lang="x-default">'.TCPDF_STATIC
::_escapeXML($this->subject
).'</rdf:li>'."\n";
9650 $xmp .= "\t\t\t\t".'</rdf:Alt>'."\n";
9651 $xmp .= "\t\t\t".'</dc:description>'."\n";
9652 $xmp .= "\t\t\t".'<dc:subject>'."\n";
9653 $xmp .= "\t\t\t\t".'<rdf:Bag>'."\n";
9654 $xmp .= "\t\t\t\t\t".'<rdf:li>'.TCPDF_STATIC
::_escapeXML($this->keywords
).'</rdf:li>'."\n";
9655 $xmp .= "\t\t\t\t".'</rdf:Bag>'."\n";
9656 $xmp .= "\t\t\t".'</dc:subject>'."\n";
9657 $xmp .= "\t\t".'</rdf:Description>'."\n";
9658 // convert doc creation date format
9659 $dcdate = TCPDF_STATIC
::getFormattedDate($this->doc_creation_timestamp
);
9660 $doccreationdate = substr($dcdate, 0, 4).'-'.substr($dcdate, 4, 2).'-'.substr($dcdate, 6, 2);
9661 $doccreationdate .= 'T'.substr($dcdate, 8, 2).':'.substr($dcdate, 10, 2).':'.substr($dcdate, 12, 2);
9662 $doccreationdate .= substr($dcdate, 14, 3).':'.substr($dcdate, 18, 2);
9663 $doccreationdate = TCPDF_STATIC
::_escapeXML($doccreationdate);
9664 // convert doc modification date format
9665 $dmdate = TCPDF_STATIC
::getFormattedDate($this->doc_modification_timestamp
);
9666 $docmoddate = substr($dmdate, 0, 4).'-'.substr($dmdate, 4, 2).'-'.substr($dmdate, 6, 2);
9667 $docmoddate .= 'T'.substr($dmdate, 8, 2).':'.substr($dmdate, 10, 2).':'.substr($dmdate, 12, 2);
9668 $docmoddate .= substr($dmdate, 14, 3).':'.substr($dmdate, 18, 2);
9669 $docmoddate = TCPDF_STATIC
::_escapeXML($docmoddate);
9670 $xmp .= "\t\t".'<rdf:Description rdf:about="" xmlns:xmp="http://ns.adobe.com/xap/1.0/">'."\n";
9671 $xmp .= "\t\t\t".'<xmp:CreateDate>'.$doccreationdate.'</xmp:CreateDate>'."\n";
9672 $xmp .= "\t\t\t".'<xmp:CreatorTool>'.$this->creator
.'</xmp:CreatorTool>'."\n";
9673 $xmp .= "\t\t\t".'<xmp:ModifyDate>'.$docmoddate.'</xmp:ModifyDate>'."\n";
9674 $xmp .= "\t\t\t".'<xmp:MetadataDate>'.$doccreationdate.'</xmp:MetadataDate>'."\n";
9675 $xmp .= "\t\t".'</rdf:Description>'."\n";
9676 $xmp .= "\t\t".'<rdf:Description rdf:about="" xmlns:pdf="http://ns.adobe.com/pdf/1.3/">'."\n";
9677 $xmp .= "\t\t\t".'<pdf:Keywords>'.TCPDF_STATIC
::_escapeXML($this->keywords
).'</pdf:Keywords>'."\n";
9678 $xmp .= "\t\t\t".'<pdf:Producer>'.TCPDF_STATIC
::_escapeXML(TCPDF_STATIC
::getTCPDFProducer()).'</pdf:Producer>'."\n";
9679 $xmp .= "\t\t".'</rdf:Description>'."\n";
9680 $xmp .= "\t\t".'<rdf:Description rdf:about="" xmlns:xmpMM="http://ns.adobe.com/xap/1.0/mm/">'."\n";
9681 $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);
9682 $xmp .= "\t\t\t".'<xmpMM:DocumentID>'.$uuid.'</xmpMM:DocumentID>'."\n";
9683 $xmp .= "\t\t\t".'<xmpMM:InstanceID>'.$uuid.'</xmpMM:InstanceID>'."\n";
9684 $xmp .= "\t\t".'</rdf:Description>'."\n";
9685 if ($this->pdfa_mode
) {
9686 $xmp .= "\t\t".'<rdf:Description rdf:about="" xmlns:pdfaid="http://www.aiim.org/pdfa/ns/id/">'."\n";
9687 $xmp .= "\t\t\t".'<pdfaid:part>'.$this->pdfa_version
.'</pdfaid:part>'."\n";
9688 $xmp .= "\t\t\t".'<pdfaid:conformance>B</pdfaid:conformance>'."\n";
9689 $xmp .= "\t\t".'</rdf:Description>'."\n";
9691 // XMP extension schemas
9692 $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";
9693 $xmp .= "\t\t\t".'<pdfaExtension:schemas>'."\n";
9694 $xmp .= "\t\t\t\t".'<rdf:Bag>'."\n";
9695 $xmp .= "\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
9696 $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:namespaceURI>http://ns.adobe.com/pdf/1.3/</pdfaSchema:namespaceURI>'."\n";
9697 $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:prefix>pdf</pdfaSchema:prefix>'."\n";
9698 $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:schema>Adobe PDF Schema</pdfaSchema:schema>'."\n";
9699 $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:property>'."\n";
9700 $xmp .= "\t\t\t\t\t\t\t".'<rdf:Seq>'."\n";
9701 $xmp .= "\t\t\t\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
9702 $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:category>internal</pdfaProperty:category>'."\n";
9703 $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:description>Adobe PDF Schema</pdfaProperty:description>'."\n";
9704 $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:name>InstanceID</pdfaProperty:name>'."\n";
9705 $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:valueType>URI</pdfaProperty:valueType>'."\n";
9706 $xmp .= "\t\t\t\t\t\t\t\t".'</rdf:li>'."\n";
9707 $xmp .= "\t\t\t\t\t\t\t".'</rdf:Seq>'."\n";
9708 $xmp .= "\t\t\t\t\t\t".'</pdfaSchema:property>'."\n";
9709 $xmp .= "\t\t\t\t\t".'</rdf:li>'."\n";
9710 $xmp .= "\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
9711 $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:namespaceURI>http://ns.adobe.com/xap/1.0/mm/</pdfaSchema:namespaceURI>'."\n";
9712 $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:prefix>xmpMM</pdfaSchema:prefix>'."\n";
9713 $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:schema>XMP Media Management Schema</pdfaSchema:schema>'."\n";
9714 $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:property>'."\n";
9715 $xmp .= "\t\t\t\t\t\t\t".'<rdf:Seq>'."\n";
9716 $xmp .= "\t\t\t\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
9717 $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:category>internal</pdfaProperty:category>'."\n";
9718 $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:description>UUID based identifier for specific incarnation of a document</pdfaProperty:description>'."\n";
9719 $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:name>InstanceID</pdfaProperty:name>'."\n";
9720 $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:valueType>URI</pdfaProperty:valueType>'."\n";
9721 $xmp .= "\t\t\t\t\t\t\t\t".'</rdf:li>'."\n";
9722 $xmp .= "\t\t\t\t\t\t\t".'</rdf:Seq>'."\n";
9723 $xmp .= "\t\t\t\t\t\t".'</pdfaSchema:property>'."\n";
9724 $xmp .= "\t\t\t\t\t".'</rdf:li>'."\n";
9725 $xmp .= "\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
9726 $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:namespaceURI>http://www.aiim.org/pdfa/ns/id/</pdfaSchema:namespaceURI>'."\n";
9727 $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:prefix>pdfaid</pdfaSchema:prefix>'."\n";
9728 $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:schema>PDF/A ID Schema</pdfaSchema:schema>'."\n";
9729 $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:property>'."\n";
9730 $xmp .= "\t\t\t\t\t\t\t".'<rdf:Seq>'."\n";
9731 $xmp .= "\t\t\t\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
9732 $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:category>internal</pdfaProperty:category>'."\n";
9733 $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:description>Part of PDF/A standard</pdfaProperty:description>'."\n";
9734 $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:name>part</pdfaProperty:name>'."\n";
9735 $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:valueType>Integer</pdfaProperty:valueType>'."\n";
9736 $xmp .= "\t\t\t\t\t\t\t\t".'</rdf:li>'."\n";
9737 $xmp .= "\t\t\t\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
9738 $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:category>internal</pdfaProperty:category>'."\n";
9739 $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:description>Amendment of PDF/A standard</pdfaProperty:description>'."\n";
9740 $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:name>amd</pdfaProperty:name>'."\n";
9741 $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:valueType>Text</pdfaProperty:valueType>'."\n";
9742 $xmp .= "\t\t\t\t\t\t\t\t".'</rdf:li>'."\n";
9743 $xmp .= "\t\t\t\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
9744 $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:category>internal</pdfaProperty:category>'."\n";
9745 $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:description>Conformance level of PDF/A standard</pdfaProperty:description>'."\n";
9746 $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:name>conformance</pdfaProperty:name>'."\n";
9747 $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:valueType>Text</pdfaProperty:valueType>'."\n";
9748 $xmp .= "\t\t\t\t\t\t\t\t".'</rdf:li>'."\n";
9749 $xmp .= "\t\t\t\t\t\t\t".'</rdf:Seq>'."\n";
9750 $xmp .= "\t\t\t\t\t\t".'</pdfaSchema:property>'."\n";
9751 $xmp .= "\t\t\t\t\t".'</rdf:li>'."\n";
9752 $xmp .= "\t\t\t\t".'</rdf:Bag>'."\n";
9753 $xmp .= "\t\t\t".'</pdfaExtension:schemas>'."\n";
9754 $xmp .= "\t\t".'</rdf:Description>'."\n";
9755 $xmp .= $this->custom_xmp_rdf
;
9756 $xmp .= "\t".'</rdf:RDF>'."\n";
9757 $xmp .= $this->custom_xmp
;
9758 $xmp .= '</x:xmpmeta>'."\n";
9759 $xmp .= '<?xpacket end="w"?>';
9760 $out = '<< /Type /Metadata /Subtype /XML /Length '.strlen($xmp).' >> stream'."\n".$xmp."\n".'endstream'."\n".'endobj';
9761 // restore previous isunicode value
9762 $this->isunicode
= $prev_isunicode;
9763 $this->encrypted
= $prev_encrypted;
9770 * @return int object id
9773 protected function _putcatalog() {
9775 $xmpobj = $this->_putXMP();
9776 // if required, add standard sRGB ICC colour profile
9777 if ($this->pdfa_mode
OR $this->force_srgb
) {
9778 $iccobj = $this->_newobj();
9779 $icc = file_get_contents(dirname(__FILE__
).'/include/sRGB.icc');
9781 if ($this->compress
) {
9782 $filter = ' /Filter /FlateDecode';
9783 $icc = gzcompress($icc);
9785 $icc = $this->_getrawstream($icc);
9786 $this->_out('<</N 3 '.$filter.'/Length '.strlen($icc).'>> stream'."\n".$icc."\n".'endstream'."\n".'endobj');
9789 $oid = $this->_newobj();
9790 $out = '<< /Type /Catalog';
9791 $out .= ' /Version /'.$this->PDFVersion
;
9792 //$out .= ' /Extensions <<>>';
9793 $out .= ' /Pages 1 0 R';
9794 //$out .= ' /PageLabels ' //...;
9795 $out .= ' /Names <<';
9796 if ((!$this->pdfa_mode
) AND !empty($this->n_js
)) {
9797 $out .= ' /JavaScript '.$this->n_js
;
9799 if (!empty($this->efnames
)) {
9800 $out .= ' /EmbeddedFiles <</Names [';
9801 foreach ($this->efnames
AS $fn => $fref) {
9802 $out .= ' '.$this->_datastring($fn).' '.$fref;
9807 if (!empty($this->dests
)) {
9808 $out .= ' /Dests '.($this->n_dests
).' 0 R';
9810 $out .= $this->_putviewerpreferences();
9811 if (isset($this->LayoutMode
) AND (!TCPDF_STATIC
::empty_string($this->LayoutMode
))) {
9812 $out .= ' /PageLayout /'.$this->LayoutMode
;
9814 if (isset($this->PageMode
) AND (!TCPDF_STATIC
::empty_string($this->PageMode
))) {
9815 $out .= ' /PageMode /'.$this->PageMode
;
9817 if (count($this->outlines
) > 0) {
9818 $out .= ' /Outlines '.$this->OutlineRoot
.' 0 R';
9819 $out .= ' /PageMode /UseOutlines';
9821 //$out .= ' /Threads []';
9822 if ($this->ZoomMode
== 'fullpage') {
9823 $out .= ' /OpenAction ['.$this->page_obj_id
[1].' 0 R /Fit]';
9824 } elseif ($this->ZoomMode
== 'fullwidth') {
9825 $out .= ' /OpenAction ['.$this->page_obj_id
[1].' 0 R /FitH null]';
9826 } elseif ($this->ZoomMode
== 'real') {
9827 $out .= ' /OpenAction ['.$this->page_obj_id
[1].' 0 R /XYZ null null 1]';
9828 } elseif (!is_string($this->ZoomMode
)) {
9829 $out .= sprintf(' /OpenAction ['.$this->page_obj_id
[1].' 0 R /XYZ null null %F]', ($this->ZoomMode
/ 100));
9831 //$out .= ' /AA <<>>';
9832 //$out .= ' /URI <<>>';
9833 $out .= ' /Metadata '.$xmpobj.' 0 R';
9834 //$out .= ' /StructTreeRoot <<>>';
9835 //$out .= ' /MarkInfo <<>>';
9836 if (isset($this->l
['a_meta_language'])) {
9837 $out .= ' /Lang '.$this->_textstring($this->l
['a_meta_language'], $oid);
9839 //$out .= ' /SpiderInfo <<>>';
9840 // set OutputIntent to sRGB IEC61966-2.1 if required
9841 if ($this->pdfa_mode
OR $this->force_srgb
) {
9842 $out .= ' /OutputIntents [<<';
9843 $out .= ' /Type /OutputIntent';
9844 $out .= ' /S /GTS_PDFA1';
9845 $out .= ' /OutputCondition '.$this->_textstring('sRGB IEC61966-2.1', $oid);
9846 $out .= ' /OutputConditionIdentifier '.$this->_textstring('sRGB IEC61966-2.1', $oid);
9847 $out .= ' /RegistryName '.$this->_textstring('http://www.color.org', $oid);
9848 $out .= ' /Info '.$this->_textstring('sRGB IEC61966-2.1', $oid);
9849 $out .= ' /DestOutputProfile '.$iccobj.' 0 R';
9852 //$out .= ' /PieceInfo <<>>';
9853 if (!empty($this->pdflayers
)) {
9857 foreach ($this->pdflayers
as $layer) {
9858 $layer_obj_ref = ' '.$layer['objid'].' 0 R';
9859 $lyrobjs .= $layer_obj_ref;
9860 if ($layer['view'] === false) {
9861 $lyrobjs_off .= $layer_obj_ref;
9863 if ($layer['lock']) {
9864 $lyrobjs_lock .= $layer_obj_ref;
9867 $out .= ' /OCProperties << /OCGs ['.$lyrobjs.']';
9869 $out .= ' /Name '.$this->_textstring('Layers', $oid);
9870 $out .= ' /Creator '.$this->_textstring('TCPDF', $oid);
9871 $out .= ' /BaseState /ON';
9872 $out .= ' /OFF ['.$lyrobjs_off.']';
9873 $out .= ' /Locked ['.$lyrobjs_lock.']';
9874 $out .= ' /Intent /View';
9876 $out .= ' << /Event /Print /OCGs ['.$lyrobjs.'] /Category [/Print] >>';
9877 $out .= ' << /Event /View /OCGs ['.$lyrobjs.'] /Category [/View] >>';
9879 $out .= ' /Order ['.$lyrobjs.']';
9880 $out .= ' /ListMode /AllPages';
9881 //$out .= ' /RBGroups ['..']';
9882 //$out .= ' /Locked ['..']';
9887 if (!empty($this->form_obj_id
)
9888 OR ($this->sign
AND isset($this->signature_data
['cert_type']))
9889 OR !empty($this->empty_signature_appearance
)) {
9890 $out .= ' /AcroForm <<';
9892 if ($this->sign
AND isset($this->signature_data
['cert_type'])) {
9893 // set reference for signature object
9894 $objrefs .= $this->sig_obj_id
.' 0 R';
9896 if (!empty($this->empty_signature_appearance
)) {
9897 foreach ($this->empty_signature_appearance
as $esa) {
9898 // set reference for empty signature objects
9899 $objrefs .= ' '.$esa['objid'].' 0 R';
9902 if (!empty($this->form_obj_id
)) {
9903 foreach($this->form_obj_id
as $objid) {
9904 $objrefs .= ' '.$objid.' 0 R';
9907 $out .= ' /Fields ['.$objrefs.']';
9908 // It's better to turn off this value and set the appearance stream for each annotation (/AP) to avoid conflicts with signature fields.
9909 if (empty($this->signature_data
['approval']) OR ($this->signature_data
['approval'] != 'A')) {
9910 $out .= ' /NeedAppearances false';
9912 if ($this->sign
AND isset($this->signature_data
['cert_type'])) {
9913 if ($this->signature_data
['cert_type'] > 0) {
9914 $out .= ' /SigFlags 3';
9916 $out .= ' /SigFlags 1';
9920 if (isset($this->annotation_fonts
) AND !empty($this->annotation_fonts
)) {
9922 $out .= ' /Font <<';
9923 foreach ($this->annotation_fonts
as $fontkey => $fontid) {
9924 $out .= ' /F'.$fontid.' '.$this->font_obj_ids
[$fontkey].' 0 R';
9928 $font = $this->getFontBuffer('helvetica');
9929 $out .= ' /DA (/F'.$font['i'].' 0 Tf 0 g)';
9930 $out .= ' /Q '.(($this->rtl
)?
'2':'0');
9934 if ($this->sign
AND isset($this->signature_data
['cert_type'])
9935 AND (empty($this->signature_data
['approval']) OR ($this->signature_data
['approval'] != 'A'))) {
9936 if ($this->signature_data
['cert_type'] > 0) {
9937 $out .= ' /Perms << /DocMDP '.($this->sig_obj_id +
1).' 0 R >>';
9939 $out .= ' /Perms << /UR3 '.($this->sig_obj_id +
1).' 0 R >>';
9943 //$out .= ' /Legal <<>>';
9944 //$out .= ' /Requirements []';
9945 //$out .= ' /Collection <<>>';
9946 //$out .= ' /NeedsRendering true';
9948 $out .= "\n".'endobj';
9954 * Output viewer preferences.
9955 * @return string for viewer preferences
9956 * @author Nicola asuni
9957 * @since 3.1.000 (2008-06-09)
9960 protected function _putviewerpreferences() {
9961 $vp = $this->viewer_preferences
;
9962 $out = ' /ViewerPreferences <<';
9964 $out .= ' /Direction /R2L';
9966 $out .= ' /Direction /L2R';
9968 if (isset($vp['HideToolbar']) AND ($vp['HideToolbar'])) {
9969 $out .= ' /HideToolbar true';
9971 if (isset($vp['HideMenubar']) AND ($vp['HideMenubar'])) {
9972 $out .= ' /HideMenubar true';
9974 if (isset($vp['HideWindowUI']) AND ($vp['HideWindowUI'])) {
9975 $out .= ' /HideWindowUI true';
9977 if (isset($vp['FitWindow']) AND ($vp['FitWindow'])) {
9978 $out .= ' /FitWindow true';
9980 if (isset($vp['CenterWindow']) AND ($vp['CenterWindow'])) {
9981 $out .= ' /CenterWindow true';
9983 if (isset($vp['DisplayDocTitle']) AND ($vp['DisplayDocTitle'])) {
9984 $out .= ' /DisplayDocTitle true';
9986 if (isset($vp['NonFullScreenPageMode'])) {
9987 $out .= ' /NonFullScreenPageMode /'.$vp['NonFullScreenPageMode'];
9989 if (isset($vp['ViewArea'])) {
9990 $out .= ' /ViewArea /'.$vp['ViewArea'];
9992 if (isset($vp['ViewClip'])) {
9993 $out .= ' /ViewClip /'.$vp['ViewClip'];
9995 if (isset($vp['PrintArea'])) {
9996 $out .= ' /PrintArea /'.$vp['PrintArea'];
9998 if (isset($vp['PrintClip'])) {
9999 $out .= ' /PrintClip /'.$vp['PrintClip'];
10001 if (isset($vp['PrintScaling'])) {
10002 $out .= ' /PrintScaling /'.$vp['PrintScaling'];
10004 if (isset($vp['Duplex']) AND (!TCPDF_STATIC
::empty_string($vp['Duplex']))) {
10005 $out .= ' /Duplex /'.$vp['Duplex'];
10007 if (isset($vp['PickTrayByPDFSize'])) {
10008 if ($vp['PickTrayByPDFSize']) {
10009 $out .= ' /PickTrayByPDFSize true';
10011 $out .= ' /PickTrayByPDFSize false';
10014 if (isset($vp['PrintPageRange'])) {
10015 $PrintPageRangeNum = '';
10016 foreach ($vp['PrintPageRange'] as $k => $v) {
10017 $PrintPageRangeNum .= ' '.($v - 1).'';
10019 $out .= ' /PrintPageRange ['.substr($PrintPageRangeNum,1).']';
10021 if (isset($vp['NumCopies'])) {
10022 $out .= ' /NumCopies '.intval($vp['NumCopies']);
10029 * Output PDF File Header (7.5.2).
10032 protected function _putheader() {
10033 $this->_out('%PDF-'.$this->PDFVersion
);
10034 $this->_out('%'.chr(0xe2).chr(0xe3).chr(0xcf).chr(0xd3));
10038 * Output end of document (EOF).
10041 protected function _enddoc() {
10042 if (isset($this->CurrentFont
['fontkey']) AND isset($this->CurrentFont
['subsetchars'])) {
10043 // save subset chars of the previous font
10044 $this->setFontSubBuffer($this->CurrentFont
['fontkey'], 'subsetchars', $this->CurrentFont
['subsetchars']);
10047 $this->_putheader();
10048 $this->_putpages();
10049 $this->_putresources();
10050 // empty signature fields
10051 if (!empty($this->empty_signature_appearance
)) {
10052 foreach ($this->empty_signature_appearance
as $key => $esa) {
10053 // widget annotation for empty signature
10054 $out = $this->_getobj($esa['objid'])."\n";
10055 $out .= '<< /Type /Annot';
10056 $out .= ' /Subtype /Widget';
10057 $out .= ' /Rect ['.$esa['rect'].']';
10058 $out .= ' /P '.$this->page_obj_id
[($esa['page'])].' 0 R'; // link to signature appearance page
10060 $out .= ' /FT /Sig';
10061 $signame = $esa['name'].sprintf(' [%03d]', ($key +
1));
10062 $out .= ' /T '.$this->_textstring($signame, $esa['objid']);
10065 $out .= "\n".'endobj';
10070 if ($this->sign
AND isset($this->signature_data
['cert_type'])) {
10071 // widget annotation for signature
10072 $out = $this->_getobj($this->sig_obj_id
)."\n";
10073 $out .= '<< /Type /Annot';
10074 $out .= ' /Subtype /Widget';
10075 $out .= ' /Rect ['.$this->signature_appearance
['rect'].']';
10076 $out .= ' /P '.$this->page_obj_id
[($this->signature_appearance
['page'])].' 0 R'; // link to signature appearance page
10078 $out .= ' /FT /Sig';
10079 $out .= ' /T '.$this->_textstring($this->signature_appearance
['name'], $this->sig_obj_id
);
10081 $out .= ' /V '.($this->sig_obj_id +
1).' 0 R';
10083 $out .= "\n".'endobj';
10086 $this->_putsignature();
10089 $objid_info = $this->_putinfo();
10091 $objid_catalog = $this->_putcatalog();
10093 $o = $this->bufferlen
;
10095 $this->_out('xref');
10096 $this->_out('0 '.($this->n +
1));
10097 $this->_out('0000000000 65535 f ');
10098 $freegen = ($this->n +
2);
10099 for ($i=1; $i <= $this->n
; ++
$i) {
10100 if (!isset($this->offsets
[$i]) AND ($i > 1)) {
10101 $this->_out(sprintf('0000000000 %05d f ', $freegen));
10104 $this->_out(sprintf('%010d 00000 n ', $this->offsets
[$i]));
10108 $out = 'trailer'."\n";
10110 $out .= ' /Size '.($this->n +
1);
10111 $out .= ' /Root '.$objid_catalog.' 0 R';
10112 $out .= ' /Info '.$objid_info.' 0 R';
10113 if ($this->encrypted
) {
10114 $out .= ' /Encrypt '.$this->encryptdata
['objid'].' 0 R';
10116 $out .= ' /ID [ <'.$this->file_id
.'> <'.$this->file_id
.'> ]';
10119 $this->_out('startxref');
10121 $this->_out('%%EOF');
10122 $this->state
= 3; // end-of-doc
10126 * Initialize a new page.
10127 * @param string $orientation page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
10128 * @param mixed $format 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().
10130 * @see getPageSizeFromFormat(), setPageFormat()
10132 protected function _beginpage($orientation='', $format='') {
10134 $this->pageobjects
[$this->page
] = array();
10135 $this->setPageBuffer($this->page
, '');
10136 // initialize array for graphics tranformation positions inside a page buffer
10137 $this->transfmrk
[$this->page
] = array();
10139 if (TCPDF_STATIC
::empty_string($orientation)) {
10140 if (isset($this->CurOrientation
)) {
10141 $orientation = $this->CurOrientation
;
10142 } elseif ($this->fwPt
> $this->fhPt
) {
10144 $orientation = 'L';
10147 $orientation = 'P';
10150 if (TCPDF_STATIC
::empty_string($format)) {
10151 $this->pagedim
[$this->page
] = $this->pagedim
[($this->page
- 1)];
10152 $this->setPageOrientation($orientation);
10154 $this->setPageFormat($format, $orientation);
10157 $this->x
= $this->w
- $this->rMargin
;
10159 $this->x
= $this->lMargin
;
10161 $this->y
= $this->tMargin
;
10162 if (isset($this->newpagegroup
[$this->page
])) {
10163 // start a new group
10164 $this->currpagegroup
= $this->newpagegroup
[$this->page
];
10165 $this->pagegroups
[$this->currpagegroup
] = 1;
10166 } elseif (isset($this->currpagegroup
) AND ($this->currpagegroup
> 0)) {
10167 ++
$this->pagegroups
[$this->currpagegroup
];
10172 * Mark end of page.
10175 protected function _endpage() {
10176 $this->setVisibility('all');
10181 * Begin a new object and return the object number.
10182 * @return int object number
10185 protected function _newobj() {
10186 $this->_out($this->_getobj());
10191 * Return the starting object string for the selected object ID.
10192 * @param int|null $objid Object ID (leave empty to get a new ID).
10193 * @return string the starting object string
10195 * @since 5.8.009 (2010-08-20)
10197 protected function _getobj($objid=null) {
10198 if (TCPDF_STATIC
::empty_string($objid)) {
10202 $this->offsets
[$objid] = $this->bufferlen
;
10203 $this->pageobjects
[$this->page
][] = $objid;
10204 return $objid.' 0 obj';
10209 * @param int $x X coordinate
10210 * @param int $y Y coordinate
10211 * @param string $txt text to underline
10214 protected function _dounderline($x, $y, $txt) {
10215 $w = $this->GetStringWidth($txt);
10216 return $this->_dounderlinew($x, $y, $w);
10220 * Underline for rectangular text area.
10221 * @param int $x X coordinate
10222 * @param int $y Y coordinate
10223 * @param int $w width to underline
10225 * @since 4.8.008 (2009-09-29)
10227 protected function _dounderlinew($x, $y, $w) {
10228 $linew = - $this->CurrentFont
['ut'] / 1000 * $this->FontSizePt
;
10229 return sprintf('%F %F %F %F re f', $x * $this->k
, ((($this->h
- $y) * $this->k
) +
$linew), $w * $this->k
, $linew);
10233 * Line through text.
10234 * @param int $x X coordinate
10235 * @param int $y Y coordinate
10236 * @param string $txt text to linethrough
10239 protected function _dolinethrough($x, $y, $txt) {
10240 $w = $this->GetStringWidth($txt);
10241 return $this->_dolinethroughw($x, $y, $w);
10245 * Line through for rectangular text area.
10246 * @param int $x X coordinate
10247 * @param int $y Y coordinate
10248 * @param int $w line length (width)
10250 * @since 4.9.008 (2009-09-29)
10252 protected function _dolinethroughw($x, $y, $w) {
10253 $linew = - $this->CurrentFont
['ut'] / 1000 * $this->FontSizePt
;
10254 return sprintf('%F %F %F %F re f', $x * $this->k
, ((($this->h
- $y) * $this->k
) +
$linew +
($this->FontSizePt
/ 3)), $w * $this->k
, $linew);
10259 * @param int $x X coordinate
10260 * @param int $y Y coordinate
10261 * @param string $txt text to overline
10263 * @since 4.9.015 (2010-04-19)
10265 protected function _dooverline($x, $y, $txt) {
10266 $w = $this->GetStringWidth($txt);
10267 return $this->_dooverlinew($x, $y, $w);
10271 * Overline for rectangular text area.
10272 * @param int $x X coordinate
10273 * @param int $y Y coordinate
10274 * @param int $w width to overline
10276 * @since 4.9.015 (2010-04-19)
10278 protected function _dooverlinew($x, $y, $w) {
10279 $linew = - $this->CurrentFont
['ut'] / 1000 * $this->FontSizePt
;
10280 return sprintf('%F %F %F %F re f', $x * $this->k
, (($this->h
- $y +
$this->FontAscent
) * $this->k
) - $linew, $w * $this->k
, $linew);
10285 * Format a data string for meta information
10286 * @param string $s data string to escape.
10287 * @param int $n object ID
10288 * @return string escaped string.
10291 protected function _datastring($s, $n=0) {
10295 $s = $this->_encrypt_data($n, $s);
10296 return '('. TCPDF_STATIC
::_escape($s).')';
10300 * Set the document creation timestamp
10301 * @param mixed $time Document creation timestamp in seconds or date-time string.
10303 * @since 5.9.152 (2012-03-23)
10305 public function setDocCreationTimestamp($time) {
10306 if (is_string($time)) {
10307 $time = TCPDF_STATIC
::getTimestamp($time);
10309 $this->doc_creation_timestamp
= intval($time);
10313 * Set the document modification timestamp
10314 * @param mixed $time Document modification timestamp in seconds or date-time string.
10316 * @since 5.9.152 (2012-03-23)
10318 public function setDocModificationTimestamp($time) {
10319 if (is_string($time)) {
10320 $time = TCPDF_STATIC
::getTimestamp($time);
10322 $this->doc_modification_timestamp
= intval($time);
10326 * Returns document creation timestamp in seconds.
10327 * @return int Creation timestamp in seconds.
10329 * @since 5.9.152 (2012-03-23)
10331 public function getDocCreationTimestamp() {
10332 return $this->doc_creation_timestamp
;
10336 * Returns document modification timestamp in seconds.
10337 * @return int Modfication timestamp in seconds.
10339 * @since 5.9.152 (2012-03-23)
10341 public function getDocModificationTimestamp() {
10342 return $this->doc_modification_timestamp
;
10346 * Returns a formatted date for meta information
10347 * @param int $n Object ID.
10348 * @param int $timestamp Timestamp to convert.
10349 * @return string escaped date string.
10351 * @since 4.6.028 (2009-08-25)
10353 protected function _datestring($n=0, $timestamp=0) {
10354 if ((empty($timestamp)) OR ($timestamp < 0)) {
10355 $timestamp = $this->doc_creation_timestamp
;
10357 return $this->_datastring('D:'.TCPDF_STATIC
::getFormattedDate($timestamp), $n);
10361 * Format a text string for meta information
10362 * @param string $s string to escape.
10363 * @param int $n object ID
10364 * @return string escaped string.
10367 protected function _textstring($s, $n=0) {
10368 if ($this->isunicode
) {
10369 //Convert string to UTF-16BE
10370 $s = TCPDF_FONTS
::UTF8ToUTF16BE($s, true, $this->isunicode
, $this->CurrentFont
);
10372 return $this->_datastring($s, $n);
10376 * get raw output stream.
10377 * @param string $s string to output.
10378 * @param int $n object reference for encryption mode
10380 * @author Nicola Asuni
10381 * @since 5.5.000 (2010-06-22)
10383 protected function _getrawstream($s, $n=0) {
10385 // default to current object
10388 return $this->_encrypt_data($n, $s);
10392 * Output a string to the document.
10393 * @param string $s string to output.
10396 protected function _out($s) {
10397 if ($this->state
== 2) {
10398 if ($this->inxobj
) {
10399 // we are inside an XObject template
10400 $this->xobjects
[$this->xobjid
]['outdata'] .= $s."\n";
10401 } elseif ((!$this->InFooter
) AND isset($this->footerlen
[$this->page
]) AND ($this->footerlen
[$this->page
] > 0)) {
10402 // puts data before page footer
10403 $pagebuff = $this->getPageBuffer($this->page
);
10404 $page = substr($pagebuff, 0, -$this->footerlen
[$this->page
]);
10405 $footer = substr($pagebuff, -$this->footerlen
[$this->page
]);
10406 $this->setPageBuffer($this->page
, $page.$s."\n".$footer);
10407 // update footer position
10408 $this->footerpos
[$this->page
] +
= strlen($s."\n");
10411 $this->setPageBuffer($this->page
, $s."\n", true);
10413 } elseif ($this->state
> 0) {
10414 // set general data
10415 $this->setBuffer($s."\n");
10421 * @param array<int,string|float|null> $font Array describing the basic font parameters: (family, style, size).
10422 * @phpstan-param array{0: string, 1: string, 2: float|null} $font
10426 public function setHeaderFont($font) {
10427 $this->header_font
= $font;
10432 * @return array<int,string|float|null> Array describing the basic font parameters: (family, style, size).
10433 * @phpstan-return array{0: string, 1: string, 2: float|null}
10435 * @since 4.0.012 (2008-07-24)
10437 public function getHeaderFont() {
10438 return $this->header_font
;
10443 * @param array<int,string|float|null> $font Array describing the basic font parameters: (family, style, size).
10444 * @phpstan-param array{0: string, 1: string, 2: float|null} $font
10448 public function setFooterFont($font) {
10449 $this->footer_font
= $font;
10454 * @return array<int,string|float|null> Array describing the basic font parameters: (family, style, size).
10455 * @phpstan-return array{0: string, 1: string, 2: float|null} $font
10457 * @since 4.0.012 (2008-07-24)
10459 public function getFooterFont() {
10460 return $this->footer_font
;
10464 * Set language array.
10465 * @param array $language
10469 public function setLanguageArray($language) {
10470 $this->l
= $language;
10471 if (isset($this->l
['a_meta_dir'])) {
10472 $this->rtl
= $this->l
['a_meta_dir']=='rtl' ?
true : false;
10474 $this->rtl
= false;
10479 * Returns the PDF data.
10482 public function getPDFData() {
10483 if ($this->state
< 3) {
10486 return $this->buffer
;
10490 * Output anchor link.
10491 * @param string $url link URL or internal link (i.e.: <a href="#23,4.5">link to page 23 at 4.5 Y position</a>)
10492 * @param string $name link name
10493 * @param boolean $fill Indicates if the cell background must be painted (true) or transparent (false).
10494 * @param boolean $firstline if true prints only the first line and return the remaining string.
10495 * @param array|null $color array of RGB text color
10496 * @param string $style font style (U, D, B, I)
10497 * @param boolean $firstblock if true the string is the starting of a line.
10498 * @return int the number of cells used or the remaining text if $firstline = true;
10501 public function addHtmlLink($url, $name, $fill=false, $firstline=false, $color=null, $style=-1, $firstblock=false) {
10502 if (isset($url[1]) AND ($url[0] == '#') AND is_numeric($url[1])) {
10503 // convert url to internal link
10504 $lnkdata = explode(',', $url);
10505 if (isset($lnkdata[0]) ) {
10506 $page = substr($lnkdata[0], 1);
10507 if (isset($lnkdata[1]) AND (strlen($lnkdata[1]) > 0)) {
10508 $lnky = floatval($lnkdata[1]);
10512 $url = $this->AddLink();
10513 $this->setLink($url, $lnky, $page);
10516 // store current settings
10517 $prevcolor = $this->fgcolor
;
10518 $prevstyle = $this->FontStyle
;
10519 if (empty($color)) {
10520 $this->setTextColorArray($this->htmlLinkColorArray
);
10522 $this->setTextColorArray($color);
10524 if ($style == -1) {
10525 $this->setFont('', $this->FontStyle
.$this->htmlLinkFontStyle
);
10527 $this->setFont('', $this->FontStyle
.$style);
10529 $ret = $this->Write($this->lasth
, $name, $url, $fill, '', false, 0, $firstline, $firstblock, 0);
10530 // restore settings
10531 $this->setFont('', $prevstyle);
10532 $this->setTextColorArray($prevcolor);
10537 * Converts pixels to User's Units.
10538 * @param int $px pixels
10539 * @return float value in user's unit
10541 * @see setImageScale(), getImageScale()
10543 public function pixelsToUnits($px) {
10544 return ($px / ($this->imgscale
* $this->k
));
10548 * Reverse function for htmlentities.
10549 * Convert entities in UTF-8.
10550 * @param string $text_to_convert Text to convert.
10551 * @return string converted text string
10554 public function unhtmlentities($text_to_convert) {
10555 return @html_entity_decode
($text_to_convert, ENT_QUOTES
, $this->encoding
);
10558 // ENCRYPTION METHODS ----------------------------------
10561 * Compute encryption key depending on object number where the encrypted data is stored.
10562 * This is used for all strings and streams without crypt filter specifier.
10563 * @param int $n object number
10564 * @return int object key
10566 * @author Nicola Asuni
10567 * @since 2.0.000 (2008-01-02)
10569 protected function _objectkey($n) {
10570 $objkey = $this->encryptdata
['key'].pack('VXxx', $n);
10571 if ($this->encryptdata
['mode'] == 2) { // AES-128
10573 $objkey .= "\x73\x41\x6C\x54"; // sAlT
10575 $objkey = substr(TCPDF_STATIC
::_md5_16($objkey), 0, (($this->encryptdata
['Length'] / 8) +
5));
10576 $objkey = substr($objkey, 0, 16);
10581 * Encrypt the input string.
10582 * @param int $n object number
10583 * @param string $s data string to encrypt
10584 * @return string encrypted string
10586 * @author Nicola Asuni
10587 * @since 5.0.005 (2010-05-11)
10589 protected function _encrypt_data($n, $s) {
10590 if (!$this->encrypted
) {
10593 switch ($this->encryptdata
['mode']) {
10595 case 1: { // RC4-128
10596 $s = TCPDF_STATIC
::_RC4($this->_objectkey($n), $s, $this->last_enc_key
, $this->last_enc_key_c
);
10599 case 2: { // AES-128
10600 $s = TCPDF_STATIC
::_AES($this->_objectkey($n), $s);
10603 case 3: { // AES-256
10604 $s = TCPDF_STATIC
::_AES($this->encryptdata
['key'], $s);
10612 * Put encryption on PDF document.
10614 * @author Nicola Asuni
10615 * @since 2.0.000 (2008-01-02)
10617 protected function _putencryption() {
10618 if (!$this->encrypted
) {
10621 $this->encryptdata
['objid'] = $this->_newobj();
10623 if (!isset($this->encryptdata
['Filter']) OR empty($this->encryptdata
['Filter'])) {
10624 $this->encryptdata
['Filter'] = 'Standard';
10626 $out .= ' /Filter /'.$this->encryptdata
['Filter'];
10627 if (isset($this->encryptdata
['SubFilter']) AND !empty($this->encryptdata
['SubFilter'])) {
10628 $out .= ' /SubFilter /'.$this->encryptdata
['SubFilter'];
10630 if (!isset($this->encryptdata
['V']) OR empty($this->encryptdata
['V'])) {
10631 $this->encryptdata
['V'] = 1;
10633 // V is a code specifying the algorithm to be used in encrypting and decrypting the document
10634 $out .= ' /V '.$this->encryptdata
['V'];
10635 if (isset($this->encryptdata
['Length']) AND !empty($this->encryptdata
['Length'])) {
10636 // The length of the encryption key, in bits. The value shall be a multiple of 8, in the range 40 to 256
10637 $out .= ' /Length '.$this->encryptdata
['Length'];
10639 $out .= ' /Length 40';
10641 if ($this->encryptdata
['V'] >= 4) {
10642 if (!isset($this->encryptdata
['StmF']) OR empty($this->encryptdata
['StmF'])) {
10643 $this->encryptdata
['StmF'] = 'Identity';
10645 if (!isset($this->encryptdata
['StrF']) OR empty($this->encryptdata
['StrF'])) {
10646 // The name of the crypt filter that shall be used when decrypting all strings in the document.
10647 $this->encryptdata
['StrF'] = 'Identity';
10649 // A dictionary whose keys shall be crypt filter names and whose values shall be the corresponding crypt filter dictionaries.
10650 if (isset($this->encryptdata
['CF']) AND !empty($this->encryptdata
['CF'])) {
10652 $out .= ' /'.$this->encryptdata
['StmF'].' <<';
10653 $out .= ' /Type /CryptFilter';
10654 if (isset($this->encryptdata
['CF']['CFM']) AND !empty($this->encryptdata
['CF']['CFM'])) {
10656 $out .= ' /CFM /'.$this->encryptdata
['CF']['CFM'];
10657 if ($this->encryptdata
['pubkey']) {
10658 $out .= ' /Recipients [';
10659 foreach ($this->encryptdata
['Recipients'] as $rec) {
10660 $out .= ' <'.$rec.'>';
10663 if (isset($this->encryptdata
['CF']['EncryptMetadata']) AND (!$this->encryptdata
['CF']['EncryptMetadata'])) {
10664 $out .= ' /EncryptMetadata false';
10666 $out .= ' /EncryptMetadata true';
10670 $out .= ' /CFM /None';
10672 if (isset($this->encryptdata
['CF']['AuthEvent']) AND !empty($this->encryptdata
['CF']['AuthEvent'])) {
10673 // The event to be used to trigger the authorization that is required to access encryption keys used by this filter.
10674 $out .= ' /AuthEvent /'.$this->encryptdata
['CF']['AuthEvent'];
10676 $out .= ' /AuthEvent /DocOpen';
10678 if (isset($this->encryptdata
['CF']['Length']) AND !empty($this->encryptdata
['CF']['Length'])) {
10679 // The bit length of the encryption key.
10680 $out .= ' /Length '.$this->encryptdata
['CF']['Length'];
10684 // The name of the crypt filter that shall be used by default when decrypting streams.
10685 $out .= ' /StmF /'.$this->encryptdata
['StmF'];
10686 // The name of the crypt filter that shall be used when decrypting all strings in the document.
10687 $out .= ' /StrF /'.$this->encryptdata
['StrF'];
10688 if (isset($this->encryptdata
['EFF']) AND !empty($this->encryptdata
['EFF'])) {
10689 // The name of the crypt filter that shall be used when encrypting embedded file streams that do not have their own crypt filter specifier.
10690 $out .= ' /EFF /'.$this->encryptdata
[''];
10693 // Additional encryption dictionary entries for the standard security handler
10694 if ($this->encryptdata
['pubkey']) {
10695 if (($this->encryptdata
['V'] < 4) AND isset($this->encryptdata
['Recipients']) AND !empty($this->encryptdata
['Recipients'])) {
10696 $out .= ' /Recipients [';
10697 foreach ($this->encryptdata
['Recipients'] as $rec) {
10698 $out .= ' <'.$rec.'>';
10704 if ($this->encryptdata
['V'] == 5) { // AES-256
10706 $out .= ' /OE ('.TCPDF_STATIC
::_escape($this->encryptdata
['OE']).')';
10707 $out .= ' /UE ('.TCPDF_STATIC
::_escape($this->encryptdata
['UE']).')';
10708 $out .= ' /Perms ('.TCPDF_STATIC
::_escape($this->encryptdata
['perms']).')';
10709 } elseif ($this->encryptdata
['V'] == 4) { // AES-128
10711 } elseif ($this->encryptdata
['V'] < 2) { // RC-40
10716 $out .= ' /O ('.TCPDF_STATIC
::_escape($this->encryptdata
['O']).')';
10717 $out .= ' /U ('.TCPDF_STATIC
::_escape($this->encryptdata
['U']).')';
10718 $out .= ' /P '.$this->encryptdata
['P'];
10719 if (isset($this->encryptdata
['EncryptMetadata']) AND (!$this->encryptdata
['EncryptMetadata'])) {
10720 $out .= ' /EncryptMetadata false';
10722 $out .= ' /EncryptMetadata true';
10726 $out .= "\n".'endobj';
10731 * Compute U value (used for encryption)
10732 * @return string U value
10734 * @since 2.0.000 (2008-01-02)
10735 * @author Nicola Asuni
10737 protected function _Uvalue() {
10738 if ($this->encryptdata
['mode'] == 0) { // RC4-40
10739 return TCPDF_STATIC
::_RC4($this->encryptdata
['key'], TCPDF_STATIC
::$enc_padding, $this->last_enc_key
, $this->last_enc_key_c
);
10740 } elseif ($this->encryptdata
['mode'] < 3) { // RC4-128, AES-128
10741 $tmp = TCPDF_STATIC
::_md5_16(TCPDF_STATIC
::$enc_padding.$this->encryptdata
['fileid']);
10742 $enc = TCPDF_STATIC
::_RC4($this->encryptdata
['key'], $tmp, $this->last_enc_key
, $this->last_enc_key_c
);
10743 $len = strlen($tmp);
10744 for ($i = 1; $i <= 19; ++
$i) {
10746 for ($j = 0; $j < $len; ++
$j) {
10747 $ek .= chr(ord($this->encryptdata
['key'][$j]) ^
$i);
10749 $enc = TCPDF_STATIC
::_RC4($ek, $enc, $this->last_enc_key
, $this->last_enc_key_c
);
10751 $enc .= str_repeat("\x00", 16);
10752 return substr($enc, 0, 32);
10753 } elseif ($this->encryptdata
['mode'] == 3) { // AES-256
10754 $seed = TCPDF_STATIC
::_md5_16(TCPDF_STATIC
::getRandomSeed());
10755 // User Validation Salt
10756 $this->encryptdata
['UVS'] = substr($seed, 0, 8);
10758 $this->encryptdata
['UKS'] = substr($seed, 8, 16);
10759 return hash('sha256', $this->encryptdata
['user_password'].$this->encryptdata
['UVS'], true).$this->encryptdata
['UVS'].$this->encryptdata
['UKS'];
10764 * Compute UE value (used for encryption)
10765 * @return string UE value
10767 * @since 5.9.006 (2010-10-19)
10768 * @author Nicola Asuni
10770 protected function _UEvalue() {
10771 $hashkey = hash('sha256', $this->encryptdata
['user_password'].$this->encryptdata
['UKS'], true);
10772 return TCPDF_STATIC
::_AESnopad($hashkey, $this->encryptdata
['key']);
10776 * Compute O value (used for encryption)
10777 * @return string O value
10779 * @since 2.0.000 (2008-01-02)
10780 * @author Nicola Asuni
10782 protected function _Ovalue() {
10783 if ($this->encryptdata
['mode'] < 3) { // RC4-40, RC4-128, AES-128
10784 $tmp = TCPDF_STATIC
::_md5_16($this->encryptdata
['owner_password']);
10785 if ($this->encryptdata
['mode'] > 0) {
10786 for ($i = 0; $i < 50; ++
$i) {
10787 $tmp = TCPDF_STATIC
::_md5_16($tmp);
10790 $owner_key = substr($tmp, 0, ($this->encryptdata
['Length'] / 8));
10791 $enc = TCPDF_STATIC
::_RC4($owner_key, $this->encryptdata
['user_password'], $this->last_enc_key
, $this->last_enc_key_c
);
10792 if ($this->encryptdata
['mode'] > 0) {
10793 $len = strlen($owner_key);
10794 for ($i = 1; $i <= 19; ++
$i) {
10796 for ($j = 0; $j < $len; ++
$j) {
10797 $ek .= chr(ord($owner_key[$j]) ^
$i);
10799 $enc = TCPDF_STATIC
::_RC4($ek, $enc, $this->last_enc_key
, $this->last_enc_key_c
);
10803 } elseif ($this->encryptdata
['mode'] == 3) { // AES-256
10804 $seed = TCPDF_STATIC
::_md5_16(TCPDF_STATIC
::getRandomSeed());
10805 // Owner Validation Salt
10806 $this->encryptdata
['OVS'] = substr($seed, 0, 8);
10808 $this->encryptdata
['OKS'] = substr($seed, 8, 16);
10809 return hash('sha256', $this->encryptdata
['owner_password'].$this->encryptdata
['OVS'].$this->encryptdata
['U'], true).$this->encryptdata
['OVS'].$this->encryptdata
['OKS'];
10814 * Compute OE value (used for encryption)
10815 * @return string OE value
10817 * @since 5.9.006 (2010-10-19)
10818 * @author Nicola Asuni
10820 protected function _OEvalue() {
10821 $hashkey = hash('sha256', $this->encryptdata
['owner_password'].$this->encryptdata
['OKS'].$this->encryptdata
['U'], true);
10822 return TCPDF_STATIC
::_AESnopad($hashkey, $this->encryptdata
['key']);
10826 * Convert password for AES-256 encryption mode
10827 * @param string $password password
10828 * @return string password
10830 * @since 5.9.006 (2010-10-19)
10831 * @author Nicola Asuni
10833 protected function _fixAES256Password($password) {
10834 $psw = ''; // password to be returned
10835 $psw_array = TCPDF_FONTS
::utf8Bidi(TCPDF_FONTS
::UTF8StringToArray($password, $this->isunicode
, $this->CurrentFont
), $password, $this->rtl
, $this->isunicode
, $this->CurrentFont
);
10836 foreach ($psw_array as $c) {
10837 $psw .= TCPDF_FONTS
::unichr($c, $this->isunicode
);
10839 return substr($psw, 0, 127);
10843 * Compute encryption key
10845 * @since 2.0.000 (2008-01-02)
10846 * @author Nicola Asuni
10848 protected function _generateencryptionkey() {
10849 $keybytelen = ($this->encryptdata
['Length'] / 8);
10850 if (!$this->encryptdata
['pubkey']) { // standard mode
10851 if ($this->encryptdata
['mode'] == 3) { // AES-256
10852 // generate 256 bit random key
10853 $this->encryptdata
['key'] = substr(hash('sha256', TCPDF_STATIC
::getRandomSeed(), true), 0, $keybytelen);
10854 // truncate passwords
10855 $this->encryptdata
['user_password'] = $this->_fixAES256Password($this->encryptdata
['user_password']);
10856 $this->encryptdata
['owner_password'] = $this->_fixAES256Password($this->encryptdata
['owner_password']);
10858 $this->encryptdata
['U'] = $this->_Uvalue();
10859 // Compute UE value
10860 $this->encryptdata
['UE'] = $this->_UEvalue();
10862 $this->encryptdata
['O'] = $this->_Ovalue();
10863 // Compute OE value
10864 $this->encryptdata
['OE'] = $this->_OEvalue();
10866 $this->encryptdata
['P'] = $this->encryptdata
['protection'];
10867 // Computing the encryption dictionary's Perms (permissions) value
10868 $perms = TCPDF_STATIC
::getEncPermissionsString($this->encryptdata
['protection']); // bytes 0-3
10869 $perms .= chr(255).chr(255).chr(255).chr(255); // bytes 4-7
10870 if (isset($this->encryptdata
['CF']['EncryptMetadata']) AND (!$this->encryptdata
['CF']['EncryptMetadata'])) { // byte 8
10875 $perms .= 'adb'; // bytes 9-11
10876 $perms .= 'nick'; // bytes 12-15
10877 $this->encryptdata
['perms'] = TCPDF_STATIC
::_AESnopad($this->encryptdata
['key'], $perms);
10878 } else { // RC4-40, RC4-128, AES-128
10880 $this->encryptdata
['user_password'] = substr($this->encryptdata
['user_password'].TCPDF_STATIC
::$enc_padding, 0, 32);
10881 $this->encryptdata
['owner_password'] = substr($this->encryptdata
['owner_password'].TCPDF_STATIC
::$enc_padding, 0, 32);
10883 $this->encryptdata
['O'] = $this->_Ovalue();
10884 // get default permissions (reverse byte order)
10885 $permissions = TCPDF_STATIC
::getEncPermissionsString($this->encryptdata
['protection']);
10886 // Compute encryption key
10887 $tmp = TCPDF_STATIC
::_md5_16($this->encryptdata
['user_password'].$this->encryptdata
['O'].$permissions.$this->encryptdata
['fileid']);
10888 if ($this->encryptdata
['mode'] > 0) {
10889 for ($i = 0; $i < 50; ++
$i) {
10890 $tmp = TCPDF_STATIC
::_md5_16(substr($tmp, 0, $keybytelen));
10893 $this->encryptdata
['key'] = substr($tmp, 0, $keybytelen);
10895 $this->encryptdata
['U'] = $this->_Uvalue();
10897 $this->encryptdata
['P'] = $this->encryptdata
['protection'];
10899 } else { // Public-Key mode
10900 // random 20-byte seed
10901 $seed = sha1(TCPDF_STATIC
::getRandomSeed(), true);
10902 $recipient_bytes = '';
10903 foreach ($this->encryptdata
['pubkeys'] as $pubkey) {
10904 // for each public certificate
10905 if (isset($pubkey['p'])) {
10906 $pkprotection = TCPDF_STATIC
::getUserPermissionCode($pubkey['p'], $this->encryptdata
['mode']);
10908 $pkprotection = $this->encryptdata
['protection'];
10910 // get default permissions (reverse byte order)
10911 $pkpermissions = TCPDF_STATIC
::getEncPermissionsString($pkprotection);
10913 $envelope = $seed.$pkpermissions;
10914 // write the envelope data to a temporary file
10915 $tempkeyfile = TCPDF_STATIC
::getObjFilename('key', $this->file_id
);
10916 $f = TCPDF_STATIC
::fopenLocal($tempkeyfile, 'wb');
10918 $this->Error('Unable to create temporary key file: '.$tempkeyfile);
10920 $envelope_length = strlen($envelope);
10921 fwrite($f, $envelope, $envelope_length);
10923 $tempencfile = TCPDF_STATIC
::getObjFilename('enc', $this->file_id
);
10924 if (!openssl_pkcs7_encrypt($tempkeyfile, $tempencfile, $pubkey['c'], array(), PKCS7_BINARY | PKCS7_DETACHED
)) {
10925 $this->Error('Unable to encrypt the file: '.$tempkeyfile);
10927 // read encryption signature
10928 $signature = file_get_contents($tempencfile, false, null, $envelope_length);
10929 // extract signature
10930 $signature = substr($signature, strpos($signature, 'Content-Disposition'));
10931 $tmparr = explode("\n\n", $signature);
10932 $signature = trim($tmparr[1]);
10934 // decode signature
10935 $signature = base64_decode($signature);
10936 // convert signature to hex
10937 $hexsignature = current(unpack('H*', $signature));
10938 // store signature on recipients array
10939 $this->encryptdata
['Recipients'][] = $hexsignature;
10940 // The bytes of each item in the Recipients array of PKCS#7 objects in the order in which they appear in the array
10941 $recipient_bytes .= $signature;
10943 // calculate encryption key
10944 if ($this->encryptdata
['mode'] == 3) { // AES-256
10945 $this->encryptdata
['key'] = substr(hash('sha256', $seed.$recipient_bytes, true), 0, $keybytelen);
10946 } else { // RC4-40, RC4-128, AES-128
10947 $this->encryptdata
['key'] = substr(sha1($seed.$recipient_bytes, true), 0, $keybytelen);
10953 * Set document protection
10954 * Remark: the protection against modification is for people who have the full Acrobat product.
10955 * 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.
10956 * 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.
10957 * @param array $permissions 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>
10958 * @param string $user_pass user password. Empty by default.
10959 * @param string|null $owner_pass owner password. If not specified, a random value is used.
10960 * @param int $mode encryption strength: 0 = RC4 40 bit; 1 = RC4 128 bit; 2 = AES 128 bit; 3 = AES 256 bit.
10961 * @param array|null $pubkeys 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')))
10963 * @since 2.0.000 (2008-01-02)
10964 * @author Nicola Asuni
10966 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) {
10967 if ($this->pdfa_mode
) {
10968 // encryption is not allowed in PDF/A mode
10971 $this->encryptdata
['protection'] = TCPDF_STATIC
::getUserPermissionCode($permissions, $mode);
10972 if (($pubkeys !== null) AND (is_array($pubkeys))) {
10974 $this->encryptdata
['pubkeys'] = $pubkeys;
10976 // public-Key Security requires at least 128 bit
10979 if (!function_exists('openssl_pkcs7_encrypt')) {
10980 $this->Error('Public-Key Security requires openssl library.');
10982 // Set Public-Key filter (available are: Entrust.PPKEF, Adobe.PPKLite, Adobe.PubSec)
10983 $this->encryptdata
['pubkey'] = true;
10984 $this->encryptdata
['Filter'] = 'Adobe.PubSec';
10985 $this->encryptdata
['StmF'] = 'DefaultCryptFilter';
10986 $this->encryptdata
['StrF'] = 'DefaultCryptFilter';
10988 // standard mode (password mode)
10989 $this->encryptdata
['pubkey'] = false;
10990 $this->encryptdata
['Filter'] = 'Standard';
10991 $this->encryptdata
['StmF'] = 'StdCF';
10992 $this->encryptdata
['StrF'] = 'StdCF';
10994 if ($mode > 1) { // AES
10995 if (!extension_loaded('openssl') && !extension_loaded('mcrypt')) {
10996 $this->Error('AES encryption requires openssl or mcrypt extension (http://www.php.net/manual/en/mcrypt.requirements.php).');
10998 if (extension_loaded('openssl') && !in_array('aes-256-cbc', openssl_get_cipher_methods())) {
10999 $this->Error('AES encryption requires openssl/aes-256-cbc cypher.');
11001 if (extension_loaded('mcrypt') && mcrypt_get_cipher_name(MCRYPT_RIJNDAEL_128
) === false) {
11002 $this->Error('AES encryption requires MCRYPT_RIJNDAEL_128 cypher.');
11004 if (($mode == 3) AND !function_exists('hash')) {
11005 // the Hash extension requires no external libraries and is enabled by default as of PHP 5.1.2.
11006 $this->Error('AES 256 encryption requires HASH Message Digest Framework (http://www.php.net/manual/en/book.hash.php).');
11009 if ($owner_pass === null) {
11010 $owner_pass = md5(TCPDF_STATIC
::getRandomSeed());
11012 $this->encryptdata
['user_password'] = $user_pass;
11013 $this->encryptdata
['owner_password'] = $owner_pass;
11014 $this->encryptdata
['mode'] = $mode;
11016 case 0: { // RC4 40 bit
11017 $this->encryptdata
['V'] = 1;
11018 $this->encryptdata
['Length'] = 40;
11019 $this->encryptdata
['CF']['CFM'] = 'V2';
11022 case 1: { // RC4 128 bit
11023 $this->encryptdata
['V'] = 2;
11024 $this->encryptdata
['Length'] = 128;
11025 $this->encryptdata
['CF']['CFM'] = 'V2';
11026 if ($this->encryptdata
['pubkey']) {
11027 $this->encryptdata
['SubFilter'] = 'adbe.pkcs7.s4';
11028 $this->encryptdata
['Recipients'] = array();
11032 case 2: { // AES 128 bit
11033 $this->encryptdata
['V'] = 4;
11034 $this->encryptdata
['Length'] = 128;
11035 $this->encryptdata
['CF']['CFM'] = 'AESV2';
11036 $this->encryptdata
['CF']['Length'] = 128;
11037 if ($this->encryptdata
['pubkey']) {
11038 $this->encryptdata
['SubFilter'] = 'adbe.pkcs7.s5';
11039 $this->encryptdata
['Recipients'] = array();
11043 case 3: { // AES 256 bit
11044 $this->encryptdata
['V'] = 5;
11045 $this->encryptdata
['Length'] = 256;
11046 $this->encryptdata
['CF']['CFM'] = 'AESV3';
11047 $this->encryptdata
['CF']['Length'] = 256;
11048 if ($this->encryptdata
['pubkey']) {
11049 $this->encryptdata
['SubFilter'] = 'adbe.pkcs7.s5';
11050 $this->encryptdata
['Recipients'] = array();
11055 $this->encrypted
= true;
11056 $this->encryptdata
['fileid'] = TCPDF_STATIC
::convertHexStringToString($this->file_id
);
11057 $this->_generateencryptionkey();
11060 // END OF ENCRYPTION FUNCTIONS -------------------------
11062 // START TRANSFORMATIONS SECTION -----------------------
11065 * Starts a 2D tranformation saving current graphic state.
11066 * This function must be called before scaling, mirroring, translation, rotation and skewing.
11067 * Use StartTransform() before, and StopTransform() after the transformations to restore the normal behavior.
11069 * @since 2.1.000 (2008-01-07)
11070 * @see StartTransform(), StopTransform()
11072 public function StartTransform() {
11073 if ($this->state
!= 2) {
11076 $this->_outSaveGraphicsState();
11077 if ($this->inxobj
) {
11078 // we are inside an XObject template
11079 $this->xobjects
[$this->xobjid
]['transfmrk'][] = strlen($this->xobjects
[$this->xobjid
]['outdata']);
11081 $this->transfmrk
[$this->page
][] = $this->pagelen
[$this->page
];
11083 ++
$this->transfmatrix_key
;
11084 $this->transfmatrix
[$this->transfmatrix_key
] = array();
11088 * Stops a 2D tranformation restoring previous graphic state.
11089 * This function must be called after scaling, mirroring, translation, rotation and skewing.
11090 * Use StartTransform() before, and StopTransform() after the transformations to restore the normal behavior.
11092 * @since 2.1.000 (2008-01-07)
11093 * @see StartTransform(), StopTransform()
11095 public function StopTransform() {
11096 if ($this->state
!= 2) {
11099 $this->_outRestoreGraphicsState();
11100 if (isset($this->transfmatrix
[$this->transfmatrix_key
])) {
11101 array_pop($this->transfmatrix
[$this->transfmatrix_key
]);
11102 --$this->transfmatrix_key
;
11104 if ($this->inxobj
) {
11105 // we are inside an XObject template
11106 array_pop($this->xobjects
[$this->xobjid
]['transfmrk']);
11108 array_pop($this->transfmrk
[$this->page
]);
11112 * Horizontal Scaling.
11113 * @param float $s_x scaling factor for width as percent. 0 is not allowed.
11114 * @param int $x abscissa of the scaling center. Default is current x position
11115 * @param int $y ordinate of the scaling center. Default is current y position
11117 * @since 2.1.000 (2008-01-07)
11118 * @see StartTransform(), StopTransform()
11120 public function ScaleX($s_x, $x='', $y='') {
11121 $this->Scale($s_x, 100, $x, $y);
11125 * Vertical Scaling.
11126 * @param float $s_y scaling factor for height as percent. 0 is not allowed.
11127 * @param int $x abscissa of the scaling center. Default is current x position
11128 * @param int $y ordinate of the scaling center. Default is current y position
11130 * @since 2.1.000 (2008-01-07)
11131 * @see StartTransform(), StopTransform()
11133 public function ScaleY($s_y, $x='', $y='') {
11134 $this->Scale(100, $s_y, $x, $y);
11138 * Vertical and horizontal proportional Scaling.
11139 * @param float $s scaling factor for width and height as percent. 0 is not allowed.
11140 * @param int $x abscissa of the scaling center. Default is current x position
11141 * @param int $y ordinate of the scaling center. Default is current y position
11143 * @since 2.1.000 (2008-01-07)
11144 * @see StartTransform(), StopTransform()
11146 public function ScaleXY($s, $x='', $y='') {
11147 $this->Scale($s, $s, $x, $y);
11151 * Vertical and horizontal non-proportional Scaling.
11152 * @param float $s_x scaling factor for width as percent. 0 is not allowed.
11153 * @param float $s_y scaling factor for height as percent. 0 is not allowed.
11154 * @param float|null $x abscissa of the scaling center. Default is current x position
11155 * @param float|null $y ordinate of the scaling center. Default is current y position
11157 * @since 2.1.000 (2008-01-07)
11158 * @see StartTransform(), StopTransform()
11160 public function Scale($s_x, $s_y, $x=null, $y=null) {
11161 if (TCPDF_STATIC
::empty_string($x)) {
11164 if (TCPDF_STATIC
::empty_string($y)) {
11167 if (($s_x == 0) OR ($s_y == 0)) {
11168 $this->Error('Please do not use values equal to zero for scaling');
11170 $y = ($this->h
- $y) * $this->k
;
11172 //calculate elements of transformation matrix
11180 $tm[4] = $x * (1 - $s_x);
11181 $tm[5] = $y * (1 - $s_y);
11182 //scale the coordinate system
11183 $this->Transform($tm);
11187 * Horizontal Mirroring.
11188 * @param float|null $x abscissa of the point. Default is current x position
11190 * @since 2.1.000 (2008-01-07)
11191 * @see StartTransform(), StopTransform()
11193 public function MirrorH($x=null) {
11194 $this->Scale(-100, 100, $x);
11198 * Verical Mirroring.
11199 * @param float|null $y ordinate of the point. Default is current y position
11201 * @since 2.1.000 (2008-01-07)
11202 * @see StartTransform(), StopTransform()
11204 public function MirrorV($y=null) {
11205 $this->Scale(100, -100, null, $y);
11209 * Point reflection mirroring.
11210 * @param float|null $x abscissa of the point. Default is current x position
11211 * @param float|null $y ordinate of the point. Default is current y position
11213 * @since 2.1.000 (2008-01-07)
11214 * @see StartTransform(), StopTransform()
11216 public function MirrorP($x=null,$y=null) {
11217 $this->Scale(-100, -100, $x, $y);
11221 * Reflection against a straight line through point (x, y) with the gradient angle (angle).
11222 * @param float $angle gradient angle of the straight line. Default is 0 (horizontal line).
11223 * @param float|null $x abscissa of the point. Default is current x position
11224 * @param float|null $y ordinate of the point. Default is current y position
11226 * @since 2.1.000 (2008-01-07)
11227 * @see StartTransform(), StopTransform()
11229 public function MirrorL($angle=0, $x=null,$y=null) {
11230 $this->Scale(-100, 100, $x, $y);
11231 $this->Rotate(-2*($angle-90), $x, $y);
11235 * Translate graphic object horizontally.
11236 * @param int $t_x movement to the right (or left for RTL)
11238 * @since 2.1.000 (2008-01-07)
11239 * @see StartTransform(), StopTransform()
11241 public function TranslateX($t_x) {
11242 $this->Translate($t_x, 0);
11246 * Translate graphic object vertically.
11247 * @param int $t_y movement to the bottom
11249 * @since 2.1.000 (2008-01-07)
11250 * @see StartTransform(), StopTransform()
11252 public function TranslateY($t_y) {
11253 $this->Translate(0, $t_y);
11257 * Translate graphic object horizontally and vertically.
11258 * @param int $t_x movement to the right
11259 * @param int $t_y movement to the bottom
11261 * @since 2.1.000 (2008-01-07)
11262 * @see StartTransform(), StopTransform()
11264 public function Translate($t_x, $t_y) {
11265 //calculate elements of transformation matrix
11271 $tm[4] = $t_x * $this->k
;
11272 $tm[5] = -$t_y * $this->k
;
11273 //translate the coordinate system
11274 $this->Transform($tm);
11279 * @param float $angle angle in degrees for counter-clockwise rotation
11280 * @param float|null $x abscissa of the rotation center. Default is current x position
11281 * @param float|null $y ordinate of the rotation center. Default is current y position
11283 * @since 2.1.000 (2008-01-07)
11284 * @see StartTransform(), StopTransform()
11286 public function Rotate($angle, $x=null, $y=null) {
11287 if (TCPDF_STATIC
::empty_string($x)) {
11290 if (TCPDF_STATIC
::empty_string($y)) {
11293 $y = ($this->h
- $y) * $this->k
;
11295 //calculate elements of transformation matrix
11297 $tm[0] = cos(deg2rad($angle));
11298 $tm[1] = sin(deg2rad($angle));
11301 $tm[4] = $x +
($tm[1] * $y) - ($tm[0] * $x);
11302 $tm[5] = $y - ($tm[0] * $y) - ($tm[1] * $x);
11303 //rotate the coordinate system around ($x,$y)
11304 $this->Transform($tm);
11308 * Skew horizontally.
11309 * @param float $angle_x angle in degrees between -90 (skew to the left) and 90 (skew to the right)
11310 * @param float|null $x abscissa of the skewing center. default is current x position
11311 * @param float|null $y ordinate of the skewing center. default is current y position
11313 * @since 2.1.000 (2008-01-07)
11314 * @see StartTransform(), StopTransform()
11316 public function SkewX($angle_x, $x=null, $y=null) {
11317 $this->Skew($angle_x, 0, $x, $y);
11322 * @param float $angle_y angle in degrees between -90 (skew to the bottom) and 90 (skew to the top)
11323 * @param float|null $x abscissa of the skewing center. default is current x position
11324 * @param float|null $y ordinate of the skewing center. default is current y position
11326 * @since 2.1.000 (2008-01-07)
11327 * @see StartTransform(), StopTransform()
11329 public function SkewY($angle_y, $x=null, $y=null) {
11330 $this->Skew(0, $angle_y, $x, $y);
11335 * @param float $angle_x angle in degrees between -90 (skew to the left) and 90 (skew to the right)
11336 * @param float $angle_y angle in degrees between -90 (skew to the bottom) and 90 (skew to the top)
11337 * @param float|null $x abscissa of the skewing center. default is current x position
11338 * @param float|null $y ordinate of the skewing center. default is current y position
11340 * @since 2.1.000 (2008-01-07)
11341 * @see StartTransform(), StopTransform()
11343 public function Skew($angle_x, $angle_y, $x=null, $y=null) {
11344 if (TCPDF_STATIC
::empty_string($x)) {
11347 if (TCPDF_STATIC
::empty_string($y)) {
11350 if (($angle_x <= -90) OR ($angle_x >= 90) OR ($angle_y <= -90) OR ($angle_y >= 90)) {
11351 $this->Error('Please use values between -90 and +90 degrees for Skewing.');
11354 $y = ($this->h
- $y) * $this->k
;
11355 //calculate elements of transformation matrix
11358 $tm[1] = tan(deg2rad($angle_y));
11359 $tm[2] = tan(deg2rad($angle_x));
11361 $tm[4] = -$tm[2] * $y;
11362 $tm[5] = -$tm[1] * $x;
11363 //skew the coordinate system
11364 $this->Transform($tm);
11368 * Apply graphic transformations.
11369 * @param array $tm transformation matrix
11371 * @since 2.1.000 (2008-01-07)
11372 * @see StartTransform(), StopTransform()
11374 protected function Transform($tm) {
11375 if ($this->state
!= 2) {
11378 $this->_out(sprintf('%F %F %F %F %F %F cm', $tm[0], $tm[1], $tm[2], $tm[3], $tm[4], $tm[5]));
11379 // add tranformation matrix
11380 $this->transfmatrix
[$this->transfmatrix_key
][] = array('a' => $tm[0], 'b' => $tm[1], 'c' => $tm[2], 'd' => $tm[3], 'e' => $tm[4], 'f' => $tm[5]);
11381 // update transformation mark
11382 if ($this->inxobj
) {
11383 // we are inside an XObject template
11384 if (end($this->xobjects
[$this->xobjid
]['transfmrk']) !== false) {
11385 $key = key($this->xobjects
[$this->xobjid
]['transfmrk']);
11386 $this->xobjects
[$this->xobjid
]['transfmrk'][$key] = strlen($this->xobjects
[$this->xobjid
]['outdata']);
11388 } elseif (end($this->transfmrk
[$this->page
]) !== false) {
11389 $key = key($this->transfmrk
[$this->page
]);
11390 $this->transfmrk
[$this->page
][$key] = $this->pagelen
[$this->page
];
11394 // END TRANSFORMATIONS SECTION -------------------------
11396 // START GRAPHIC FUNCTIONS SECTION ---------------------
11397 // The following section is based on the code provided by David Hernandez Sanz
11400 * 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.
11401 * @param float $width The width.
11404 * @see Line(), Rect(), Cell(), MultiCell()
11406 public function setLineWidth($width) {
11408 $this->LineWidth
= $width;
11409 $this->linestyleWidth
= sprintf('%F w', ($width * $this->k
));
11410 if ($this->state
== 2) {
11411 $this->_out($this->linestyleWidth
);
11416 * Returns the current the line width.
11417 * @return int Line width
11419 * @since 2.1.000 (2008-01-07)
11420 * @see Line(), SetLineWidth()
11422 public function GetLineWidth() {
11423 return $this->LineWidth
;
11428 * @param array $style Line style. Array with keys among the following:
11430 * <li>width (float): Width of the line in user units.</li>
11431 * <li>cap (string): Type of cap to put on the line. Possible values are:
11432 * butt, round, square. The difference between "square" and "butt" is that
11433 * "square" projects a flat end past the end of the line.</li>
11434 * <li>join (string): Type of join. Possible values are: miter, round,
11436 * <li>dash (mixed): Dash pattern. Is 0 (without dash) or string with
11437 * series of length values, which are the lengths of the on and off dashes.
11438 * For example: "2" represents 2 on, 2 off, 2 on, 2 off, ...; "2,1" is 2 on,
11439 * 1 off, 2 on, 1 off, ...</li>
11440 * <li>phase (integer): Modifier on the dash pattern which is used to shift
11441 * the point at which the pattern starts.</li>
11442 * <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>
11444 * @param boolean $ret if true do not send the command.
11445 * @return string the PDF command
11447 * @since 2.1.000 (2008-01-08)
11449 public function setLineStyle($style, $ret=false) {
11450 $s = ''; // string to be returned
11451 if (!is_array($style)) {
11454 if (isset($style['width'])) {
11455 $this->LineWidth
= $style['width'];
11456 $this->linestyleWidth
= sprintf('%F w', ($style['width'] * $this->k
));
11457 $s .= $this->linestyleWidth
.' ';
11459 if (isset($style['cap'])) {
11460 $ca = array('butt' => 0, 'round'=> 1, 'square' => 2);
11461 if (isset($ca[$style['cap']])) {
11462 $this->linestyleCap
= $ca[$style['cap']].' J';
11463 $s .= $this->linestyleCap
.' ';
11466 if (isset($style['join'])) {
11467 $ja = array('miter' => 0, 'round' => 1, 'bevel' => 2);
11468 if (isset($ja[$style['join']])) {
11469 $this->linestyleJoin
= $ja[$style['join']].' j';
11470 $s .= $this->linestyleJoin
.' ';
11473 if (isset($style['dash'])) {
11475 if ($style['dash']) {
11476 if (preg_match('/^.+,/', $style['dash']) > 0) {
11477 $tab = explode(',', $style['dash']);
11479 $tab = array($style['dash']);
11482 foreach ($tab as $i => $v) {
11484 $dash_string .= ' ';
11486 $dash_string .= sprintf('%F', $v);
11489 if (!isset($style['phase']) OR !$style['dash']) {
11490 $style['phase'] = 0;
11492 $this->linestyleDash
= sprintf('[%s] %F d', $dash_string, $style['phase']);
11493 $s .= $this->linestyleDash
.' ';
11495 if (isset($style['color'])) {
11496 $s .= $this->setDrawColorArray($style['color'], true).' ';
11498 if (!$ret AND ($this->state
== 2)) {
11505 * Begin a new subpath by moving the current point to coordinates (x, y), omitting any connecting line segment.
11506 * @param float $x Abscissa of point.
11507 * @param float $y Ordinate of point.
11509 * @since 2.1.000 (2008-01-08)
11511 protected function _outPoint($x, $y) {
11512 if ($this->state
== 2) {
11513 $this->_out(sprintf('%F %F m', ($x * $this->k
), (($this->h
- $y) * $this->k
)));
11518 * Append a straight line segment from the current point to the point (x, y).
11519 * The new current point shall be (x, y).
11520 * @param float $x Abscissa of end point.
11521 * @param float $y Ordinate of end point.
11523 * @since 2.1.000 (2008-01-08)
11525 protected function _outLine($x, $y) {
11526 if ($this->state
== 2) {
11527 $this->_out(sprintf('%F %F l', ($x * $this->k
), (($this->h
- $y) * $this->k
)));
11532 * Append a rectangle to the current path as a complete subpath, with lower-left corner (x, y) and dimensions widthand height in user space.
11533 * @param float $x Abscissa of upper-left corner.
11534 * @param float $y Ordinate of upper-left corner.
11535 * @param float $w Width.
11536 * @param float $h Height.
11537 * @param string $op options
11539 * @since 2.1.000 (2008-01-08)
11541 protected function _outRect($x, $y, $w, $h, $op) {
11542 if ($this->state
== 2) {
11543 $this->_out(sprintf('%F %F %F %F re %s', ($x * $this->k
), (($this->h
- $y) * $this->k
), ($w * $this->k
), (-$h * $this->k
), $op));
11548 * 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.
11549 * The new current point shall be (x3, y3).
11550 * @param float $x1 Abscissa of control point 1.
11551 * @param float $y1 Ordinate of control point 1.
11552 * @param float $x2 Abscissa of control point 2.
11553 * @param float $y2 Ordinate of control point 2.
11554 * @param float $x3 Abscissa of end point.
11555 * @param float $y3 Ordinate of end point.
11557 * @since 2.1.000 (2008-01-08)
11559 protected function _outCurve($x1, $y1, $x2, $y2, $x3, $y3) {
11560 if ($this->state
== 2) {
11561 $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
)));
11566 * 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.
11567 * The new current point shall be (x3, y3).
11568 * @param float $x2 Abscissa of control point 2.
11569 * @param float $y2 Ordinate of control point 2.
11570 * @param float $x3 Abscissa of end point.
11571 * @param float $y3 Ordinate of end point.
11573 * @since 4.9.019 (2010-04-26)
11575 protected function _outCurveV($x2, $y2, $x3, $y3) {
11576 if ($this->state
== 2) {
11577 $this->_out(sprintf('%F %F %F %F v', ($x2 * $this->k
), (($this->h
- $y2) * $this->k
), ($x3 * $this->k
), (($this->h
- $y3) * $this->k
)));
11582 * 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.
11583 * The new current point shall be (x3, y3).
11584 * @param float $x1 Abscissa of control point 1.
11585 * @param float $y1 Ordinate of control point 1.
11586 * @param float $x3 Abscissa of end point.
11587 * @param float $y3 Ordinate of end point.
11589 * @since 2.1.000 (2008-01-08)
11591 protected function _outCurveY($x1, $y1, $x3, $y3) {
11592 if ($this->state
== 2) {
11593 $this->_out(sprintf('%F %F %F %F y', ($x1 * $this->k
), (($this->h
- $y1) * $this->k
), ($x3 * $this->k
), (($this->h
- $y3) * $this->k
)));
11598 * Draws a line between two points.
11599 * @param float $x1 Abscissa of first point.
11600 * @param float $y1 Ordinate of first point.
11601 * @param float $x2 Abscissa of second point.
11602 * @param float $y2 Ordinate of second point.
11603 * @param array $style Line style. Array like for SetLineStyle(). Default value: default line style (empty array).
11606 * @see SetLineWidth(), SetDrawColor(), SetLineStyle()
11608 public function Line($x1, $y1, $x2, $y2, $style=array()) {
11609 if ($this->state
!= 2) {
11612 if (is_array($style)) {
11613 $this->setLineStyle($style);
11615 $this->_outPoint($x1, $y1);
11616 $this->_outLine($x2, $y2);
11621 * Draws a rectangle.
11622 * @param float $x Abscissa of upper-left corner.
11623 * @param float $y Ordinate of upper-left corner.
11624 * @param float $w Width.
11625 * @param float $h Height.
11626 * @param string $style Style of rendering. See the getPathPaintOperator() function for more information.
11627 * @param array $border_style Border style of rectangle. Array with keys among the following:
11629 * <li>all: Line style of all borders. Array like for SetLineStyle().</li>
11630 * <li>L, T, R, B or combinations: Line style of left, top, right or bottom border. Array like for SetLineStyle().</li>
11632 * If a key is not present or is null, the correspondent border is not drawn. Default value: default line style (empty array).
11633 * @param array $fill_color 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).
11636 * @see SetLineStyle()
11638 public function Rect($x, $y, $w, $h, $style='', $border_style=array(), $fill_color=array()) {
11639 if ($this->state
!= 2) {
11642 if (empty($style)) {
11645 if (!(strpos($style, 'F') === false) AND !empty($fill_color)) {
11646 // set background color
11647 $this->setFillColorArray($fill_color);
11649 if (!empty($border_style)) {
11650 if (isset($border_style['all']) AND !empty($border_style['all'])) {
11651 //set global style for border
11652 $this->setLineStyle($border_style['all']);
11653 $border_style = array();
11655 // remove stroke operator from style
11656 $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*' );
11657 if (isset($opnostroke[$style])) {
11658 $style = $opnostroke[$style];
11662 if (!empty($style)) {
11663 $op = TCPDF_STATIC
::getPathPaintOperator($style);
11664 $this->_outRect($x, $y, $w, $h, $op);
11666 if (!empty($border_style)) {
11667 $border_style2 = array();
11668 foreach ($border_style as $line => $value) {
11669 $length = strlen($line);
11670 for ($i = 0; $i < $length; ++
$i) {
11671 $border_style2[$line[$i]] = $value;
11674 $border_style = $border_style2;
11675 if (isset($border_style['L']) AND $border_style['L']) {
11676 $this->Line($x, $y, $x, $y +
$h, $border_style['L']);
11678 if (isset($border_style['T']) AND $border_style['T']) {
11679 $this->Line($x, $y, $x +
$w, $y, $border_style['T']);
11681 if (isset($border_style['R']) AND $border_style['R']) {
11682 $this->Line($x +
$w, $y, $x +
$w, $y +
$h, $border_style['R']);
11684 if (isset($border_style['B']) AND $border_style['B']) {
11685 $this->Line($x, $y +
$h, $x +
$w, $y +
$h, $border_style['B']);
11691 * Draws a Bezier curve.
11692 * The Bezier curve is a tangent to the line between the control points at
11693 * either end of the curve.
11694 * @param float $x0 Abscissa of start point.
11695 * @param float $y0 Ordinate of start point.
11696 * @param float $x1 Abscissa of control point 1.
11697 * @param float $y1 Ordinate of control point 1.
11698 * @param float $x2 Abscissa of control point 2.
11699 * @param float $y2 Ordinate of control point 2.
11700 * @param float $x3 Abscissa of end point.
11701 * @param float $y3 Ordinate of end point.
11702 * @param string $style Style of rendering. See the getPathPaintOperator() function for more information.
11703 * @param array $line_style Line style of curve. Array like for SetLineStyle(). Default value: default line style (empty array).
11704 * @param array $fill_color 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).
11706 * @see SetLineStyle()
11707 * @since 2.1.000 (2008-01-08)
11709 public function Curve($x0, $y0, $x1, $y1, $x2, $y2, $x3, $y3, $style='', $line_style=array(), $fill_color=array()) {
11710 if ($this->state
!= 2) {
11713 if (!(false === strpos($style, 'F')) AND is_array($fill_color)) {
11714 $this->setFillColorArray($fill_color);
11716 $op = TCPDF_STATIC
::getPathPaintOperator($style);
11718 $this->setLineStyle($line_style);
11720 $this->_outPoint($x0, $y0);
11721 $this->_outCurve($x1, $y1, $x2, $y2, $x3, $y3);
11726 * Draws a poly-Bezier curve.
11727 * Each Bezier curve segment is a tangent to the line between the control points at
11728 * either end of the curve.
11729 * @param float $x0 Abscissa of start point.
11730 * @param float $y0 Ordinate of start point.
11731 * @param float[] $segments An array of bezier descriptions. Format: array(x1, y1, x2, y2, x3, y3).
11732 * @param string $style Style of rendering. See the getPathPaintOperator() function for more information.
11733 * @param array $line_style Line style of curve. Array like for SetLineStyle(). Default value: default line style (empty array).
11734 * @param array $fill_color 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).
11736 * @see SetLineStyle()
11737 * @since 3.0008 (2008-05-12)
11739 public function Polycurve($x0, $y0, $segments, $style='', $line_style=array(), $fill_color=array()) {
11740 if ($this->state
!= 2) {
11743 if (!(false === strpos($style, 'F')) AND is_array($fill_color)) {
11744 $this->setFillColorArray($fill_color);
11746 $op = TCPDF_STATIC
::getPathPaintOperator($style);
11748 $line_style = array();
11751 $this->setLineStyle($line_style);
11753 $this->_outPoint($x0, $y0);
11754 foreach ($segments as $segment) {
11755 list($x1, $y1, $x2, $y2, $x3, $y3) = $segment;
11756 $this->_outCurve($x1, $y1, $x2, $y2, $x3, $y3);
11762 * Draws an ellipse.
11763 * An ellipse is formed from n Bezier curves.
11764 * @param float $x0 Abscissa of center point.
11765 * @param float $y0 Ordinate of center point.
11766 * @param float $rx Horizontal radius.
11767 * @param float $ry Vertical radius (if ry = 0 then is a circle, see Circle()). Default value: 0.
11768 * @param float $angle Angle oriented (anti-clockwise). Default value: 0.
11769 * @param float $astart Angle start of draw line. Default value: 0.
11770 * @param float $afinish Angle finish of draw line. Default value: 360.
11771 * @param string $style Style of rendering. See the getPathPaintOperator() function for more information.
11772 * @param array $line_style Line style of ellipse. Array like for SetLineStyle(). Default value: default line style (empty array).
11773 * @param array $fill_color 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).
11774 * @param integer $nc Number of curves used to draw a 90 degrees portion of ellipse.
11775 * @author Nicola Asuni
11777 * @since 2.1.000 (2008-01-08)
11779 public function Ellipse($x0, $y0, $rx, $ry=0, $angle=0, $astart=0, $afinish=360, $style='', $line_style=array(), $fill_color=array(), $nc=2) {
11780 if ($this->state
!= 2) {
11783 if (TCPDF_STATIC
::empty_string($ry) OR ($ry == 0)) {
11786 if (!(false === strpos($style, 'F')) AND is_array($fill_color)) {
11787 $this->setFillColorArray($fill_color);
11789 $op = TCPDF_STATIC
::getPathPaintOperator($style);
11791 $line_style = array();
11794 $this->setLineStyle($line_style);
11796 $this->_outellipticalarc($x0, $y0, $rx, $ry, $angle, $astart, $afinish, false, $nc, true, true, false);
11801 * Append an elliptical arc to the current path.
11802 * An ellipse is formed from n Bezier curves.
11803 * @param float $xc Abscissa of center point.
11804 * @param float $yc Ordinate of center point.
11805 * @param float $rx Horizontal radius.
11806 * @param float $ry Vertical radius (if ry = 0 then is a circle, see Circle()). Default value: 0.
11807 * @param float $xang Angle between the X-axis and the major axis of the ellipse. Default value: 0.
11808 * @param float $angs Angle start of draw line. Default value: 0.
11809 * @param float $angf Angle finish of draw line. Default value: 360.
11810 * @param boolean $pie if true do not mark the border point (used to draw pie sectors).
11811 * @param integer $nc Number of curves used to draw a 90 degrees portion of ellipse.
11812 * @param boolean $startpoint if true output a starting point.
11813 * @param boolean $ccw if true draws in counter-clockwise.
11814 * @param boolean $svg if true the angles are in svg mode (already calculated).
11815 * @return array bounding box coordinates (x min, y min, x max, y max)
11816 * @author Nicola Asuni
11818 * @since 4.9.019 (2010-04-26)
11820 protected function _outellipticalarc($xc, $yc, $rx, $ry, $xang=0, $angs=0, $angf=360, $pie=false, $nc=2, $startpoint=true, $ccw=true, $svg=false) {
11821 if (($rx <= 0) OR ($ry < 0)) {
11828 $xmin = 2147483647;
11829 $ymin = 2147483647;
11833 // center of the arc
11834 $this->_outPoint($xc, $yc);
11836 $xang = deg2rad((float) $xang);
11837 $angs = deg2rad((float) $angs);
11838 $angf = deg2rad((float) $angf);
11843 $as = atan2((sin($angs) / $ry), (cos($angs) / $rx));
11844 $af = atan2((sin($angf) / $ry), (cos($angf) / $rx));
11852 if ($ccw AND ($as > $af)) {
11853 // reverse rotation
11855 } elseif (!$ccw AND ($as < $af)) {
11856 // reverse rotation
11859 $total_angle = ($af - $as);
11863 // total arcs to draw
11864 $nc *= (2 * abs($total_angle) / M_PI
);
11865 $nc = round($nc) +
1;
11866 // angle of each arc
11867 $arcang = ($total_angle / $nc);
11868 // center point in PDF coordinates
11870 $y0 = ($this->h
- $yc);
11873 $alpha = sin($arcang) * ((sqrt(4 +
(3 * pow(tan(($arcang) / 2), 2))) - 1) / 3);
11874 $cos_xang = cos($xang);
11875 $sin_xang = sin($xang);
11876 $cos_ang = cos($ang);
11877 $sin_ang = sin($ang);
11879 $px1 = $x0 +
($rx * $cos_xang * $cos_ang) - ($ry * $sin_xang * $sin_ang);
11880 $py1 = $y0 +
($rx * $sin_xang * $cos_ang) +
($ry * $cos_xang * $sin_ang);
11881 // first Bezier control point
11882 $qx1 = ($alpha * ((-$rx * $cos_xang * $sin_ang) - ($ry * $sin_xang * $cos_ang)));
11883 $qy1 = ($alpha * ((-$rx * $sin_xang * $sin_ang) +
($ry * $cos_xang * $cos_ang)));
11885 // line from center to arc starting point
11886 $this->_outLine($px1, $this->h
- $py1);
11887 } elseif ($startpoint) {
11888 // arc starting point
11889 $this->_outPoint($px1, $this->h
- $py1);
11892 for ($i = 1; $i <= $nc; ++
$i) {
11894 $ang = $as +
($i * $arcang);
11898 $cos_ang = cos($ang);
11899 $sin_ang = sin($ang);
11900 // second arc point
11901 $px2 = $x0 +
($rx * $cos_xang * $cos_ang) - ($ry * $sin_xang * $sin_ang);
11902 $py2 = $y0 +
($rx * $sin_xang * $cos_ang) +
($ry * $cos_xang * $sin_ang);
11903 // second Bezier control point
11904 $qx2 = ($alpha * ((-$rx * $cos_xang * $sin_ang) - ($ry * $sin_xang * $cos_ang)));
11905 $qy2 = ($alpha * ((-$rx * $sin_xang * $sin_ang) +
($ry * $cos_xang * $cos_ang)));
11907 $cx1 = ($px1 +
$qx1);
11908 $cy1 = ($this->h
- ($py1 +
$qy1));
11909 $cx2 = ($px2 - $qx2);
11910 $cy2 = ($this->h
- ($py2 - $qy2));
11912 $cy3 = ($this->h
- $py2);
11913 $this->_outCurve($cx1, $cy1, $cx2, $cy2, $cx3, $cy3);
11914 // get bounding box coordinates
11915 $xmin = min($xmin, $cx1, $cx2, $cx3);
11916 $ymin = min($ymin, $cy1, $cy2, $cy3);
11917 $xmax = max($xmax, $cx1, $cx2, $cx3);
11918 $ymax = max($ymax, $cy1, $cy2, $cy3);
11919 // move to next point
11926 $this->_outLine($xc, $yc);
11927 // get bounding box coordinates
11928 $xmin = min($xmin, $xc);
11929 $ymin = min($ymin, $yc);
11930 $xmax = max($xmax, $xc);
11931 $ymax = max($ymax, $yc);
11933 return array($xmin, $ymin, $xmax, $ymax);
11938 * A circle is formed from n Bezier curves.
11939 * @param float $x0 Abscissa of center point.
11940 * @param float $y0 Ordinate of center point.
11941 * @param float $r Radius.
11942 * @param float $angstr Angle start of draw line. Default value: 0.
11943 * @param float $angend Angle finish of draw line. Default value: 360.
11944 * @param string $style Style of rendering. See the getPathPaintOperator() function for more information.
11945 * @param array $line_style Line style of circle. Array like for SetLineStyle(). Default value: default line style (empty array).
11946 * @param array $fill_color Fill color. Format: array(red, green, blue). Default value: default color (empty array).
11947 * @param integer $nc Number of curves used to draw a 90 degrees portion of circle.
11949 * @since 2.1.000 (2008-01-08)
11951 public function Circle($x0, $y0, $r, $angstr=0, $angend=360, $style='', $line_style=array(), $fill_color=array(), $nc=2) {
11952 $this->Ellipse($x0, $y0, $r, $r, 0, $angstr, $angend, $style, $line_style, $fill_color, $nc);
11956 * Draws a polygonal line
11957 * @param array $p Points 0 to ($np - 1). Array with values (x0, y0, x1, y1,..., x(np-1), y(np - 1))
11958 * @param string $style Style of rendering. See the getPathPaintOperator() function for more information.
11959 * @param array $line_style Line style of polygon. Array with keys among the following:
11961 * <li>all: Line style of all lines. Array like for SetLineStyle().</li>
11962 * <li>0 to ($np - 1): Line style of each line. Array like for SetLineStyle().</li>
11964 * If a key is not present or is null, not draws the line. Default value is default line style (empty array).
11965 * @param array $fill_color 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).
11966 * @since 4.8.003 (2009-09-15)
11969 public function PolyLine($p, $style='', $line_style=array(), $fill_color=array()) {
11970 $this->Polygon($p, $style, $line_style, $fill_color, false);
11975 * @param array $p Points 0 to ($np - 1). Array with values (x0, y0, x1, y1,..., x(np-1), y(np - 1))
11976 * @param string $style Style of rendering. See the getPathPaintOperator() function for more information.
11977 * @param array $line_style Line style of polygon. Array with keys among the following:
11979 * <li>all: Line style of all lines. Array like for SetLineStyle().</li>
11980 * <li>0 to ($np - 1): Line style of each line. Array like for SetLineStyle().</li>
11982 * If a key is not present or is null, not draws the line. Default value is default line style (empty array).
11983 * @param array $fill_color 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).
11984 * @param boolean $closed if true the polygon is closes, otherwise will remain open
11986 * @since 2.1.000 (2008-01-08)
11988 public function Polygon($p, $style='', $line_style=array(), $fill_color=array(), $closed=true) {
11989 if ($this->state
!= 2) {
11992 $nc = count($p); // number of coordinates
11993 $np = $nc / 2; // number of points
11995 // close polygon by adding the first 2 points at the end (one line)
11996 for ($i = 0; $i < 4; ++
$i) {
11997 $p[$nc +
$i] = $p[$i];
11999 // copy style for the last added line
12000 if (isset($line_style[0])) {
12001 $line_style[$np] = $line_style[0];
12005 if (!(false === strpos($style, 'F')) AND is_array($fill_color)) {
12006 $this->setFillColorArray($fill_color);
12008 $op = TCPDF_STATIC
::getPathPaintOperator($style);
12010 $line_style = array();
12014 if (isset($line_style['all'])) {
12015 $this->setLineStyle($line_style['all']);
12021 $this->_outPoint($p[0], $p[1]);
12022 for ($i = 2; $i < $nc; $i = $i +
2) {
12023 $this->_outLine($p[$i], $p[$i +
1]);
12028 $this->_outPoint($p[0], $p[1]);
12029 for ($i = 2; $i < $nc; $i = $i +
2) {
12030 $line_num = ($i / 2) - 1;
12031 if (isset($line_style[$line_num])) {
12032 if ($line_style[$line_num] != 0) {
12033 if (is_array($line_style[$line_num])) {
12035 $this->setLineStyle($line_style[$line_num]);
12036 $this->_outPoint($p[$i - 2], $p[$i - 1]);
12037 $this->_outLine($p[$i], $p[$i +
1]);
12039 $this->_outPoint($p[$i], $p[$i +
1]);
12041 $this->_outLine($p[$i], $p[$i +
1]);
12045 $this->_outLine($p[$i], $p[$i +
1]);
12052 $this->_outPoint($p[0], $p[1]);
12053 for ($i = 2; $i < $nc; $i = $i +
2) {
12054 $this->_outLine($p[$i], $p[$i +
1]);
12061 * Draws a regular polygon.
12062 * @param float $x0 Abscissa of center point.
12063 * @param float $y0 Ordinate of center point.
12064 * @param float $r Radius of inscribed circle.
12065 * @param integer $ns Number of sides.
12066 * @param float $angle Angle oriented (anti-clockwise). Default value: 0.
12067 * @param boolean $draw_circle Draw inscribed circle or not. Default value: false.
12068 * @param string $style Style of rendering. See the getPathPaintOperator() function for more information.
12069 * @param array $line_style Line style of polygon sides. Array with keys among the following:
12071 * <li>all: Line style of all sides. Array like for SetLineStyle().</li>
12072 * <li>0 to ($ns - 1): Line style of each side. Array like for SetLineStyle().</li>
12074 * If a key is not present or is null, not draws the side. Default value is default line style (empty array).
12075 * @param array $fill_color Fill color. Format: array(red, green, blue). Default value: default color (empty array).
12076 * @param string $circle_style Style of rendering of inscribed circle (if draws). Possible values are:
12078 * <li>D or empty string: Draw (default).</li>
12079 * <li>F: Fill.</li>
12080 * <li>DF or FD: Draw and fill.</li>
12081 * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
12082 * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
12084 * @param array $circle_outLine_style Line style of inscribed circle (if draws). Array like for SetLineStyle(). Default value: default line style (empty array).
12085 * @param array $circle_fill_color Fill color of inscribed circle (if draws). Format: array(red, green, blue). Default value: default color (empty array).
12087 * @since 2.1.000 (2008-01-08)
12089 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()) {
12093 if ($draw_circle) {
12094 $this->Circle($x0, $y0, $r, 0, 360, $circle_style, $circle_outLine_style, $circle_fill_color);
12097 for ($i = 0; $i < $ns; ++
$i) {
12098 $a = $angle +
($i * 360 / $ns);
12099 $a_rad = deg2rad((float) $a);
12100 $p[] = $x0 +
($r * sin($a_rad));
12101 $p[] = $y0 +
($r * cos($a_rad));
12103 $this->Polygon($p, $style, $line_style, $fill_color);
12107 * Draws a star polygon
12108 * @param float $x0 Abscissa of center point.
12109 * @param float $y0 Ordinate of center point.
12110 * @param float $r Radius of inscribed circle.
12111 * @param integer $nv Number of vertices.
12112 * @param integer $ng Number of gap (if ($ng % $nv = 1) then is a regular polygon).
12113 * @param float $angle Angle oriented (anti-clockwise). Default value: 0.
12114 * @param boolean $draw_circle Draw inscribed circle or not. Default value is false.
12115 * @param string $style Style of rendering. See the getPathPaintOperator() function for more information.
12116 * @param array $line_style Line style of polygon sides. Array with keys among the following:
12118 * <li>all: Line style of all sides. Array like for
12119 * SetLineStyle().</li>
12120 * <li>0 to (n - 1): Line style of each side. Array like for SetLineStyle().</li>
12122 * If a key is not present or is null, not draws the side. Default value is default line style (empty array).
12123 * @param array $fill_color Fill color. Format: array(red, green, blue). Default value: default color (empty array).
12124 * @param string $circle_style Style of rendering of inscribed circle (if draws). Possible values are:
12126 * <li>D or empty string: Draw (default).</li>
12127 * <li>F: Fill.</li>
12128 * <li>DF or FD: Draw and fill.</li>
12129 * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
12130 * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
12132 * @param array $circle_outLine_style Line style of inscribed circle (if draws). Array like for SetLineStyle(). Default value: default line style (empty array).
12133 * @param array $circle_fill_color Fill color of inscribed circle (if draws). Format: array(red, green, blue). Default value: default color (empty array).
12135 * @since 2.1.000 (2008-01-08)
12137 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()) {
12141 if ($draw_circle) {
12142 $this->Circle($x0, $y0, $r, 0, 360, $circle_style, $circle_outLine_style, $circle_fill_color);
12145 $visited = array();
12146 for ($i = 0; $i < $nv; ++
$i) {
12147 $a = $angle +
($i * 360 / $nv);
12148 $a_rad = deg2rad((float) $a);
12149 $p2[] = $x0 +
($r * sin($a_rad));
12150 $p2[] = $y0 +
($r * cos($a_rad));
12151 $visited[] = false;
12156 $p[] = $p2[$i * 2];
12157 $p[] = $p2[($i * 2) +
1];
12158 $visited[$i] = true;
12161 } while (!$visited[$i]);
12162 $this->Polygon($p, $style, $line_style, $fill_color);
12166 * Draws a rounded rectangle.
12167 * @param float $x Abscissa of upper-left corner.
12168 * @param float $y Ordinate of upper-left corner.
12169 * @param float $w Width.
12170 * @param float $h Height.
12171 * @param float $r the radius of the circle used to round off the corners of the rectangle.
12172 * @param string $round_corner Draws rounded corner or not. String with a 0 (not rounded i-corner) or 1 (rounded i-corner) in i-position. Positions are, in order and begin to 0: top right, bottom right, bottom left and top left. Default value: all rounded corner ("1111").
12173 * @param string $style Style of rendering. See the getPathPaintOperator() function for more information.
12174 * @param array $border_style Border style of rectangle. Array like for SetLineStyle(). Default value: default line style (empty array).
12175 * @param array $fill_color 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).
12177 * @since 2.1.000 (2008-01-08)
12179 public function RoundedRect($x, $y, $w, $h, $r, $round_corner='1111', $style='', $border_style=array(), $fill_color=array()) {
12180 $this->RoundedRectXY($x, $y, $w, $h, $r, $r, $round_corner, $style, $border_style, $fill_color);
12184 * Draws a rounded rectangle.
12185 * @param float $x Abscissa of upper-left corner.
12186 * @param float $y Ordinate of upper-left corner.
12187 * @param float $w Width.
12188 * @param float $h Height.
12189 * @param float $rx the x-axis radius of the ellipse used to round off the corners of the rectangle.
12190 * @param float $ry the y-axis radius of the ellipse used to round off the corners of the rectangle.
12191 * @param string $round_corner Draws rounded corner or not. String with a 0 (not rounded i-corner) or 1 (rounded i-corner) in i-position. Positions are, in order and begin to 0: top right, bottom right, bottom left and top left. Default value: all rounded corner ("1111").
12192 * @param string $style Style of rendering. See the getPathPaintOperator() function for more information.
12193 * @param array $border_style Border style of rectangle. Array like for SetLineStyle(). Default value: default line style (empty array).
12194 * @param array $fill_color 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).
12196 * @since 4.9.019 (2010-04-22)
12198 public function RoundedRectXY($x, $y, $w, $h, $rx, $ry, $round_corner='1111', $style='', $border_style=array(), $fill_color=array()) {
12199 if ($this->state
!= 2) {
12202 if (($round_corner == '0000') OR (($rx == $ry) AND ($rx == 0))) {
12204 $this->Rect($x, $y, $w, $h, $style, $border_style, $fill_color);
12208 if (!(false === strpos($style, 'F')) AND is_array($fill_color)) {
12209 $this->setFillColorArray($fill_color);
12211 $op = TCPDF_STATIC
::getPathPaintOperator($style);
12213 $border_style = array();
12215 if ($border_style) {
12216 $this->setLineStyle($border_style);
12218 $MyArc = 4 / 3 * (sqrt(2) - 1);
12219 $this->_outPoint($x +
$rx, $y);
12220 $xc = $x +
$w - $rx;
12222 $this->_outLine($xc, $y);
12223 if ($round_corner[0]) {
12224 $this->_outCurve($xc +
($rx * $MyArc), $yc - $ry, $xc +
$rx, $yc - ($ry * $MyArc), $xc +
$rx, $yc);
12226 $this->_outLine($x +
$w, $y);
12228 $xc = $x +
$w - $rx;
12229 $yc = $y +
$h - $ry;
12230 $this->_outLine($x +
$w, $yc);
12231 if ($round_corner[1]) {
12232 $this->_outCurve($xc +
$rx, $yc +
($ry * $MyArc), $xc +
($rx * $MyArc), $yc +
$ry, $xc, $yc +
$ry);
12234 $this->_outLine($x +
$w, $y +
$h);
12237 $yc = $y +
$h - $ry;
12238 $this->_outLine($xc, $y +
$h);
12239 if ($round_corner[2]) {
12240 $this->_outCurve($xc - ($rx * $MyArc), $yc +
$ry, $xc - $rx, $yc +
($ry * $MyArc), $xc - $rx, $yc);
12242 $this->_outLine($x, $y +
$h);
12246 $this->_outLine($x, $yc);
12247 if ($round_corner[3]) {
12248 $this->_outCurve($xc - $rx, $yc - ($ry * $MyArc), $xc - ($rx * $MyArc), $yc - $ry, $xc, $yc - $ry);
12250 $this->_outLine($x, $y);
12251 $this->_outLine($x +
$rx, $y);
12257 * Draws a grahic arrow.
12258 * @param float $x0 Abscissa of first point.
12259 * @param float $y0 Ordinate of first point.
12260 * @param float $x1 Abscissa of second point.
12261 * @param float $y1 Ordinate of second point.
12262 * @param int $head_style (0 = draw only arrowhead arms, 1 = draw closed arrowhead, but no fill, 2 = closed and filled arrowhead, 3 = filled arrowhead)
12263 * @param float $arm_size length of arrowhead arms
12264 * @param int $arm_angle angle between an arm and the shaft
12265 * @author Piotr Galecki, Nicola Asuni, Andy Meier
12266 * @since 4.6.018 (2009-07-10)
12268 public function Arrow($x0, $y0, $x1, $y1, $head_style=0, $arm_size=5, $arm_angle=15) {
12269 // getting arrow direction angle
12270 // 0 deg angle is when both arms go along X axis. angle grows clockwise.
12271 $dir_angle = atan2(($y0 - $y1), ($x0 - $x1));
12272 if ($dir_angle < 0) {
12273 $dir_angle +
= (2 * M_PI
);
12275 $arm_angle = deg2rad($arm_angle);
12278 if ($head_style > 0) {
12279 // calculate the stopping point for the arrow shaft
12280 $sx1 = $x1 +
(($arm_size - $this->LineWidth
) * cos($dir_angle));
12281 $sy1 = $y1 +
(($arm_size - $this->LineWidth
) * sin($dir_angle));
12283 // main arrow line / shaft
12284 $this->Line($x0, $y0, $sx1, $sy1);
12285 // left arrowhead arm tip
12286 $x2L = $x1 +
($arm_size * cos($dir_angle +
$arm_angle));
12287 $y2L = $y1 +
($arm_size * sin($dir_angle +
$arm_angle));
12288 // right arrowhead arm tip
12289 $x2R = $x1 +
($arm_size * cos($dir_angle - $arm_angle));
12290 $y2R = $y1 +
($arm_size * sin($dir_angle - $arm_angle));
12293 switch ($head_style) {
12295 // draw only arrowhead arms
12297 $style = array(1, 1, 0);
12301 // draw closed arrowhead, but no fill
12306 // closed and filled arrowhead
12311 // filled arrowhead
12316 $this->Polygon(array($x2L, $y2L, $x1, $y1, $x2R, $y2R), $mode, $style, array());
12319 // END GRAPHIC FUNCTIONS SECTION -----------------------
12322 * Add a Named Destination.
12323 * NOTE: destination names are unique, so only last entry will be saved.
12324 * @param string $name Destination name.
12325 * @param float $y Y position in user units of the destiantion on the selected page (default = -1 = current position; 0 = page start;).
12326 * @param int|string $page 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.
12327 * @param float $x X position in user units of the destiantion on the selected page (default = -1 = current position;).
12328 * @return string|false Stripped named destination identifier or false in case of error.
12330 * @author Christian Deligant, Nicola Asuni
12331 * @since 5.9.097 (2011-06-23)
12333 public function setDestination($name, $y=-1, $page='', $x=-1) {
12334 // remove unsupported characters
12335 $name = TCPDF_STATIC
::encodeNameObject($name);
12336 if (TCPDF_STATIC
::empty_string($name)) {
12340 $y = $this->GetY();
12341 } elseif ($y < 0) {
12343 } elseif ($y > $this->h
) {
12347 $x = $this->GetX();
12348 } elseif ($x < 0) {
12350 } elseif ($x > $this->w
) {
12354 if (!empty($page) AND (substr($page, 0, 1) == '*')) {
12355 $page = intval(substr($page, 1));
12356 // this page number will not be changed when moving/add/deleting pages
12359 if (empty($page)) {
12360 $page = $this->PageNo();
12361 if (empty($page)) {
12365 $this->dests
[$name] = array('x' => $x, 'y' => $y, 'p' => $page, 'f' => $fixed);
12370 * Return the Named Destination array.
12371 * @return array Named Destination array.
12373 * @author Nicola Asuni
12374 * @since 5.9.097 (2011-06-23)
12376 public function getDestination() {
12377 return $this->dests
;
12381 * Insert Named Destinations.
12383 * @author Johannes G\FCntert, Nicola Asuni
12384 * @since 5.9.098 (2011-06-23)
12386 protected function _putdests() {
12387 if (empty($this->dests
)) {
12390 $this->n_dests
= $this->_newobj();
12392 foreach($this->dests
as $name => $o) {
12393 $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
)));
12396 $out .= "\n".'endobj';
12401 * Adds a bookmark - alias for Bookmark().
12402 * @param string $txt Bookmark description.
12403 * @param int $level Bookmark level (minimum value is 0).
12404 * @param float $y Y position in user units of the bookmark on the selected page (default = -1 = current position; 0 = page start;).
12405 * @param int|string $page 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.
12406 * @param string $style Font style: B = Bold, I = Italic, BI = Bold + Italic.
12407 * @param array $color RGB color array (values from 0 to 255).
12408 * @param float $x X position in user units of the bookmark on the selected page (default = -1 = current position;).
12409 * @param mixed $link URL, or numerical link ID, or named destination (# character followed by the destination name), or embedded file (* character followed by the file name).
12412 public function setBookmark($txt, $level=0, $y=-1, $page='', $style='', $color=array(0,0,0), $x=-1, $link='') {
12413 $this->Bookmark($txt, $level, $y, $page, $style, $color, $x, $link);
12418 * @param string $txt Bookmark description.
12419 * @param int $level Bookmark level (minimum value is 0).
12420 * @param float $y Y position in user units of the bookmark on the selected page (default = -1 = current position; 0 = page start;).
12421 * @param int|string $page 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.
12422 * @param string $style Font style: B = Bold, I = Italic, BI = Bold + Italic.
12423 * @param array $color RGB color array (values from 0 to 255).
12424 * @param float $x X position in user units of the bookmark on the selected page (default = -1 = current position;).
12425 * @param mixed $link URL, or numerical link ID, or named destination (# character followed by the destination name), or embedded file (* character followed by the file name).
12427 * @since 2.1.002 (2008-02-12)
12429 public function Bookmark($txt, $level=0, $y=-1, $page='', $style='', $color=array(0,0,0), $x=-1, $link='') {
12433 if (isset($this->outlines
[0])) {
12434 $lastoutline = end($this->outlines
);
12435 $maxlevel = $lastoutline['l'] +
1;
12439 if ($level > $maxlevel) {
12440 $level = $maxlevel;
12443 $y = $this->GetY();
12444 } elseif ($y < 0) {
12446 } elseif ($y > $this->h
) {
12450 $x = $this->GetX();
12451 } elseif ($x < 0) {
12453 } elseif ($x > $this->w
) {
12457 $pageAsString = (string) $page;
12458 if ($pageAsString && $pageAsString[0] == '*') {
12459 $page = intval(substr($page, 1));
12460 // this page number will not be changed when moving/add/deleting pages
12463 if (empty($page)) {
12464 $page = $this->PageNo();
12465 if (empty($page)) {
12469 $this->outlines
[] = array('t' => $txt, 'l' => $level, 'x' => $x, 'y' => $y, 'p' => $page, 'f' => $fixed, 's' => strtoupper($style), 'c' => $color, 'u' => $link);
12473 * Sort bookmarks for page and key.
12475 * @since 5.9.119 (2011-09-19)
12477 protected function sortBookmarks() {
12478 // get sorting columns
12479 $outline_p = array();
12480 $outline_y = array();
12481 foreach ($this->outlines
as $key => $row) {
12482 $outline_p[$key] = $row['p'];
12483 $outline_k[$key] = $key;
12485 // sort outlines by page and original position
12486 array_multisort($outline_p, SORT_NUMERIC
, SORT_ASC
, $outline_k, SORT_NUMERIC
, SORT_ASC
, $this->outlines
);
12490 * Create a bookmark PDF string.
12492 * @author Olivier Plathey, Nicola Asuni
12493 * @since 2.1.002 (2008-02-12)
12495 protected function _putbookmarks() {
12496 $nb = count($this->outlines
);
12501 $this->sortBookmarks();
12504 foreach ($this->outlines
as $i => $o) {
12506 $parent = $lru[($o['l'] - 1)];
12507 //Set parent and last pointers
12508 $this->outlines
[$i]['parent'] = $parent;
12509 $this->outlines
[$parent]['last'] = $i;
12510 if ($o['l'] > $level) {
12511 //Level increasing: set first pointer
12512 $this->outlines
[$parent]['first'] = $i;
12515 $this->outlines
[$i]['parent'] = $nb;
12517 if (($o['l'] <= $level) AND ($i > 0)) {
12518 //Set prev and next pointers
12519 $prev = $lru[$o['l']];
12520 $this->outlines
[$prev]['next'] = $i;
12521 $this->outlines
[$i]['prev'] = $prev;
12523 $lru[$o['l']] = $i;
12528 $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';
12529 foreach ($this->outlines
as $i => $o) {
12530 $oid = $this->_newobj();
12531 // covert HTML title to string
12532 $title = preg_replace($nltags, "\n", $o['t']);
12533 $title = preg_replace("/[\r]+/si", '', $title);
12534 $title = preg_replace("/[\n]+/si", "\n", $title);
12535 $title = strip_tags($title);
12536 $title = $this->stringTrim($title);
12537 $out = '<</Title '.$this->_textstring($title, $oid);
12538 $out .= ' /Parent '.($n +
$o['parent']).' 0 R';
12539 if (isset($o['prev'])) {
12540 $out .= ' /Prev '.($n +
$o['prev']).' 0 R';
12542 if (isset($o['next'])) {
12543 $out .= ' /Next '.($n +
$o['next']).' 0 R';
12545 if (isset($o['first'])) {
12546 $out .= ' /First '.($n +
$o['first']).' 0 R';
12548 if (isset($o['last'])) {
12549 $out .= ' /Last '.($n +
$o['last']).' 0 R';
12551 if (isset($o['u']) AND !empty($o['u'])) {
12553 if (is_string($o['u'])) {
12554 if ($o['u'][0] == '#') {
12555 // internal destination
12556 $out .= ' /Dest /'.TCPDF_STATIC
::encodeNameObject(substr($o['u'], 1));
12557 } elseif ($o['u'][0] == '%') {
12558 // embedded PDF file
12559 $filename = basename(substr($o['u'], 1));
12560 $out .= ' /A <</S /GoToE /D [0 /Fit] /NewWindow true /T << /R /C /P '.($o['p'] - 1).' /A '.$this->embeddedfiles
[$filename]['a'].' >> >>';
12561 } elseif ($o['u'][0] == '*') {
12562 // embedded generic file
12563 $filename = basename(substr($o['u'], 1));
12564 $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});';
12565 $out .= ' /A <</S /JavaScript /JS '.$this->_textstring($jsa, $oid).'>>';
12567 // external URI link
12568 $out .= ' /A <</S /URI /URI '.$this->_datastring($this->unhtmlentities($o['u']), $oid).'>>';
12570 } elseif (isset($this->links
[$o['u']])) {
12571 // internal link ID
12572 $l = $this->links
[$o['u']];
12573 if (isset($this->page_obj_id
[($l['p'])])) {
12574 $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
)));
12577 } elseif (isset($this->page_obj_id
[($o['p'])])) {
12579 $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
)));
12583 if (!empty($o['s'])) {
12585 if (strpos($o['s'], 'B') !== false) {
12589 if (strpos($o['s'], 'I') !== false) {
12593 $out .= sprintf(' /F %d', $style);
12594 // set bookmark color
12595 if (isset($o['c']) AND is_array($o['c']) AND (count($o['c']) == 3)) {
12596 $color = array_values($o['c']);
12597 $out .= sprintf(' /C [%F %F %F]', ($color[0] / 255), ($color[1] / 255), ($color[2] / 255));
12600 $out .= ' /C [0.0 0.0 0.0]';
12602 $out .= ' /Count 0'; // normally closed item
12604 $out .= "\n".'endobj';
12608 $this->OutlineRoot
= $this->_newobj();
12609 $this->_out('<< /Type /Outlines /First '.$n.' 0 R /Last '.($n +
$lru[0]).' 0 R >>'."\n".'endobj');
12612 // --- JAVASCRIPT ------------------------------------------------------
12615 * Adds a javascript
12616 * @param string $script Javascript code
12618 * @author Johannes G\FCntert, Nicola Asuni
12619 * @since 2.1.002 (2008-02-12)
12621 public function IncludeJS($script) {
12622 $this->javascript
.= $script;
12626 * Adds a javascript object and return object ID
12627 * @param string $script Javascript code
12628 * @param boolean $onload if true executes this object when opening the document
12629 * @return int internal object ID
12631 * @author Nicola Asuni
12632 * @since 4.8.000 (2009-09-07)
12634 public function addJavascriptObject($script, $onload=false) {
12635 if ($this->pdfa_mode
) {
12636 // javascript is not allowed in PDF/A mode
12640 $this->js_objects
[$this->n
] = array('n' => $this->n
, 'js' => $script, 'onload' => $onload);
12645 * Create a javascript PDF string.
12647 * @author Johannes G\FCntert, Nicola Asuni
12648 * @since 2.1.002 (2008-02-12)
12650 protected function _putjavascript() {
12651 if ($this->pdfa_mode
OR (empty($this->javascript
) AND empty($this->js_objects
))) {
12654 if (strpos($this->javascript
, 'this.addField') > 0) {
12655 if (!$this->ur
['enabled']) {
12656 //$this->setUserRights();
12658 // the following two lines are used to avoid form fields duplication after saving
12659 // The addField method only works when releasing user rights (UR3)
12660 $jsa = sprintf("ftcpdfdocsaved=this.addField('%s','%s',%d,[%F,%F,%F,%F]);", 'tcpdfdocsaved', 'text', 0, 0, 1, 0, 1);
12661 $jsb = "getField('tcpdfdocsaved').value='saved';";
12662 $this->javascript
= $jsa."\n".$this->javascript
."\n".$jsb;
12664 // name tree for javascript
12665 $this->n_js
= '<< /Names [';
12666 if (!empty($this->javascript
)) {
12667 $this->n_js
.= ' (EmbeddedJS) '.($this->n +
1).' 0 R';
12669 if (!empty($this->js_objects
)) {
12670 foreach ($this->js_objects
as $key => $val) {
12671 if ($val['onload']) {
12672 $this->n_js
.= ' (JS'.$key.') '.$key.' 0 R';
12676 $this->n_js
.= ' ] >>';
12677 // default Javascript object
12678 if (!empty($this->javascript
)) {
12679 $obj_id = $this->_newobj();
12680 $out = '<< /S /JavaScript';
12681 $out .= ' /JS '.$this->_textstring($this->javascript
, $obj_id);
12683 $out .= "\n".'endobj';
12686 // additional Javascript objects
12687 if (!empty($this->js_objects
)) {
12688 foreach ($this->js_objects
as $key => $val) {
12689 $out = $this->_getobj($key)."\n".' << /S /JavaScript /JS '.$this->_textstring($val['js'], $key).' >>'."\n".'endobj';
12696 * Adds a javascript form field.
12697 * @param string $type field type
12698 * @param string $name field name
12699 * @param int $x horizontal position
12700 * @param int $y vertical position
12701 * @param int $w width
12702 * @param int $h height
12703 * @param array $prop javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
12705 * @author Denis Van Nuffelen, Nicola Asuni
12706 * @since 2.1.002 (2008-02-12)
12708 protected function _addfield($type, $name, $x, $y, $w, $h, $prop) {
12712 // the followind avoid fields duplication after saving the document
12713 $this->javascript
.= "if (getField('tcpdfdocsaved').value != 'saved') {";
12715 $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";
12716 $this->javascript
.= 'f'.$name.'.textSize='.$this->FontSizePt
.";\n";
12717 foreach($prop as $key => $val) {
12718 if (strcmp(substr($key, -5), 'Color') == 0) {
12719 $val = TCPDF_COLORS
::_JScolor($val);
12721 $val = "'".$val."'";
12723 $this->javascript
.= 'f'.$name.'.'.$key.'='.$val.";\n";
12730 $this->javascript
.= '}';
12733 // --- FORM FIELDS -----------------------------------------------------
12738 * Set default properties for form fields.
12739 * @param array $prop javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
12741 * @author Nicola Asuni
12742 * @since 4.8.000 (2009-09-06)
12744 public function setFormDefaultProp($prop=array()) {
12745 $this->default_form_prop
= $prop;
12749 * Return the default properties for form fields.
12750 * @return array $prop javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
12752 * @author Nicola Asuni
12753 * @since 4.8.000 (2009-09-06)
12755 public function getFormDefaultProp() {
12756 return $this->default_form_prop
;
12760 * Creates a text field
12761 * @param string $name field name
12762 * @param float $w Width of the rectangle
12763 * @param float $h Height of the rectangle
12764 * @param array $prop javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
12765 * @param array $opt annotation parameters. Possible values are described on official PDF32000_2008 reference.
12766 * @param float|null $x Abscissa of the upper-left corner of the rectangle
12767 * @param float|null $y Ordinate of the upper-left corner of the rectangle
12768 * @param boolean $js if true put the field using JavaScript (requires Acrobat Writer to be rendered).
12770 * @author Nicola Asuni
12771 * @since 4.8.000 (2009-09-07)
12773 public function TextField($name, $w, $h, $prop=array(), $opt=array(), $x=null, $y=null, $js=false) {
12774 if (TCPDF_STATIC
::empty_string($x)) {
12777 if (TCPDF_STATIC
::empty_string($y)) {
12780 // check page for no-write regions and adapt page margins if necessary
12781 list($x, $y) = $this->checkPageRegions($h, $x, $y);
12783 $this->_addfield('text', $name, $x, $y, $w, $h, $prop);
12786 // get default style
12787 $prop = array_merge($this->getFormDefaultProp(), $prop);
12788 // get annotation data
12789 $popt = TCPDF_STATIC
::getAnnotOptFromJSProp($prop, $this->spot_colors
, $this->rtl
);
12790 // set default appearance stream
12791 $this->annotation_fonts
[$this->CurrentFont
['fontkey']] = $this->CurrentFont
['i'];
12792 $fontstyle = sprintf('/F%d %F Tf %s', $this->CurrentFont
['i'], $this->FontSizePt
, $this->TextColor
);
12793 $popt['da'] = $fontstyle;
12794 // build appearance stream
12795 $popt['ap'] = array();
12796 $popt['ap']['n'] = '/Tx BMC q '.$fontstyle.' ';
12798 if (isset($prop['value']) AND !empty($prop['value'])) {
12799 $text = $prop['value'];
12800 } elseif (isset($opt['v']) AND !empty($opt['v'])) {
12803 $tmpid = $this->startTemplate($w, $h, false);
12805 if (isset($popt['q'])) {
12806 switch ($popt['q']) {
12825 $this->MultiCell($w, $h, $text, 0, $align, false, 0, 0, 0, true, 0, false, true, 0, 'T', false);
12826 $this->endTemplate();
12828 $popt['ap']['n'] .= $this->xobjects
[$tmpid]['outdata'];
12829 unset($this->xobjects
[$tmpid]);
12830 $popt['ap']['n'] .= 'Q EMC';
12832 $opt = array_merge($popt, $opt);
12833 // remove some conflicting options
12835 // set remaining annotation data
12836 $opt['Subtype'] = 'Widget';
12839 // Additional annotation's parameters (check _putannotsobj() method):
12849 //$opt['mk']['bc'];
12850 //$opt['mk']['bg'];
12851 unset($opt['mk']['ca']);
12852 unset($opt['mk']['rc']);
12853 unset($opt['mk']['ac']);
12854 unset($opt['mk']['i']);
12855 unset($opt['mk']['ri']);
12856 unset($opt['mk']['ix']);
12857 unset($opt['mk']['if']);
12858 //$opt['mk']['if']['sw'];
12859 //$opt['mk']['if']['s'];
12860 //$opt['mk']['if']['a'];
12861 //$opt['mk']['if']['fb'];
12862 unset($opt['mk']['tp']);
12871 $this->Annotation($x, $y, $w, $h, $name, $opt, 0);
12880 * Creates a RadioButton field.
12881 * @param string $name Field name.
12882 * @param int $w Width of the radio button.
12883 * @param array $prop Javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
12884 * @param array $opt Annotation parameters. Possible values are described on official PDF32000_2008 reference.
12885 * @param string $onvalue Value to be returned if selected.
12886 * @param boolean $checked Define the initial state.
12887 * @param float|null $x Abscissa of the upper-left corner of the rectangle
12888 * @param float|null $y Ordinate of the upper-left corner of the rectangle
12889 * @param boolean $js If true put the field using JavaScript (requires Acrobat Writer to be rendered).
12891 * @author Nicola Asuni
12892 * @since 4.8.000 (2009-09-07)
12894 public function RadioButton($name, $w, $prop=array(), $opt=array(), $onvalue='On', $checked=false, $x=null, $y=null, $js=false) {
12895 if (TCPDF_STATIC
::empty_string($x)) {
12898 if (TCPDF_STATIC
::empty_string($y)) {
12901 // check page for no-write regions and adapt page margins if necessary
12902 list($x, $y) = $this->checkPageRegions($w, $x, $y);
12904 $this->_addfield('radiobutton', $name, $x, $y, $w, $w, $prop);
12907 if (TCPDF_STATIC
::empty_string($onvalue)) {
12911 $defval = $onvalue;
12916 $font = 'zapfdingbats';
12917 if ($this->pdfa_mode
) {
12918 // all fonts must be embedded
12919 $font = 'pdfa'.$font;
12921 $this->AddFont($font);
12922 $tmpfont = $this->getFontBuffer($font);
12923 // set data for parent group
12924 if (!isset($this->radiobutton_groups
[$this->page
])) {
12925 $this->radiobutton_groups
[$this->page
] = array();
12927 if (!isset($this->radiobutton_groups
[$this->page
][$name])) {
12928 $this->radiobutton_groups
[$this->page
][$name] = array();
12930 $this->radiobutton_groups
[$this->page
][$name]['n'] = $this->n
;
12931 $this->radio_groups
[] = $this->n
;
12933 $kid = ($this->n +
1);
12934 // save object ID to be added on Kids entry on parent object
12935 $this->radiobutton_groups
[$this->page
][$name][] = array('kid' => $kid, 'def' => $defval);
12936 // get default style
12937 $prop = array_merge($this->getFormDefaultProp(), $prop);
12938 $prop['NoToggleToOff'] = 'true';
12939 $prop['Radio'] = 'true';
12940 $prop['borderStyle'] = 'inset';
12941 // get annotation data
12942 $popt = TCPDF_STATIC
::getAnnotOptFromJSProp($prop, $this->spot_colors
, $this->rtl
);
12943 // set additional default options
12944 $this->annotation_fonts
[$tmpfont['fontkey']] = $tmpfont['i'];
12945 $fontstyle = sprintf('/F%d %F Tf %s', $tmpfont['i'], $this->FontSizePt
, $this->TextColor
);
12946 $popt['da'] = $fontstyle;
12947 // build appearance stream
12948 $popt['ap'] = array();
12949 $popt['ap']['n'] = array();
12950 $fx = ((($w - $this->getAbsFontMeasure($tmpfont['cw'][108])) / 2) * $this->k
);
12951 $fy = (($w - ((($tmpfont['desc']['Ascent'] - $tmpfont['desc']['Descent']) * $this->FontSizePt
/ 1000) / $this->k
)) * $this->k
);
12952 $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);
12953 $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);
12954 if (!isset($popt['mk'])) {
12955 $popt['mk'] = array();
12957 $popt['mk']['ca'] = '(l)';
12959 $opt = array_merge($popt, $opt);
12960 // set remaining annotation data
12961 $opt['Subtype'] = 'Widget';
12962 $opt['ft'] = 'Btn';
12964 $opt['v'] = array('/'.$onvalue);
12965 $opt['as'] = $onvalue;
12967 $opt['as'] = 'Off';
12969 // store readonly flag
12970 if (!isset($this->radiobutton_groups
[$this->page
][$name]['#readonly#'])) {
12971 $this->radiobutton_groups
[$this->page
][$name]['#readonly#'] = false;
12973 $this->radiobutton_groups
[$this->page
][$name]['#readonly#'] |
= ($opt['f'] & 64);
12974 $this->Annotation($x, $y, $w, $w, $name, $opt, 0);
12983 * Creates a List-box field
12984 * @param string $name field name
12985 * @param int $w width
12986 * @param int $h height
12987 * @param array $values array containing the list of values.
12988 * @param array $prop javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
12989 * @param array $opt annotation parameters. Possible values are described on official PDF32000_2008 reference.
12990 * @param float|null $x Abscissa of the upper-left corner of the rectangle
12991 * @param float|null $y Ordinate of the upper-left corner of the rectangle
12992 * @param boolean $js if true put the field using JavaScript (requires Acrobat Writer to be rendered).
12994 * @author Nicola Asuni
12995 * @since 4.8.000 (2009-09-07)
12997 public function ListBox($name, $w, $h, $values, $prop=array(), $opt=array(), $x=null, $y=null, $js=false) {
12998 if (TCPDF_STATIC
::empty_string($x)) {
13001 if (TCPDF_STATIC
::empty_string($y)) {
13004 // check page for no-write regions and adapt page margins if necessary
13005 list($x, $y) = $this->checkPageRegions($h, $x, $y);
13007 $this->_addfield('listbox', $name, $x, $y, $w, $h, $prop);
13009 foreach ($values as $value) {
13010 if (is_array($value)) {
13011 $s .= ',[\''.addslashes($value[1]).'\',\''.addslashes($value[0]).'\']';
13013 $s .= ',[\''.addslashes($value).'\',\''.addslashes($value).'\']';
13016 $this->javascript
.= 'f'.$name.'.setItems('.substr($s, 1).');'."\n";
13019 // get default style
13020 $prop = array_merge($this->getFormDefaultProp(), $prop);
13021 // get annotation data
13022 $popt = TCPDF_STATIC
::getAnnotOptFromJSProp($prop, $this->spot_colors
, $this->rtl
);
13023 // set additional default values
13024 $this->annotation_fonts
[$this->CurrentFont
['fontkey']] = $this->CurrentFont
['i'];
13025 $fontstyle = sprintf('/F%d %F Tf %s', $this->CurrentFont
['i'], $this->FontSizePt
, $this->TextColor
);
13026 $popt['da'] = $fontstyle;
13027 // build appearance stream
13028 $popt['ap'] = array();
13029 $popt['ap']['n'] = '/Tx BMC q '.$fontstyle.' ';
13031 foreach($values as $item) {
13032 if (is_array($item)) {
13033 $text .= $item[1]."\n";
13035 $text .= $item."\n";
13038 $tmpid = $this->startTemplate($w, $h, false);
13039 $this->MultiCell($w, $h, $text, 0, '', false, 0, 0, 0, true, 0, false, true, 0, 'T', false);
13040 $this->endTemplate();
13042 $popt['ap']['n'] .= $this->xobjects
[$tmpid]['outdata'];
13043 unset($this->xobjects
[$tmpid]);
13044 $popt['ap']['n'] .= 'Q EMC';
13046 $opt = array_merge($popt, $opt);
13047 // set remaining annotation data
13048 $opt['Subtype'] = 'Widget';
13051 $opt['opt'] = $values;
13052 unset($opt['mk']['ca']);
13053 unset($opt['mk']['rc']);
13054 unset($opt['mk']['ac']);
13055 unset($opt['mk']['i']);
13056 unset($opt['mk']['ri']);
13057 unset($opt['mk']['ix']);
13058 unset($opt['mk']['if']);
13059 unset($opt['mk']['tp']);
13060 $this->Annotation($x, $y, $w, $h, $name, $opt, 0);
13069 * Creates a Combo-box field
13070 * @param string $name field name
13071 * @param int $w width
13072 * @param int $h height
13073 * @param array $values array containing the list of values.
13074 * @param array $prop javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
13075 * @param array $opt annotation parameters. Possible values are described on official PDF32000_2008 reference.
13076 * @param float|null $x Abscissa of the upper-left corner of the rectangle
13077 * @param float|null $y Ordinate of the upper-left corner of the rectangle
13078 * @param boolean $js if true put the field using JavaScript (requires Acrobat Writer to be rendered).
13080 * @author Nicola Asuni
13081 * @since 4.8.000 (2009-09-07)
13083 public function ComboBox($name, $w, $h, $values, $prop=array(), $opt=array(), $x=null, $y=null, $js=false) {
13084 if (TCPDF_STATIC
::empty_string($x)) {
13087 if (TCPDF_STATIC
::empty_string($y)) {
13090 // check page for no-write regions and adapt page margins if necessary
13091 list($x, $y) = $this->checkPageRegions($h, $x, $y);
13093 $this->_addfield('combobox', $name, $x, $y, $w, $h, $prop);
13095 foreach ($values as $value) {
13096 if (is_array($value)) {
13097 $s .= ',[\''.addslashes($value[1]).'\',\''.addslashes($value[0]).'\']';
13099 $s .= ',[\''.addslashes($value).'\',\''.addslashes($value).'\']';
13102 $this->javascript
.= 'f'.$name.'.setItems('.substr($s, 1).');'."\n";
13105 // get default style
13106 $prop = array_merge($this->getFormDefaultProp(), $prop);
13107 $prop['Combo'] = true;
13108 // get annotation data
13109 $popt = TCPDF_STATIC
::getAnnotOptFromJSProp($prop, $this->spot_colors
, $this->rtl
);
13110 // set additional default options
13111 $this->annotation_fonts
[$this->CurrentFont
['fontkey']] = $this->CurrentFont
['i'];
13112 $fontstyle = sprintf('/F%d %F Tf %s', $this->CurrentFont
['i'], $this->FontSizePt
, $this->TextColor
);
13113 $popt['da'] = $fontstyle;
13114 // build appearance stream
13115 $popt['ap'] = array();
13116 $popt['ap']['n'] = '/Tx BMC q '.$fontstyle.' ';
13118 foreach($values as $item) {
13119 if (is_array($item)) {
13120 $text .= $item[1]."\n";
13122 $text .= $item."\n";
13125 $tmpid = $this->startTemplate($w, $h, false);
13126 $this->MultiCell($w, $h, $text, 0, '', false, 0, 0, 0, true, 0, false, true, 0, 'T', false);
13127 $this->endTemplate();
13129 $popt['ap']['n'] .= $this->xobjects
[$tmpid]['outdata'];
13130 unset($this->xobjects
[$tmpid]);
13131 $popt['ap']['n'] .= 'Q EMC';
13133 $opt = array_merge($popt, $opt);
13134 // set remaining annotation data
13135 $opt['Subtype'] = 'Widget';
13138 $opt['opt'] = $values;
13139 unset($opt['mk']['ca']);
13140 unset($opt['mk']['rc']);
13141 unset($opt['mk']['ac']);
13142 unset($opt['mk']['i']);
13143 unset($opt['mk']['ri']);
13144 unset($opt['mk']['ix']);
13145 unset($opt['mk']['if']);
13146 unset($opt['mk']['tp']);
13147 $this->Annotation($x, $y, $w, $h, $name, $opt, 0);
13156 * Creates a CheckBox field
13157 * @param string $name field name
13158 * @param int $w width
13159 * @param boolean $checked define the initial state.
13160 * @param array $prop javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
13161 * @param array $opt annotation parameters. Possible values are described on official PDF32000_2008 reference.
13162 * @param string $onvalue value to be returned if selected.
13163 * @param float|null $x Abscissa of the upper-left corner of the rectangle
13164 * @param float|null $y Ordinate of the upper-left corner of the rectangle
13165 * @param boolean $js if true put the field using JavaScript (requires Acrobat Writer to be rendered).
13167 * @author Nicola Asuni
13168 * @since 4.8.000 (2009-09-07)
13170 public function CheckBox($name, $w, $checked=false, $prop=array(), $opt=array(), $onvalue='Yes', $x=null, $y=null, $js=false) {
13171 if (TCPDF_STATIC
::empty_string($x)) {
13174 if (TCPDF_STATIC
::empty_string($y)) {
13177 // check page for no-write regions and adapt page margins if necessary
13178 list($x, $y) = $this->checkPageRegions($w, $x, $y);
13180 $this->_addfield('checkbox', $name, $x, $y, $w, $w, $prop);
13183 if (!isset($prop['value'])) {
13184 $prop['value'] = array('Yes');
13186 // get default style
13187 $prop = array_merge($this->getFormDefaultProp(), $prop);
13188 $prop['borderStyle'] = 'inset';
13189 // get annotation data
13190 $popt = TCPDF_STATIC
::getAnnotOptFromJSProp($prop, $this->spot_colors
, $this->rtl
);
13191 // set additional default options
13192 $font = 'zapfdingbats';
13193 if ($this->pdfa_mode
) {
13194 // all fonts must be embedded
13195 $font = 'pdfa'.$font;
13197 $this->AddFont($font);
13198 $tmpfont = $this->getFontBuffer($font);
13199 $this->annotation_fonts
[$tmpfont['fontkey']] = $tmpfont['i'];
13200 $fontstyle = sprintf('/F%d %F Tf %s', $tmpfont['i'], $this->FontSizePt
, $this->TextColor
);
13201 $popt['da'] = $fontstyle;
13202 // build appearance stream
13203 $popt['ap'] = array();
13204 $popt['ap']['n'] = array();
13205 $fx = ((($w - $this->getAbsFontMeasure($tmpfont['cw'][110])) / 2) * $this->k
);
13206 $fy = (($w - ((($tmpfont['desc']['Ascent'] - $tmpfont['desc']['Descent']) * $this->FontSizePt
/ 1000) / $this->k
)) * $this->k
);
13207 $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);
13208 $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);
13210 $opt = array_merge($popt, $opt);
13211 // set remaining annotation data
13212 $opt['Subtype'] = 'Widget';
13213 $opt['ft'] = 'Btn';
13215 if (TCPDF_STATIC
::empty_string($onvalue)) {
13218 $opt['opt'] = array($onvalue);
13220 $opt['v'] = array('/Yes');
13221 $opt['as'] = 'Yes';
13223 $opt['v'] = array('/Off');
13224 $opt['as'] = 'Off';
13226 $this->Annotation($x, $y, $w, $w, $name, $opt, 0);
13235 * Creates a button field
13236 * @param string $name field name
13237 * @param int $w width
13238 * @param int $h height
13239 * @param string $caption caption.
13240 * @param mixed $action 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.
13241 * @param array $prop javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
13242 * @param array $opt annotation parameters. Possible values are described on official PDF32000_2008 reference.
13243 * @param float|null $x Abscissa of the upper-left corner of the rectangle
13244 * @param float|null $y Ordinate of the upper-left corner of the rectangle
13245 * @param boolean $js if true put the field using JavaScript (requires Acrobat Writer to be rendered).
13247 * @author Nicola Asuni
13248 * @since 4.8.000 (2009-09-07)
13250 public function Button($name, $w, $h, $caption, $action, $prop=array(), $opt=array(), $x=null, $y=null, $js=false) {
13251 if (TCPDF_STATIC
::empty_string($x)) {
13254 if (TCPDF_STATIC
::empty_string($y)) {
13257 // check page for no-write regions and adapt page margins if necessary
13258 list($x, $y) = $this->checkPageRegions($h, $x, $y);
13260 $this->_addfield('button', $name, $this->x
, $this->y
, $w, $h, $prop);
13261 $this->javascript
.= 'f'.$name.".buttonSetCaption('".addslashes($caption)."');\n";
13262 $this->javascript
.= 'f'.$name.".setAction('MouseUp','".addslashes($action)."');\n";
13263 $this->javascript
.= 'f'.$name.".highlight='push';\n";
13264 $this->javascript
.= 'f'.$name.".print=false;\n";
13267 // get default style
13268 $prop = array_merge($this->getFormDefaultProp(), $prop);
13269 $prop['Pushbutton'] = 'true';
13270 $prop['highlight'] = 'push';
13271 $prop['display'] = 'display.noPrint';
13272 // get annotation data
13273 $popt = TCPDF_STATIC
::getAnnotOptFromJSProp($prop, $this->spot_colors
, $this->rtl
);
13274 $this->annotation_fonts
[$this->CurrentFont
['fontkey']] = $this->CurrentFont
['i'];
13275 $fontstyle = sprintf('/F%d %F Tf %s', $this->CurrentFont
['i'], $this->FontSizePt
, $this->TextColor
);
13276 $popt['da'] = $fontstyle;
13277 // build appearance stream
13278 $popt['ap'] = array();
13279 $popt['ap']['n'] = '/Tx BMC q '.$fontstyle.' ';
13280 $tmpid = $this->startTemplate($w, $h, false);
13281 $bw = (2 / $this->k
); // border width
13283 'L' => array('width' => $bw, 'cap' => 'square', 'join' => 'miter', 'dash' => 0, 'color' => array(231)),
13284 'R' => array('width' => $bw, 'cap' => 'square', 'join' => 'miter', 'dash' => 0, 'color' => array(51)),
13285 'T' => array('width' => $bw, 'cap' => 'square', 'join' => 'miter', 'dash' => 0, 'color' => array(231)),
13286 'B' => array('width' => $bw, 'cap' => 'square', 'join' => 'miter', 'dash' => 0, 'color' => array(51)));
13287 $this->setFillColor(204);
13288 $this->Cell($w, $h, $caption, $border, 0, 'C', true, '', 1, false, 'T', 'M');
13289 $this->endTemplate();
13291 $popt['ap']['n'] .= $this->xobjects
[$tmpid]['outdata'];
13292 unset($this->xobjects
[$tmpid]);
13293 $popt['ap']['n'] .= 'Q EMC';
13294 // set additional default options
13295 if (!isset($popt['mk'])) {
13296 $popt['mk'] = array();
13298 $ann_obj_id = ($this->n +
1);
13299 if (!empty($action) AND !is_array($action)) {
13300 $ann_obj_id = ($this->n +
2);
13302 $popt['mk']['ca'] = $this->_textstring($caption, $ann_obj_id);
13303 $popt['mk']['rc'] = $this->_textstring($caption, $ann_obj_id);
13304 $popt['mk']['ac'] = $this->_textstring($caption, $ann_obj_id);
13306 $opt = array_merge($popt, $opt);
13307 // set remaining annotation data
13308 $opt['Subtype'] = 'Widget';
13309 $opt['ft'] = 'Btn';
13310 $opt['t'] = $caption;
13312 if (!empty($action)) {
13313 if (is_array($action)) {
13314 // form action options as on section 12.7.5 of PDF32000_2008.
13315 $opt['aa'] = '/D <<';
13316 $bmode = array('SubmitForm', 'ResetForm', 'ImportData');
13317 foreach ($action AS $key => $val) {
13318 if (($key == 'S') AND in_array($val, $bmode)) {
13319 $opt['aa'] .= ' /S /'.$val;
13320 } elseif (($key == 'F') AND (!empty($val))) {
13321 $opt['aa'] .= ' /F '.$this->_datastring($val, $ann_obj_id);
13322 } elseif (($key == 'Fields') AND is_array($val) AND !empty($val)) {
13323 $opt['aa'] .= ' /Fields [';
13324 foreach ($val AS $field) {
13325 $opt['aa'] .= ' '.$this->_textstring($field, $ann_obj_id);
13328 } elseif (($key == 'Flags')) {
13330 if (is_array($val)) {
13331 foreach ($val AS $flag) {
13333 case 'Include/Exclude': {
13337 case 'IncludeNoValueFields': {
13341 case 'ExportFormat': {
13345 case 'GetMethod': {
13349 case 'SubmitCoordinates': {
13357 case 'IncludeAppendSaves': {
13361 case 'IncludeAnnotations': {
13365 case 'SubmitPDF': {
13369 case 'CanonicalFormat': {
13373 case 'ExclNonUserAnnots': {
13381 case 'EmbedForm': {
13388 $ff = intval($val);
13390 $opt['aa'] .= ' /Flags '.$ff;
13393 $opt['aa'] .= ' >>';
13395 // Javascript action or raw action command
13396 $js_obj_id = $this->addJavascriptObject($action);
13397 $opt['aa'] = '/D '.$js_obj_id.' 0 R';
13400 $this->Annotation($x, $y, $w, $h, $name, $opt, 0);
13408 // --- END FORMS FIELDS ------------------------------------------------
13411 * Add certification signature (DocMDP or UR3)
13412 * You can set only one signature type
13414 * @author Nicola Asuni
13415 * @since 4.6.008 (2009-05-07)
13417 protected function _putsignature() {
13418 if ((!$this->sign
) OR (!isset($this->signature_data
['cert_type']))) {
13421 $sigobjid = ($this->sig_obj_id +
1);
13422 $out = $this->_getobj($sigobjid)."\n";
13423 $out .= '<< /Type /Sig';
13424 $out .= ' /Filter /Adobe.PPKLite';
13425 $out .= ' /SubFilter /adbe.pkcs7.detached';
13426 $out .= ' '.TCPDF_STATIC
::$byterange_string;
13427 $out .= ' /Contents<'.str_repeat('0', $this->signature_max_length
).'>';
13428 if (empty($this->signature_data
['approval']) OR ($this->signature_data
['approval'] != 'A')) {
13429 $out .= ' /Reference ['; // array of signature reference dictionaries
13430 $out .= ' << /Type /SigRef';
13431 if ($this->signature_data
['cert_type'] > 0) {
13432 $out .= ' /TransformMethod /DocMDP';
13433 $out .= ' /TransformParams <<';
13434 $out .= ' /Type /TransformParams';
13435 $out .= ' /P '.$this->signature_data
['cert_type'];
13436 $out .= ' /V /1.2';
13438 $out .= ' /TransformMethod /UR3';
13439 $out .= ' /TransformParams <<';
13440 $out .= ' /Type /TransformParams';
13441 $out .= ' /V /2.2';
13442 if (!TCPDF_STATIC
::empty_string($this->ur
['document'])) {
13443 $out .= ' /Document['.$this->ur
['document'].']';
13445 if (!TCPDF_STATIC
::empty_string($this->ur
['form'])) {
13446 $out .= ' /Form['.$this->ur
['form'].']';
13448 if (!TCPDF_STATIC
::empty_string($this->ur
['signature'])) {
13449 $out .= ' /Signature['.$this->ur
['signature'].']';
13451 if (!TCPDF_STATIC
::empty_string($this->ur
['annots'])) {
13452 $out .= ' /Annots['.$this->ur
['annots'].']';
13454 if (!TCPDF_STATIC
::empty_string($this->ur
['ef'])) {
13455 $out .= ' /EF['.$this->ur
['ef'].']';
13457 if (!TCPDF_STATIC
::empty_string($this->ur
['formex'])) {
13458 $out .= ' /FormEX['.$this->ur
['formex'].']';
13461 $out .= ' >>'; // close TransformParams
13462 // optional digest data (values must be calculated and replaced later)
13463 //$out .= ' /Data ********** 0 R';
13464 //$out .= ' /DigestMethod/MD5';
13465 //$out .= ' /DigestLocation[********** 34]';
13466 //$out .= ' /DigestValue<********************************>';
13468 $out .= ' ]'; // end of reference
13470 if (isset($this->signature_data
['info']['Name']) AND !TCPDF_STATIC
::empty_string($this->signature_data
['info']['Name'])) {
13471 $out .= ' /Name '.$this->_textstring($this->signature_data
['info']['Name'], $sigobjid);
13473 if (isset($this->signature_data
['info']['Location']) AND !TCPDF_STATIC
::empty_string($this->signature_data
['info']['Location'])) {
13474 $out .= ' /Location '.$this->_textstring($this->signature_data
['info']['Location'], $sigobjid);
13476 if (isset($this->signature_data
['info']['Reason']) AND !TCPDF_STATIC
::empty_string($this->signature_data
['info']['Reason'])) {
13477 $out .= ' /Reason '.$this->_textstring($this->signature_data
['info']['Reason'], $sigobjid);
13479 if (isset($this->signature_data
['info']['ContactInfo']) AND !TCPDF_STATIC
::empty_string($this->signature_data
['info']['ContactInfo'])) {
13480 $out .= ' /ContactInfo '.$this->_textstring($this->signature_data
['info']['ContactInfo'], $sigobjid);
13482 $out .= ' /M '.$this->_datestring($sigobjid, $this->doc_modification_timestamp
);
13484 $out .= "\n".'endobj';
13489 * Set User's Rights for PDF Reader
13490 * WARNING: This is experimental and currently do not work.
13491 * Check the PDF Reference 8.7.1 Transform Methods,
13492 * Table 8.105 Entries in the UR transform parameters dictionary
13493 * @param boolean $enable if true enable user's rights on PDF reader
13494 * @param string $document Names specifying additional document-wide usage rights for the document. The only defined value is "/FullSave", which permits a user to save the document along with modified form and/or annotation data.
13495 * @param string $annots Names specifying additional annotation-related usage rights for the document. Valid names in PDF 1.5 and later are /Create/Delete/Modify/Copy/Import/Export, which permit the user to perform the named operation on annotations.
13496 * @param string $form Names specifying additional form-field-related usage rights for the document. Valid names are: /Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate
13497 * @param string $signature Names specifying additional signature-related usage rights for the document. The only defined value is /Modify, which permits a user to apply a digital signature to an existing signature form field or clear a signed signature form field.
13498 * @param string $ef 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
13499 Names specifying additional embedded-files-related usage rights for the document.
13500 * @param string $formex 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.
13502 * @author Nicola Asuni
13503 * @since 2.9.000 (2008-03-26)
13505 public function setUserRights(
13507 $document='/FullSave',
13508 $annots='/Create/Delete/Modify/Copy/Import/Export',
13509 $form='/Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate',
13510 $signature='/Modify',
13511 $ef='/Create/Delete/Modify/Import',
13513 $this->ur
['enabled'] = $enable;
13514 $this->ur
['document'] = $document;
13515 $this->ur
['annots'] = $annots;
13516 $this->ur
['form'] = $form;
13517 $this->ur
['signature'] = $signature;
13518 $this->ur
['ef'] = $ef;
13519 $this->ur
['formex'] = $formex;
13520 if (!$this->sign
) {
13521 $this->setSignature('', '', '', '', 0, array());
13526 * Enable document signature (requires the OpenSSL Library).
13527 * The digital signature improve document authenticity and integrity and allows o enable extra features on Acrobat Reader.
13528 * To create self-signed signature: openssl req -x509 -nodes -days 365000 -newkey rsa:1024 -keyout tcpdf.crt -out tcpdf.crt
13529 * To export crt to p12: openssl pkcs12 -export -in tcpdf.crt -out tcpdf.p12
13530 * To convert pfx certificate to pem: openssl pkcs12 -in tcpdf.pfx -out tcpdf.crt -nodes
13531 * @param mixed $signing_cert signing certificate (string or filename prefixed with 'file://')
13532 * @param mixed $private_key private key (string or filename prefixed with 'file://')
13533 * @param string $private_key_password password
13534 * @param string $extracerts 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.
13535 * @param int $cert_type 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.
13536 * @param array $info array of option information: Name, Location, Reason, ContactInfo.
13537 * @param string $approval Enable approval signature eg. for PDF incremental update
13539 * @author Nicola Asuni
13540 * @since 4.6.005 (2009-04-24)
13542 public function setSignature($signing_cert='', $private_key='', $private_key_password='', $extracerts='', $cert_type=2, $info=array(), $approval='') {
13543 // to create self-signed signature: openssl req -x509 -nodes -days 365000 -newkey rsa:1024 -keyout tcpdf.crt -out tcpdf.crt
13544 // to export crt to p12: openssl pkcs12 -export -in tcpdf.crt -out tcpdf.p12
13545 // to convert pfx certificate to pem: openssl
13546 // OpenSSL> pkcs12 -in <cert.pfx> -out <cert.crt> -nodes
13547 $this->sign
= true;
13549 $this->sig_obj_id
= $this->n
; // signature widget
13550 ++
$this->n
; // signature object ($this->sig_obj_id + 1)
13551 $this->signature_data
= array();
13552 if (strlen($signing_cert) == 0) {
13553 $this->Error('Please provide a certificate file and password!');
13555 if (strlen($private_key) == 0) {
13556 $private_key = $signing_cert;
13558 $this->signature_data
['signcert'] = $signing_cert;
13559 $this->signature_data
['privkey'] = $private_key;
13560 $this->signature_data
['password'] = $private_key_password;
13561 $this->signature_data
['extracerts'] = $extracerts;
13562 $this->signature_data
['cert_type'] = $cert_type;
13563 $this->signature_data
['info'] = $info;
13564 $this->signature_data
['approval'] = $approval;
13568 * Set the digital signature appearance (a cliccable rectangle area to get signature properties)
13569 * @param float $x Abscissa of the upper-left corner.
13570 * @param float $y Ordinate of the upper-left corner.
13571 * @param float $w Width of the signature area.
13572 * @param float $h Height of the signature area.
13573 * @param int $page option page number (if < 0 the current page is used).
13574 * @param string $name Name of the signature.
13576 * @author Nicola Asuni
13577 * @since 5.3.011 (2010-06-17)
13579 public function setSignatureAppearance($x=0, $y=0, $w=0, $h=0, $page=-1, $name='') {
13580 $this->signature_appearance
= $this->getSignatureAppearanceArray($x, $y, $w, $h, $page, $name);
13584 * Add an empty digital signature appearance (a cliccable rectangle area to get signature properties)
13585 * @param float $x Abscissa of the upper-left corner.
13586 * @param float $y Ordinate of the upper-left corner.
13587 * @param float $w Width of the signature area.
13588 * @param float $h Height of the signature area.
13589 * @param int $page option page number (if < 0 the current page is used).
13590 * @param string $name Name of the signature.
13592 * @author Nicola Asuni
13593 * @since 5.9.101 (2011-07-06)
13595 public function addEmptySignatureAppearance($x=0, $y=0, $w=0, $h=0, $page=-1, $name='') {
13597 $this->empty_signature_appearance
[] = array('objid' => $this->n
) +
$this->getSignatureAppearanceArray($x, $y, $w, $h, $page, $name);
13601 * Get the array that defines the signature appearance (page and rectangle coordinates).
13602 * @param float $x Abscissa of the upper-left corner.
13603 * @param float $y Ordinate of the upper-left corner.
13604 * @param float $w Width of the signature area.
13605 * @param float $h Height of the signature area.
13606 * @param int $page option page number (if < 0 the current page is used).
13607 * @param string $name Name of the signature.
13608 * @return array Array defining page and rectangle coordinates of signature appearance.
13610 * @author Nicola Asuni
13611 * @since 5.9.101 (2011-07-06)
13613 protected function getSignatureAppearanceArray($x=0, $y=0, $w=0, $h=0, $page=-1, $name='') {
13615 if (($page < 1) OR ($page > $this->numpages
)) {
13616 $sigapp['page'] = $this->page
;
13618 $sigapp['page'] = intval($page);
13620 if (empty($name)) {
13621 $sigapp['name'] = 'Signature';
13623 $sigapp['name'] = $name;
13625 $a = $x * $this->k
;
13626 $b = $this->pagedim
[($sigapp['page'])]['h'] - (($y +
$h) * $this->k
);
13627 $c = $w * $this->k
;
13628 $d = $h * $this->k
;
13629 $sigapp['rect'] = sprintf('%F %F %F %F', $a, $b, ($a +
$c), ($b +
$d));
13634 * Enable document timestamping (requires the OpenSSL Library).
13635 * The trusted timestamping improve document security that means that no one should be able to change the document once it has been recorded.
13636 * Use with digital signature only!
13637 * @param string $tsa_host Time Stamping Authority (TSA) server (prefixed with 'https://')
13638 * @param string $tsa_username Specifies the username for TSA authorization (optional) OR specifies the TSA authorization PEM file (see: example_66.php, optional)
13639 * @param string $tsa_password Specifies the password for TSA authorization (optional)
13640 * @param string $tsa_cert Specifies the location of TSA certificate for authorization (optional for cURL)
13642 * @author Richard Stockinger
13643 * @since 6.0.090 (2014-06-16)
13645 public function setTimeStamp($tsa_host='', $tsa_username='', $tsa_password='', $tsa_cert='') {
13646 $this->tsa_data
= array();
13647 if (!function_exists('curl_init')) {
13648 $this->Error('Please enable cURL PHP extension!');
13650 if (strlen($tsa_host) == 0) {
13651 $this->Error('Please specify the host of Time Stamping Authority (TSA)!');
13653 $this->tsa_data
['tsa_host'] = $tsa_host;
13654 if (is_file($tsa_username)) {
13655 $this->tsa_data
['tsa_auth'] = $tsa_username;
13657 $this->tsa_data
['tsa_username'] = $tsa_username;
13659 $this->tsa_data
['tsa_password'] = $tsa_password;
13660 $this->tsa_data
['tsa_cert'] = $tsa_cert;
13661 $this->tsa_timestamp
= true;
13665 * NOT YET IMPLEMENTED
13666 * Request TSA for a timestamp
13667 * @param string $signature Digital signature as binary string
13668 * @return string Timestamped digital signature
13670 * @author Richard Stockinger
13671 * @since 6.0.090 (2014-06-16)
13673 protected function applyTSA($signature) {
13674 if (!$this->tsa_timestamp
) {
13677 //@TODO: implement this feature
13682 * Create a new page group.
13683 * NOTE: call this function before calling AddPage()
13684 * @param int|null $page starting group page (leave empty for next page).
13686 * @since 3.0.000 (2008-03-27)
13688 public function startPageGroup($page=null) {
13689 if (empty($page)) {
13690 $page = $this->page +
1;
13692 $this->newpagegroup
[$page] = sizeof($this->newpagegroup
) +
1;
13696 * Set the starting page number.
13697 * @param int $num Starting page number.
13698 * @since 5.9.093 (2011-06-16)
13701 public function setStartingPageNumber($num=1) {
13702 $this->starting_page_number
= max(0, intval($num));
13706 * Returns the string alias used right align page numbers.
13707 * If the current font is unicode type, the returned string wil contain an additional open curly brace.
13709 * @since 5.9.099 (2011-06-27)
13712 public function getAliasRightShift() {
13713 // calculate aproximatively the ratio between widths of aliases and replacements.
13714 $ref = '{'.TCPDF_STATIC
::$alias_right_shift.'}{'.TCPDF_STATIC
::$alias_tot_pages.'}{'.TCPDF_STATIC
::$alias_num_page.'}';
13715 $rep = str_repeat(' ', $this->GetNumChars($ref));
13716 $wrep = $this->GetStringWidth($rep);
13718 $wdiff = max(1, ($this->GetStringWidth($ref) / $wrep));
13722 $sdiff = sprintf('%F', $wdiff);
13723 $alias = TCPDF_STATIC
::$alias_right_shift.$sdiff.'}';
13724 if ($this->isUnicodeFont()) {
13725 $alias = '{'.$alias;
13731 * Returns the string alias used for the total number of pages.
13732 * If the current font is unicode type, the returned string is surrounded by additional curly braces.
13733 * This alias will be replaced by the total number of pages in the document.
13735 * @since 4.0.018 (2008-08-08)
13738 public function getAliasNbPages() {
13739 if ($this->isUnicodeFont()) {
13740 return '{'.TCPDF_STATIC
::$alias_tot_pages.'}';
13742 return TCPDF_STATIC
::$alias_tot_pages;
13746 * Returns the string alias used for the page number.
13747 * If the current font is unicode type, the returned string is surrounded by additional curly braces.
13748 * This alias will be replaced by the page number.
13750 * @since 4.5.000 (2009-01-02)
13753 public function getAliasNumPage() {
13754 if ($this->isUnicodeFont()) {
13755 return '{'.TCPDF_STATIC
::$alias_num_page.'}';
13757 return TCPDF_STATIC
::$alias_num_page;
13761 * Return the alias for the total number of pages in the current page group.
13762 * If the current font is unicode type, the returned string is surrounded by additional curly braces.
13763 * This alias will be replaced by the total number of pages in this group.
13764 * @return string alias of the current page group
13766 * @since 3.0.000 (2008-03-27)
13768 public function getPageGroupAlias() {
13769 if ($this->isUnicodeFont()) {
13770 return '{'.TCPDF_STATIC
::$alias_group_tot_pages.'}';
13772 return TCPDF_STATIC
::$alias_group_tot_pages;
13776 * Return the alias for the page number on the current page group.
13777 * If the current font is unicode type, the returned string is surrounded by additional curly braces.
13778 * This alias will be replaced by the page number (relative to the belonging group).
13779 * @return string alias of the current page group
13781 * @since 4.5.000 (2009-01-02)
13783 public function getPageNumGroupAlias() {
13784 if ($this->isUnicodeFont()) {
13785 return '{'.TCPDF_STATIC
::$alias_group_num_page.'}';
13787 return TCPDF_STATIC
::$alias_group_num_page;
13791 * Return the current page in the group.
13792 * @return int current page in the group
13794 * @since 3.0.000 (2008-03-27)
13796 public function getGroupPageNo() {
13797 return $this->pagegroups
[$this->currpagegroup
];
13801 * Returns the current group page number formatted as a string.
13803 * @since 4.3.003 (2008-11-18)
13804 * @see PaneNo(), formatPageNumber()
13806 public function getGroupPageNoFormatted() {
13807 return TCPDF_STATIC
::formatPageNumber($this->getGroupPageNo());
13811 * Returns the current page number formatted as a string.
13813 * @since 4.2.005 (2008-11-06)
13814 * @see PaneNo(), formatPageNumber()
13816 public function PageNoFormatted() {
13817 return TCPDF_STATIC
::formatPageNumber($this->PageNo());
13823 * @since 3.0.000 (2008-03-27)
13825 protected function _putocg() {
13826 if (empty($this->pdflayers
)) {
13829 foreach ($this->pdflayers
as $key => $layer) {
13830 $this->pdflayers
[$key]['objid'] = $this->_newobj();
13831 $out = '<< /Type /OCG';
13832 $out .= ' /Name '.$this->_textstring($layer['name'], $this->pdflayers
[$key]['objid']);
13833 $out .= ' /Usage <<';
13834 if (isset($layer['print']) AND ($layer['print'] !== NULL)) {
13835 $out .= ' /Print <</PrintState /'.($layer['print']?
'ON':'OFF').'>>';
13837 $out .= ' /View <</ViewState /'.($layer['view']?
'ON':'OFF').'>>';
13839 $out .= "\n".'endobj';
13845 * Start a new pdf layer.
13846 * @param string $name Layer name (only a-z letters and numbers). Leave empty for automatic name.
13847 * @param boolean|null $print Set to TRUE to print this layer, FALSE to not print and NULL to not set this option
13848 * @param boolean $view Set to true to view this layer.
13849 * @param boolean $lock If true lock the layer
13851 * @since 5.9.102 (2011-07-13)
13853 public function startLayer($name='', $print=true, $view=true, $lock=true) {
13854 if ($this->state
!= 2) {
13857 $layer = sprintf('LYR%03d', (count($this->pdflayers
) +
1));
13858 if (empty($name)) {
13861 $name = preg_replace('/[^a-zA-Z0-9_\-]/', '', $name);
13863 $this->pdflayers
[] = array('layer' => $layer, 'name' => $name, 'print' => $print, 'view' => $view, 'lock' => $lock);
13864 $this->openMarkedContent
= true;
13865 $this->_out('/OC /'.$layer.' BDC');
13869 * End the current PDF layer.
13871 * @since 5.9.102 (2011-07-13)
13873 public function endLayer() {
13874 if ($this->state
!= 2) {
13877 if ($this->openMarkedContent
) {
13878 // close existing open marked-content layer
13879 $this->_out('EMC');
13880 $this->openMarkedContent
= false;
13885 * Set the visibility of the successive elements.
13886 * This can be useful, for instance, to put a background
13887 * image or color that will show on screen but won't print.
13888 * @param string $v visibility mode. Legal values are: all, print, screen or view.
13890 * @since 3.0.000 (2008-03-27)
13892 public function setVisibility($v) {
13893 if ($this->state
!= 2) {
13899 $this->startLayer('Print', true, false);
13904 $this->startLayer('View', false, true);
13912 $this->Error('Incorrect visibility: '.$v);
13919 * Add transparency parameters to the current extgstate
13920 * @param array $parms parameters
13921 * @return int|void the number of extgstates
13923 * @since 3.0.000 (2008-03-27)
13925 protected function addExtGState($parms) {
13926 if ($this->pdfa_mode ||
$this->pdfa_version
>= 2) {
13927 // transparencies are not allowed in PDF/A mode
13930 // check if this ExtGState already exist
13931 foreach ($this->extgstates
as $i => $ext) {
13932 if ($ext['parms'] == $parms) {
13933 if ($this->inxobj
) {
13934 // we are inside an XObject template
13935 $this->xobjects
[$this->xobjid
]['extgstates'][$i] = $ext;
13937 // return reference to existing ExtGState
13941 $n = (count($this->extgstates
) +
1);
13942 $this->extgstates
[$n] = array('parms' => $parms);
13943 if ($this->inxobj
) {
13944 // we are inside an XObject template
13945 $this->xobjects
[$this->xobjid
]['extgstates'][$n] = $this->extgstates
[$n];
13952 * @param int $gs extgstate
13954 * @since 3.0.000 (2008-03-27)
13956 protected function setExtGState($gs) {
13957 if (($this->pdfa_mode
&& $this->pdfa_version
< 2) OR ($this->state
!= 2)) {
13958 // transparency is not allowed in PDF/A-1 mode
13961 $this->_out(sprintf('/GS%d gs', $gs));
13965 * Put extgstates for object transparency
13967 * @since 3.0.000 (2008-03-27)
13969 protected function _putextgstates() {
13970 foreach ($this->extgstates
as $i => $ext) {
13971 $this->extgstates
[$i]['n'] = $this->_newobj();
13972 $out = '<< /Type /ExtGState';
13973 foreach ($ext['parms'] as $k => $v) {
13974 if (is_float($v)) {
13975 $v = sprintf('%F', $v);
13976 } elseif ($v === true) {
13978 } elseif ($v === false) {
13981 $out .= ' /'.$k.' '.$v;
13984 $out .= "\n".'endobj';
13990 * Set overprint mode for stroking (OP) and non-stroking (op) painting operations.
13991 * (Check the "Entries in a Graphics State Parameter Dictionary" on PDF 32000-1:2008).
13992 * @param boolean $stroking If true apply overprint for stroking operations.
13993 * @param boolean|null $nonstroking If true apply overprint for painting operations other than stroking.
13994 * @param integer $mode 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).
13996 * @since 5.9.152 (2012-03-23)
13998 public function setOverprint($stroking=true, $nonstroking=null, $mode=0) {
13999 if ($this->state
!= 2) {
14002 $stroking = $stroking ?
true : false;
14003 if (TCPDF_STATIC
::empty_string($nonstroking)) {
14004 // default value if not set
14005 $nonstroking = $stroking;
14007 $nonstroking = $nonstroking ?
true : false;
14009 if (($mode != 0) AND ($mode != 1)) {
14012 $this->overprint
= array('OP' => $stroking, 'op' => $nonstroking, 'OPM' => $mode);
14013 $gs = $this->addExtGState($this->overprint
);
14014 $this->setExtGState($gs);
14018 * Get the overprint mode array (OP, op, OPM).
14019 * (Check the "Entries in a Graphics State Parameter Dictionary" on PDF 32000-1:2008).
14020 * @return array<string,bool|int>
14022 * @since 5.9.152 (2012-03-23)
14024 public function getOverprint() {
14025 return $this->overprint
;
14029 * Set alpha for stroking (CA) and non-stroking (ca) operations.
14030 * @param float $stroking Alpha value for stroking operations: real value from 0 (transparent) to 1 (opaque).
14031 * @param string $bm blend mode, one of the following: Normal, Multiply, Screen, Overlay, Darken, Lighten, ColorDodge, ColorBurn, HardLight, SoftLight, Difference, Exclusion, Hue, Saturation, Color, Luminosity
14032 * @param float|null $nonstroking Alpha value for non-stroking operations: real value from 0 (transparent) to 1 (opaque).
14033 * @param boolean $ais
14035 * @since 3.0.000 (2008-03-27)
14037 public function setAlpha($stroking=1, $bm='Normal', $nonstroking=null, $ais=false) {
14038 if ($this->pdfa_mode
&& $this->pdfa_version
< 2) {
14039 // transparency is not allowed in PDF/A-1 mode
14042 $stroking = floatval($stroking);
14043 if (TCPDF_STATIC
::empty_string($nonstroking)) {
14044 // default value if not set
14045 $nonstroking = $stroking;
14047 $nonstroking = floatval($nonstroking);
14049 if ($bm[0] == '/') {
14050 // remove trailing slash
14051 $bm = substr($bm, 1);
14053 if (!in_array($bm, array('Normal', 'Multiply', 'Screen', 'Overlay', 'Darken', 'Lighten', 'ColorDodge', 'ColorBurn', 'HardLight', 'SoftLight', 'Difference', 'Exclusion', 'Hue', 'Saturation', 'Color', 'Luminosity'))) {
14056 $ais = $ais ?
true : false;
14057 $this->alpha
= array('CA' => $stroking, 'ca' => $nonstroking, 'BM' => '/'.$bm, 'AIS' => $ais);
14058 $gs = $this->addExtGState($this->alpha
);
14059 $this->setExtGState($gs);
14063 * Get the alpha mode array (CA, ca, BM, AIS).
14064 * (Check the "Entries in a Graphics State Parameter Dictionary" on PDF 32000-1:2008).
14065 * @return array<string,bool|string>
14067 * @since 5.9.152 (2012-03-23)
14069 public function getAlpha() {
14070 return $this->alpha
;
14074 * Set the default JPEG compression quality (1-100)
14075 * @param int $quality JPEG quality, integer between 1 and 100
14077 * @since 3.0.000 (2008-03-27)
14079 public function setJPEGQuality($quality) {
14080 if (($quality < 1) OR ($quality > 100)) {
14083 $this->jpeg_quality
= intval($quality);
14087 * Set the default number of columns in a row for HTML tables.
14088 * @param int $cols number of columns
14090 * @since 3.0.014 (2008-06-04)
14092 public function setDefaultTableColumns($cols=4) {
14093 $this->default_table_columns
= intval($cols);
14097 * Set the height of the cell (line height) respect the font height.
14098 * @param float $h cell proportion respect font height (typical value = 1.25).
14100 * @since 3.0.014 (2008-06-04)
14102 public function setCellHeightRatio($h) {
14103 $this->cell_height_ratio
= $h;
14107 * return the height of cell repect font height.
14110 * @since 4.0.012 (2008-07-24)
14112 public function getCellHeightRatio() {
14113 return $this->cell_height_ratio
;
14117 * Set the PDF version (check PDF reference for valid values).
14118 * @param string $version PDF document version.
14120 * @since 3.1.000 (2008-06-09)
14122 public function setPDFVersion($version='1.7') {
14123 if ($this->pdfa_mode
&& $this->pdfa_version
== 1 ) {
14125 $this->PDFVersion
= '1.4';
14126 } elseif ($this->pdfa_mode
&& $this->pdfa_version
>= 2 ) {
14128 $this->PDFVersion
= '1.7';
14130 $this->PDFVersion
= $version;
14135 * Set the viewer preferences dictionary controlling the way the document is to be presented on the screen or in print.
14136 * (see Section 8.1 of PDF reference, "Viewer Preferences").
14137 * <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>
14138 * @param array $preferences array of options.
14139 * @author Nicola Asuni
14141 * @since 3.1.000 (2008-06-09)
14143 public function setViewerPreferences($preferences) {
14144 $this->viewer_preferences
= $preferences;
14148 * Paints color transition registration bars
14149 * @param float $x abscissa of the top left corner of the rectangle.
14150 * @param float $y ordinate of the top left corner of the rectangle.
14151 * @param float $w width of the rectangle.
14152 * @param float $h height of the rectangle.
14153 * @param boolean $transition if true prints tcolor transitions to white.
14154 * @param boolean $vertical if true prints bar vertically.
14155 * @param string $colors 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.
14156 * @author Nicola Asuni
14157 * @since 4.9.000 (2010-03-26)
14160 public function colorRegistrationBar($x, $y, $w, $h, $transition=true, $vertical=false, $colors='A,R,G,B,C,M,Y,K') {
14161 if (strpos($colors, 'ALLSPOT') !== false) {
14162 // expand spot colors
14164 foreach ($this->spot_colors
as $spot_color_name => $v) {
14165 $spot_colors .= ','.$spot_color_name;
14167 if (!empty($spot_colors)) {
14168 $spot_colors = substr($spot_colors, 1);
14169 $colors = str_replace('ALLSPOT', $spot_colors, $colors);
14171 $colors = str_replace('ALLSPOT', 'NONE', $colors);
14174 $bars = explode(',', $colors);
14175 $numbars = count($bars); // number of bars to print
14176 if ($numbars <= 0) {
14179 // set bar measures
14181 $coords = array(0, 0, 0, 1);
14182 $wb = $w / $numbars; // bar width
14183 $hb = $h; // bar height
14184 $xd = $wb; // delta x
14185 $yd = 0; // delta y
14187 $coords = array(1, 0, 0, 0);
14188 $wb = $w; // bar width
14189 $hb = $h / $numbars; // bar height
14190 $xd = 0; // delta x
14191 $yd = $hb; // delta y
14195 foreach ($bars as $col) {
14197 // set transition colors
14198 case 'A': { // BLACK (GRAYSCALE)
14199 $col_a = array(255);
14203 case 'W': { // WHITE (GRAYSCALE)
14205 $col_b = array(255);
14208 case 'R': { // RED (RGB)
14209 $col_a = array(255,255,255);
14210 $col_b = array(255,0,0);
14213 case 'G': { // GREEN (RGB)
14214 $col_a = array(255,255,255);
14215 $col_b = array(0,255,0);
14218 case 'B': { // BLUE (RGB)
14219 $col_a = array(255,255,255);
14220 $col_b = array(0,0,255);
14223 case 'C': { // CYAN (CMYK)
14224 $col_a = array(0,0,0,0);
14225 $col_b = array(100,0,0,0);
14228 case 'M': { // MAGENTA (CMYK)
14229 $col_a = array(0,0,0,0);
14230 $col_b = array(0,100,0,0);
14233 case 'Y': { // YELLOW (CMYK)
14234 $col_a = array(0,0,0,0);
14235 $col_b = array(0,0,100,0);
14238 case 'K': { // KEY - BLACK (CMYK)
14239 $col_a = array(0,0,0,0);
14240 $col_b = array(0,0,0,100);
14243 case 'RGB': { // BLACK REGISTRATION (RGB)
14244 $col_a = array(255,255,255);
14245 $col_b = array(0,0,0);
14248 case 'CMYK': { // BLACK REGISTRATION (CMYK)
14249 $col_a = array(0,0,0,0);
14250 $col_b = array(100,100,100,100);
14253 case 'ALL': { // SPOT COLOR REGISTRATION
14254 $col_a = array(0,0,0,0,'None');
14255 $col_b = array(100,100,100,100,'All');
14258 case 'NONE': { // SKIP THIS COLOR
14259 $col_a = array(0,0,0,0,'None');
14260 $col_b = array(0,0,0,0,'None');
14263 default: { // SPECIFIC SPOT COLOR NAME
14264 $col_a = array(0,0,0,0,'None');
14265 $col_b = TCPDF_COLORS
::getSpotColor($col, $this->spot_colors
);
14266 if ($col_b === false) {
14267 // in case of error defaults to the registration color
14268 $col_b = array(100,100,100,100,'All');
14273 if ($col != 'NONE') {
14276 $this->LinearGradient($xb, $yb, $wb, $hb, $col_a, $col_b, $coords);
14278 $this->setFillColorArray($col_b);
14279 // colored rectangle
14280 $this->Rect($xb, $yb, $wb, $hb, 'F', array());
14289 * Paints crop marks.
14290 * @param float $x abscissa of the crop mark center.
14291 * @param float $y ordinate of the crop mark center.
14292 * @param float $w width of the crop mark.
14293 * @param float $h height of the crop mark.
14294 * @param string $type 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.
14295 * @param array $color crop mark color (default spot registration color).
14296 * @author Nicola Asuni
14297 * @since 4.9.000 (2010-03-26)
14300 public function cropMark($x, $y, $w, $h, $type='T,R,B,L', $color=array(100,100,100,100,'All')) {
14301 $this->setLineStyle(array('width' => (0.5 / $this->k
), 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => $color));
14302 $type = strtoupper($type);
14303 $type = preg_replace('/[^A-Z\-\,]*/', '', $type);
14304 // split type in single components
14305 $type = str_replace('-', ',', $type);
14306 $type = str_replace('TL', 'T,L', $type);
14307 $type = str_replace('TR', 'T,R', $type);
14308 $type = str_replace('BL', 'F,L', $type);
14309 $type = str_replace('BR', 'F,R', $type);
14310 $type = str_replace('A', 'T,L', $type);
14311 $type = str_replace('B', 'T,R', $type);
14312 $type = str_replace('T,RO', 'BO', $type);
14313 $type = str_replace('C', 'F,L', $type);
14314 $type = str_replace('D', 'F,R', $type);
14315 $crops = explode(',', strtoupper($type));
14316 // remove duplicates
14317 $crops = array_unique($crops);
14318 $dw = ($w / 4); // horizontal space to leave before the intersection point
14319 $dh = ($h / 4); // vertical space to leave before the intersection point
14320 foreach ($crops as $crop) {
14355 $this->Line($x1, $y1, $x2, $y2);
14360 * Paints a registration mark
14361 * @param float $x abscissa of the registration mark center.
14362 * @param float $y ordinate of the registration mark center.
14363 * @param float $r radius of the crop mark.
14364 * @param boolean $double if true print two concentric crop marks.
14365 * @param array $cola crop mark color (default spot registration color 'All').
14366 * @param array $colb second crop mark color (default spot registration color 'None').
14367 * @author Nicola Asuni
14368 * @since 4.9.000 (2010-03-26)
14371 public function registrationMark($x, $y, $r, $double=false, $cola=array(100,100,100,100,'All'), $colb=array(0,0,0,0,'None')) {
14372 $line_style = array('width' => max((0.5 / $this->k
),($r / 30)), 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => $cola);
14373 $this->setFillColorArray($cola);
14374 $this->PieSector($x, $y, $r, 90, 180, 'F');
14375 $this->PieSector($x, $y, $r, 270, 360, 'F');
14376 $this->Circle($x, $y, $r, 0, 360, 'C', $line_style, array(), 8);
14379 $this->setFillColorArray($colb);
14380 $this->PieSector($x, $y, $ri, 90, 180, 'F');
14381 $this->PieSector($x, $y, $ri, 270, 360, 'F');
14382 $this->setFillColorArray($cola);
14383 $this->PieSector($x, $y, $ri, 0, 90, 'F');
14384 $this->PieSector($x, $y, $ri, 180, 270, 'F');
14385 $this->Circle($x, $y, $ri, 0, 360, 'C', $line_style, array(), 8);
14390 * Paints a CMYK registration mark
14391 * @param float $x abscissa of the registration mark center.
14392 * @param float $y ordinate of the registration mark center.
14393 * @param float $r radius of the crop mark.
14394 * @author Nicola Asuni
14395 * @since 6.0.038 (2013-09-30)
14398 public function registrationMarkCMYK($x, $y, $r) {
14400 $lw = max((0.5 / $this->k
),($r / 8));
14406 $this->setFillColorArray(array(100,0,0,0));
14407 $this->PieSector($x, $y, $ri, 270, 360, 'F');
14409 $this->setFillColorArray(array(0,100,0,0));
14410 $this->PieSector($x, $y, $ri, 0, 90, 'F');
14412 $this->setFillColorArray(array(0,0,100,0));
14413 $this->PieSector($x, $y, $ri, 90, 180, 'F');
14415 $this->setFillColorArray(array(0,0,0,100));
14416 $this->PieSector($x, $y, $ri, 180, 270, 'F');
14417 // registration color
14418 $line_style = array('width' => $lw, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(100,100,100,100,'All'));
14419 $this->setFillColorArray(array(100,100,100,100,'All'));
14421 $this->Circle($x, $y, $r, 0, 360, 'C', $line_style, array(), 8);
14423 $this->Line($x, ($y - $re), $x, ($y - $ri));
14424 $this->Line($x, ($y +
$ri), $x, ($y +
$re));
14425 $this->Line(($x - $re), $y, ($x - $ri), $y);
14426 $this->Line(($x +
$ri), $y, ($x +
$re), $y);
14430 * Paints a linear colour gradient.
14431 * @param float $x abscissa of the top left corner of the rectangle.
14432 * @param float $y ordinate of the top left corner of the rectangle.
14433 * @param float $w width of the rectangle.
14434 * @param float $h height of the rectangle.
14435 * @param array $col1 first color (Grayscale, RGB or CMYK components).
14436 * @param array $col2 second color (Grayscale, RGB or CMYK components).
14437 * @param array $coords array of the form (x1, y1, x2, y2) which defines the gradient vector (see linear_gradient_coords.jpg). The default value is from left to right (x1=0, y1=0, x2=1, y2=0).
14438 * @author Andreas W\FCrmser, Nicola Asuni
14439 * @since 3.1.000 (2008-06-09)
14442 public function LinearGradient($x, $y, $w, $h, $col1=array(), $col2=array(), $coords=array(0,0,1,0)) {
14443 $this->Clip($x, $y, $w, $h);
14444 $this->Gradient(2, $coords, array(array('color' => $col1, 'offset' => 0, 'exponent' => 1), array('color' => $col2, 'offset' => 1, 'exponent' => 1)), array(), false);
14448 * Paints a radial colour gradient.
14449 * @param float $x abscissa of the top left corner of the rectangle.
14450 * @param float $y ordinate of the top left corner of the rectangle.
14451 * @param float $w width of the rectangle.
14452 * @param float $h height of the rectangle.
14453 * @param array $col1 first color (Grayscale, RGB or CMYK components).
14454 * @param array $col2 second color (Grayscale, RGB or CMYK components).
14455 * @param array $coords array of the form (fx, fy, cx, cy, r) where (fx, fy) is the starting point of the gradient with color1, (cx, cy) is the center of the circle with color2, and r is the radius of the circle (see radial_gradient_coords.jpg). (fx, fy) should be inside the circle, otherwise some areas will not be defined.
14456 * @author Andreas W\FCrmser, Nicola Asuni
14457 * @since 3.1.000 (2008-06-09)
14460 public function RadialGradient($x, $y, $w, $h, $col1=array(), $col2=array(), $coords=array(0.5,0.5,0.5,0.5,1)) {
14461 $this->Clip($x, $y, $w, $h);
14462 $this->Gradient(3, $coords, array(array('color' => $col1, 'offset' => 0, 'exponent' => 1), array('color' => $col2, 'offset' => 1, 'exponent' => 1)), array(), false);
14466 * Paints a coons patch mesh.
14467 * @param float $x abscissa of the top left corner of the rectangle.
14468 * @param float $y ordinate of the top left corner of the rectangle.
14469 * @param float $w width of the rectangle.
14470 * @param float $h height of the rectangle.
14471 * @param array $col1 first color (lower left corner) (RGB components).
14472 * @param array $col2 second color (lower right corner) (RGB components).
14473 * @param array $col3 third color (upper right corner) (RGB components).
14474 * @param array $col4 fourth color (upper left corner) (RGB components).
14475 * @param array $coords <ul><li>for one patch mesh: array(float x1, float y1, .... float x12, float y12): 12 pairs of coordinates (normally from 0 to 1) which specify the Bezier control points that define the patch. First pair is the lower left edge point, next is its right control point (control point 2). Then the other points are defined in the order: control point 1, edge point, control point 2 going counter-clockwise around the patch. Last (x12, y12) is the first edge point's left control point (control point 1).</li><li>for two or more patch meshes: array[number of patches]: arrays with the following keys for each patch: f: where to put that patch (0 = first patch, 1, 2, 3 = right, top and left of precedent patch - I didn't figure this out completely - just try and error ;-) points: 12 pairs of coordinates of the Bezier control points as above for the first patch, 8 pairs of coordinates for the following patches, ignoring the coordinates already defined by the precedent patch (I also didn't figure out the order of these - also: try and see what's happening) colors: must be 4 colors for the first patch, 2 colors for the following patches</li></ul>
14476 * @param array $coords_min minimum value used by the coordinates. If a coordinate's value is smaller than this it will be cut to coords_min. default: 0
14477 * @param array $coords_max maximum value used by the coordinates. If a coordinate's value is greater than this it will be cut to coords_max. default: 1
14478 * @param boolean $antialias A flag indicating whether to filter the shading function to prevent aliasing artifacts.
14479 * @author Andreas W\FCrmser, Nicola Asuni
14480 * @since 3.1.000 (2008-06-09)
14483 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) {
14484 if (($this->pdfa_mode
&& $this->pdfa_version
< 2) OR ($this->state
!= 2)) {
14487 $this->Clip($x, $y, $w, $h);
14488 $n = count($this->gradients
) +
1;
14489 $this->gradients
[$n] = array();
14490 $this->gradients
[$n]['type'] = 6; //coons patch mesh
14491 $this->gradients
[$n]['coords'] = array();
14492 $this->gradients
[$n]['antialias'] = $antialias;
14493 $this->gradients
[$n]['colors'] = array();
14494 $this->gradients
[$n]['transparency'] = false;
14495 //check the coords array if it is the simple array or the multi patch array
14496 if (!isset($coords[0]['f'])) {
14497 //simple array -> convert to multi patch array
14498 if (!isset($col1[1])) {
14499 $col1[1] = $col1[2] = $col1[0];
14501 if (!isset($col2[1])) {
14502 $col2[1] = $col2[2] = $col2[0];
14504 if (!isset($col3[1])) {
14505 $col3[1] = $col3[2] = $col3[0];
14507 if (!isset($col4[1])) {
14508 $col4[1] = $col4[2] = $col4[0];
14510 $patch_array[0]['f'] = 0;
14511 $patch_array[0]['points'] = $coords;
14512 $patch_array[0]['colors'][0]['r'] = $col1[0];
14513 $patch_array[0]['colors'][0]['g'] = $col1[1];
14514 $patch_array[0]['colors'][0]['b'] = $col1[2];
14515 $patch_array[0]['colors'][1]['r'] = $col2[0];
14516 $patch_array[0]['colors'][1]['g'] = $col2[1];
14517 $patch_array[0]['colors'][1]['b'] = $col2[2];
14518 $patch_array[0]['colors'][2]['r'] = $col3[0];
14519 $patch_array[0]['colors'][2]['g'] = $col3[1];
14520 $patch_array[0]['colors'][2]['b'] = $col3[2];
14521 $patch_array[0]['colors'][3]['r'] = $col4[0];
14522 $patch_array[0]['colors'][3]['g'] = $col4[1];
14523 $patch_array[0]['colors'][3]['b'] = $col4[2];
14525 //multi patch array
14526 $patch_array = $coords;
14528 $bpcd = 65535; //16 bits per coordinate
14529 //build the data stream
14530 $this->gradients
[$n]['stream'] = '';
14531 $count_patch = count($patch_array);
14532 for ($i=0; $i < $count_patch; ++
$i) {
14533 $this->gradients
[$n]['stream'] .= chr($patch_array[$i]['f']); //start with the edge flag as 8 bit
14534 $count_points = count($patch_array[$i]['points']);
14535 for ($j=0; $j < $count_points; ++
$j) {
14536 //each point as 16 bit
14537 $patch_array[$i]['points'][$j] = (($patch_array[$i]['points'][$j] - $coords_min) / ($coords_max - $coords_min)) * $bpcd;
14538 if ($patch_array[$i]['points'][$j] < 0) {
14539 $patch_array[$i]['points'][$j] = 0;
14541 if ($patch_array[$i]['points'][$j] > $bpcd) {
14542 $patch_array[$i]['points'][$j] = $bpcd;
14544 $this->gradients
[$n]['stream'] .= chr((int) floor($patch_array[$i]['points'][$j] / 256));
14545 $this->gradients
[$n]['stream'] .= chr((int) floor(intval($patch_array[$i]['points'][$j]) %
256));
14547 $count_cols = count($patch_array[$i]['colors']);
14548 for ($j=0; $j < $count_cols; ++
$j) {
14549 //each color component as 8 bit
14550 $this->gradients
[$n]['stream'] .= chr($patch_array[$i]['colors'][$j]['r']);
14551 $this->gradients
[$n]['stream'] .= chr($patch_array[$i]['colors'][$j]['g']);
14552 $this->gradients
[$n]['stream'] .= chr($patch_array[$i]['colors'][$j]['b']);
14555 //paint the gradient
14556 $this->_out('/Sh'.$n.' sh');
14557 //restore previous Graphic State
14558 $this->_outRestoreGraphicsState();
14559 if ($this->inxobj
) {
14560 // we are inside an XObject template
14561 $this->xobjects
[$this->xobjid
]['gradients'][$n] = $this->gradients
[$n];
14566 * Set a rectangular clipping area.
14567 * @param float $x abscissa of the top left corner of the rectangle (or top right corner for RTL mode).
14568 * @param float $y ordinate of the top left corner of the rectangle.
14569 * @param float $w width of the rectangle.
14570 * @param float $h height of the rectangle.
14571 * @author Andreas W\FCrmser, Nicola Asuni
14572 * @since 3.1.000 (2008-06-09)
14575 protected function Clip($x, $y, $w, $h) {
14576 if ($this->state
!= 2) {
14580 $x = $this->w
- $x - $w;
14582 //save current Graphic State
14584 //set clipping area
14585 $s .= sprintf(' %F %F %F %F re W n', $x*$this->k
, ($this->h
-$y)*$this->k
, $w*$this->k
, -$h*$this->k
);
14586 //set up transformation matrix for gradient
14587 $s .= sprintf(' %F 0 0 %F %F %F cm', $w*$this->k
, $h*$this->k
, $x*$this->k
, ($this->h
-($y+
$h))*$this->k
);
14593 * @param int $type 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)
14594 * @param array $coords array of coordinates.
14595 * @param array $stops 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).
14596 * @param array $background An array of colour components appropriate to the colour space, specifying a single background colour value.
14597 * @param boolean $antialias A flag indicating whether to filter the shading function to prevent aliasing artifacts.
14598 * @author Nicola Asuni
14599 * @since 3.1.000 (2008-06-09)
14602 public function Gradient($type, $coords, $stops, $background=array(), $antialias=false) {
14603 if (($this->pdfa_mode
&& $this->pdfa_version
< 2) OR ($this->state
!= 2)) {
14606 $n = count($this->gradients
) +
1;
14607 $this->gradients
[$n] = array();
14608 $this->gradients
[$n]['type'] = $type;
14609 $this->gradients
[$n]['coords'] = $coords;
14610 $this->gradients
[$n]['antialias'] = $antialias;
14611 $this->gradients
[$n]['colors'] = array();
14612 $this->gradients
[$n]['transparency'] = false;
14614 $numcolspace = count($stops[0]['color']);
14615 $bcolor = array_values($background);
14616 switch($numcolspace) {
14619 $this->gradients
[$n]['colspace'] = 'DeviceCMYK';
14620 if (!empty($background)) {
14621 $this->gradients
[$n]['background'] = sprintf('%F %F %F %F', $bcolor[0]/100, $bcolor[1]/100, $bcolor[2]/100, $bcolor[3]/100);
14626 $this->gradients
[$n]['colspace'] = 'DeviceRGB';
14627 if (!empty($background)) {
14628 $this->gradients
[$n]['background'] = sprintf('%F %F %F', $bcolor[0]/255, $bcolor[1]/255, $bcolor[2]/255);
14632 case 1: { // GRAY SCALE
14633 $this->gradients
[$n]['colspace'] = 'DeviceGray';
14634 if (!empty($background)) {
14635 $this->gradients
[$n]['background'] = sprintf('%F', $bcolor[0]/255);
14640 $num_stops = count($stops);
14641 $last_stop_id = $num_stops - 1;
14642 foreach ($stops as $key => $stop) {
14643 $this->gradients
[$n]['colors'][$key] = array();
14644 // offset represents a location along the gradient vector
14645 if (isset($stop['offset'])) {
14646 $this->gradients
[$n]['colors'][$key]['offset'] = $stop['offset'];
14649 $this->gradients
[$n]['colors'][$key]['offset'] = 0;
14650 } elseif ($key == $last_stop_id) {
14651 $this->gradients
[$n]['colors'][$key]['offset'] = 1;
14653 $offsetstep = (1 - $this->gradients
[$n]['colors'][($key - 1)]['offset']) / ($num_stops - $key);
14654 $this->gradients
[$n]['colors'][$key]['offset'] = $this->gradients
[$n]['colors'][($key - 1)]['offset'] +
$offsetstep;
14657 if (isset($stop['opacity'])) {
14658 $this->gradients
[$n]['colors'][$key]['opacity'] = $stop['opacity'];
14659 if ((!($this->pdfa_mode
&& $this->pdfa_version
< 2)) AND ($stop['opacity'] < 1)) {
14660 $this->gradients
[$n]['transparency'] = true;
14663 $this->gradients
[$n]['colors'][$key]['opacity'] = 1;
14665 // exponent for the exponential interpolation function
14666 if (isset($stop['exponent'])) {
14667 $this->gradients
[$n]['colors'][$key]['exponent'] = $stop['exponent'];
14669 $this->gradients
[$n]['colors'][$key]['exponent'] = 1;
14672 $color = array_values($stop['color']);
14673 switch($numcolspace) {
14676 $this->gradients
[$n]['colors'][$key]['color'] = sprintf('%F %F %F %F', $color[0]/100, $color[1]/100, $color[2]/100, $color[3]/100);
14680 $this->gradients
[$n]['colors'][$key]['color'] = sprintf('%F %F %F', $color[0]/255, $color[1]/255, $color[2]/255);
14683 case 1: { // GRAY SCALE
14684 $this->gradients
[$n]['colors'][$key]['color'] = sprintf('%F', $color[0]/255);
14689 if ($this->gradients
[$n]['transparency']) {
14690 // paint luminosity gradient
14691 $this->_out('/TGS'.$n.' gs');
14693 //paint the gradient
14694 $this->_out('/Sh'.$n.' sh');
14695 //restore previous Graphic State
14696 $this->_outRestoreGraphicsState();
14697 if ($this->inxobj
) {
14698 // we are inside an XObject template
14699 $this->xobjects
[$this->xobjid
]['gradients'][$n] = $this->gradients
[$n];
14704 * Output gradient shaders.
14705 * @author Nicola Asuni
14706 * @since 3.1.000 (2008-06-09)
14709 function _putshaders() {
14710 if ($this->pdfa_mode
&& $this->pdfa_version
< 2) {
14713 $idt = count($this->gradients
); //index for transparency gradients
14714 foreach ($this->gradients
as $id => $grad) {
14715 if (($grad['type'] == 2) OR ($grad['type'] == 3)) {
14716 $fc = $this->_newobj();
14718 $out .= ' /FunctionType 3';
14719 $out .= ' /Domain [0 1]';
14724 $num_cols = count($grad['colors']);
14725 $lastcols = $num_cols - 1;
14726 for ($i = 1; $i < $num_cols; ++
$i) {
14727 $functions .= ($fc +
$i).' 0 R ';
14728 if ($i < $lastcols) {
14729 $bounds .= sprintf('%F ', $grad['colors'][$i]['offset']);
14733 $out .= ' /Functions ['.trim($functions).']';
14734 $out .= ' /Bounds ['.trim($bounds).']';
14735 $out .= ' /Encode ['.trim($encode).']';
14737 $out .= "\n".'endobj';
14739 for ($i = 1; $i < $num_cols; ++
$i) {
14742 $out .= ' /FunctionType 2';
14743 $out .= ' /Domain [0 1]';
14744 $out .= ' /C0 ['.$grad['colors'][($i - 1)]['color'].']';
14745 $out .= ' /C1 ['.$grad['colors'][$i]['color'].']';
14746 $out .= ' /N '.$grad['colors'][$i]['exponent'];
14748 $out .= "\n".'endobj';
14751 // set transparency functions
14752 if ($grad['transparency']) {
14753 $ft = $this->_newobj();
14755 $out .= ' /FunctionType 3';
14756 $out .= ' /Domain [0 1]';
14759 $num_cols = count($grad['colors']);
14760 for ($i = 1; $i < $num_cols; ++
$i) {
14761 $functions .= ($ft +
$i).' 0 R ';
14763 $out .= ' /Functions ['.trim($functions).']';
14764 $out .= ' /Bounds ['.trim($bounds).']';
14765 $out .= ' /Encode ['.trim($encode).']';
14767 $out .= "\n".'endobj';
14769 for ($i = 1; $i < $num_cols; ++
$i) {
14772 $out .= ' /FunctionType 2';
14773 $out .= ' /Domain [0 1]';
14774 $out .= ' /C0 ['.$grad['colors'][($i - 1)]['opacity'].']';
14775 $out .= ' /C1 ['.$grad['colors'][$i]['opacity'].']';
14776 $out .= ' /N '.$grad['colors'][$i]['exponent'];
14778 $out .= "\n".'endobj';
14783 // set shading object
14785 $out = '<< /ShadingType '.$grad['type'];
14786 if (isset($grad['colspace'])) {
14787 $out .= ' /ColorSpace /'.$grad['colspace'];
14789 $out .= ' /ColorSpace /DeviceRGB';
14791 if (isset($grad['background']) AND !empty($grad['background'])) {
14792 $out .= ' /Background ['.$grad['background'].']';
14794 if (isset($grad['antialias']) AND ($grad['antialias'] === true)) {
14795 $out .= ' /AntiAlias true';
14797 if ($grad['type'] == 2) {
14798 $out .= ' '.sprintf('/Coords [%F %F %F %F]', $grad['coords'][0], $grad['coords'][1], $grad['coords'][2], $grad['coords'][3]);
14799 $out .= ' /Domain [0 1]';
14800 $out .= ' /Function '.$fc.' 0 R';
14801 $out .= ' /Extend [true true]';
14803 } elseif ($grad['type'] == 3) {
14804 //x0, y0, r0, x1, y1, r1
14805 //at this this time radius of inner circle is 0
14806 $out .= ' '.sprintf('/Coords [%F %F 0 %F %F %F]', $grad['coords'][0], $grad['coords'][1], $grad['coords'][2], $grad['coords'][3], $grad['coords'][4]);
14807 $out .= ' /Domain [0 1]';
14808 $out .= ' /Function '.$fc.' 0 R';
14809 $out .= ' /Extend [true true]';
14811 } elseif ($grad['type'] == 6) {
14812 $out .= ' /BitsPerCoordinate 16';
14813 $out .= ' /BitsPerComponent 8';
14814 $out .= ' /Decode[0 1 0 1 0 1 0 1 0 1]';
14815 $out .= ' /BitsPerFlag 8';
14816 $stream = $this->_getrawstream($grad['stream']);
14817 $out .= ' /Length '.strlen($stream);
14819 $out .= ' stream'."\n".$stream."\n".'endstream';
14821 $out .= "\n".'endobj';
14823 if ($grad['transparency']) {
14824 $shading_transparency = preg_replace('/\/ColorSpace \/[^\s]+/si', '/ColorSpace /DeviceGray', $out);
14825 $shading_transparency = preg_replace('/\/Function [0-9]+ /si', '/Function '.$ft.' ', $shading_transparency);
14827 $this->gradients
[$id]['id'] = $this->n
;
14828 // set pattern object
14830 $out = '<< /Type /Pattern /PatternType 2';
14831 $out .= ' /Shading '.$this->gradients
[$id]['id'].' 0 R';
14833 $out .= "\n".'endobj';
14835 $this->gradients
[$id]['pattern'] = $this->n
;
14836 // set shading and pattern for transparency mask
14837 if ($grad['transparency']) {
14838 // luminosity pattern
14839 $idgs = $id +
$idt;
14841 $this->_out($shading_transparency);
14842 $this->gradients
[$idgs]['id'] = $this->n
;
14844 $out = '<< /Type /Pattern /PatternType 2';
14845 $out .= ' /Shading '.$this->gradients
[$idgs]['id'].' 0 R';
14847 $out .= "\n".'endobj';
14849 $this->gradients
[$idgs]['pattern'] = $this->n
;
14850 // luminosity XObject
14851 $oid = $this->_newobj();
14852 $this->xobjects
['LX'.$oid] = array('n' => $oid);
14854 $stream = 'q /a0 gs /Pattern cs /p'.$idgs.' scn 0 0 '.$this->wPt
.' '.$this->hPt
.' re f Q';
14855 if ($this->compress
) {
14856 $filter = ' /Filter /FlateDecode';
14857 $stream = gzcompress($stream);
14859 $stream = $this->_getrawstream($stream);
14860 $out = '<< /Type /XObject /Subtype /Form /FormType 1'.$filter;
14861 $out .= ' /Length '.strlen($stream);
14862 $rect = sprintf('%F %F', $this->wPt
, $this->hPt
);
14863 $out .= ' /BBox [0 0 '.$rect.']';
14864 $out .= ' /Group << /Type /Group /S /Transparency /CS /DeviceGray >>';
14865 $out .= ' /Resources <<';
14866 $out .= ' /ExtGState << /a0 << /ca 1 /CA 1 >> >>';
14867 $out .= ' /Pattern << /p'.$idgs.' '.$this->gradients
[$idgs]['pattern'].' 0 R >>';
14870 $out .= ' stream'."\n".$stream."\n".'endstream';
14871 $out .= "\n".'endobj';
14875 $out = '<< /Type /Mask /S /Luminosity /G '.($this->n
- 1).' 0 R >>'."\n".'endobj';
14879 $out = '<< /Type /ExtGState /SMask '.($this->n
- 1).' 0 R /AIS false >>'."\n".'endobj';
14881 $this->extgstates
[] = array('n' => $this->n
, 'name' => 'TGS'.$id);
14887 * Draw the sector of a circle.
14888 * It can be used for instance to render pie charts.
14889 * @param float $xc abscissa of the center.
14890 * @param float $yc ordinate of the center.
14891 * @param float $r radius.
14892 * @param float $a start angle (in degrees).
14893 * @param float $b end angle (in degrees).
14894 * @param string $style Style of rendering. See the getPathPaintOperator() function for more information.
14895 * @param float $cw indicates whether to go clockwise (default: true).
14896 * @param float $o origin of angles (0 for 3 o'clock, 90 for noon, 180 for 9 o'clock, 270 for 6 o'clock). Default: 90.
14897 * @author Maxime Delorme, Nicola Asuni
14898 * @since 3.1.000 (2008-06-09)
14901 public function PieSector($xc, $yc, $r, $a, $b, $style='FD', $cw=true, $o=90) {
14902 $this->PieSectorXY($xc, $yc, $r, $r, $a, $b, $style, $cw, $o);
14906 * Draw the sector of an ellipse.
14907 * It can be used for instance to render pie charts.
14908 * @param float $xc abscissa of the center.
14909 * @param float $yc ordinate of the center.
14910 * @param float $rx the x-axis radius.
14911 * @param float $ry the y-axis radius.
14912 * @param float $a start angle (in degrees).
14913 * @param float $b end angle (in degrees).
14914 * @param string $style Style of rendering. See the getPathPaintOperator() function for more information.
14915 * @param float $cw indicates whether to go clockwise.
14916 * @param float $o origin of angles (0 for 3 o'clock, 90 for noon, 180 for 9 o'clock, 270 for 6 o'clock).
14917 * @param integer $nc Number of curves used to draw a 90 degrees portion of arc.
14918 * @author Maxime Delorme, Nicola Asuni
14919 * @since 3.1.000 (2008-06-09)
14922 public function PieSectorXY($xc, $yc, $rx, $ry, $a, $b, $style='FD', $cw=false, $o=0, $nc=2) {
14923 if ($this->state
!= 2) {
14927 $xc = ($this->w
- $xc);
14929 $op = TCPDF_STATIC
::getPathPaintOperator($style);
14931 $line_style = array();
14935 $b = (360 - $a +
$o);
14936 $a = (360 - $d +
$o);
14941 $this->_outellipticalarc($xc, $yc, $rx, $ry, 0, $a, $b, true, $nc);
14946 * Embed vector-based Adobe Illustrator (AI) or AI-compatible EPS files.
14947 * NOTE: EPS is not yet fully implemented, use the setRasterizeVectorImages() method to enable/disable rasterization of vector images using ImageMagick library.
14948 * Only vector drawing is supported, not text or bitmap.
14949 * 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).
14950 * @param string $file Name of the file containing the image or a '@' character followed by the EPS/AI data string.
14951 * @param float|null $x Abscissa of the upper-left corner.
14952 * @param float|null $y Ordinate of the upper-left corner.
14953 * @param float $w Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
14954 * @param float $h Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
14955 * @param mixed $link URL or identifier returned by AddLink().
14956 * @param boolean $useBoundingBox specifies whether to position the bounding box (true) or the complete canvas (false) at location (x,y). Default value is true.
14957 * @param string $align Indicates the alignment of the pointer next to image insertion relative to image height. The value can be:<ul><li>T: top-right for LTR or top-left for RTL</li><li>M: middle-right for LTR or middle-left for RTL</li><li>B: bottom-right for LTR or bottom-left for RTL</li><li>N: next line</li></ul>
14958 * @param string $palign Allows to center or align the image on the current line. Possible values are:<ul><li>L : left align</li><li>C : center</li><li>R : right align</li><li>'' : empty string : left for LTR or right for RTL</li></ul>
14959 * @param mixed $border 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)))
14960 * @param boolean $fitonpage if true the image is resized to not exceed page dimensions.
14961 * @param boolean $fixoutvals if true remove values outside the bounding box.
14962 * @author Valentin Schmidt, Nicola Asuni
14963 * @since 3.1.000 (2008-06-09)
14966 public function ImageEps($file, $x=null, $y=null, $w=0, $h=0, $link='', $useBoundingBox=true, $align='', $palign='', $border=0, $fitonpage=false, $fixoutvals=false) {
14967 if ($this->state
!= 2) {
14970 if ($this->rasterize_vector_images
AND ($w > 0) AND ($h > 0)) {
14971 // convert EPS to raster image using GD or ImageMagick libraries
14972 return $this->Image($file, $x, $y, $w, $h, 'EPS', $link, $align, true, 300, $palign, false, false, $border, false, false, $fitonpage);
14974 if (TCPDF_STATIC
::empty_string($x)) {
14977 if (TCPDF_STATIC
::empty_string($y)) {
14980 // check page for no-write regions and adapt page margins if necessary
14981 list($x, $y) = $this->checkPageRegions($h, $x, $y);
14983 if ($file[0] === '@') { // image from string
14984 $data = substr($file, 1);
14985 } else { // EPS/AI file
14986 $data = $this->getCachedFileContents($file);
14988 if ($data === FALSE) {
14989 $this->Error('EPS file not found: '.$file);
14992 // EPS/AI compatibility check (only checks files created by Adobe Illustrator!)
14993 preg_match("/%%Creator:([^\r\n]+)/", $data, $regs); # find Creator
14994 if (count($regs) > 1) {
14995 $version_str = trim($regs[1]); # e.g. "Adobe Illustrator(R) 8.0"
14996 if (strpos($version_str, 'Adobe Illustrator') !== false) {
14997 $versexp = explode(' ', $version_str);
14998 $version = (float)array_pop($versexp);
14999 if ($version >= 9) {
15000 $this->Error('This version of Adobe Illustrator file is not supported: '.$file);
15004 // strip binary bytes in front of PS-header
15005 $start = strpos($data, '%!PS-Adobe');
15007 $data = substr($data, $start);
15009 // find BoundingBox params
15010 preg_match("/%%BoundingBox:([^\r\n]+)/", $data, $regs);
15011 if (count($regs) > 1) {
15012 list($x1, $y1, $x2, $y2) = explode(' ', trim($regs[1]));
15014 $this->Error('No BoundingBox found in EPS/AI file: '.$file);
15016 $start = strpos($data, '%%EndSetup');
15017 if ($start === false) {
15018 $start = strpos($data, '%%EndProlog');
15020 if ($start === false) {
15021 $start = strpos($data, '%%BoundingBox');
15023 $data = substr($data, $start);
15024 $end = strpos($data, '%%PageTrailer');
15025 if ($end===false) {
15026 $end = strpos($data, 'showpage');
15029 $data = substr($data, 0, $end);
15031 // calculate image width and height on document
15032 if (($w <= 0) AND ($h <= 0)) {
15033 $w = ($x2 - $x1) / $k;
15034 $h = ($y2 - $y1) / $k;
15035 } elseif ($w <= 0) {
15036 $w = ($x2-$x1) / $k * ($h / (($y2 - $y1) / $k));
15037 } elseif ($h <= 0) {
15038 $h = ($y2 - $y1) / $k * ($w / (($x2 - $x1) / $k));
15040 // fit the image on available space
15041 list($w, $h, $x, $y) = $this->fitBlock($w, $h, $x, $y, $fitonpage);
15042 if ($this->rasterize_vector_images
) {
15043 // convert EPS to raster image using GD or ImageMagick libraries
15044 return $this->Image($file, $x, $y, $w, $h, 'EPS', $link, $align, true, 300, $palign, false, false, $border, false, false, $fitonpage);
15046 // set scaling factors
15047 $scale_x = $w / (($x2 - $x1) / $k);
15048 $scale_y = $h / (($y2 - $y1) / $k);
15050 $this->img_rb_y
= $y +
$h;
15053 if ($palign == 'L') {
15054 $ximg = $this->lMargin
;
15055 } elseif ($palign == 'C') {
15056 $ximg = ($this->w +
$this->lMargin
- $this->rMargin
- $w) / 2;
15057 } elseif ($palign == 'R') {
15058 $ximg = $this->w
- $this->rMargin
- $w;
15062 $this->img_rb_x
= $ximg;
15064 if ($palign == 'L') {
15065 $ximg = $this->lMargin
;
15066 } elseif ($palign == 'C') {
15067 $ximg = ($this->w +
$this->lMargin
- $this->rMargin
- $w) / 2;
15068 } elseif ($palign == 'R') {
15069 $ximg = $this->w
- $this->rMargin
- $w;
15073 $this->img_rb_x
= $ximg +
$w;
15075 if ($useBoundingBox) {
15076 $dx = $ximg * $k - $x1;
15077 $dy = $y * $k - $y1;
15082 // save the current graphic state
15083 $this->_out('q'.$this->epsmarker
);
15085 $this->_out(sprintf('%F %F %F %F %F %F cm', 1, 0, 0, 1, $dx, $dy +
($this->hPt
- (2 * $y * $k) - ($y2 - $y1))));
15087 $this->_out(sprintf('%F %F %F %F %F %F cm', $scale_x, 0, 0, $scale_y, $x1 * (1 - $scale_x), $y2 * (1 - $scale_y)));
15088 // handle pc/unix/mac line endings
15089 $lines = preg_split('/[\r\n]+/si', $data, -1, PREG_SPLIT_NO_EMPTY
);
15091 $cnt = count($lines);
15092 for ($i=0; $i < $cnt; ++
$i) {
15093 $line = $lines[$i];
15094 if (($line == '') OR ($line[0] == '%')) {
15097 $len = strlen($line);
15098 // check for spot color names
15100 if (strcasecmp('x', substr(trim($line), -1)) == 0) {
15101 if (preg_match('/\([^\)]*\)/', $line, $matches) > 0) {
15102 // extract spot color name
15103 $color_name = $matches[0];
15104 // remove color name from string
15105 $line = str_replace(' '.$color_name, '', $line);
15106 // remove pharentesis from color name
15107 $color_name = substr($color_name, 1, -1);
15110 $chunks = explode(' ', $line);
15111 $cmd = trim(array_pop($chunks));
15113 if (($cmd == 'Xa') OR ($cmd == 'XA')) {
15114 $b = array_pop($chunks);
15115 $g = array_pop($chunks);
15116 $r = array_pop($chunks);
15117 $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!
15122 // check for values outside the bounding box
15127 // skip values outside bounding box
15128 foreach ($chunks as $key => $val) {
15129 if ((($key %
2) == 0) AND (($val < $x1) OR ($val > $x2))) {
15131 } elseif ((($key %
2) != 0) AND (($val < $y1) OR ($val > $y2))) {
15159 $this->_out($line);
15162 case 'x': {// custom fill color
15163 if (empty($color_name)) {
15165 list($col_c, $col_m, $col_y, $col_k) = $chunks;
15166 $this->_out(''.$col_c.' '.$col_m.' '.$col_y.' '.$col_k.' k');
15168 // Spot Color (CMYK + tint)
15169 list($col_c, $col_m, $col_y, $col_k, $col_t) = $chunks;
15170 $this->AddSpotColor($color_name, ($col_c * 100), ($col_m * 100), ($col_y * 100), ($col_k * 100));
15171 $color_cmd = sprintf('/CS%d cs %F scn', $this->spot_colors
[$color_name]['i'], (1 - $col_t));
15172 $this->_out($color_cmd);
15176 case 'X': { // custom stroke color
15177 if (empty($color_name)) {
15179 list($col_c, $col_m, $col_y, $col_k) = $chunks;
15180 $this->_out(''.$col_c.' '.$col_m.' '.$col_y.' '.$col_k.' K');
15182 // Spot Color (CMYK + tint)
15183 list($col_c, $col_m, $col_y, $col_k, $col_t) = $chunks;
15184 $this->AddSpotColor($color_name, ($col_c * 100), ($col_m * 100), ($col_y * 100), ($col_k * 100));
15185 $color_cmd = sprintf('/CS%d CS %F SCN', $this->spot_colors
[$color_name]['i'], (1 - $col_t));
15186 $this->_out($color_cmd);
15198 $line[($len - 1)] = strtolower($cmd);
15199 $this->_out($line);
15204 $this->_out($cmd . '*');
15211 $max = min(($i +
5), $cnt);
15212 for ($j = ($i +
1); $j < $max; ++
$j) {
15213 $isU = ($isU OR (($lines[$j] == 'U') OR ($lines[$j] == '*U')));
15233 // restore previous graphic state
15234 $this->_out($this->epsmarker
.'Q');
15235 if (!empty($border)) {
15243 $this->Cell($w, $h, '', $border, 0, '', 0, '', 0, true);
15248 $this->Link($ximg, $y, $w, $h, $link, 0);
15250 // set pointer to align the next text/objects
15254 $this->x
= $this->img_rb_x
;
15258 $this->y
= $y +
round($h/2);
15259 $this->x
= $this->img_rb_x
;
15263 $this->y
= $this->img_rb_y
;
15264 $this->x
= $this->img_rb_x
;
15268 $this->setY($this->img_rb_y
);
15275 $this->endlinex
= $this->img_rb_x
;
15279 * Set document barcode.
15280 * @param string $bc barcode
15283 public function setBarcode($bc='') {
15284 $this->barcode
= $bc;
15288 * Get current barcode.
15291 * @since 4.0.012 (2008-07-24)
15293 public function getBarcode() {
15294 return $this->barcode
;
15298 * Print a Linear Barcode.
15299 * @param string $code code to print
15300 * @param string $type type of barcode (see tcpdf_barcodes_1d.php for supported formats).
15301 * @param float|null $x x position in user units (null = current x position)
15302 * @param float|null $y y position in user units (null = current y position)
15303 * @param float|null $w width in user units (null = remaining page width)
15304 * @param float|null $h height in user units (null = remaining page height)
15305 * @param float|null $xres width of the smallest bar in user units (null = default value = 0.4mm)
15306 * @param array $style array of options:<ul>
15307 * <li>boolean $style['border'] if true prints a border</li>
15308 * <li>int $style['padding'] padding to leave around the barcode in user units (set to 'auto' for automatic padding)</li>
15309 * <li>int $style['hpadding'] horizontal padding in user units (set to 'auto' for automatic padding)</li>
15310 * <li>int $style['vpadding'] vertical padding in user units (set to 'auto' for automatic padding)</li>
15311 * <li>array $style['fgcolor'] color array for bars and text</li>
15312 * <li>mixed $style['bgcolor'] color array for background (set to false for transparent)</li>
15313 * <li>boolean $style['text'] if true prints text below the barcode</li>
15314 * <li>string $style['label'] override default label</li>
15315 * <li>string $style['font'] font name for text</li><li>int $style['fontsize'] font size for text</li>
15316 * <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>
15317 * <li>string $style['position'] horizontal position of the containing barcode cell on the page: L = left margin; C = center; R = right margin.</li>
15318 * <li>string $style['align'] horizontal position of the barcode on the containing rectangle: L = left; C = center; R = right.</li>
15319 * <li>string $style['stretch'] if true stretch the barcode to best fit the available width, otherwise uses $xres resolution for a single bar.</li>
15320 * <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>
15321 * <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>
15322 * @param string $align 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>
15323 * @author Nicola Asuni
15324 * @since 3.1.000 (2008-06-09)
15327 public function write1DBarcode($code, $type, $x=null, $y=null, $w=null, $h=null, $xres=null, $style=array(), $align='') {
15328 if (TCPDF_STATIC
::empty_string(trim($code))) {
15331 require_once(dirname(__FILE__
).'/tcpdf_barcodes_1d.php');
15332 // save current graphic settings
15333 $gvars = $this->getGraphicVars();
15334 // create new barcode object
15335 $barcodeobj = new TCPDFBarcode($code, $type);
15336 $arrcode = $barcodeobj->getBarcodeArray();
15337 if (empty($arrcode) OR ($arrcode['maxw'] <= 0)) {
15338 $this->Error('Error in 1D barcode string');
15340 if ($arrcode['maxh'] <= 0) {
15341 $arrcode['maxh'] = 1;
15343 // set default values
15344 if (!isset($style['position'])) {
15345 $style['position'] = '';
15346 } elseif ($style['position'] == 'S') {
15347 // keep this for backward compatibility
15348 $style['position'] = '';
15349 $style['stretch'] = true;
15351 if (!isset($style['fitwidth'])) {
15352 if (!isset($style['stretch'])) {
15353 $style['fitwidth'] = true;
15355 $style['fitwidth'] = false;
15358 if ($style['fitwidth']) {
15360 $style['stretch'] = false;
15362 if (!isset($style['stretch'])) {
15363 if (($w === '') OR ($w <= 0)) {
15364 $style['stretch'] = false;
15366 $style['stretch'] = true;
15369 if (!isset($style['fgcolor'])) {
15370 $style['fgcolor'] = array(0,0,0); // default black
15372 if (!isset($style['bgcolor'])) {
15373 $style['bgcolor'] = false; // default transparent
15375 if (!isset($style['border'])) {
15376 $style['border'] = false;
15379 if (!isset($style['text'])) {
15380 $style['text'] = false;
15382 if ($style['text'] AND isset($style['font'])) {
15383 if (isset($style['fontsize'])) {
15384 $fontsize = $style['fontsize'];
15386 $this->setFont($style['font'], '', $fontsize);
15388 if (!isset($style['stretchtext'])) {
15389 $style['stretchtext'] = 4;
15391 if (TCPDF_STATIC
::empty_string($x)) {
15394 if (TCPDF_STATIC
::empty_string($y)) {
15397 // check page for no-write regions and adapt page margins if necessary
15398 list($x, $y) = $this->checkPageRegions($h, $x, $y);
15399 if (TCPDF_STATIC
::empty_string($w) OR ($w <= 0)) {
15401 $w = $x - $this->lMargin
;
15403 $w = $this->w
- $this->rMargin
- $x;
15407 if (!isset($style['padding'])) {
15409 } elseif ($style['padding'] === 'auto') {
15410 $padding = 10 * ($w / ($arrcode['maxw'] +
20));
15412 $padding = floatval($style['padding']);
15414 // horizontal padding
15415 if (!isset($style['hpadding'])) {
15416 $hpadding = $padding;
15417 } elseif ($style['hpadding'] === 'auto') {
15418 $hpadding = 10 * ($w / ($arrcode['maxw'] +
20));
15420 $hpadding = floatval($style['hpadding']);
15422 // vertical padding
15423 if (!isset($style['vpadding'])) {
15424 $vpadding = $padding;
15425 } elseif ($style['vpadding'] === 'auto') {
15426 $vpadding = ($hpadding / 2);
15428 $vpadding = floatval($style['vpadding']);
15430 // calculate xres (single bar width)
15431 $max_xres = ($w - (2 * $hpadding)) / $arrcode['maxw'];
15432 if ($style['stretch']) {
15435 if (TCPDF_STATIC
::empty_string($xres)) {
15436 $xres = (0.141 * $this->k
); // default bar width = 0.4 mm
15438 if ($xres > $max_xres) {
15439 // correct xres to fit on $w
15442 if ((isset($style['padding']) AND ($style['padding'] === 'auto'))
15443 OR (isset($style['hpadding']) AND ($style['hpadding'] === 'auto'))) {
15444 $hpadding = 10 * $xres;
15445 if (isset($style['vpadding']) AND ($style['vpadding'] === 'auto')) {
15446 $vpadding = ($hpadding / 2);
15450 if ($style['fitwidth']) {
15452 $w = (($arrcode['maxw'] * $xres) +
(2 * $hpadding));
15453 if (isset($style['cellfitalign'])) {
15454 switch ($style['cellfitalign']) {
15457 $x -= ($wold - $w);
15463 $x +
= ($wold - $w);
15469 $x -= (($wold - $w) / 2);
15471 $x +
= (($wold - $w) / 2);
15481 $text_height = $this->getCellHeight($fontsize / $this->k
);
15483 if (TCPDF_STATIC
::empty_string($h) OR ($h <= 0)) {
15484 // set default height
15485 $h = (($arrcode['maxw'] * $xres) / 3) +
(2 * $vpadding) +
$text_height;
15487 $barh = $h - $text_height - (2 * $vpadding);
15489 // try to reduce font or padding to fit barcode on available height
15490 if ($text_height > $h) {
15491 $fontsize = (($h * $this->k
) / (4 * $this->cell_height_ratio
));
15492 $text_height = $this->getCellHeight($fontsize / $this->k
);
15493 $this->setFont($style['font'], '', $fontsize);
15495 if ($vpadding > 0) {
15496 $vpadding = (($h - $text_height) / 4);
15498 $barh = $h - $text_height - (2 * $vpadding);
15500 // fit the barcode on available space
15501 list($w, $h, $x, $y) = $this->fitBlock($w, $h, $x, $y, false);
15503 $this->img_rb_y
= $y +
$h;
15506 if ($style['position'] == 'L') {
15507 $xpos = $this->lMargin
;
15508 } elseif ($style['position'] == 'C') {
15509 $xpos = ($this->w +
$this->lMargin
- $this->rMargin
- $w) / 2;
15510 } elseif ($style['position'] == 'R') {
15511 $xpos = $this->w
- $this->rMargin
- $w;
15515 $this->img_rb_x
= $xpos;
15517 if ($style['position'] == 'L') {
15518 $xpos = $this->lMargin
;
15519 } elseif ($style['position'] == 'C') {
15520 $xpos = ($this->w +
$this->lMargin
- $this->rMargin
- $w) / 2;
15521 } elseif ($style['position'] == 'R') {
15522 $xpos = $this->w
- $this->rMargin
- $w;
15526 $this->img_rb_x
= $xpos +
$w;
15528 $xpos_rect = $xpos;
15529 if (!isset($style['align'])) {
15530 $style['align'] = 'C';
15532 switch ($style['align']) {
15534 $xpos = $xpos_rect +
$hpadding;
15538 $xpos = $xpos_rect +
($w - ($arrcode['maxw'] * $xres)) - $hpadding;
15543 $xpos = $xpos_rect +
(($w - ($arrcode['maxw'] * $xres)) / 2);
15547 $xpos_text = $xpos;
15548 // barcode is always printed in LTR direction
15549 $tempRTL = $this->rtl
;
15550 $this->rtl
= false;
15551 // print background color
15552 if ($style['bgcolor']) {
15553 $this->Rect($xpos_rect, $y, $w, $h, $style['border'] ?
'DF' : 'F', '', $style['bgcolor']);
15554 } elseif ($style['border']) {
15555 $this->Rect($xpos_rect, $y, $w, $h, 'D');
15557 // set foreground color
15558 $this->setDrawColorArray($style['fgcolor']);
15559 $this->setTextColorArray($style['fgcolor']);
15561 foreach ($arrcode['bcode'] as $k => $v) {
15562 $bw = ($v['w'] * $xres);
15564 // draw a vertical bar
15565 $ypos = $y +
$vpadding +
($v['p'] * $barh / $arrcode['maxh']);
15566 $this->Rect($xpos, $ypos, $bw, ($v['h'] * $barh / $arrcode['maxh']), 'F', array(), $style['fgcolor']);
15571 if ($style['text']) {
15572 if (isset($style['label']) AND !TCPDF_STATIC
::empty_string($style['label'])) {
15573 $label = $style['label'];
15577 $txtwidth = ($arrcode['maxw'] * $xres);
15578 if ($this->GetStringWidth($label) > $txtwidth) {
15579 $style['stretchtext'] = 2;
15582 $this->x
= $xpos_text;
15583 $this->y
= $y +
$vpadding +
$barh;
15584 $cellpadding = $this->cell_padding
;
15585 $this->setCellPadding(0);
15586 $this->Cell($txtwidth, 0, $label, 0, 0, 'C', false, '', $style['stretchtext'], false, 'T', 'T');
15587 $this->cell_padding
= $cellpadding;
15589 // restore original direction
15590 $this->rtl
= $tempRTL;
15591 // restore previous settings
15592 $this->setGraphicVars($gvars);
15593 // set pointer to align the next text/objects
15597 $this->x
= $this->img_rb_x
;
15601 $this->y
= $y +
round($h / 2);
15602 $this->x
= $this->img_rb_x
;
15606 $this->y
= $this->img_rb_y
;
15607 $this->x
= $this->img_rb_x
;
15611 $this->setY($this->img_rb_y
);
15618 $this->endlinex
= $this->img_rb_x
;
15622 * Print 2D Barcode.
15623 * @param string $code code to print
15624 * @param string $type type of barcode (see tcpdf_barcodes_2d.php for supported formats).
15625 * @param float|null $x x position in user units
15626 * @param float|null $y y position in user units
15627 * @param float|null $w width in user units
15628 * @param float|null $h height in user units
15629 * @param array $style array of options:<ul>
15630 * <li>boolean $style['border'] if true prints a border around the barcode</li>
15631 * <li>int $style['padding'] padding to leave around the barcode in barcode units (set to 'auto' for automatic padding)</li>
15632 * <li>int $style['hpadding'] horizontal padding in barcode units (set to 'auto' for automatic padding)</li>
15633 * <li>int $style['vpadding'] vertical padding in barcode units (set to 'auto' for automatic padding)</li>
15634 * <li>int $style['module_width'] width of a single module in points</li>
15635 * <li>int $style['module_height'] height of a single module in points</li>
15636 * <li>array $style['fgcolor'] color array for bars and text</li>
15637 * <li>mixed $style['bgcolor'] color array for background or false for transparent</li>
15638 * <li>string $style['position'] barcode position on the page: L = left margin; C = center; R = right margin; S = stretch</li>
15639 * @param string $align 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>
15640 * @param boolean $distort if true distort the barcode to fit width and height, otherwise preserve aspect ratio
15641 * @author Nicola Asuni
15642 * @since 4.5.037 (2009-04-07)
15645 public function write2DBarcode($code, $type, $x=null, $y=null, $w=null, $h=null, $style=array(), $align='', $distort=false) {
15646 if (TCPDF_STATIC
::empty_string(trim($code))) {
15649 require_once(dirname(__FILE__
).'/tcpdf_barcodes_2d.php');
15650 // save current graphic settings
15651 $gvars = $this->getGraphicVars();
15652 // create new barcode object
15653 $barcodeobj = new TCPDF2DBarcode($code, $type);
15654 $arrcode = $barcodeobj->getBarcodeArray();
15655 if (empty($arrcode) OR !isset($arrcode['num_rows']) OR ($arrcode['num_rows'] == 0) OR !isset($arrcode['num_cols']) OR ($arrcode['num_cols'] == 0)) {
15656 $this->Error('Error in 2D barcode string');
15658 // set default values
15659 if (!isset($style['position'])) {
15660 $style['position'] = '';
15662 if (!isset($style['fgcolor'])) {
15663 $style['fgcolor'] = array(0,0,0); // default black
15665 if (!isset($style['bgcolor'])) {
15666 $style['bgcolor'] = false; // default transparent
15668 if (!isset($style['border'])) {
15669 $style['border'] = false;
15672 if (!isset($style['padding'])) {
15673 $style['padding'] = 0;
15674 } elseif ($style['padding'] === 'auto') {
15675 $style['padding'] = 4;
15677 if (!isset($style['hpadding'])) {
15678 $style['hpadding'] = $style['padding'];
15679 } elseif ($style['hpadding'] === 'auto') {
15680 $style['hpadding'] = 4;
15682 if (!isset($style['vpadding'])) {
15683 $style['vpadding'] = $style['padding'];
15684 } elseif ($style['vpadding'] === 'auto') {
15685 $style['vpadding'] = 4;
15687 $hpad = (2 * $style['hpadding']);
15688 $vpad = (2 * $style['vpadding']);
15689 // cell (module) dimension
15690 if (!isset($style['module_width'])) {
15691 $style['module_width'] = 1; // width of a single module in points
15693 if (!isset($style['module_height'])) {
15694 $style['module_height'] = 1; // height of a single module in points
15696 if (TCPDF_STATIC
::empty_string($x)) {
15699 if (TCPDF_STATIC
::empty_string($y)) {
15702 // check page for no-write regions and adapt page margins if necessary
15703 list($x, $y) = $this->checkPageRegions($h, $x, $y);
15704 // number of barcode columns and rows
15705 $rows = $arrcode['num_rows'];
15706 $cols = $arrcode['num_cols'];
15707 if (($rows <= 0) ||
($cols <= 0)){
15708 $this->Error('Error in 2D barcode string');
15710 // module width and height
15711 $mw = $style['module_width'];
15712 $mh = $style['module_height'];
15713 if (($mw <= 0) OR ($mh <= 0)) {
15714 $this->Error('Error in 2D barcode string');
15716 // get max dimensions
15718 $maxw = $x - $this->lMargin
;
15720 $maxw = $this->w
- $this->rMargin
- $x;
15722 $maxh = ($this->h
- $this->tMargin
- $this->bMargin
);
15723 $ratioHW = ((($rows * $mh) +
$hpad) / (($cols * $mw) +
$vpad));
15724 $ratioWH = ((($cols * $mw) +
$vpad) / (($rows * $mh) +
$hpad));
15726 if (($maxw * $ratioHW) > $maxh) {
15727 $maxw = $maxh * $ratioWH;
15729 if (($maxh * $ratioWH) > $maxw) {
15730 $maxh = $maxw * $ratioHW;
15733 // set maximum dimensions
15741 if ((TCPDF_STATIC
::empty_string($w) OR ($w <= 0)) AND (TCPDF_STATIC
::empty_string($h) OR ($h <= 0))) {
15742 $w = ($cols +
$hpad) * ($mw / $this->k
);
15743 $h = ($rows +
$vpad) * ($mh / $this->k
);
15744 } elseif (($w === '') OR ($w <= 0)) {
15745 $w = $h * $ratioWH;
15746 } elseif (($h === '') OR ($h <= 0)) {
15747 $h = $w * $ratioHW;
15749 // barcode size (excluding padding)
15750 $bw = ($w * $cols) / ($cols +
$hpad);
15751 $bh = ($h * $rows) / ($rows +
$vpad);
15752 // dimension of single barcode cell unit
15756 if (($cw / $ch) > ($mw / $mh)) {
15757 // correct horizontal distortion
15758 $cw = $ch * $mw / $mh;
15760 $style['hpadding'] = ($w - $bw) / (2 * $cw);
15762 // correct vertical distortion
15763 $ch = $cw * $mh / $mw;
15765 $style['vpadding'] = ($h - $bh) / (2 * $ch);
15768 // fit the barcode on available space
15769 list($w, $h, $x, $y) = $this->fitBlock($w, $h, $x, $y, false);
15771 $this->img_rb_y
= $y +
$h;
15774 if ($style['position'] == 'L') {
15775 $xpos = $this->lMargin
;
15776 } elseif ($style['position'] == 'C') {
15777 $xpos = ($this->w +
$this->lMargin
- $this->rMargin
- $w) / 2;
15778 } elseif ($style['position'] == 'R') {
15779 $xpos = $this->w
- $this->rMargin
- $w;
15783 $this->img_rb_x
= $xpos;
15785 if ($style['position'] == 'L') {
15786 $xpos = $this->lMargin
;
15787 } elseif ($style['position'] == 'C') {
15788 $xpos = ($this->w +
$this->lMargin
- $this->rMargin
- $w) / 2;
15789 } elseif ($style['position'] == 'R') {
15790 $xpos = $this->w
- $this->rMargin
- $w;
15794 $this->img_rb_x
= $xpos +
$w;
15796 $xstart = $xpos +
($style['hpadding'] * $cw);
15797 $ystart = $y +
($style['vpadding'] * $ch);
15798 // barcode is always printed in LTR direction
15799 $tempRTL = $this->rtl
;
15800 $this->rtl
= false;
15801 // print background color
15802 if ($style['bgcolor']) {
15803 $this->Rect($xpos, $y, $w, $h, $style['border'] ?
'DF' : 'F', '', $style['bgcolor']);
15804 } elseif ($style['border']) {
15805 $this->Rect($xpos, $y, $w, $h, 'D');
15807 // set foreground color
15808 $this->setDrawColorArray($style['fgcolor']);
15809 // print barcode cells
15811 for ($r = 0; $r < $rows; ++
$r) {
15814 for ($c = 0; $c < $cols; ++
$c) {
15815 if ($arrcode['bcode'][$r][$c] == 1) {
15816 // draw a single barcode cell
15817 $this->Rect($xr, $ystart, $cw, $ch, 'F', array(), $style['fgcolor']);
15823 // restore original direction
15824 $this->rtl
= $tempRTL;
15825 // restore previous settings
15826 $this->setGraphicVars($gvars);
15827 // set pointer to align the next text/objects
15831 $this->x
= $this->img_rb_x
;
15835 $this->y
= $y +
round($h/2);
15836 $this->x
= $this->img_rb_x
;
15840 $this->y
= $this->img_rb_y
;
15841 $this->x
= $this->img_rb_x
;
15845 $this->setY($this->img_rb_y
);
15852 $this->endlinex
= $this->img_rb_x
;
15856 * Returns an array containing current margins:
15858 <li>$ret['left'] = left margin</li>
15859 <li>$ret['right'] = right margin</li>
15860 <li>$ret['top'] = top margin</li>
15861 <li>$ret['bottom'] = bottom margin</li>
15862 <li>$ret['header'] = header margin</li>
15863 <li>$ret['footer'] = footer margin</li>
15864 <li>$ret['cell'] = cell padding array</li>
15865 <li>$ret['padding_left'] = cell left padding</li>
15866 <li>$ret['padding_top'] = cell top padding</li>
15867 <li>$ret['padding_right'] = cell right padding</li>
15868 <li>$ret['padding_bottom'] = cell bottom padding</li>
15870 * @return array containing all margins measures
15872 * @since 3.2.000 (2008-06-23)
15874 public function getMargins() {
15876 'left' => $this->lMargin
,
15877 'right' => $this->rMargin
,
15878 'top' => $this->tMargin
,
15879 'bottom' => $this->bMargin
,
15880 'header' => $this->header_margin
,
15881 'footer' => $this->footer_margin
,
15882 'cell' => $this->cell_padding
,
15883 'padding_left' => $this->cell_padding
['L'],
15884 'padding_top' => $this->cell_padding
['T'],
15885 'padding_right' => $this->cell_padding
['R'],
15886 'padding_bottom' => $this->cell_padding
['B']
15892 * Returns an array containing original margins:
15894 <li>$ret['left'] = left margin</li>
15895 <li>$ret['right'] = right margin</li>
15897 * @return array containing all margins measures
15899 * @since 4.0.012 (2008-07-24)
15901 public function getOriginalMargins() {
15903 'left' => $this->original_lMargin
,
15904 'right' => $this->original_rMargin
15910 * Returns the current font size.
15911 * @return float current font size
15913 * @since 3.2.000 (2008-06-23)
15915 public function getFontSize() {
15916 return $this->FontSize
;
15920 * Returns the current font size in points unit.
15921 * @return int current font size in points unit
15923 * @since 3.2.000 (2008-06-23)
15925 public function getFontSizePt() {
15926 return $this->FontSizePt
;
15930 * Returns the current font family name.
15931 * @return string current font family name
15933 * @since 4.3.008 (2008-12-05)
15935 public function getFontFamily() {
15936 return $this->FontFamily
;
15940 * Returns the current font style.
15941 * @return string current font style
15943 * @since 4.3.008 (2008-12-05)
15945 public function getFontStyle() {
15946 return $this->FontStyle
;
15950 * Cleanup HTML code (requires HTML Tidy library).
15951 * @param string $html htmlcode to fix
15952 * @param string $default_css CSS commands to add
15953 * @param array|null $tagvs parameters for setHtmlVSpace method
15954 * @param array|null $tidy_options options for tidy_parse_string function
15955 * @return string XHTML code cleaned up
15956 * @author Nicola Asuni
15958 * @since 5.9.017 (2010-11-16)
15959 * @see setHtmlVSpace()
15961 public function fixHTMLCode($html, $default_css='', $tagvs=null, $tidy_options=null) {
15962 return TCPDF_STATIC
::fixHTMLCode($html, $default_css, $tagvs, $tidy_options, $this->tagvspaces
);
15966 * Returns the border width from CSS property
15967 * @param string $width border width
15968 * @return int with in user units
15970 * @since 5.7.000 (2010-08-02)
15972 protected function getCSSBorderWidth($width) {
15973 if ($width == 'thin') {
15974 $width = (2 / $this->k
);
15975 } elseif ($width == 'medium') {
15976 $width = (4 / $this->k
);
15977 } elseif ($width == 'thick') {
15978 $width = (6 / $this->k
);
15980 $width = $this->getHTMLUnitToUnits($width, 1, 'px', false);
15986 * Returns the border dash style from CSS property
15987 * @param string $style border style to convert
15988 * @return int sash style (return -1 in case of none or hidden border)
15990 * @since 5.7.000 (2010-08-02)
15992 protected function getCSSBorderDashStyle($style) {
15993 switch (strtolower($style)) {
16022 * Returns the border style array from CSS border properties
16023 * @param string $cssborder border properties
16024 * @return array containing border properties
16026 * @since 5.7.000 (2010-08-02)
16028 protected function getCSSBorderStyle($cssborder) {
16029 $bprop = preg_split('/[\s]+/', trim($cssborder));
16030 $count = count($bprop);
16031 if ($count > 0 && $bprop[$count - 1] === '!important') {
16032 unset($bprop[$count - 1]);
16036 $border = array(); // value to be returned
16040 $style = $bprop[0];
16041 $color = $bprop[1];
16046 $style = $bprop[0];
16057 $width = $bprop[0];
16058 $style = $bprop[1];
16059 $color = $bprop[2];
16063 if ($style == 'none') {
16066 $border['cap'] = 'square';
16067 $border['join'] = 'miter';
16068 $border['dash'] = $this->getCSSBorderDashStyle($style);
16069 if ($border['dash'] < 0) {
16072 $border['width'] = $this->getCSSBorderWidth($width);
16073 $border['color'] = TCPDF_COLORS
::convertHTMLColorToDec($color, $this->spot_colors
);
16078 * Get the internal Cell padding from CSS attribute.
16079 * @param string $csspadding padding properties
16080 * @param float $width width of the containing element
16081 * @return array of cell paddings
16083 * @since 5.9.000 (2010-10-04)
16085 public function getCSSPadding($csspadding, $width=0) {
16086 $padding = preg_split('/[\s]+/', trim($csspadding));
16087 $cell_padding = array(); // value to be returned
16088 switch (count($padding)) {
16090 $cell_padding['T'] = $padding[0];
16091 $cell_padding['R'] = $padding[1];
16092 $cell_padding['B'] = $padding[2];
16093 $cell_padding['L'] = $padding[3];
16097 $cell_padding['T'] = $padding[0];
16098 $cell_padding['R'] = $padding[1];
16099 $cell_padding['B'] = $padding[2];
16100 $cell_padding['L'] = $padding[1];
16104 $cell_padding['T'] = $padding[0];
16105 $cell_padding['R'] = $padding[1];
16106 $cell_padding['B'] = $padding[0];
16107 $cell_padding['L'] = $padding[1];
16111 $cell_padding['T'] = $padding[0];
16112 $cell_padding['R'] = $padding[0];
16113 $cell_padding['B'] = $padding[0];
16114 $cell_padding['L'] = $padding[0];
16118 return $this->cell_padding
;
16122 $width = $this->w
- $this->lMargin
- $this->rMargin
;
16124 $cell_padding['T'] = $this->getHTMLUnitToUnits($cell_padding['T'], $width, 'px', false);
16125 $cell_padding['R'] = $this->getHTMLUnitToUnits($cell_padding['R'], $width, 'px', false);
16126 $cell_padding['B'] = $this->getHTMLUnitToUnits($cell_padding['B'], $width, 'px', false);
16127 $cell_padding['L'] = $this->getHTMLUnitToUnits($cell_padding['L'], $width, 'px', false);
16128 return $cell_padding;
16132 * Get the internal Cell margin from CSS attribute.
16133 * @param string $cssmargin margin properties
16134 * @param float $width width of the containing element
16135 * @return array of cell margins
16137 * @since 5.9.000 (2010-10-04)
16139 public function getCSSMargin($cssmargin, $width=0) {
16140 $margin = preg_split('/[\s]+/', trim($cssmargin));
16141 $cell_margin = array(); // value to be returned
16142 switch (count($margin)) {
16144 $cell_margin['T'] = $margin[0];
16145 $cell_margin['R'] = $margin[1];
16146 $cell_margin['B'] = $margin[2];
16147 $cell_margin['L'] = $margin[3];
16151 $cell_margin['T'] = $margin[0];
16152 $cell_margin['R'] = $margin[1];
16153 $cell_margin['B'] = $margin[2];
16154 $cell_margin['L'] = $margin[1];
16158 $cell_margin['T'] = $margin[0];
16159 $cell_margin['R'] = $margin[1];
16160 $cell_margin['B'] = $margin[0];
16161 $cell_margin['L'] = $margin[1];
16165 $cell_margin['T'] = $margin[0];
16166 $cell_margin['R'] = $margin[0];
16167 $cell_margin['B'] = $margin[0];
16168 $cell_margin['L'] = $margin[0];
16172 return $this->cell_margin
;
16176 $width = $this->w
- $this->lMargin
- $this->rMargin
;
16178 $cell_margin['T'] = $this->getHTMLUnitToUnits(str_replace('auto', '0', $cell_margin['T']), $width, 'px', false);
16179 $cell_margin['R'] = $this->getHTMLUnitToUnits(str_replace('auto', '0', $cell_margin['R']), $width, 'px', false);
16180 $cell_margin['B'] = $this->getHTMLUnitToUnits(str_replace('auto', '0', $cell_margin['B']), $width, 'px', false);
16181 $cell_margin['L'] = $this->getHTMLUnitToUnits(str_replace('auto', '0', $cell_margin['L']), $width, 'px', false);
16182 return $cell_margin;
16186 * Get the border-spacing from CSS attribute.
16187 * @param string $cssbspace border-spacing CSS properties
16188 * @param float $width width of the containing element
16189 * @return array of border spacings
16191 * @since 5.9.010 (2010-10-27)
16193 public function getCSSBorderMargin($cssbspace, $width=0) {
16194 $space = preg_split('/[\s]+/', trim($cssbspace));
16195 $border_spacing = array(); // value to be returned
16196 switch (count($space)) {
16198 $border_spacing['H'] = $space[0];
16199 $border_spacing['V'] = $space[1];
16203 $border_spacing['H'] = $space[0];
16204 $border_spacing['V'] = $space[0];
16208 return array('H' => 0, 'V' => 0);
16212 $width = $this->w
- $this->lMargin
- $this->rMargin
;
16214 $border_spacing['H'] = $this->getHTMLUnitToUnits($border_spacing['H'], $width, 'px', false);
16215 $border_spacing['V'] = $this->getHTMLUnitToUnits($border_spacing['V'], $width, 'px', false);
16216 return $border_spacing;
16220 * Returns the letter-spacing value from CSS value
16221 * @param string $spacing letter-spacing value
16222 * @param float $parent font spacing (tracking) value of the parent element
16223 * @return float quantity to increases or decreases the space between characters in a text.
16225 * @since 5.9.000 (2010-10-02)
16227 protected function getCSSFontSpacing($spacing, $parent=0) {
16228 $val = 0; // value to be returned
16229 $spacing = trim($spacing);
16230 switch ($spacing) {
16236 if ($parent == 'normal') {
16244 $val = $this->getHTMLUnitToUnits($spacing, 0, 'px', false);
16251 * Returns the percentage of font stretching from CSS value
16252 * @param string $stretch stretch mode
16253 * @param float $parent stretch value of the parent element
16254 * @return float font stretching percentage
16256 * @since 5.9.000 (2010-10-02)
16258 protected function getCSSFontStretching($stretch, $parent=100) {
16259 $val = 100; // value to be returned
16260 $stretch = trim($stretch);
16261 switch ($stretch) {
16262 case 'ultra-condensed': {
16266 case 'extra-condensed': {
16270 case 'condensed': {
16274 case 'semi-condensed': {
16282 case 'semi-expanded': {
16290 case 'extra-expanded': {
16294 case 'ultra-expanded': {
16299 $val = ($parent +
10);
16303 $val = ($parent - 10);
16307 if ($parent == 'normal') {
16315 $val = $this->getHTMLUnitToUnits($stretch, 100, '%', false);
16322 * Convert HTML string containing font size value to points
16323 * @param string $val String containing font size value and unit.
16324 * @param float $refsize Reference font size in points.
16325 * @param float $parent_size Parent font size in points.
16326 * @param string $defaultunit Default unit (can be one of the following: %, em, ex, px, in, mm, pc, pt).
16327 * @return float value in points
16330 public function getHTMLFontUnits($val, $refsize=12, $parent_size=12, $defaultunit='pt') {
16331 $refsize = TCPDF_FONTS
::getFontRefSize($refsize);
16332 $parent_size = TCPDF_FONTS
::getFontRefSize($parent_size, $refsize);
16335 $size = ($refsize - 4);
16339 $size = ($refsize - 3);
16343 $size = ($refsize - 2);
16351 $size = ($refsize +
2);
16355 $size = ($refsize +
4);
16359 $size = ($refsize +
6);
16363 $size = ($parent_size - 3);
16367 $size = ($parent_size +
3);
16371 $parentSize = $this->getHTMLUnitToUnits($parent_size, $refsize, $defaultunit, true);
16372 $size = $this->getHTMLUnitToUnits($val, $parent_size, $defaultunit, true);
16379 * Returns the HTML DOM array.
16380 * @param string $html html code
16383 * @since 3.2.000 (2008-06-20)
16385 protected function getHtmlDomArray($html) {
16386 // array of CSS styles ( selector => properties).
16388 // get CSS array defined at previous call
16389 $matches = array();
16390 if (preg_match_all('/<cssarray>([^\<]*?)<\/cssarray>/is', $html, $matches) > 0) {
16391 if (isset($matches[1][0])) {
16392 $css = array_merge($css, json_decode($this->unhtmlentities($matches[1][0]), true));
16394 $html = preg_replace('/<cssarray>(.*?)<\/cssarray>/is', '', $html);
16396 // extract external CSS files
16397 $matches = array();
16398 if (preg_match_all('/<link([^\>]*?)>/is', $html, $matches) > 0) {
16399 foreach ($matches[1] as $key => $link) {
16401 if (preg_match('/type[\s]*=[\s]*"text\/css"/', $link, $type)) {
16403 preg_match('/media[\s]*=[\s]*"([^"]*)"/', $link, $type);
16404 // get 'all' and 'print' media, other media types are discarded
16405 // (all, braille, embossed, handheld, print, projection, screen, speech, tty, tv)
16406 if (empty($type) OR (isset($type[1]) AND (($type[1] == 'all') OR ($type[1] == 'print')))) {
16408 if (preg_match('/href[\s]*=[\s]*"([^"]*)"/', $link, $type) > 0) {
16409 // read CSS data file
16410 $cssdata = $this->getCachedFileContents(trim($type[1]));
16411 if (($cssdata !== FALSE) AND (strlen($cssdata) > 0)) {
16412 $css = array_merge($css, TCPDF_STATIC
::extractCSSproperties($cssdata));
16419 // extract style tags
16420 $matches = array();
16421 if (preg_match_all('/<style([^\>]*?)>([^\<]*?)<\/style>/is', $html, $matches) > 0) {
16422 foreach ($matches[1] as $key => $media) {
16424 preg_match('/media[\s]*=[\s]*"([^"]*)"/', $media, $type);
16425 // get 'all' and 'print' media, other media types are discarded
16426 // (all, braille, embossed, handheld, print, projection, screen, speech, tty, tv)
16427 if (empty($type) OR (isset($type[1]) AND (($type[1] == 'all') OR ($type[1] == 'print')))) {
16428 $cssdata = $matches[2][$key];
16429 $css = array_merge($css, TCPDF_STATIC
::extractCSSproperties($cssdata));
16433 // create a special tag to contain the CSS array (used for table content)
16434 $csstagarray = '<cssarray>'.htmlentities(json_encode($css)).'</cssarray>';
16435 // remove head and style blocks
16436 $html = preg_replace('/<head([^\>]*?)>(.*?)<\/head>/is', '', $html);
16437 $html = preg_replace('/<style([^\>]*?)>([^\<]*?)<\/style>/is', '', $html);
16438 // define block tags
16439 $blocktags = array('blockquote','br','dd','dl','div','dt','h1','h2','h3','h4','h5','h6','hr','li','ol','p','pre','ul','tcpdf','table','tr','td');
16440 // define self-closing tags
16441 $selfclosingtags = array('area','base','basefont','br','hr','input','img','link','meta');
16442 // remove all unsupported tags (the line below lists all supported tags)
16443 $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>');
16444 //replace some blank characters
16445 $html = preg_replace('/<pre/', '<xre', $html); // preserve pre tag
16446 $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);
16447 $html = preg_replace('@(\r\n|\r)@', "\n", $html);
16448 $repTable = array("\t" => ' ', "\0" => ' ', "\x0B" => ' ', "\\" => "\\\\");
16449 $html = strtr($html, $repTable);
16451 while (($offset < strlen($html)) AND ($pos = strpos($html, '</pre>', $offset)) !== false) {
16452 $html_a = substr($html, 0, $offset);
16453 $html_b = substr($html, $offset, ($pos - $offset +
6));
16454 while (preg_match("'<xre([^\>]*)>(.*?)\n(.*?)</pre>'si", $html_b)) {
16455 // preserve newlines on <pre> tag
16456 $html_b = preg_replace("'<xre([^\>]*)>(.*?)\n(.*?)</pre>'si", "<xre\\1>\\2<br />\\3</pre>", $html_b);
16458 while (preg_match("'<xre([^\>]*)>(.*?)".$this->re_space
['p']."(.*?)</pre>'".$this->re_space
['m'], $html_b)) {
16459 // preserve spaces on <pre> tag
16460 $html_b = preg_replace("'<xre([^\>]*)>(.*?)".$this->re_space
['p']."(.*?)</pre>'".$this->re_space
['m'], "<xre\\1>\\2 \\3</pre>", $html_b);
16462 $html = $html_a.$html_b.substr($html, $pos +
6);
16463 $offset = strlen($html_a.$html_b);
16466 while (($offset < strlen($html)) AND ($pos = strpos($html, '</textarea>', $offset)) !== false) {
16467 $html_a = substr($html, 0, $offset);
16468 $html_b = substr($html, $offset, ($pos - $offset +
11));
16469 while (preg_match("'<textarea([^\>]*)>(.*?)\n(.*?)</textarea>'si", $html_b)) {
16470 // preserve newlines on <textarea> tag
16471 $html_b = preg_replace("'<textarea([^\>]*)>(.*?)\n(.*?)</textarea>'si", "<textarea\\1>\\2<TBR>\\3</textarea>", $html_b);
16472 $html_b = preg_replace("'<textarea([^\>]*)>(.*?)[\"](.*?)</textarea>'si", "<textarea\\1>\\2''\\3</textarea>", $html_b);
16474 $html = $html_a.$html_b.substr($html, $pos +
11);
16475 $offset = strlen($html_a.$html_b);
16477 $html = preg_replace('/([\s]*)<option/si', '<option', $html);
16478 $html = preg_replace('/<\/option>([\s]*)/si', '</option>', $html);
16480 while (($offset < strlen($html)) AND ($pos = strpos($html, '</option>', $offset)) !== false) {
16481 $html_a = substr($html, 0, $offset);
16482 $html_b = substr($html, $offset, ($pos - $offset +
9));
16483 while (preg_match("'<option([^\>]*)>(.*?)</option>'si", $html_b)) {
16484 $html_b = preg_replace("'<option([\s]+)value=\"([^\"]*)\"([^\>]*)>(.*?)</option>'si", "\\2#!TaB!#\\4#!NwL!#", $html_b);
16485 $html_b = preg_replace("'<option([^\>]*)>(.*?)</option>'si", "\\2#!NwL!#", $html_b);
16487 $html = $html_a.$html_b.substr($html, $pos +
9);
16488 $offset = strlen($html_a.$html_b);
16490 if (preg_match("'</select'si", $html)) {
16491 $html = preg_replace("'<select([^\>]*)>'si", "<select\\1 opt=\"", $html);
16492 $html = preg_replace("'#!NwL!#</select>'si", "\" />", $html);
16494 $html = str_replace("\n", ' ', $html);
16495 // restore textarea newlines
16496 $html = str_replace('<TBR>', "\n", $html);
16497 // remove extra spaces from code
16498 $html = preg_replace('/[\s]+<\/(table|tr|ul|ol|dl)>/', '</\\1>', $html);
16499 $html = preg_replace('/'.$this->re_space
['p'].'+<\/(td|th|li|dt|dd)>/'.$this->re_space
['m'], '</\\1>', $html);
16500 $html = preg_replace('/[\s]+<(tr|td|th|li|dt|dd)/', '<\\1', $html);
16501 $html = preg_replace('/'.$this->re_space
['p'].'+<(ul|ol|dl|br)/'.$this->re_space
['m'], '<\\1', $html);
16502 $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);
16503 $html = preg_replace('/<\/(td|th)>/', '<marker style="font-size:0"/></\\1>', $html);
16504 $html = preg_replace('/<\/table>([\s]*)<marker style="font-size:0"\/>/', '</table>', $html);
16505 $html = preg_replace('/'.$this->re_space
['p'].'+<img/'.$this->re_space
['m'], chr(32).'<img', $html);
16506 $html = preg_replace('/<img([^\>]*)>[\s]+([^\<])/xi', '<img\\1> \\2', $html);
16507 $html = preg_replace('/<img([^\>]*)>/xi', '<img\\1><span><marker style="font-size:0"/></span>', $html);
16508 $html = preg_replace('/<xre/', '<pre', $html); // restore pre tag
16509 $html = preg_replace('/<textarea([^\>]*)>([^\<]*)<\/textarea>/xi', '<textarea\\1 value="\\2" />', $html);
16510 $html = preg_replace('/<li([^\>]*)><\/li>/', '<li\\1> </li>', $html);
16511 $html = preg_replace('/<li([^\>]*)>'.$this->re_space
['p'].'*<img/'.$this->re_space
['m'], '<li\\1><font size="1"> </font><img', $html);
16512 $html = preg_replace('/<([^\>\/]*)>[\s]/', '<\\1> ', $html); // preserve some spaces
16513 $html = preg_replace('/[\s]<\/([^\>]*)>/', ' </\\1>', $html); // preserve some spaces
16514 $html = preg_replace('/<su([bp])/', '<zws/><su\\1', $html); // fix sub/sup alignment
16515 $html = preg_replace('/<\/su([bp])>/', '</su\\1><zws/>', $html); // fix sub/sup alignment
16516 $html = preg_replace('/'.$this->re_space
['p'].'+/'.$this->re_space
['m'], chr(32), $html); // replace multiple spaces with a single space
16518 $html = $this->stringTrim($html);
16519 // fix br tag after li
16520 $html = preg_replace('/<li><br([^\>]*)>/', '<li> <br\\1>', $html);
16521 // fix first image tag alignment
16522 $html = preg_replace('/^<img/', '<span style="font-size:0"><br /></span> <img', $html, 1);
16523 // pattern for generic tag
16524 $tagpattern = '/(<[^>]+>)/';
16525 // explodes the string
16526 $a = preg_split($tagpattern, $html, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY
);
16528 $maxel = count($a);
16531 // create an array of elements
16533 $dom[$key] = array();
16534 // set inheritable properties fot the first void element
16535 // 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
16536 $dom[$key]['tag'] = false;
16537 $dom[$key]['block'] = false;
16538 $dom[$key]['value'] = '';
16539 $dom[$key]['parent'] = 0;
16540 $dom[$key]['hide'] = false;
16541 $dom[$key]['fontname'] = $this->FontFamily
;
16542 $dom[$key]['fontstyle'] = $this->FontStyle
;
16543 $dom[$key]['fontsize'] = $this->FontSizePt
;
16544 $dom[$key]['font-stretch'] = $this->font_stretching
;
16545 $dom[$key]['letter-spacing'] = $this->font_spacing
;
16546 $dom[$key]['stroke'] = $this->textstrokewidth
;
16547 $dom[$key]['fill'] = (($this->textrendermode %
2) == 0);
16548 $dom[$key]['clip'] = ($this->textrendermode
> 3);
16549 $dom[$key]['line-height'] = $this->cell_height_ratio
;
16550 $dom[$key]['bgcolor'] = false;
16551 $dom[$key]['fgcolor'] = $this->fgcolor
; // color
16552 $dom[$key]['strokecolor'] = $this->strokecolor
;
16553 $dom[$key]['align'] = '';
16554 $dom[$key]['listtype'] = '';
16555 $dom[$key]['text-indent'] = 0;
16556 $dom[$key]['text-transform'] = '';
16557 $dom[$key]['border'] = array();
16558 $dom[$key]['dir'] = $this->rtl?
'rtl':'ltr';
16559 $thead = false; // true when we are inside the THEAD tag
16562 array_push($level, 0); // root
16563 while ($elkey < $maxel) {
16564 $dom[$key] = array();
16565 $element = $a[$elkey];
16566 $dom[$key]['elkey'] = $elkey;
16567 if (preg_match($tagpattern, $element)) {
16569 $element = substr($element, 1, -1);
16571 preg_match('/[\/]?([a-zA-Z0-9]*)/', $element, $tag);
16572 $tagname = strtolower($tag[1]);
16573 // check if we are inside a table header
16574 if ($tagname == 'thead') {
16575 if ($element[0] == '/') {
16583 $dom[$key]['tag'] = true;
16584 $dom[$key]['value'] = $tagname;
16585 if (in_array($dom[$key]['value'], $blocktags)) {
16586 $dom[$key]['block'] = true;
16588 $dom[$key]['block'] = false;
16590 if ($element[0] == '/') {
16591 // *** closing html tag
16592 $dom[$key]['opening'] = false;
16593 $dom[$key]['parent'] = end($level);
16595 $dom[$key]['hide'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['hide'];
16596 $dom[$key]['fontname'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fontname'];
16597 $dom[$key]['fontstyle'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fontstyle'];
16598 $dom[$key]['fontsize'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fontsize'];
16599 $dom[$key]['font-stretch'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['font-stretch'];
16600 $dom[$key]['letter-spacing'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['letter-spacing'];
16601 $dom[$key]['stroke'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['stroke'];
16602 $dom[$key]['fill'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fill'];
16603 $dom[$key]['clip'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['clip'];
16604 $dom[$key]['line-height'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['line-height'];
16605 $dom[$key]['bgcolor'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['bgcolor'];
16606 $dom[$key]['fgcolor'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fgcolor'];
16607 $dom[$key]['strokecolor'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['strokecolor'];
16608 $dom[$key]['align'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['align'];
16609 $dom[$key]['text-transform'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['text-transform'];
16610 $dom[$key]['dir'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['dir'];
16611 if (isset($dom[($dom[($dom[$key]['parent'])]['parent'])]['listtype'])) {
16612 $dom[$key]['listtype'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['listtype'];
16614 // set the number of columns in table tag
16615 if (($dom[$key]['value'] == 'tr') AND (!isset($dom[($dom[($dom[$key]['parent'])]['parent'])]['cols']))) {
16616 $dom[($dom[($dom[$key]['parent'])]['parent'])]['cols'] = $dom[($dom[$key]['parent'])]['cols'];
16618 if (($dom[$key]['value'] == 'td') OR ($dom[$key]['value'] == 'th')) {
16619 $dom[($dom[$key]['parent'])]['content'] = $csstagarray;
16620 for ($i = ($dom[$key]['parent'] +
1); $i < $key; ++
$i) {
16621 $dom[($dom[$key]['parent'])]['content'] .= stripslashes($a[$dom[$i]['elkey']]);
16624 // mark nested tables
16625 $dom[($dom[$key]['parent'])]['content'] = str_replace('<table', '<table nested="true"', $dom[($dom[$key]['parent'])]['content']);
16626 // remove thead sections from nested tables
16627 $dom[($dom[$key]['parent'])]['content'] = str_replace('<thead>', '', $dom[($dom[$key]['parent'])]['content']);
16628 $dom[($dom[$key]['parent'])]['content'] = str_replace('</thead>', '', $dom[($dom[$key]['parent'])]['content']);
16630 // store header rows on a new table
16632 ($dom[$key]['value'] === 'tr')
16633 && !empty($dom[($dom[$key]['parent'])]['thead'])
16634 && ($dom[($dom[$key]['parent'])]['thead'] === true)
16636 if (TCPDF_STATIC
::empty_string($dom[($dom[($dom[$key]['parent'])]['parent'])]['thead'])) {
16637 $dom[($dom[($dom[$key]['parent'])]['parent'])]['thead'] = $csstagarray.$a[$dom[($dom[($dom[$key]['parent'])]['parent'])]['elkey']];
16639 for ($i = $dom[$key]['parent']; $i <= $key; ++
$i) {
16640 $dom[($dom[($dom[$key]['parent'])]['parent'])]['thead'] .= $a[$dom[$i]['elkey']];
16642 if (!isset($dom[($dom[$key]['parent'])]['attribute'])) {
16643 $dom[($dom[$key]['parent'])]['attribute'] = array();
16645 // header elements must be always contained in a single page
16646 $dom[($dom[$key]['parent'])]['attribute']['nobr'] = 'true';
16648 if (($dom[$key]['value'] == 'table') AND (!TCPDF_STATIC
::empty_string($dom[($dom[$key]['parent'])]['thead']))) {
16649 // remove the nobr attributes from the table header
16650 $dom[($dom[$key]['parent'])]['thead'] = str_replace(' nobr="true"', '', $dom[($dom[$key]['parent'])]['thead']);
16651 $dom[($dom[$key]['parent'])]['thead'] .= '</tablehead>';
16654 // *** opening or self-closing html tag
16655 $dom[$key]['opening'] = true;
16656 $dom[$key]['parent'] = end($level);
16657 if ((substr($element, -1, 1) == '/') OR (in_array($dom[$key]['value'], $selfclosingtags))) {
16658 // self-closing tag
16659 $dom[$key]['self'] = true;
16662 array_push($level, $key);
16663 $dom[$key]['self'] = false;
16665 // copy some values from parent
16668 $parentkey = $dom[$key]['parent'];
16669 $dom[$key]['hide'] = $dom[$parentkey]['hide'];
16670 $dom[$key]['fontname'] = $dom[$parentkey]['fontname'];
16671 $dom[$key]['fontstyle'] = $dom[$parentkey]['fontstyle'];
16672 $dom[$key]['fontsize'] = $dom[$parentkey]['fontsize'];
16673 $dom[$key]['font-stretch'] = $dom[$parentkey]['font-stretch'];
16674 $dom[$key]['letter-spacing'] = $dom[$parentkey]['letter-spacing'];
16675 $dom[$key]['stroke'] = $dom[$parentkey]['stroke'];
16676 $dom[$key]['fill'] = $dom[$parentkey]['fill'];
16677 $dom[$key]['clip'] = $dom[$parentkey]['clip'];
16678 $dom[$key]['line-height'] = $dom[$parentkey]['line-height'];
16679 $dom[$key]['bgcolor'] = $dom[$parentkey]['bgcolor'];
16680 $dom[$key]['fgcolor'] = $dom[$parentkey]['fgcolor'];
16681 $dom[$key]['strokecolor'] = $dom[$parentkey]['strokecolor'];
16682 $dom[$key]['align'] = $dom[$parentkey]['align'];
16683 $dom[$key]['listtype'] = $dom[$parentkey]['listtype'];
16684 $dom[$key]['text-indent'] = $dom[$parentkey]['text-indent'];
16685 $dom[$key]['text-transform'] = $dom[$parentkey]['text-transform'];
16686 $dom[$key]['border'] = array();
16687 $dom[$key]['dir'] = $dom[$parentkey]['dir'];
16690 preg_match_all('/([^=\s]*)[\s]*=[\s]*"([^"]*)"/', $element, $attr_array, PREG_PATTERN_ORDER
);
16691 $dom[$key]['attribute'] = array(); // reset attribute array
16692 foreach($attr_array[1] as $id => $name) {
16693 $dom[$key]['attribute'][strtolower($name)] = $attr_array[2][$id];
16695 if (!empty($css)) {
16696 // merge CSS style to current style
16697 list($dom[$key]['csssel'], $dom[$key]['cssdata']) = TCPDF_STATIC
::getCSSdataArray($dom, $key, $css);
16698 $dom[$key]['attribute']['style'] = TCPDF_STATIC
::getTagStyleFromCSSarray($dom[$key]['cssdata']);
16700 // split style attributes
16701 if (isset($dom[$key]['attribute']['style']) AND !empty($dom[$key]['attribute']['style'])) {
16702 // get style attributes
16703 preg_match_all('/([^;:\s]*):([^;]*)/', $dom[$key]['attribute']['style'], $style_array, PREG_PATTERN_ORDER
);
16704 $dom[$key]['style'] = array(); // reset style attribute array
16705 foreach($style_array[1] as $id => $name) {
16706 // in case of duplicate attribute the last replace the previous
16707 $dom[$key]['style'][strtolower($name)] = trim($style_array[2][$id]);
16709 // --- get some style attributes ---
16711 if (isset($dom[$key]['style']['direction'])) {
16712 $dom[$key]['dir'] = $dom[$key]['style']['direction'];
16715 if (isset($dom[$key]['style']['display'])) {
16716 $dom[$key]['hide'] = (trim(strtolower($dom[$key]['style']['display'])) == 'none');
16719 if (isset($dom[$key]['style']['font-family'])) {
16720 $dom[$key]['fontname'] = $this->getFontFamilyName($dom[$key]['style']['font-family']);
16723 if (isset($dom[$key]['style']['list-style-type'])) {
16724 $dom[$key]['listtype'] = trim(strtolower($dom[$key]['style']['list-style-type']));
16725 if ($dom[$key]['listtype'] == 'inherit') {
16726 $dom[$key]['listtype'] = $dom[$parentkey]['listtype'];
16730 if (isset($dom[$key]['style']['text-indent'])) {
16731 $dom[$key]['text-indent'] = $this->getHTMLUnitToUnits($dom[$key]['style']['text-indent']);
16732 if ($dom[$key]['text-indent'] == 'inherit') {
16733 $dom[$key]['text-indent'] = $dom[$parentkey]['text-indent'];
16737 if (isset($dom[$key]['style']['text-transform'])) {
16738 $dom[$key]['text-transform'] = $dom[$key]['style']['text-transform'];
16741 if (isset($dom[$key]['style']['font-size'])) {
16742 $fsize = trim($dom[$key]['style']['font-size']);
16743 $dom[$key]['fontsize'] = $this->getHTMLFontUnits($fsize, $dom[0]['fontsize'], $dom[$parentkey]['fontsize'], 'pt');
16746 if (isset($dom[$key]['style']['font-stretch'])) {
16747 $dom[$key]['font-stretch'] = $this->getCSSFontStretching($dom[$key]['style']['font-stretch'], $dom[$parentkey]['font-stretch']);
16750 if (isset($dom[$key]['style']['letter-spacing'])) {
16751 $dom[$key]['letter-spacing'] = $this->getCSSFontSpacing($dom[$key]['style']['letter-spacing'], $dom[$parentkey]['letter-spacing']);
16753 // line-height (internally is the cell height ratio)
16754 if (isset($dom[$key]['style']['line-height'])) {
16755 $lineheight = trim($dom[$key]['style']['line-height']);
16756 switch ($lineheight) {
16757 // A normal line height. This is default
16759 $dom[$key]['line-height'] = $dom[0]['line-height'];
16763 $dom[$key]['line-height'] = $dom[$parentkey]['line-height'];
16766 if (is_numeric($lineheight)) {
16767 // convert to percentage of font height
16768 $lineheight = ($lineheight * 100).'%';
16770 $dom[$key]['line-height'] = $this->getHTMLUnitToUnits($lineheight, 1, '%', true);
16771 if (substr($lineheight, -1) !== '%') {
16772 if ($dom[$key]['fontsize'] <= 0) {
16773 $dom[$key]['line-height'] = 1;
16775 $dom[$key]['line-height'] = (($dom[$key]['line-height'] - $this->cell_padding
['T'] - $this->cell_padding
['B']) / $dom[$key]['fontsize']);
16782 if (isset($dom[$key]['style']['font-weight'])) {
16783 if (strtolower($dom[$key]['style']['font-weight'][0]) == 'n') {
16784 if (strpos($dom[$key]['fontstyle'], 'B') !== false) {
16785 $dom[$key]['fontstyle'] = str_replace('B', '', $dom[$key]['fontstyle']);
16787 } elseif (strtolower($dom[$key]['style']['font-weight'][0]) == 'b') {
16788 $dom[$key]['fontstyle'] .= 'B';
16791 if (isset($dom[$key]['style']['font-style']) AND (strtolower($dom[$key]['style']['font-style'][0]) == 'i')) {
16792 $dom[$key]['fontstyle'] .= 'I';
16795 if (isset($dom[$key]['style']['color']) AND (!TCPDF_STATIC
::empty_string($dom[$key]['style']['color']))) {
16796 $dom[$key]['fgcolor'] = TCPDF_COLORS
::convertHTMLColorToDec($dom[$key]['style']['color'], $this->spot_colors
);
16797 } elseif ($dom[$key]['value'] == 'a') {
16798 $dom[$key]['fgcolor'] = $this->htmlLinkColorArray
;
16800 // background color
16801 if (isset($dom[$key]['style']['background-color']) AND (!TCPDF_STATIC
::empty_string($dom[$key]['style']['background-color']))) {
16802 $dom[$key]['bgcolor'] = TCPDF_COLORS
::convertHTMLColorToDec($dom[$key]['style']['background-color'], $this->spot_colors
);
16805 if (isset($dom[$key]['style']['text-decoration'])) {
16806 $decors = explode(' ', strtolower($dom[$key]['style']['text-decoration']));
16807 foreach ($decors as $dec) {
16809 if (!TCPDF_STATIC
::empty_string($dec)) {
16810 if ($dec[0] == 'u') {
16812 $dom[$key]['fontstyle'] .= 'U';
16813 } elseif ($dec[0] == 'l') {
16815 $dom[$key]['fontstyle'] .= 'D';
16816 } elseif ($dec[0] == 'o') {
16818 $dom[$key]['fontstyle'] .= 'O';
16822 } elseif ($dom[$key]['value'] == 'a') {
16823 $dom[$key]['fontstyle'] = $this->htmlLinkFontStyle
;
16825 // check for width attribute
16826 if (isset($dom[$key]['style']['width'])) {
16827 $dom[$key]['width'] = $dom[$key]['style']['width'];
16829 // check for height attribute
16830 if (isset($dom[$key]['style']['height'])) {
16831 $dom[$key]['height'] = $dom[$key]['style']['height'];
16833 // check for text alignment
16834 if (isset($dom[$key]['style']['text-align'])) {
16835 $dom[$key]['align'] = strtoupper($dom[$key]['style']['text-align'][0]);
16837 // check for CSS border properties
16838 if (isset($dom[$key]['style']['border'])) {
16839 $borderstyle = $this->getCSSBorderStyle($dom[$key]['style']['border']);
16840 if (!empty($borderstyle)) {
16841 $dom[$key]['border']['LTRB'] = $borderstyle;
16844 if (isset($dom[$key]['style']['border-color'])) {
16845 $brd_colors = preg_split('/[\s]+/', trim($dom[$key]['style']['border-color']));
16846 if (isset($brd_colors[3])) {
16847 $dom[$key]['border']['L']['color'] = TCPDF_COLORS
::convertHTMLColorToDec($brd_colors[3], $this->spot_colors
);
16849 if (isset($brd_colors[1])) {
16850 $dom[$key]['border']['R']['color'] = TCPDF_COLORS
::convertHTMLColorToDec($brd_colors[1], $this->spot_colors
);
16852 if (isset($brd_colors[0])) {
16853 $dom[$key]['border']['T']['color'] = TCPDF_COLORS
::convertHTMLColorToDec($brd_colors[0], $this->spot_colors
);
16855 if (isset($brd_colors[2])) {
16856 $dom[$key]['border']['B']['color'] = TCPDF_COLORS
::convertHTMLColorToDec($brd_colors[2], $this->spot_colors
);
16859 if (isset($dom[$key]['style']['border-width'])) {
16860 $brd_widths = preg_split('/[\s]+/', trim($dom[$key]['style']['border-width']));
16861 if (isset($brd_widths[3])) {
16862 $dom[$key]['border']['L']['width'] = $this->getCSSBorderWidth($brd_widths[3]);
16864 if (isset($brd_widths[1])) {
16865 $dom[$key]['border']['R']['width'] = $this->getCSSBorderWidth($brd_widths[1]);
16867 if (isset($brd_widths[0])) {
16868 $dom[$key]['border']['T']['width'] = $this->getCSSBorderWidth($brd_widths[0]);
16870 if (isset($brd_widths[2])) {
16871 $dom[$key]['border']['B']['width'] = $this->getCSSBorderWidth($brd_widths[2]);
16874 if (isset($dom[$key]['style']['border-style'])) {
16875 $brd_styles = preg_split('/[\s]+/', trim($dom[$key]['style']['border-style']));
16876 if (isset($brd_styles[3]) AND ($brd_styles[3]!='none')) {
16877 $dom[$key]['border']['L']['cap'] = 'square';
16878 $dom[$key]['border']['L']['join'] = 'miter';
16879 $dom[$key]['border']['L']['dash'] = $this->getCSSBorderDashStyle($brd_styles[3]);
16880 if ($dom[$key]['border']['L']['dash'] < 0) {
16881 $dom[$key]['border']['L'] = array();
16884 if (isset($brd_styles[1])) {
16885 $dom[$key]['border']['R']['cap'] = 'square';
16886 $dom[$key]['border']['R']['join'] = 'miter';
16887 $dom[$key]['border']['R']['dash'] = $this->getCSSBorderDashStyle($brd_styles[1]);
16888 if ($dom[$key]['border']['R']['dash'] < 0) {
16889 $dom[$key]['border']['R'] = array();
16892 if (isset($brd_styles[0])) {
16893 $dom[$key]['border']['T']['cap'] = 'square';
16894 $dom[$key]['border']['T']['join'] = 'miter';
16895 $dom[$key]['border']['T']['dash'] = $this->getCSSBorderDashStyle($brd_styles[0]);
16896 if ($dom[$key]['border']['T']['dash'] < 0) {
16897 $dom[$key]['border']['T'] = array();
16900 if (isset($brd_styles[2])) {
16901 $dom[$key]['border']['B']['cap'] = 'square';
16902 $dom[$key]['border']['B']['join'] = 'miter';
16903 $dom[$key]['border']['B']['dash'] = $this->getCSSBorderDashStyle($brd_styles[2]);
16904 if ($dom[$key]['border']['B']['dash'] < 0) {
16905 $dom[$key]['border']['B'] = array();
16909 $cellside = array('L' => 'left', 'R' => 'right', 'T' => 'top', 'B' => 'bottom');
16910 foreach ($cellside as $bsk => $bsv) {
16911 if (isset($dom[$key]['style']['border-'.$bsv])) {
16912 $borderstyle = $this->getCSSBorderStyle($dom[$key]['style']['border-'.$bsv]);
16913 if (!empty($borderstyle)) {
16914 $dom[$key]['border'][$bsk] = $borderstyle;
16917 if (isset($dom[$key]['style']['border-'.$bsv.'-color'])) {
16918 $dom[$key]['border'][$bsk]['color'] = TCPDF_COLORS
::convertHTMLColorToDec($dom[$key]['style']['border-'.$bsv.'-color'], $this->spot_colors
);
16920 if (isset($dom[$key]['style']['border-'.$bsv.'-width'])) {
16921 $dom[$key]['border'][$bsk]['width'] = $this->getCSSBorderWidth($dom[$key]['style']['border-'.$bsv.'-width']);
16923 if (isset($dom[$key]['style']['border-'.$bsv.'-style'])) {
16924 $dom[$key]['border'][$bsk]['dash'] = $this->getCSSBorderDashStyle($dom[$key]['style']['border-'.$bsv.'-style']);
16925 if ($dom[$key]['border'][$bsk]['dash'] < 0) {
16926 $dom[$key]['border'][$bsk] = array();
16930 // check for CSS padding properties
16931 if (isset($dom[$key]['style']['padding'])) {
16932 $dom[$key]['padding'] = $this->getCSSPadding($dom[$key]['style']['padding']);
16934 $dom[$key]['padding'] = $this->cell_padding
;
16936 foreach ($cellside as $psk => $psv) {
16937 if (isset($dom[$key]['style']['padding-'.$psv])) {
16938 $dom[$key]['padding'][$psk] = $this->getHTMLUnitToUnits($dom[$key]['style']['padding-'.$psv], 0, 'px', false);
16941 // check for CSS margin properties
16942 if (isset($dom[$key]['style']['margin'])) {
16943 $dom[$key]['margin'] = $this->getCSSMargin($dom[$key]['style']['margin']);
16945 $dom[$key]['margin'] = $this->cell_margin
;
16947 foreach ($cellside as $psk => $psv) {
16948 if (isset($dom[$key]['style']['margin-'.$psv])) {
16949 $dom[$key]['margin'][$psk] = $this->getHTMLUnitToUnits(str_replace('auto', '0', $dom[$key]['style']['margin-'.$psv]), 0, 'px', false);
16952 // check for CSS border-spacing properties
16953 if (isset($dom[$key]['style']['border-spacing'])) {
16954 $dom[$key]['border-spacing'] = $this->getCSSBorderMargin($dom[$key]['style']['border-spacing']);
16956 // page-break-inside
16957 if (isset($dom[$key]['style']['page-break-inside']) AND ($dom[$key]['style']['page-break-inside'] == 'avoid')) {
16958 $dom[$key]['attribute']['nobr'] = 'true';
16960 // page-break-before
16961 if (isset($dom[$key]['style']['page-break-before'])) {
16962 if ($dom[$key]['style']['page-break-before'] == 'always') {
16963 $dom[$key]['attribute']['pagebreak'] = 'true';
16964 } elseif ($dom[$key]['style']['page-break-before'] == 'left') {
16965 $dom[$key]['attribute']['pagebreak'] = 'left';
16966 } elseif ($dom[$key]['style']['page-break-before'] == 'right') {
16967 $dom[$key]['attribute']['pagebreak'] = 'right';
16970 // page-break-after
16971 if (isset($dom[$key]['style']['page-break-after'])) {
16972 if ($dom[$key]['style']['page-break-after'] == 'always') {
16973 $dom[$key]['attribute']['pagebreakafter'] = 'true';
16974 } elseif ($dom[$key]['style']['page-break-after'] == 'left') {
16975 $dom[$key]['attribute']['pagebreakafter'] = 'left';
16976 } elseif ($dom[$key]['style']['page-break-after'] == 'right') {
16977 $dom[$key]['attribute']['pagebreakafter'] = 'right';
16981 if (isset($dom[$key]['attribute']['display'])) {
16982 $dom[$key]['hide'] = (trim(strtolower($dom[$key]['attribute']['display'])) == 'none');
16984 if (isset($dom[$key]['attribute']['border']) AND ($dom[$key]['attribute']['border'] != 0)) {
16985 $borderstyle = $this->getCSSBorderStyle($dom[$key]['attribute']['border'].' solid black');
16986 if (!empty($borderstyle)) {
16987 $dom[$key]['border']['LTRB'] = $borderstyle;
16990 // check for font tag
16991 if ($dom[$key]['value'] == 'font') {
16993 if (isset($dom[$key]['attribute']['face'])) {
16994 $dom[$key]['fontname'] = $this->getFontFamilyName($dom[$key]['attribute']['face']);
16997 if (isset($dom[$key]['attribute']['size'])) {
16999 if ($dom[$key]['attribute']['size'][0] == '+') {
17000 $dom[$key]['fontsize'] = $dom[($dom[$key]['parent'])]['fontsize'] +
intval(substr($dom[$key]['attribute']['size'], 1));
17001 } elseif ($dom[$key]['attribute']['size'][0] == '-') {
17002 $dom[$key]['fontsize'] = $dom[($dom[$key]['parent'])]['fontsize'] - intval(substr($dom[$key]['attribute']['size'], 1));
17004 $dom[$key]['fontsize'] = intval($dom[$key]['attribute']['size']);
17007 $dom[$key]['fontsize'] = intval($dom[$key]['attribute']['size']);
17011 // force natural alignment for lists
17012 if ((($dom[$key]['value'] == 'ul') OR ($dom[$key]['value'] == 'ol') OR ($dom[$key]['value'] == 'dl'))
17013 AND (!isset($dom[$key]['align']) OR TCPDF_STATIC
::empty_string($dom[$key]['align']) OR ($dom[$key]['align'] != 'J'))) {
17015 $dom[$key]['align'] = 'R';
17017 $dom[$key]['align'] = 'L';
17020 if (($dom[$key]['value'] == 'small') OR ($dom[$key]['value'] == 'sup') OR ($dom[$key]['value'] == 'sub')) {
17021 if (!isset($dom[$key]['attribute']['size']) AND !isset($dom[$key]['style']['font-size'])) {
17022 $dom[$key]['fontsize'] = $dom[$key]['fontsize'] * K_SMALL_RATIO
;
17025 if (($dom[$key]['value'] == 'strong') OR ($dom[$key]['value'] == 'b')) {
17026 $dom[$key]['fontstyle'] .= 'B';
17028 if (($dom[$key]['value'] == 'em') OR ($dom[$key]['value'] == 'i')) {
17029 $dom[$key]['fontstyle'] .= 'I';
17031 if ($dom[$key]['value'] == 'u') {
17032 $dom[$key]['fontstyle'] .= 'U';
17034 if (($dom[$key]['value'] == 'del') OR ($dom[$key]['value'] == 's') OR ($dom[$key]['value'] == 'strike')) {
17035 $dom[$key]['fontstyle'] .= 'D';
17037 if (!isset($dom[$key]['style']['text-decoration']) AND ($dom[$key]['value'] == 'a')) {
17038 $dom[$key]['fontstyle'] = $this->htmlLinkFontStyle
;
17040 if (($dom[$key]['value'] == 'pre') OR ($dom[$key]['value'] == 'tt')) {
17041 $dom[$key]['fontname'] = $this->default_monospaced_font
;
17043 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)) {
17044 // headings h1, h2, h3, h4, h5, h6
17045 if (!isset($dom[$key]['attribute']['size']) AND !isset($dom[$key]['style']['font-size'])) {
17046 $headsize = (4 - intval($dom[$key]['value'][1])) * 2;
17047 $dom[$key]['fontsize'] = $dom[0]['fontsize'] +
$headsize;
17049 if (!isset($dom[$key]['style']['font-weight'])) {
17050 $dom[$key]['fontstyle'] .= 'B';
17053 if (($dom[$key]['value'] == 'table')) {
17054 $dom[$key]['rows'] = 0; // number of rows
17055 $dom[$key]['trids'] = array(); // IDs of TR elements
17056 $dom[$key]['thead'] = ''; // table header rows
17058 if (($dom[$key]['value'] == 'tr')) {
17059 $dom[$key]['cols'] = 0;
17061 $dom[$key]['thead'] = true;
17062 // rows on thead block are printed as a separate table
17064 $dom[$key]['thead'] = false;
17065 $parent = $dom[$key]['parent'];
17067 if (!isset($dom[$parent]['rows'])) {
17068 $dom[$parent]['rows'] = 0;
17070 // store the number of rows on table element
17071 ++
$dom[$parent]['rows'];
17073 if (!isset($dom[$parent]['trids'])) {
17074 $dom[$parent]['trids'] = array();
17077 // store the TR elements IDs on table element
17078 array_push($dom[$parent]['trids'], $key);
17081 if (($dom[$key]['value'] == 'th') OR ($dom[$key]['value'] == 'td')) {
17082 if (isset($dom[$key]['attribute']['colspan'])) {
17083 $colspan = intval($dom[$key]['attribute']['colspan']);
17087 $dom[$key]['attribute']['colspan'] = $colspan;
17088 $dom[($dom[$key]['parent'])]['cols'] +
= $colspan;
17091 if (isset($dom[$key]['attribute']['dir'])) {
17092 $dom[$key]['dir'] = $dom[$key]['attribute']['dir'];
17094 // set foreground color attribute
17095 if (isset($dom[$key]['attribute']['color']) AND (!TCPDF_STATIC
::empty_string($dom[$key]['attribute']['color']))) {
17096 $dom[$key]['fgcolor'] = TCPDF_COLORS
::convertHTMLColorToDec($dom[$key]['attribute']['color'], $this->spot_colors
);
17097 } elseif (!isset($dom[$key]['style']['color']) AND ($dom[$key]['value'] == 'a')) {
17098 $dom[$key]['fgcolor'] = $this->htmlLinkColorArray
;
17100 // set background color attribute
17101 if (isset($dom[$key]['attribute']['bgcolor']) AND (!TCPDF_STATIC
::empty_string($dom[$key]['attribute']['bgcolor']))) {
17102 $dom[$key]['bgcolor'] = TCPDF_COLORS
::convertHTMLColorToDec($dom[$key]['attribute']['bgcolor'], $this->spot_colors
);
17104 // set stroke color attribute
17105 if (isset($dom[$key]['attribute']['strokecolor']) AND (!TCPDF_STATIC
::empty_string($dom[$key]['attribute']['strokecolor']))) {
17106 $dom[$key]['strokecolor'] = TCPDF_COLORS
::convertHTMLColorToDec($dom[$key]['attribute']['strokecolor'], $this->spot_colors
);
17108 // check for width attribute
17109 if (isset($dom[$key]['attribute']['width'])) {
17110 $dom[$key]['width'] = $dom[$key]['attribute']['width'];
17112 // check for height attribute
17113 if (isset($dom[$key]['attribute']['height'])) {
17114 $dom[$key]['height'] = $dom[$key]['attribute']['height'];
17116 // check for text alignment
17117 if (isset($dom[$key]['attribute']['align']) AND (!TCPDF_STATIC
::empty_string($dom[$key]['attribute']['align'])) AND ($dom[$key]['value'] !== 'img')) {
17118 $dom[$key]['align'] = strtoupper($dom[$key]['attribute']['align'][0]);
17120 // check for text rendering mode (the following attributes do not exist in HTML)
17121 if (isset($dom[$key]['attribute']['stroke'])) {
17122 // font stroke width
17123 $dom[$key]['stroke'] = $this->getHTMLUnitToUnits($dom[$key]['attribute']['stroke'], $dom[$key]['fontsize'], 'pt', true);
17125 if (isset($dom[$key]['attribute']['fill'])) {
17127 if ($dom[$key]['attribute']['fill'] == 'true') {
17128 $dom[$key]['fill'] = true;
17130 $dom[$key]['fill'] = false;
17133 if (isset($dom[$key]['attribute']['clip'])) {
17135 if ($dom[$key]['attribute']['clip'] == 'true') {
17136 $dom[$key]['clip'] = true;
17138 $dom[$key]['clip'] = false;
17141 } // end opening tag
17144 $dom[$key]['tag'] = false;
17145 $dom[$key]['block'] = false;
17146 $dom[$key]['parent'] = end($level);
17147 $dom[$key]['dir'] = $dom[$dom[$key]['parent']]['dir'];
17148 if (!empty($dom[$dom[$key]['parent']]['text-transform'])) {
17149 // text-transform for unicode requires mb_convert_case (Multibyte String Functions)
17150 if (function_exists('mb_convert_case')) {
17151 $ttm = array('capitalize' => MB_CASE_TITLE
, 'uppercase' => MB_CASE_UPPER
, 'lowercase' => MB_CASE_LOWER
);
17152 if (isset($ttm[$dom[$dom[$key]['parent']]['text-transform']])) {
17153 $element = mb_convert_case($element, $ttm[$dom[$dom[$key]['parent']]['text-transform']], $this->encoding
);
17155 } elseif (!$this->isunicode
) {
17156 switch ($dom[$dom[$key]['parent']]['text-transform']) {
17157 case 'capitalize': {
17158 $element = ucwords(strtolower($element));
17161 case 'uppercase': {
17162 $element = strtoupper($element);
17165 case 'lowercase': {
17166 $element = strtolower($element);
17171 $element = preg_replace("/&NBSP;/i", " ", $element);
17173 $dom[$key]['value'] = stripslashes($this->unhtmlentities($element));
17182 * Returns the string used to find spaces
17185 * @author Nicola Asuni
17186 * @since 4.8.024 (2010-01-15)
17188 protected function getSpaceString() {
17189 $spacestr = chr(32);
17190 if ($this->isUnicodeFont()) {
17191 $spacestr = chr(0).chr(32);
17197 * Return an hash code used to ensure that the serialized data has been generated by this TCPDF instance.
17198 * @param string $data serialized data
17202 protected function getHashForTCPDFtagParams($data) {
17203 return md5(strlen($data).$this->file_id
.$data);
17207 * Serialize an array of parameters to be used with TCPDF tag in HTML code.
17208 * @param array $data parameters array
17209 * @return string containing serialized data
17212 public function serializeTCPDFtagParameters($data) {
17213 $encoded = urlencode(json_encode($data));
17214 return $this->getHashForTCPDFtagParams($encoded).$encoded;
17218 * Unserialize parameters to be used with TCPDF tag in HTML code.
17219 * @param string $data serialized data
17220 * @return array containing unserialized data
17221 * @protected static
17223 protected function unserializeTCPDFtagParameters($data) {
17224 $hash = substr($data, 0, 32);
17225 $encoded = substr($data, 32);
17226 if ($hash != $this->getHashForTCPDFtagParams($encoded)) {
17227 $this->Error('Invalid parameters');
17229 return json_decode(urldecode($encoded), true);
17233 * Prints a cell (rectangular area) with optional borders, background color and html text string.
17234 * 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 />
17235 * If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting.
17236 * IMPORTANT: The HTML must be well formatted - try to clean-up it using an application like HTML-Tidy before submitting.
17237 * 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
17238 * NOTE: all the HTML attributes must be enclosed in double-quote.
17239 * @param float $w Cell width. If 0, the cell extends up to the right margin.
17240 * @param float $h Cell minimum height. The cell extends automatically if needed.
17241 * @param float|null $x upper-left corner X coordinate
17242 * @param float|null $y upper-left corner Y coordinate
17243 * @param string $html html text to print. Default value: empty string.
17244 * @param mixed $border 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)))
17245 * @param int $ln Indicates where the current position should go after the call. Possible values are:<ul><li>0: to the right (or left for RTL language)</li><li>1: to the beginning of the next line</li><li>2: below</li></ul>
17246 Putting 1 is equivalent to putting 0 and calling Ln() just after. Default value: 0.
17247 * @param boolean $fill Indicates if the cell background must be painted (true) or transparent (false).
17248 * @param boolean $reseth if true reset the last cell height (default true).
17249 * @param string $align Allows to center or align the text. Possible values are:<ul><li>L : left align</li><li>C : center</li><li>R : right align</li><li>'' : empty string : left for LTR or right for RTL</li></ul>
17250 * @param boolean $autopadding if true, uses internal padding and automatically adjust it to account for line width.
17251 * @see Multicell(), writeHTML()
17254 public function writeHTMLCell($w, $h, $x, $y, $html='', $border=0, $ln=0, $fill=false, $reseth=true, $align='', $autopadding=true) {
17255 return $this->MultiCell($w, $h, $html, $border, $align, $fill, $ln, $x, $y, $reseth, 0, true, $autopadding, 0, 'T', false);
17259 * Allows to preserve some HTML formatting (limited support).<br />
17260 * IMPORTANT: The HTML must be well formatted - try to clean-up it using an application like HTML-Tidy before submitting.
17261 * 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
17262 * NOTE: all the HTML attributes must be enclosed in double-quote.
17263 * @param string $html text to display
17264 * @param boolean $ln if true add a new line after text (default = true)
17265 * @param boolean $fill Indicates if the background must be painted (true) or transparent (false).
17266 * @param boolean $reseth if true reset the last cell height (default false).
17267 * @param boolean $cell if true add the current left (or right for RTL) padding to each Write (default false).
17268 * @param string $align Allows to center or align the text. Possible values are:<ul><li>L : left align</li><li>C : center</li><li>R : right align</li><li>'' : empty string : left for LTR or right for RTL</li></ul>
17271 public function writeHTML($html, $ln=true, $fill=false, $reseth=false, $cell=false, $align='') {
17272 $gvars = $this->getGraphicVars();
17273 // store current values
17274 $prev_cell_margin = $this->cell_margin
;
17275 $prev_cell_padding = $this->cell_padding
;
17276 $prevPage = $this->page
;
17277 $prevlMargin = $this->lMargin
;
17278 $prevrMargin = $this->rMargin
;
17279 $curfontname = $this->FontFamily
;
17280 $curfontstyle = $this->FontStyle
;
17281 $curfontsize = $this->FontSizePt
;
17282 $curfontascent = $this->getFontAscent($curfontname, $curfontstyle, $curfontsize);
17283 $curfontdescent = $this->getFontDescent($curfontname, $curfontstyle, $curfontsize);
17284 $curfontstretcing = $this->font_stretching
;
17285 $curfonttracking = $this->font_spacing
;
17286 $this->newline
= true;
17288 $startlinepage = $this->page
;
17289 $minstartliney = $this->y
;
17290 $maxbottomliney = 0;
17291 $startlinex = $this->x
;
17292 $startliney = $this->y
;
17296 $this_method_vars = array();
17298 $fontaligned = false;
17299 $reverse_dir = false; // true when the text direction is reversed
17300 $this->premode
= false;
17301 if ($this->inxobj
) {
17302 // we are inside an XObject template
17303 $pask = count($this->xobjects
[$this->xobjid
]['annotations']);
17304 } elseif (isset($this->PageAnnots
[$this->page
])) {
17305 $pask = count($this->PageAnnots
[$this->page
]);
17309 if ($this->inxobj
) {
17310 // we are inside an XObject template
17311 $startlinepos = strlen($this->xobjects
[$this->xobjid
]['outdata']);
17312 } elseif (!$this->InFooter
) {
17313 if (isset($this->footerlen
[$this->page
])) {
17314 $this->footerpos
[$this->page
] = $this->pagelen
[$this->page
] - $this->footerlen
[$this->page
];
17316 $this->footerpos
[$this->page
] = $this->pagelen
[$this->page
];
17318 $startlinepos = $this->footerpos
[$this->page
];
17320 // we are inside the footer
17321 $startlinepos = $this->pagelen
[$this->page
];
17326 $w = $this->x
- $this->lMargin
;
17328 $w = $this->w
- $this->rMargin
- $this->x
;
17330 $w -= ($this->cell_padding
['L'] +
$this->cell_padding
['R']);
17333 $this->x
-= $this->cell_padding
['R'];
17334 $this->lMargin +
= $this->cell_padding
['L'];
17336 $this->x +
= $this->cell_padding
['L'];
17337 $this->rMargin +
= $this->cell_padding
['R'];
17340 if ($this->customlistindent
>= 0) {
17341 $this->listindent
= $this->customlistindent
;
17343 $this->listindent
= $this->GetStringWidth('000000');
17345 $this->listindentlevel
= 0;
17346 // save previous states
17347 $prev_cell_height_ratio = $this->cell_height_ratio
;
17348 $prev_listnum = $this->listnum
;
17349 $prev_listordered = $this->listordered
;
17350 $prev_listcount = $this->listcount
;
17351 $prev_lispacer = $this->lispacer
;
17352 $this->listnum
= 0;
17353 $this->listordered
= array();
17354 $this->listcount
= array();
17355 $this->lispacer
= '';
17356 if ((TCPDF_STATIC
::empty_string($this->lasth
)) OR ($reseth)) {
17357 // reset row height
17358 $this->resetLastH();
17360 $dom = $this->getHtmlDomArray($html);
17361 $maxel = count($dom);
17363 while ($key < $maxel) {
17364 if ($dom[$key]['tag'] AND $dom[$key]['opening'] AND $dom[$key]['hide']) {
17365 // store the node key
17366 $hidden_node_key = $key;
17367 if ($dom[$key]['self']) {
17368 // skip just this self-closing tag
17371 // skip this and all children tags
17372 while (($key < $maxel) AND (!$dom[$key]['tag'] OR $dom[$key]['opening'] OR ($dom[$key]['parent'] != $hidden_node_key))) {
17373 // skip hidden objects
17379 if ($key == $maxel) break;
17380 if ($dom[$key]['tag'] AND isset($dom[$key]['attribute']['pagebreak'])) {
17381 // check for pagebreak
17382 if (($dom[$key]['attribute']['pagebreak'] == 'true') OR ($dom[$key]['attribute']['pagebreak'] == 'left') OR ($dom[$key]['attribute']['pagebreak'] == 'right')) {
17383 // add a page (or trig AcceptPageBreak() for multicolumn mode)
17384 $this->checkPageBreak($this->PageBreakTrigger +
1);
17385 $this->htmlvspace
= ($this->PageBreakTrigger +
1);
17387 if ((($dom[$key]['attribute']['pagebreak'] == 'left') AND (((!$this->rtl
) AND (($this->page %
2) == 0)) OR (($this->rtl
) AND (($this->page %
2) != 0))))
17388 OR (($dom[$key]['attribute']['pagebreak'] == 'right') AND (((!$this->rtl
) AND (($this->page %
2) != 0)) OR (($this->rtl
) AND (($this->page %
2) == 0))))) {
17389 // add a page (or trig AcceptPageBreak() for multicolumn mode)
17390 $this->checkPageBreak($this->PageBreakTrigger +
1);
17391 $this->htmlvspace
= ($this->PageBreakTrigger +
1);
17394 if ($dom[$key]['tag'] AND $dom[$key]['opening'] AND isset($dom[$key]['attribute']['nobr']) AND ($dom[$key]['attribute']['nobr'] == 'true')) {
17395 if (isset($dom[($dom[$key]['parent'])]['attribute']['nobr']) AND ($dom[($dom[$key]['parent'])]['attribute']['nobr'] == 'true')) {
17396 $dom[$key]['attribute']['nobr'] = false;
17398 // store current object
17399 $this->startTransaction();
17400 // save this method vars
17401 $this_method_vars['html'] = $html;
17402 $this_method_vars['ln'] = $ln;
17403 $this_method_vars['fill'] = $fill;
17404 $this_method_vars['reseth'] = $reseth;
17405 $this_method_vars['cell'] = $cell;
17406 $this_method_vars['align'] = $align;
17407 $this_method_vars['gvars'] = $gvars;
17408 $this_method_vars['prevPage'] = $prevPage;
17409 $this_method_vars['prev_cell_margin'] = $prev_cell_margin;
17410 $this_method_vars['prev_cell_padding'] = $prev_cell_padding;
17411 $this_method_vars['prevlMargin'] = $prevlMargin;
17412 $this_method_vars['prevrMargin'] = $prevrMargin;
17413 $this_method_vars['curfontname'] = $curfontname;
17414 $this_method_vars['curfontstyle'] = $curfontstyle;
17415 $this_method_vars['curfontsize'] = $curfontsize;
17416 $this_method_vars['curfontascent'] = $curfontascent;
17417 $this_method_vars['curfontdescent'] = $curfontdescent;
17418 $this_method_vars['curfontstretcing'] = $curfontstretcing;
17419 $this_method_vars['curfonttracking'] = $curfonttracking;
17420 $this_method_vars['minstartliney'] = $minstartliney;
17421 $this_method_vars['maxbottomliney'] = $maxbottomliney;
17422 $this_method_vars['yshift'] = $yshift;
17423 $this_method_vars['startlinepage'] = $startlinepage;
17424 $this_method_vars['startlinepos'] = $startlinepos;
17425 $this_method_vars['startlinex'] = $startlinex;
17426 $this_method_vars['startliney'] = $startliney;
17427 $this_method_vars['newline'] = $newline;
17428 $this_method_vars['loop'] = $loop;
17429 $this_method_vars['curpos'] = $curpos;
17430 $this_method_vars['pask'] = $pask;
17431 $this_method_vars['lalign'] = $lalign;
17432 $this_method_vars['plalign'] = $plalign;
17433 $this_method_vars['w'] = $w;
17434 $this_method_vars['prev_cell_height_ratio'] = $prev_cell_height_ratio;
17435 $this_method_vars['prev_listnum'] = $prev_listnum;
17436 $this_method_vars['prev_listordered'] = $prev_listordered;
17437 $this_method_vars['prev_listcount'] = $prev_listcount;
17438 $this_method_vars['prev_lispacer'] = $prev_lispacer;
17439 $this_method_vars['fontaligned'] = $fontaligned;
17440 $this_method_vars['key'] = $key;
17441 $this_method_vars['dom'] = $dom;
17444 // print THEAD block
17445 if (($dom[$key]['value'] == 'tr') AND isset($dom[$key]['thead']) AND $dom[$key]['thead']) {
17446 if (isset($dom[$key]['parent']) AND isset($dom[$dom[$key]['parent']]['thead']) AND !TCPDF_STATIC
::empty_string($dom[$dom[$key]['parent']]['thead'])) {
17447 $this->inthead
= true;
17448 // print table header (thead)
17449 $this->writeHTML($this->thead
, false, false, false, false, '');
17450 // check if we are on a new page or on a new column
17451 if (($this->y
< $this->start_transaction_y
) OR ($this->checkPageBreak($this->lasth
, '', false))) {
17452 // we are on a new page or on a new column and the total object height is less than the available vertical space.
17453 // restore previous object
17454 $this->rollbackTransaction(true);
17455 // restore previous values
17456 foreach ($this_method_vars as $vkey => $vval) {
17459 // disable table header
17460 $tmp_thead = $this->thead
;
17462 // add a page (or trig AcceptPageBreak() for multicolumn mode)
17464 if ((!$this->checkPageBreak($this->PageBreakTrigger +
1)) AND ($this->y
< $pre_y)) {
17465 // fix for multicolumn mode
17466 $startliney = $this->y
;
17468 $this->start_transaction_page
= $this->page
;
17469 $this->start_transaction_y
= $this->y
;
17470 // restore table header
17471 $this->thead
= $tmp_thead;
17472 // fix table border properties
17473 if (isset($dom[$dom[$key]['parent']]['attribute']['cellspacing'])) {
17474 $tmp_cellspacing = $this->getHTMLUnitToUnits($dom[$dom[$key]['parent']]['attribute']['cellspacing'], 1, 'px');
17475 } elseif (isset($dom[$dom[$key]['parent']]['border-spacing'])) {
17476 $tmp_cellspacing = $dom[$dom[$key]['parent']]['border-spacing']['V'];
17478 $tmp_cellspacing = 0;
17480 $dom[$dom[$key]['parent']]['borderposition']['page'] = $this->page
;
17481 $dom[$dom[$key]['parent']]['borderposition']['column'] = $this->current_column
;
17482 $dom[$dom[$key]['parent']]['borderposition']['y'] = $this->y +
$tmp_cellspacing;
17483 $xoffset = ($this->x
- $dom[$dom[$key]['parent']]['borderposition']['x']);
17484 $dom[$dom[$key]['parent']]['borderposition']['x'] +
= $xoffset;
17485 $dom[$dom[$key]['parent']]['borderposition']['xmax'] +
= $xoffset;
17486 // print table header (thead)
17487 $this->writeHTML($this->thead
, false, false, false, false, '');
17490 // move $key index forward to skip THEAD block
17491 while ( ($key < $maxel) AND (!(
17492 ($dom[$key]['tag'] AND $dom[$key]['opening'] AND ($dom[$key]['value'] == 'tr') AND (!isset($dom[$key]['thead']) OR !$dom[$key]['thead']))
17493 OR ($dom[$key]['tag'] AND (!$dom[$key]['opening']) AND ($dom[$key]['value'] == 'table'))) )) {
17497 if ($dom[$key]['tag'] OR ($key == 0)) {
17498 if ((($dom[$key]['value'] == 'table') OR ($dom[$key]['value'] == 'tr')) AND (isset($dom[$key]['align']))) {
17499 $dom[$key]['align'] = ($this->rtl
) ?
'R' : 'L';
17501 // vertically align image in line
17502 if ((!$this->newline
) AND ($dom[$key]['value'] == 'img') AND (isset($dom[$key]['height'])) AND ($dom[$key]['height'] > 0)) {
17503 // get image height
17504 $imgh = $this->getHTMLUnitToUnits($dom[$key]['height'], ($dom[$key]['fontsize'] / $this->k
), 'px');
17505 $autolinebreak = false;
17506 if (!empty($dom[$key]['width'])) {
17507 $imgw = $this->getHTMLUnitToUnits($dom[$key]['width'], ($dom[$key]['fontsize'] / $this->k
), 'px', false);
17508 if (($imgw <= ($this->w
- $this->lMargin
- $this->rMargin
- $this->cell_padding
['L'] - $this->cell_padding
['R']))
17509 AND ((($this->rtl
) AND (($this->x
- $imgw) < ($this->lMargin +
$this->cell_padding
['L'])))
17510 OR ((!$this->rtl
) AND (($this->x +
$imgw) > ($this->w
- $this->rMargin
- $this->cell_padding
['R']))))) {
17511 // add automatic line break
17512 $autolinebreak = true;
17513 $this->Ln('', $cell);
17514 if ((!$dom[($key-1)]['tag']) AND ($dom[($key-1)]['value'] == ' ')) {
17515 // go back to evaluate this line break
17520 if (!$autolinebreak) {
17521 if ($this->inPageBody()) {
17523 // check for page break
17524 if ((!$this->checkPageBreak($imgh)) AND ($this->y
< $pre_y)) {
17525 // fix for multicolumn mode
17526 $startliney = $this->y
;
17529 if ($this->page
> $startlinepage) {
17530 // fix line splitted over two pages
17531 if (isset($this->footerlen
[$startlinepage])) {
17532 $curpos = $this->pagelen
[$startlinepage] - $this->footerlen
[$startlinepage];
17534 // line to be moved one page forward
17535 $pagebuff = $this->getPageBuffer($startlinepage);
17536 $linebeg = substr($pagebuff, $startlinepos, ($curpos - $startlinepos));
17537 $tstart = substr($pagebuff, 0, $startlinepos);
17538 $tend = substr($this->getPageBuffer($startlinepage), $curpos);
17539 // remove line from previous page
17540 $this->setPageBuffer($startlinepage, $tstart.''.$tend);
17541 $pagebuff = $this->getPageBuffer($this->page
);
17542 $tstart = substr($pagebuff, 0, $this->cntmrk
[$this->page
]);
17543 $tend = substr($pagebuff, $this->cntmrk
[$this->page
]);
17544 // add line start to current page
17545 $yshift = ($minstartliney - $this->y
);
17546 if ($fontaligned) {
17547 $yshift +
= ($curfontsize / $this->k
);
17549 $try = sprintf('1 0 0 1 0 %F cm', ($yshift * $this->k
));
17550 $this->setPageBuffer($this->page
, $tstart."\nq\n".$try."\n".$linebeg."\nQ\n".$tend);
17551 // shift the annotations and links
17552 if (isset($this->PageAnnots
[$this->page
])) {
17553 $next_pask = count($this->PageAnnots
[$this->page
]);
17557 if (isset($this->PageAnnots
[$startlinepage])) {
17558 foreach ($this->PageAnnots
[$startlinepage] as $pak => $pac) {
17559 if ($pak >= $pask) {
17560 $this->PageAnnots
[$this->page
][] = $pac;
17561 unset($this->PageAnnots
[$startlinepage][$pak]);
17562 $npak = count($this->PageAnnots
[$this->page
]) - 1;
17563 $this->PageAnnots
[$this->page
][$npak]['y'] -= $yshift;
17567 $pask = $next_pask;
17568 $startlinepos = $this->cntmrk
[$this->page
];
17569 $startlinepage = $this->page
;
17570 $startliney = $this->y
;
17571 $this->newline
= false;
17573 $this->y +
= ($this->getCellHeight($curfontsize / $this->k
) - ($curfontdescent * $this->cell_height_ratio
) - $imgh);
17574 $minstartliney = min($this->y
, $minstartliney);
17575 $maxbottomliney = ($startliney +
$this->getCellHeight($curfontsize / $this->k
));
17577 } elseif (isset($dom[$key]['fontname']) OR isset($dom[$key]['fontstyle']) OR isset($dom[$key]['fontsize']) OR isset($dom[$key]['line-height'])) {
17578 // account for different font size
17579 $pfontname = $curfontname;
17580 $pfontstyle = $curfontstyle;
17581 $pfontsize = $curfontsize;
17582 $fontname = (isset($dom[$key]['fontname']) ?
$dom[$key]['fontname'] : $curfontname);
17583 $fontstyle = (isset($dom[$key]['fontstyle']) ?
$dom[$key]['fontstyle'] : $curfontstyle);
17584 $fontsize = (isset($dom[$key]['fontsize']) ?
$dom[$key]['fontsize'] : $curfontsize);
17585 $fontascent = $this->getFontAscent($fontname, $fontstyle, $fontsize);
17586 $fontdescent = $this->getFontDescent($fontname, $fontstyle, $fontsize);
17587 if (($fontname != $curfontname) OR ($fontstyle != $curfontstyle) OR ($fontsize != $curfontsize)
17588 OR ($this->cell_height_ratio
!= $dom[$key]['line-height'])
17589 OR ($dom[$key]['tag'] AND $dom[$key]['opening'] AND ($dom[$key]['value'] == 'li')) ) {
17590 if (($key < ($maxel - 1)) AND (
17591 ($dom[$key]['tag'] AND $dom[$key]['opening'] AND ($dom[$key]['value'] == 'li'))
17592 OR ($this->cell_height_ratio
!= $dom[$key]['line-height'])
17593 OR (!$this->newline
AND is_numeric($fontsize) AND is_numeric($curfontsize)
17594 AND ($fontsize >= 0) AND ($curfontsize >= 0)
17595 AND (($fontsize != $curfontsize) OR ($fontstyle != $curfontstyle) OR ($fontname != $curfontname)))
17597 if ($this->page
> $startlinepage) {
17598 // fix lines splitted over two pages
17599 if (isset($this->footerlen
[$startlinepage])) {
17600 $curpos = $this->pagelen
[$startlinepage] - $this->footerlen
[$startlinepage];
17602 // line to be moved one page forward
17603 $pagebuff = $this->getPageBuffer($startlinepage);
17604 $linebeg = substr($pagebuff, $startlinepos, ($curpos - $startlinepos));
17605 $tstart = substr($pagebuff, 0, $startlinepos);
17606 $tend = substr($this->getPageBuffer($startlinepage), $curpos);
17607 // remove line start from previous page
17608 $this->setPageBuffer($startlinepage, $tstart.''.$tend);
17609 $pagebuff = $this->getPageBuffer($this->page
);
17610 $tstart = substr($pagebuff, 0, $this->cntmrk
[$this->page
]);
17611 $tend = substr($pagebuff, $this->cntmrk
[$this->page
]);
17612 // add line start to current page
17613 $yshift = ($minstartliney - $this->y
);
17614 $try = sprintf('1 0 0 1 0 %F cm', ($yshift * $this->k
));
17615 $this->setPageBuffer($this->page
, $tstart."\nq\n".$try."\n".$linebeg."\nQ\n".$tend);
17616 // shift the annotations and links
17617 if (isset($this->PageAnnots
[$this->page
])) {
17618 $next_pask = count($this->PageAnnots
[$this->page
]);
17622 if (isset($this->PageAnnots
[$startlinepage])) {
17623 foreach ($this->PageAnnots
[$startlinepage] as $pak => $pac) {
17624 if ($pak >= $pask) {
17625 $this->PageAnnots
[$this->page
][] = $pac;
17626 unset($this->PageAnnots
[$startlinepage][$pak]);
17627 $npak = count($this->PageAnnots
[$this->page
]) - 1;
17628 $this->PageAnnots
[$this->page
][$npak]['y'] -= $yshift;
17632 $pask = $next_pask;
17633 $startlinepos = $this->cntmrk
[$this->page
];
17634 $startlinepage = $this->page
;
17635 $startliney = $this->y
;
17637 if (!isset($dom[$key]['line-height'])) {
17638 $dom[$key]['line-height'] = $this->cell_height_ratio
;
17640 if (!$dom[$key]['block']) {
17641 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']))) {
17642 $this->y +
= (((($curfontsize * $this->cell_height_ratio
) - ($fontsize * $dom[$key]['line-height'])) / $this->k
) +
$curfontascent - $fontascent - $curfontdescent +
$fontdescent) / 2;
17644 if (($dom[$key]['value'] != 'sup') AND ($dom[$key]['value'] != 'sub')) {
17645 $current_line_align_data = array($key, $minstartliney, $maxbottomliney);
17646 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)))) {
17647 $minstartliney = min($this->y
, $line_align_data[1]);
17648 $maxbottomliney = max(($this->y +
$this->getCellHeight($fontsize / $this->k
)), $line_align_data[2]);
17650 $minstartliney = min($this->y
, $minstartliney);
17651 $maxbottomliney = max(($this->y +
$this->getCellHeight($fontsize / $this->k
)), $maxbottomliney);
17653 $line_align_data = $current_line_align_data;
17656 $this->cell_height_ratio
= $dom[$key]['line-height'];
17657 $fontaligned = true;
17659 $this->setFont($fontname, $fontstyle, $fontsize);
17660 // reset row height
17661 $this->resetLastH();
17662 $curfontname = $fontname;
17663 $curfontstyle = $fontstyle;
17664 $curfontsize = $fontsize;
17665 $curfontascent = $fontascent;
17666 $curfontdescent = $fontdescent;
17669 // set text rendering mode
17670 $textstroke = isset($dom[$key]['stroke']) ?
$dom[$key]['stroke'] : $this->textstrokewidth
;
17671 $textfill = isset($dom[$key]['fill']) ?
$dom[$key]['fill'] : (($this->textrendermode %
2) == 0);
17672 $textclip = isset($dom[$key]['clip']) ?
$dom[$key]['clip'] : ($this->textrendermode
> 3);
17673 $this->setTextRenderingMode($textstroke, $textfill, $textclip);
17674 if (isset($dom[$key]['font-stretch']) AND ($dom[$key]['font-stretch'] !== false)) {
17675 $this->setFontStretching($dom[$key]['font-stretch']);
17677 if (isset($dom[$key]['letter-spacing']) AND ($dom[$key]['letter-spacing'] !== false)) {
17678 $this->setFontSpacing($dom[$key]['letter-spacing']);
17680 if (($plalign == 'J') AND $dom[$key]['block']) {
17683 // get current position on page buffer
17684 $curpos = $this->pagelen
[$startlinepage];
17685 if (isset($dom[$key]['bgcolor']) AND ($dom[$key]['bgcolor'] !== false)) {
17686 $this->setFillColorArray($dom[$key]['bgcolor']);
17689 $wfill = $fill |
false;
17691 if (isset($dom[$key]['fgcolor']) AND ($dom[$key]['fgcolor'] !== false)) {
17692 $this->setTextColorArray($dom[$key]['fgcolor']);
17694 if (isset($dom[$key]['strokecolor']) AND ($dom[$key]['strokecolor'] !== false)) {
17695 $this->setDrawColorArray($dom[$key]['strokecolor']);
17697 if (isset($dom[$key]['align'])) {
17698 $lalign = $dom[$key]['align'];
17700 if (TCPDF_STATIC
::empty_string($lalign)) {
17705 if ($this->newline
AND (strlen($dom[$key]['value']) > 0) AND ($dom[$key]['value'] != 'td') AND ($dom[$key]['value'] != 'th')) {
17707 $fontaligned = false;
17708 // we are at the beginning of a new line
17709 if (isset($startlinex)) {
17710 $yshift = ($minstartliney - $startliney);
17711 if (($yshift > 0) OR ($this->page
> $startlinepage)) {
17715 // the last line must be shifted to be aligned as requested
17716 $linew = abs($this->endlinex
- $startlinex);
17717 if ($this->inxobj
) {
17718 // we are inside an XObject template
17719 $pstart = substr($this->xobjects
[$this->xobjid
]['outdata'], 0, $startlinepos);
17720 if (isset($opentagpos)) {
17721 $midpos = $opentagpos;
17726 $pmid = substr($this->xobjects
[$this->xobjid
]['outdata'], $startlinepos, ($midpos - $startlinepos));
17727 $pend = substr($this->xobjects
[$this->xobjid
]['outdata'], $midpos);
17729 $pmid = substr($this->xobjects
[$this->xobjid
]['outdata'], $startlinepos);
17733 $pstart = substr($this->getPageBuffer($startlinepage), 0, $startlinepos);
17734 if (isset($opentagpos) AND isset($this->footerlen
[$startlinepage]) AND (!$this->InFooter
)) {
17735 $this->footerpos
[$startlinepage] = $this->pagelen
[$startlinepage] - $this->footerlen
[$startlinepage];
17736 $midpos = min($opentagpos, $this->footerpos
[$startlinepage]);
17737 } elseif (isset($opentagpos)) {
17738 $midpos = $opentagpos;
17739 } elseif (isset($this->footerlen
[$startlinepage]) AND (!$this->InFooter
)) {
17740 $this->footerpos
[$startlinepage] = $this->pagelen
[$startlinepage] - $this->footerlen
[$startlinepage];
17741 $midpos = $this->footerpos
[$startlinepage];
17746 $pmid = substr($this->getPageBuffer($startlinepage), $startlinepos, ($midpos - $startlinepos));
17747 $pend = substr($this->getPageBuffer($startlinepage), $midpos);
17749 $pmid = substr($this->getPageBuffer($startlinepage), $startlinepos);
17753 if ((((($plalign == 'C') OR ($plalign == 'J') OR (($plalign == 'R') AND (!$this->rtl
)) OR (($plalign == 'L') AND ($this->rtl
)))))) {
17754 // calculate shifting amount
17756 if (($plalign == 'J') AND $this->isRTLTextDir() AND ($this->num_columns
> 1)) {
17757 $tw +
= $this->cell_padding
['R'];
17759 if ($this->lMargin
!= $prevlMargin) {
17760 $tw +
= ($prevlMargin - $this->lMargin
);
17762 if ($this->rMargin
!= $prevrMargin) {
17763 $tw +
= ($prevrMargin - $this->rMargin
);
17765 $one_space_width = $this->GetStringWidth(chr(32));
17766 $no = 0; // number of spaces on a line contained on a single block
17767 if ($this->isRTLTextDir()) { // RTL
17768 // remove left space if exist
17769 $pos1 = TCPDF_STATIC
::revstrpos($pmid, '[(');
17771 $pos1 = intval($pos1);
17772 if ($this->isUnicodeFont()) {
17773 $pos2 = intval(TCPDF_STATIC
::revstrpos($pmid, '[('.chr(0).chr(32)));
17776 $pos2 = intval(TCPDF_STATIC
::revstrpos($pmid, '[('.chr(32)));
17779 if ($pos1 == $pos2) {
17780 $pmid = substr($pmid, 0, ($pos1 +
2)).substr($pmid, ($pos1 +
2 +
$spacelen));
17781 if (substr($pmid, $pos1, 4) == '[()]') {
17782 $linew -= $one_space_width;
17783 } elseif ($pos1 == strpos($pmid, '[(')) {
17789 // remove right space if exist
17790 $pos1 = TCPDF_STATIC
::revstrpos($pmid, ')]');
17792 $pos1 = intval($pos1);
17793 if ($this->isUnicodeFont()) {
17794 $pos2 = intval(TCPDF_STATIC
::revstrpos($pmid, chr(0).chr(32).')]')) +
2;
17797 $pos2 = intval(TCPDF_STATIC
::revstrpos($pmid, chr(32).')]')) +
1;
17800 if ($pos1 == $pos2) {
17801 $pmid = substr($pmid, 0, ($pos1 - $spacelen)).substr($pmid, $pos1);
17802 $linew -= $one_space_width;
17806 $mdiff = ($tw - $linew);
17807 if ($plalign == 'C') {
17809 $t_x = -($mdiff / 2);
17811 $t_x = ($mdiff / 2);
17813 } elseif ($plalign == 'R') {
17814 // right alignment on LTR document
17816 } elseif ($plalign == 'L') {
17817 // left alignment on RTL document
17819 } elseif (($plalign == 'J') AND ($plalign == $lalign)) {
17821 if ($this->isRTLTextDir()) {
17822 // align text on the left
17825 $ns = 0; // number of spaces
17827 // escape special characters
17828 $pmidtemp = preg_replace('/[\\\][\(]/x', '\\#!#OP#!#', $pmidtemp);
17829 $pmidtemp = preg_replace('/[\\\][\)]/x', '\\#!#CP#!#', $pmidtemp);
17831 if (preg_match_all('/\[\(([^\)]*)\)\]/x', $pmidtemp, $lnstring, PREG_PATTERN_ORDER
)) {
17832 $spacestr = $this->getSpaceString();
17833 $maxkk = count($lnstring[1]) - 1;
17834 for ($kk=0; $kk <= $maxkk; ++
$kk) {
17835 // restore special characters
17836 $lnstring[1][$kk] = str_replace('#!#OP#!#', '(', $lnstring[1][$kk]);
17837 $lnstring[1][$kk] = str_replace('#!#CP#!#', ')', $lnstring[1][$kk]);
17838 // store number of spaces on the strings
17839 $lnstring[2][$kk] = substr_count($lnstring[1][$kk], $spacestr);
17840 // count total spaces on line
17841 $ns +
= $lnstring[2][$kk];
17842 $lnstring[3][$kk] = $ns;
17847 // calculate additional space to add to each existing space
17848 $spacewidth = ($mdiff / ($ns - $no)) * $this->k
;
17849 if ($this->FontSize
<= 0) {
17850 $this->FontSize
= 1;
17852 $spacewidthu = -1000 * ($mdiff +
(($ns +
$no) * $one_space_width)) / $ns / $this->FontSize
;
17853 if ($this->font_spacing
!= 0) {
17854 // fixed spacing mode
17855 $osw = -1000 * $this->font_spacing
/ $this->FontSize
;
17856 $spacewidthu +
= $osw;
17863 $prev_epsposbeg = 0;
17865 if ($this->isRTLTextDir()) {
17866 $textpos = $this->wPt
;
17868 while (preg_match('/([0-9\.\+\-]*)[\s](Td|cm|m|l|c|re)[\s]/x', $pmid, $strpiece, PREG_OFFSET_CAPTURE
, $offset) == 1) {
17869 // check if we are inside a string section '[( ... )]'
17870 $stroffset = strpos($pmid, '[(', $offset);
17871 if (($stroffset !== false) AND ($stroffset <= $strpiece[2][1])) {
17872 // set offset to the end of string section
17873 $offset = strpos($pmid, ')]', $stroffset);
17874 while (($offset !== false) AND ($pmid[($offset - 1)] == '\\')) {
17875 $offset = strpos($pmid, ')]', ($offset +
1));
17877 if ($offset === false) {
17878 $this->Error('HTML Justification: malformed PDF code.');
17882 if ($this->isRTLTextDir()) {
17883 $spacew = ($spacewidth * ($nsmax - $ns));
17885 $spacew = ($spacewidth * $ns);
17887 $offset = $strpiece[2][1] +
strlen($strpiece[2][0]);
17888 $epsposend = strpos($pmid, $this->epsmarker
.'Q', $offset);
17889 if ($epsposend !== null) {
17890 $epsposend +
= strlen($this->epsmarker
.'Q');
17891 $epsposbeg = strpos($pmid, 'q'.$this->epsmarker
, $offset);
17892 if ($epsposbeg === null) {
17893 $epsposbeg = strpos($pmid, 'q'.$this->epsmarker
, ($prev_epsposbeg - 6));
17894 $prev_epsposbeg = $epsposbeg;
17896 if (($epsposbeg > 0) AND ($epsposend > 0) AND ($offset > $epsposbeg) AND ($offset < $epsposend)) {
17897 // shift EPS images
17898 $trx = sprintf('1 0 0 1 %F 0 cm', $spacew);
17899 $pmid_b = substr($pmid, 0, $epsposbeg);
17900 $pmid_m = substr($pmid, $epsposbeg, ($epsposend - $epsposbeg));
17901 $pmid_e = substr($pmid, $epsposend);
17902 $pmid = $pmid_b."\nq\n".$trx."\n".$pmid_m."\nQ\n".$pmid_e;
17903 $offset = $epsposend;
17908 // shift blocks of code
17909 switch ($strpiece[2][0]) {
17914 // get current X position
17915 preg_match('/([0-9\.\+\-]*)[\s]('.$strpiece[1][0].')[\s]('.$strpiece[2][0].')([\s]*)/x', $pmid, $xmatches);
17916 if (!isset($xmatches[1])) {
17919 $currentxpos = $xmatches[1];
17920 $textpos = $currentxpos;
17921 if (($strcount <= $maxkk) AND ($strpiece[2][0] == 'Td')) {
17922 $ns = $lnstring[3][$strcount];
17923 if ($this->isRTLTextDir()) {
17924 $spacew = ($spacewidth * ($nsmax - $ns));
17929 if (preg_match('/([0-9\.\+\-]*)[\s]('.$strpiece[1][0].')[\s]('.$strpiece[2][0].')([\s]*)/x', $pmid, $pmatch) == 1) {
17930 $newpmid = sprintf('%F',(floatval($pmatch[1]) +
$spacew)).' '.$pmatch[2].' x*#!#*x'.$pmatch[3].$pmatch[4];
17931 $pmid = str_replace($pmatch[0], $newpmid, $pmid);
17932 unset($pmatch, $newpmid);
17938 if (!TCPDF_STATIC
::empty_string($this->lispacer
)) {
17939 $this->lispacer
= '';
17942 preg_match('/([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]('.$strpiece[1][0].')[\s](re)([\s]*)/x', $pmid, $xmatches);
17943 if (!isset($xmatches[1])) {
17946 $currentxpos = $xmatches[1];
17949 if ($this->isRTLTextDir()) { // RTL
17950 if ($currentxpos < $textpos) {
17951 $x_diff = ($spacewidth * ($nsmax - $lnstring[3][$strcount]));
17952 $w_diff = ($spacewidth * $lnstring[2][$strcount]);
17954 if ($strcount > 0) {
17955 $x_diff = ($spacewidth * ($nsmax - $lnstring[3][($strcount - 1)]));
17956 $w_diff = ($spacewidth * $lnstring[2][($strcount - 1)]);
17960 if ($currentxpos > $textpos) {
17961 if ($strcount > 0) {
17962 $x_diff = ($spacewidth * $lnstring[3][($strcount - 1)]);
17964 $w_diff = ($spacewidth * $lnstring[2][$strcount]);
17966 if ($strcount > 1) {
17967 $x_diff = ($spacewidth * $lnstring[3][($strcount - 2)]);
17969 if ($strcount > 0) {
17970 $w_diff = ($spacewidth * $lnstring[2][($strcount - 1)]);
17974 if (preg_match('/('.$xmatches[1].')[\s]('.$xmatches[2].')[\s]('.$xmatches[3].')[\s]('.$strpiece[1][0].')[\s](re)([\s]*)/x', $pmid, $pmatch) == 1) {
17975 $newx = sprintf('%F',(floatval($pmatch[1]) +
$x_diff));
17976 $neww = sprintf('%F',(floatval($pmatch[3]) +
$w_diff));
17977 $newpmid = $newx.' '.$pmatch[2].' '.$neww.' '.$pmatch[4].' x*#!#*x'.$pmatch[5].$pmatch[6];
17978 $pmid = str_replace($pmatch[0], $newpmid, $pmid);
17979 unset($pmatch, $newpmid, $newx, $neww);
17984 // get current X position
17985 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);
17986 if (!isset($xmatches[1])) {
17989 $currentxpos = $xmatches[1];
17991 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) {
17992 $newx1 = sprintf('%F',(floatval($pmatch[1]) +
$spacew));
17993 $newx2 = sprintf('%F',(floatval($pmatch[3]) +
$spacew));
17994 $newx3 = sprintf('%F',(floatval($pmatch[5]) +
$spacew));
17995 $newpmid = $newx1.' '.$pmatch[2].' '.$newx2.' '.$pmatch[4].' '.$newx3.' '.$pmatch[6].' x*#!#*x'.$pmatch[7].$pmatch[8];
17996 $pmid = str_replace($pmatch[0], $newpmid, $pmid);
17997 unset($pmatch, $newpmid, $newx1, $newx2, $newx3);
18002 // shift the annotations and links
18003 $cxpos = ($currentxpos / $this->k
);
18004 $lmpos = ($this->lMargin +
$this->cell_padding
['L'] +
$this->feps
);
18005 if ($this->inxobj
) {
18006 // we are inside an XObject template
18007 foreach ($this->xobjects
[$this->xobjid
]['annotations'] as $pak => $pac) {
18008 if (($pac['y'] >= $minstartliney) AND (($pac['x'] * $this->k
) >= ($currentxpos - $this->feps
)) AND (($pac['x'] * $this->k
) <= ($currentxpos +
$this->feps
))) {
18009 if ($cxpos > $lmpos) {
18010 $this->xobjects
[$this->xobjid
]['annotations'][$pak]['x'] +
= ($spacew / $this->k
);
18011 $this->xobjects
[$this->xobjid
]['annotations'][$pak]['w'] +
= (($spacewidth * $pac['numspaces']) / $this->k
);
18013 $this->xobjects
[$this->xobjid
]['annotations'][$pak]['w'] +
= (($spacewidth * $pac['numspaces']) / $this->k
);
18018 } elseif (isset($this->PageAnnots
[$this->page
])) {
18019 foreach ($this->PageAnnots
[$this->page
] as $pak => $pac) {
18020 if (($pac['y'] >= $minstartliney) AND (($pac['x'] * $this->k
) >= ($currentxpos - $this->feps
)) AND (($pac['x'] * $this->k
) <= ($currentxpos +
$this->feps
))) {
18021 if ($cxpos > $lmpos) {
18022 $this->PageAnnots
[$this->page
][$pak]['x'] +
= ($spacew / $this->k
);
18023 $this->PageAnnots
[$this->page
][$pak]['w'] +
= (($spacewidth * $pac['numspaces']) / $this->k
);
18025 $this->PageAnnots
[$this->page
][$pak]['w'] +
= (($spacewidth * $pac['numspaces']) / $this->k
);
18033 $pmid = str_replace('x*#!#*x', '', $pmid);
18034 if ($this->isUnicodeFont()) {
18035 // multibyte characters
18036 $spacew = $spacewidthu;
18037 if ($this->font_stretching
!= 100) {
18038 // word spacing is affected by stretching
18039 $spacew /= ($this->font_stretching
/ 100);
18041 // escape special characters
18043 $pmid = preg_replace('/[\\\][\(]/x', '\\#!#OP#!#', $pmid);
18044 $pmid = preg_replace('/[\\\][\)]/x', '\\#!#CP#!#', $pmid);
18045 if (preg_match_all('/\[\(([^\)]*)\)\]/x', $pmid, $pamatch) > 0) {
18046 foreach($pamatch[0] as $pk => $pmatch) {
18047 $replace = $pamatch[1][$pk];
18048 $replace = str_replace('#!#OP#!#', '(', $replace);
18049 $replace = str_replace('#!#CP#!#', ')', $replace);
18050 $newpmid = '[('.str_replace(chr(0).chr(32), ') '.sprintf('%F', $spacew).' (', $replace).')]';
18051 $pos = strpos($pmid, $pmatch, $pos);
18052 if ($pos !== FALSE) {
18053 $pmid = substr_replace($pmid, $newpmid, $pos, strlen($pmatch));
18059 if ($this->inxobj
) {
18060 // we are inside an XObject template
18061 $this->xobjects
[$this->xobjid
]['outdata'] = $pstart."\n".$pmid."\n".$pend;
18063 $this->setPageBuffer($startlinepage, $pstart."\n".$pmid."\n".$pend);
18065 $endlinepos = strlen($pstart."\n".$pmid."\n");
18067 // non-unicode (single-byte characters)
18068 if ($this->font_stretching
!= 100) {
18069 // word spacing (Tw) is affected by stretching
18070 $spacewidth /= ($this->font_stretching
/ 100);
18072 $rs = sprintf('%F Tw', $spacewidth);
18073 $pmid = preg_replace("/\[\(/x", $rs.' [(', $pmid);
18074 if ($this->inxobj
) {
18075 // we are inside an XObject template
18076 $this->xobjects
[$this->xobjid
]['outdata'] = $pstart."\n".$pmid."\nBT 0 Tw ET\n".$pend;
18078 $this->setPageBuffer($startlinepage, $pstart."\n".$pmid."\nBT 0 Tw ET\n".$pend);
18080 $endlinepos = strlen($pstart."\n".$pmid."\nBT 0 Tw ET\n");
18084 } // end if $startlinex
18085 if (($t_x != 0) OR ($yshift < 0)) {
18087 $trx = sprintf('1 0 0 1 %F %F cm', ($t_x * $this->k
), ($yshift * $this->k
));
18088 $pstart .= "\nq\n".$trx."\n".$pmid."\nQ\n";
18089 $endlinepos = strlen($pstart);
18090 if ($this->inxobj
) {
18091 // we are inside an XObject template
18092 $this->xobjects
[$this->xobjid
]['outdata'] = $pstart.$pend;
18093 foreach ($this->xobjects
[$this->xobjid
]['annotations'] as $pak => $pac) {
18094 if ($pak >= $pask) {
18095 $this->xobjects
[$this->xobjid
]['annotations'][$pak]['x'] +
= $t_x;
18096 $this->xobjects
[$this->xobjid
]['annotations'][$pak]['y'] -= $yshift;
18100 $this->setPageBuffer($startlinepage, $pstart.$pend);
18101 // shift the annotations and links
18102 if (isset($this->PageAnnots
[$this->page
])) {
18103 foreach ($this->PageAnnots
[$this->page
] as $pak => $pac) {
18104 if ($pak >= $pask) {
18105 $this->PageAnnots
[$this->page
][$pak]['x'] +
= $t_x;
18106 $this->PageAnnots
[$this->page
][$pak]['y'] -= $yshift;
18111 $this->y
-= $yshift;
18114 $pbrk = $this->checkPageBreak($this->lasth
);
18115 $this->newline
= false;
18116 $startlinex = $this->x
;
18117 $startliney = $this->y
;
18118 if ($dom[$dom[$key]['parent']]['value'] == 'sup') {
18119 $startliney -= ((0.3 * $this->FontSizePt
) / $this->k
);
18120 } elseif ($dom[$dom[$key]['parent']]['value'] == 'sub') {
18121 $startliney -= (($this->FontSizePt
/ 0.7) / $this->k
);
18123 $minstartliney = $startliney;
18124 $maxbottomliney = ($this->y +
$this->getCellHeight($fontsize / $this->k
));
18126 $startlinepage = $this->page
;
18127 if (isset($endlinepos) AND (!$pbrk)) {
18128 $startlinepos = $endlinepos;
18130 if ($this->inxobj
) {
18131 // we are inside an XObject template
18132 $startlinepos = strlen($this->xobjects
[$this->xobjid
]['outdata']);
18133 } elseif (!$this->InFooter
) {
18134 if (isset($this->footerlen
[$this->page
])) {
18135 $this->footerpos
[$this->page
] = $this->pagelen
[$this->page
] - $this->footerlen
[$this->page
];
18137 $this->footerpos
[$this->page
] = $this->pagelen
[$this->page
];
18139 $startlinepos = $this->footerpos
[$this->page
];
18141 $startlinepos = $this->pagelen
[$this->page
];
18144 unset($endlinepos);
18145 $plalign = $lalign;
18146 if (isset($this->PageAnnots
[$this->page
])) {
18147 $pask = count($this->PageAnnots
[$this->page
]);
18151 if (!($dom[$key]['tag'] AND !$dom[$key]['opening'] AND ($dom[$key]['value'] == 'table')
18152 AND (isset($this->emptypagemrk
[$this->page
]))
18153 AND ($this->emptypagemrk
[$this->page
] == $this->pagelen
[$this->page
]))) {
18154 $this->setFont($fontname, $fontstyle, $fontsize);
18156 $this->setFillColorArray($this->bgcolor
);
18160 if (isset($opentagpos)) {
18161 unset($opentagpos);
18163 if ($dom[$key]['tag']) {
18164 if ($dom[$key]['opening']) {
18165 // get text indentation (if any)
18166 if (isset($dom[$key]['text-indent']) AND $dom[$key]['block']) {
18167 $this->textindent
= $dom[$key]['text-indent'];
18168 $this->newline
= true;
18171 if (($dom[$key]['value'] == 'table') AND isset($dom[$key]['cols']) AND ($dom[$key]['cols'] > 0)) {
18172 // available page width
18174 $wtmp = $this->x
- $this->lMargin
;
18176 $wtmp = $this->w
- $this->rMargin
- $this->x
;
18178 // get cell spacing
18179 if (isset($dom[$key]['attribute']['cellspacing'])) {
18180 $clsp = $this->getHTMLUnitToUnits($dom[$key]['attribute']['cellspacing'], 1, 'px');
18181 $cellspacing = array('H' => $clsp, 'V' => $clsp);
18182 } elseif (isset($dom[$key]['border-spacing'])) {
18183 $cellspacing = $dom[$key]['border-spacing'];
18185 $cellspacing = array('H' => 0, 'V' => 0);
18188 if (isset($dom[$key]['width'])) {
18189 $table_width = $this->getHTMLUnitToUnits($dom[$key]['width'], $wtmp, 'px');
18191 $table_width = $wtmp;
18193 $table_width -= (2 * $cellspacing['H']);
18194 if (!$this->inthead
) {
18195 $this->y +
= $cellspacing['V'];
18198 $cellspacingx = -$cellspacing['H'];
18200 $cellspacingx = $cellspacing['H'];
18202 // total table width without cellspaces
18203 $table_columns_width = ($table_width - ($cellspacing['H'] * ($dom[$key]['cols'] - 1)));
18204 // minimum column width
18205 $table_min_column_width = ($table_columns_width / $dom[$key]['cols']);
18206 // array of custom column widths
18207 $table_colwidths = array_fill(0, $dom[$key]['cols'], $table_min_column_width);
18210 if ($dom[$key]['value'] == 'tr') {
18211 // reset column counter
18215 if (($dom[$key]['value'] == 'td') OR ($dom[$key]['value'] == 'th')) {
18216 $trid = $dom[$key]['parent'];
18217 $table_el = $dom[$trid]['parent'];
18218 if (!isset($dom[$table_el]['cols'])) {
18219 $dom[$table_el]['cols'] = $dom[$trid]['cols'];
18221 // store border info
18223 if (isset($dom[$key]['border']) AND !empty($dom[$key]['border'])) {
18224 $tdborder = $dom[$key]['border'];
18226 $colspan = intval($dom[$key]['attribute']['colspan']);
18227 if ($colspan <= 0) {
18230 $old_cell_padding = $this->cell_padding
;
18231 if (isset($dom[($dom[$trid]['parent'])]['attribute']['cellpadding'])) {
18232 $crclpd = $this->getHTMLUnitToUnits($dom[($dom[$trid]['parent'])]['attribute']['cellpadding'], 1, 'px');
18233 $current_cell_padding = array('L' => $crclpd, 'T' => $crclpd, 'R' => $crclpd, 'B' => $crclpd);
18234 } elseif (isset($dom[($dom[$trid]['parent'])]['padding'])) {
18235 $current_cell_padding = $dom[($dom[$trid]['parent'])]['padding'];
18237 $current_cell_padding = array('L' => 0, 'T' => 0, 'R' => 0, 'B' => 0);
18239 $this->cell_padding
= $current_cell_padding;
18240 if (isset($dom[$key]['height'])) {
18241 // minimum cell height
18242 $cellh = $this->getHTMLUnitToUnits($dom[$key]['height'], 0, 'px');
18246 if (isset($dom[$key]['content'])) {
18247 $cell_content = $dom[$key]['content'];
18249 $cell_content = ' ';
18251 $tagtype = $dom[$key]['value'];
18253 while (($key < $maxel) AND (!(($dom[$key]['tag']) AND (!$dom[$key]['opening']) AND ($dom[$key]['value'] == $tagtype) AND ($dom[$key]['parent'] == $parentid)))) {
18254 // move $key index forward
18257 if (!isset($dom[$trid]['startpage'])) {
18258 $dom[$trid]['startpage'] = $this->page
;
18260 $this->setPage($dom[$trid]['startpage']);
18262 if (!isset($dom[$trid]['startcolumn'])) {
18263 $dom[$trid]['startcolumn'] = $this->current_column
;
18264 } elseif ($this->current_column
!= $dom[$trid]['startcolumn']) {
18266 $this->selectColumn($dom[$trid]['startcolumn']);
18269 if (!isset($dom[$trid]['starty'])) {
18270 $dom[$trid]['starty'] = $this->y
;
18272 $this->y
= $dom[$trid]['starty'];
18274 if (!isset($dom[$trid]['startx'])) {
18275 $dom[$trid]['startx'] = $this->x
;
18276 $this->x +
= $cellspacingx;
18278 $this->x +
= ($cellspacingx / 2);
18280 if (isset($dom[$parentid]['attribute']['rowspan'])) {
18281 $rowspan = intval($dom[$parentid]['attribute']['rowspan']);
18285 // skip row-spanned cells started on the previous rows
18286 if (isset($dom[$table_el]['rowspans'])) {
18288 $rskmax = count($dom[$table_el]['rowspans']);
18289 while ($rsk < $rskmax) {
18290 $trwsp = $dom[$table_el]['rowspans'][$rsk];
18291 $rsstartx = $trwsp['startx'];
18292 $rsendx = $trwsp['endx'];
18293 // account for margin changes
18294 if ($trwsp['startpage'] < $this->page
) {
18295 if (($this->rtl
) AND ($this->pagedim
[$this->page
]['orm'] != $this->pagedim
[$trwsp['startpage']]['orm'])) {
18296 $dl = ($this->pagedim
[$this->page
]['orm'] - $this->pagedim
[$trwsp['startpage']]['orm']);
18299 } elseif ((!$this->rtl
) AND ($this->pagedim
[$this->page
]['olm'] != $this->pagedim
[$trwsp['startpage']]['olm'])) {
18300 $dl = ($this->pagedim
[$this->page
]['olm'] - $this->pagedim
[$trwsp['startpage']]['olm']);
18305 if (($trwsp['rowspan'] > 0)
18306 AND ($rsstartx > ($this->x
- $cellspacing['H'] - $current_cell_padding['L'] - $this->feps
))
18307 AND ($rsstartx < ($this->x +
$cellspacing['H'] +
$current_cell_padding['R'] +
$this->feps
))
18308 AND (($trwsp['starty'] < ($this->y
- $this->feps
)) OR ($trwsp['startpage'] < $this->page
) OR ($trwsp['startcolumn'] < $this->current_column
))) {
18309 // set the starting X position of the current cell
18310 $this->x
= $rsendx +
$cellspacingx;
18311 // increment column indicator
18312 $colid +
= $trwsp['colspan'];
18313 if (($trwsp['rowspan'] == 1)
18314 AND (isset($dom[$trid]['endy']))
18315 AND (isset($dom[$trid]['endpage']))
18316 AND (isset($dom[$trid]['endcolumn']))
18317 AND ($trwsp['endpage'] == $dom[$trid]['endpage'])
18318 AND ($trwsp['endcolumn'] == $dom[$trid]['endcolumn'])) {
18319 // set ending Y position for row
18320 $dom[$table_el]['rowspans'][$rsk]['endy'] = max($dom[$trid]['endy'], $trwsp['endy']);
18321 $dom[$trid]['endy'] = $dom[$table_el]['rowspans'][$rsk]['endy'];
18329 if (isset($dom[$parentid]['width'])) {
18330 // user specified width
18331 $cellw = $this->getHTMLUnitToUnits($dom[$parentid]['width'], $table_columns_width, 'px');
18332 $tmpcw = ($cellw / $colspan);
18333 for ($i = 0; $i < $colspan; ++
$i) {
18334 $table_colwidths[($colid +
$i)] = $tmpcw;
18337 // inherit column width
18339 for ($i = 0; $i < $colspan; ++
$i) {
18340 $cellw +
= (isset($table_colwidths[($colid +
$i)]) ?
$table_colwidths[($colid +
$i)] : 0);
18343 $cellw +
= (($colspan - 1) * $cellspacing['H']);
18344 // increment column indicator
18345 $colid +
= $colspan;
18346 // add rowspan information to table element
18347 if ($rowspan > 1) {
18348 $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
));
18350 $cellid = array_push($dom[$trid]['cellpos'], array('startx' => $this->x
));
18351 if ($rowspan > 1) {
18352 $dom[$trid]['cellpos'][($cellid - 1)]['rowspanid'] = ($trsid - 1);
18354 // push background colors
18355 if (isset($dom[$parentid]['bgcolor']) AND ($dom[$parentid]['bgcolor'] !== false)) {
18356 $dom[$trid]['cellpos'][($cellid - 1)]['bgcolor'] = $dom[$parentid]['bgcolor'];
18358 // store border info
18359 if (!empty($tdborder)) {
18360 $dom[$trid]['cellpos'][($cellid - 1)]['border'] = $tdborder;
18362 $prevLastH = $this->lasth
;
18363 // store some info for multicolumn mode
18365 $this->colxshift
['x'] = $this->w
- $this->x
- $this->rMargin
;
18367 $this->colxshift
['x'] = $this->x
- $this->lMargin
;
18369 $this->colxshift
['s'] = $cellspacing;
18370 $this->colxshift
['p'] = $current_cell_padding;
18371 // ****** write the cell content ******
18372 $this->MultiCell($cellw, $cellh, $cell_content, false, $lalign, false, 2, '', '', true, 0, true, true, 0, 'T', false);
18373 // restore some values
18374 $this->colxshift
= array('x' => 0, 's' => array('H' => 0, 'V' => 0), 'p' => array('L' => 0, 'T' => 0, 'R' => 0, 'B' => 0));
18375 $this->lasth
= $prevLastH;
18376 $this->cell_padding
= $old_cell_padding;
18377 $dom[$trid]['cellpos'][($cellid - 1)]['endx'] = $this->x
;
18378 // update the end of row position
18379 if ($rowspan <= 1) {
18380 if (isset($dom[$trid]['endy'])) {
18381 if (($this->page
== $dom[$trid]['endpage']) AND ($this->current_column
== $dom[$trid]['endcolumn'])) {
18382 $dom[$trid]['endy'] = max($this->y
, $dom[$trid]['endy']);
18383 } elseif (($this->page
> $dom[$trid]['endpage']) OR ($this->current_column
> $dom[$trid]['endcolumn'])) {
18384 $dom[$trid]['endy'] = $this->y
;
18387 $dom[$trid]['endy'] = $this->y
;
18389 if (isset($dom[$trid]['endpage'])) {
18390 $dom[$trid]['endpage'] = max($this->page
, $dom[$trid]['endpage']);
18392 $dom[$trid]['endpage'] = $this->page
;
18394 if (isset($dom[$trid]['endcolumn'])) {
18395 $dom[$trid]['endcolumn'] = max($this->current_column
, $dom[$trid]['endcolumn']);
18397 $dom[$trid]['endcolumn'] = $this->current_column
;
18400 // account for row-spanned cells
18401 $dom[$table_el]['rowspans'][($trsid - 1)]['endx'] = $this->x
;
18402 $dom[$table_el]['rowspans'][($trsid - 1)]['endy'] = $this->y
;
18403 $dom[$table_el]['rowspans'][($trsid - 1)]['endpage'] = $this->page
;
18404 $dom[$table_el]['rowspans'][($trsid - 1)]['endcolumn'] = $this->current_column
;
18406 if (isset($dom[$table_el]['rowspans'])) {
18407 // update endy and endpage on rowspanned cells
18408 foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
18409 if ($trwsp['rowspan'] > 0) {
18410 if (isset($dom[$trid]['endpage'])) {
18411 if (($trwsp['endpage'] == $dom[$trid]['endpage']) AND ($trwsp['endcolumn'] == $dom[$trid]['endcolumn'])) {
18412 $dom[$table_el]['rowspans'][$k]['endy'] = max($dom[$trid]['endy'], $trwsp['endy']);
18413 } elseif (($trwsp['endpage'] < $dom[$trid]['endpage']) OR ($trwsp['endcolumn'] < $dom[$trid]['endcolumn'])) {
18414 $dom[$table_el]['rowspans'][$k]['endy'] = $dom[$trid]['endy'];
18415 $dom[$table_el]['rowspans'][$k]['endpage'] = $dom[$trid]['endpage'];
18416 $dom[$table_el]['rowspans'][$k]['endcolumn'] = $dom[$trid]['endcolumn'];
18418 $dom[$trid]['endy'] = $this->pagedim
[$dom[$trid]['endpage']]['hk'] - $this->pagedim
[$dom[$trid]['endpage']]['bm'];
18424 $this->x +
= ($cellspacingx / 2);
18426 // opening tag (or self-closing tag)
18427 if (!isset($opentagpos)) {
18428 if ($this->inxobj
) {
18429 // we are inside an XObject template
18430 $opentagpos = strlen($this->xobjects
[$this->xobjid
]['outdata']);
18431 } elseif (!$this->InFooter
) {
18432 if (isset($this->footerlen
[$this->page
])) {
18433 $this->footerpos
[$this->page
] = $this->pagelen
[$this->page
] - $this->footerlen
[$this->page
];
18435 $this->footerpos
[$this->page
] = $this->pagelen
[$this->page
];
18437 $opentagpos = $this->footerpos
[$this->page
];
18440 $dom = $this->openHTMLTagHandler($dom, $key, $cell);
18442 } else { // closing tag
18443 $prev_numpages = $this->numpages
;
18444 $old_bordermrk = $this->bordermrk
[$this->page
];
18445 $dom = $this->closeHTMLTagHandler($dom, $key, $cell, $maxbottomliney);
18446 if ($this->bordermrk
[$this->page
] > $old_bordermrk) {
18447 $startlinepos +
= ($this->bordermrk
[$this->page
] - $old_bordermrk);
18449 if ($prev_numpages > $this->numpages
) {
18450 $startlinepage = $this->page
;
18453 } elseif (strlen($dom[$key]['value']) > 0) {
18455 if (!TCPDF_STATIC
::empty_string($this->lispacer
) AND ($this->lispacer
!= '^')) {
18456 $this->setFont($pfontname, $pfontstyle, $pfontsize);
18457 $this->resetLastH();
18458 $minstartliney = $this->y
;
18459 $maxbottomliney = ($startliney +
$this->getCellHeight($this->FontSize
));
18460 if (is_numeric($pfontsize) AND ($pfontsize > 0)) {
18461 $this->putHtmlListBullet($this->listnum
, $this->lispacer
, $pfontsize);
18463 $this->setFont($curfontname, $curfontstyle, $curfontsize);
18464 $this->resetLastH();
18465 if (is_numeric($pfontsize) AND ($pfontsize > 0) AND is_numeric($curfontsize) AND ($curfontsize > 0) AND ($pfontsize != $curfontsize)) {
18466 $pfontascent = $this->getFontAscent($pfontname, $pfontstyle, $pfontsize);
18467 $pfontdescent = $this->getFontDescent($pfontname, $pfontstyle, $pfontsize);
18468 $this->y +
= ($this->getCellHeight(($pfontsize - $curfontsize) / $this->k
) +
$pfontascent - $curfontascent - $pfontdescent +
$curfontdescent) / 2;
18469 $minstartliney = min($this->y
, $minstartliney);
18470 $maxbottomliney = max(($this->y +
$this->getCellHeight($pfontsize / $this->k
)), $maxbottomliney);
18474 $this->htmlvspace
= 0;
18475 $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']);
18476 if ((!$this->premode
) AND $this->isRTLTextDir() AND !$isRTLString) {
18477 // reverse spaces order
18478 $lsp = ''; // left spaces
18479 $rsp = ''; // right spaces
18480 if (preg_match('/^('.$this->re_space
['p'].'+)/'.$this->re_space
['m'], $dom[$key]['value'], $matches)) {
18481 $lsp = $matches[1];
18483 if (preg_match('/('.$this->re_space
['p'].'+)$/'.$this->re_space
['m'], $dom[$key]['value'], $matches)) {
18484 $rsp = $matches[1];
18486 $dom[$key]['value'] = $rsp.$this->stringTrim($dom[$key]['value']).$lsp;
18489 if (!$this->premode
) {
18490 $prelen = strlen($dom[$key]['value']);
18491 if ($this->isRTLTextDir() AND !$isRTLString) {
18492 // right trim except non-breaking space
18493 $dom[$key]['value'] = $this->stringRightTrim($dom[$key]['value']);
18495 // left trim except non-breaking space
18496 $dom[$key]['value'] = $this->stringLeftTrim($dom[$key]['value']);
18498 $postlen = strlen($dom[$key]['value']);
18499 if (($postlen == 0) AND ($prelen > 0)) {
18500 $dom[$key]['trimmed_space'] = true;
18504 $firstblock = true;
18506 $firstblock = false;
18507 // replace empty multiple spaces string with a single space
18508 $dom[$key]['value'] = preg_replace('/^'.$this->re_space
['p'].'+$/'.$this->re_space
['m'], chr(32), $dom[$key]['value']);
18512 $this->x
-= $this->textindent
;
18514 $this->x +
= $this->textindent
;
18516 if (!isset($dom[$key]['trimmed_space']) OR !$dom[$key]['trimmed_space']) {
18517 $strlinelen = $this->GetStringWidth($dom[$key]['value']);
18518 if (!empty($this->HREF
) AND (isset($this->HREF
['url']))) {
18521 if (isset($dom[($dom[$key]['parent'])]['fgcolor']) AND ($dom[($dom[$key]['parent'])]['fgcolor'] !== false)) {
18522 $hrefcolor = $dom[($dom[$key]['parent'])]['fgcolor'];
18525 if (isset($dom[($dom[$key]['parent'])]['fontstyle']) AND ($dom[($dom[$key]['parent'])]['fontstyle'] !== false)) {
18526 $hrefstyle = $dom[($dom[$key]['parent'])]['fontstyle'];
18528 $strrest = $this->addHtmlLink($this->HREF
['url'], $dom[$key]['value'], $wfill, true, $hrefcolor, $hrefstyle, true);
18530 $wadj = 0; // space to leave for block continuity
18532 $cwa = ($this->x
- $this->lMargin
);
18534 $cwa = ($this->w
- $this->rMargin
- $this->x
);
18536 if (($strlinelen < $cwa) AND (isset($dom[($key +
1)])) AND ($dom[($key +
1)]['tag']) AND (!$dom[($key +
1)]['block'])) {
18537 // check the next text blocks for continuity
18538 $nkey = ($key +
1);
18539 $write_block = true;
18540 $same_textdir = true;
18541 $tmp_fontname = $this->FontFamily
;
18542 $tmp_fontstyle = $this->FontStyle
;
18543 $tmp_fontsize = $this->FontSizePt
;
18544 while ($write_block AND isset($dom[$nkey])) {
18545 if ($dom[$nkey]['tag']) {
18546 if ($dom[$nkey]['block']) {
18548 $write_block = false;
18550 $tmp_fontname = isset($dom[$nkey]['fontname']) ?
$dom[$nkey]['fontname'] : $this->FontFamily
;
18551 $tmp_fontstyle = isset($dom[$nkey]['fontstyle']) ?
$dom[$nkey]['fontstyle'] : $this->FontStyle
;
18552 $tmp_fontsize = isset($dom[$nkey]['fontsize']) ?
$dom[$nkey]['fontsize'] : $this->FontSizePt
;
18553 $same_textdir = ($dom[$nkey]['dir'] == $dom[$key]['dir']);
18555 $nextstr = TCPDF_STATIC
::pregSplit('/'.$this->re_space
['p'].'+/', $this->re_space
['m'], $dom[$nkey]['value']);
18556 if (isset($nextstr[0]) AND $same_textdir) {
18557 $wadj +
= $this->GetStringWidth($nextstr[0], $tmp_fontname, $tmp_fontstyle, $tmp_fontsize);
18558 if (isset($nextstr[1])) {
18559 $write_block = false;
18566 if (($wadj > 0) AND (($strlinelen +
$wadj) >= $cwa)) {
18568 $nextstr = TCPDF_STATIC
::pregSplit('/'.$this->re_space
['p'].'/', $this->re_space
['m'], $dom[$key]['value']);
18569 $numblks = count($nextstr);
18570 if ($numblks > 1) {
18571 // try to split on blank spaces
18572 $wadj = ($cwa - $strlinelen +
$this->GetStringWidth($nextstr[($numblks - 1)]));
18574 // set the entire block on new line
18575 $wadj = $this->GetStringWidth($nextstr[0]);
18578 // check for reversed text direction
18579 if (($wadj > 0) AND (($this->rtl
AND ($this->tmprtl
=== 'L')) OR (!$this->rtl
AND ($this->tmprtl
=== 'R')))) {
18580 // LTR text on RTL direction or RTL text on LTR direction
18581 $reverse_dir = true;
18582 $this->rtl
= !$this->rtl
;
18583 $revshift = ($strlinelen +
$wadj +
0.000001); // add little quantity for rounding problems
18585 $this->x +
= $revshift;
18587 $this->x
-= $revshift;
18591 // ****** write only until the end of the line and get the rest ******
18592 $strrest = $this->Write($this->lasth
, $dom[$key]['value'], '', $wfill, '', false, 0, true, $firstblock, 0, $wadj);
18593 // restore default direction
18594 if ($reverse_dir AND ($wadj == 0)) {
18595 $this->x
= $xws; // @phpstan-ignore-line
18596 $this->rtl
= !$this->rtl
;
18597 $reverse_dir = false;
18601 $this->textindent
= 0;
18602 if (strlen($strrest) > 0) {
18603 // store the remaining string on the previous $key position
18604 $this->newline
= true;
18605 if ($strrest == $dom[$key]['value']) {
18606 // used to avoid infinite loop
18611 $dom[$key]['value'] = $strrest;
18614 $this->x
-= $this->cell_padding
['R'];
18616 $this->x +
= $this->cell_padding
['L'];
18624 // add the positive font spacing of the last character (if any)
18625 if ($this->font_spacing
> 0) {
18627 $this->x
-= $this->font_spacing
;
18629 $this->x +
= $this->font_spacing
;
18635 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')) {
18636 // check if we are on a new page or on a new column
18637 if ((!$undo) AND (($this->y
< $this->start_transaction_y
) OR (($dom[$key]['value'] == 'tr') AND ($dom[($dom[$key]['parent'])]['endy'] < $this->start_transaction_y
)))) {
18638 // we are on a new page or on a new column and the total object height is less than the available vertical space.
18639 // restore previous object
18640 $this->rollbackTransaction(true);
18641 // restore previous values
18642 foreach ($this_method_vars as $vkey => $vval) {
18645 if (!empty($dom[$key]['thead'])) {
18646 $this->inthead
= true;
18648 // add a page (or trig AcceptPageBreak() for multicolumn mode)
18650 if ((!$this->checkPageBreak($this->PageBreakTrigger +
1)) AND ($this->y
< $pre_y)) {
18651 $startliney = $this->y
;
18653 $undo = true; // avoid infinite loop
18658 } // end for each $key
18659 // align the last line
18660 if (isset($startlinex)) {
18661 $yshift = ($minstartliney - $startliney);
18662 if (($yshift > 0) OR ($this->page
> $startlinepage)) {
18666 // the last line must be shifted to be aligned as requested
18667 $linew = abs($this->endlinex
- $startlinex);
18668 if ($this->inxobj
) {
18669 // we are inside an XObject template
18670 $pstart = substr($this->xobjects
[$this->xobjid
]['outdata'], 0, $startlinepos);
18671 if (isset($opentagpos)) {
18672 $midpos = $opentagpos;
18677 $pmid = substr($this->xobjects
[$this->xobjid
]['outdata'], $startlinepos, ($midpos - $startlinepos));
18678 $pend = substr($this->xobjects
[$this->xobjid
]['outdata'], $midpos);
18680 $pmid = substr($this->xobjects
[$this->xobjid
]['outdata'], $startlinepos);
18684 $pstart = substr($this->getPageBuffer($startlinepage), 0, $startlinepos);
18685 if (isset($opentagpos) AND isset($this->footerlen
[$startlinepage]) AND (!$this->InFooter
)) {
18686 $this->footerpos
[$startlinepage] = $this->pagelen
[$startlinepage] - $this->footerlen
[$startlinepage];
18687 $midpos = min($opentagpos, $this->footerpos
[$startlinepage]);
18688 } elseif (isset($opentagpos)) {
18689 $midpos = $opentagpos;
18690 } elseif (isset($this->footerlen
[$startlinepage]) AND (!$this->InFooter
)) {
18691 $this->footerpos
[$startlinepage] = $this->pagelen
[$startlinepage] - $this->footerlen
[$startlinepage];
18692 $midpos = $this->footerpos
[$startlinepage];
18697 $pmid = substr($this->getPageBuffer($startlinepage), $startlinepos, ($midpos - $startlinepos));
18698 $pend = substr($this->getPageBuffer($startlinepage), $midpos);
18700 $pmid = substr($this->getPageBuffer($startlinepage), $startlinepos);
18704 if ((((($plalign == 'C') OR (($plalign == 'R') AND (!$this->rtl
)) OR (($plalign == 'L') AND ($this->rtl
)))))) {
18705 // calculate shifting amount
18707 if ($this->lMargin
!= $prevlMargin) {
18708 $tw +
= ($prevlMargin - $this->lMargin
);
18710 if ($this->rMargin
!= $prevrMargin) {
18711 $tw +
= ($prevrMargin - $this->rMargin
);
18713 $one_space_width = $this->GetStringWidth(chr(32));
18714 $no = 0; // number of spaces on a line contained on a single block
18715 if ($this->isRTLTextDir()) { // RTL
18716 // remove left space if exist
18717 $pos1 = TCPDF_STATIC
::revstrpos($pmid, '[(');
18719 $pos1 = intval($pos1);
18720 if ($this->isUnicodeFont()) {
18721 $pos2 = intval(TCPDF_STATIC
::revstrpos($pmid, '[('.chr(0).chr(32)));
18724 $pos2 = intval(TCPDF_STATIC
::revstrpos($pmid, '[('.chr(32)));
18727 if ($pos1 == $pos2) {
18728 $pmid = substr($pmid, 0, ($pos1 +
2)).substr($pmid, ($pos1 +
2 +
$spacelen));
18729 if (substr($pmid, $pos1, 4) == '[()]') {
18730 $linew -= $one_space_width;
18731 } elseif ($pos1 == strpos($pmid, '[(')) {
18737 // remove right space if exist
18738 $pos1 = TCPDF_STATIC
::revstrpos($pmid, ')]');
18740 $pos1 = intval($pos1);
18741 if ($this->isUnicodeFont()) {
18742 $pos2 = intval(TCPDF_STATIC
::revstrpos($pmid, chr(0).chr(32).')]')) +
2;
18745 $pos2 = intval(TCPDF_STATIC
::revstrpos($pmid, chr(32).')]')) +
1;
18748 if ($pos1 == $pos2) {
18749 $pmid = substr($pmid, 0, ($pos1 - $spacelen)).substr($pmid, $pos1);
18750 $linew -= $one_space_width;
18754 $mdiff = ($tw - $linew);
18755 if ($plalign == 'C') {
18757 $t_x = -($mdiff / 2);
18759 $t_x = ($mdiff / 2);
18761 } elseif ($plalign == 'R') {
18762 // right alignment on LTR document
18764 } elseif ($plalign == 'L') {
18765 // left alignment on RTL document
18768 } // end if startlinex
18769 if (($t_x != 0) OR ($yshift < 0)) {
18771 $trx = sprintf('1 0 0 1 %F %F cm', ($t_x * $this->k
), ($yshift * $this->k
));
18772 $pstart .= "\nq\n".$trx."\n".$pmid."\nQ\n";
18773 $endlinepos = strlen($pstart);
18774 if ($this->inxobj
) {
18775 // we are inside an XObject template
18776 $this->xobjects
[$this->xobjid
]['outdata'] = $pstart.$pend;
18777 foreach ($this->xobjects
[$this->xobjid
]['annotations'] as $pak => $pac) {
18778 if ($pak >= $pask) {
18779 $this->xobjects
[$this->xobjid
]['annotations'][$pak]['x'] +
= $t_x;
18780 $this->xobjects
[$this->xobjid
]['annotations'][$pak]['y'] -= $yshift;
18784 $this->setPageBuffer($startlinepage, $pstart.$pend);
18785 // shift the annotations and links
18786 if (isset($this->PageAnnots
[$this->page
])) {
18787 foreach ($this->PageAnnots
[$this->page
] as $pak => $pac) {
18788 if ($pak >= $pask) {
18789 $this->PageAnnots
[$this->page
][$pak]['x'] +
= $t_x;
18790 $this->PageAnnots
[$this->page
][$pak]['y'] -= $yshift;
18795 $this->y
-= $yshift;
18799 // restore previous values
18800 $this->setGraphicVars($gvars);
18801 if ($this->num_columns
> 1) {
18802 $this->selectColumn();
18803 } elseif ($this->page
> $prevPage) {
18804 $this->lMargin
= $this->pagedim
[$this->page
]['olm'];
18805 $this->rMargin
= $this->pagedim
[$this->page
]['orm'];
18807 // restore previous list state
18808 $this->cell_height_ratio
= $prev_cell_height_ratio;
18809 $this->listnum
= $prev_listnum;
18810 $this->listordered
= $prev_listordered;
18811 $this->listcount
= $prev_listcount;
18812 $this->lispacer
= $prev_lispacer;
18813 if ($ln AND (!($cell AND ($dom[$key-1]['value'] == 'table')))) {
18814 $this->Ln($this->lasth
);
18815 if (($this->y
< $maxbottomliney) AND ($startlinepage == $this->page
)) {
18816 $this->y
= $maxbottomliney;
18823 * Process opening tags.
18824 * @param array $dom html dom array
18825 * @param int $key current element id
18826 * @param boolean $cell if true add the default left (or right if RTL) padding to each new line (default false).
18827 * @return array $dom
18830 protected function openHTMLTagHandler($dom, $key, $cell) {
18832 $parent = $dom[($dom[$key]['parent'])];
18833 $firsttag = ($key == 1);
18834 // check for text direction attribute
18835 if (isset($tag['dir'])) {
18836 $this->setTempRTL($tag['dir']);
18838 $this->tmprtl
= false;
18840 if ($tag['block']) {
18841 $hbz = 0; // distance from y to line bottom
18842 $hb = 0; // vertical space between block tags
18843 // calculate vertical space for block tags
18844 if (isset($this->tagvspaces
[$tag['value']][0]['h']) && !empty($this->tagvspaces
[$tag['value']][0]['h']) && ($this->tagvspaces
[$tag['value']][0]['h'] >= 0)) {
18845 $cur_h = $this->tagvspaces
[$tag['value']][0]['h'];
18846 } elseif (isset($tag['fontsize'])) {
18847 $cur_h = $this->getCellHeight($tag['fontsize'] / $this->k
);
18849 $cur_h = $this->getCellHeight($this->FontSize
);
18851 if (isset($this->tagvspaces
[$tag['value']][0]['n'])) {
18852 $on = $this->tagvspaces
[$tag['value']][0]['n'];
18853 } elseif (preg_match('/[h][0-9]/', $tag['value']) > 0) {
18858 if ((!isset($this->tagvspaces
[$tag['value']])) AND (in_array($tag['value'], array('div', 'dt', 'dd', 'li', 'br', 'hr')))) {
18861 $hb = ($on * $cur_h);
18863 if (($this->htmlvspace
<= 0) AND ($on > 0)) {
18864 if (isset($parent['fontsize'])) {
18865 $hbz = (($parent['fontsize'] / $this->k
) * $this->cell_height_ratio
);
18867 $hbz = $this->getCellHeight($this->FontSize
);
18870 if (isset($dom[($key - 1)]) AND ($dom[($key - 1)]['value'] == 'table')) {
18871 // fix vertical space after table
18874 // closing vertical space
18876 if (isset($this->tagvspaces
[$tag['value']][1]['h']) && !empty($this->tagvspaces
[$tag['value']][1]['h']) && ($this->tagvspaces
[$tag['value']][1]['h'] >= 0)) {
18877 $pre_h = $this->tagvspaces
[$tag['value']][1]['h'];
18878 } elseif (isset($parent['fontsize'])) {
18879 $pre_h = $this->getCellHeight($parent['fontsize'] / $this->k
);
18881 $pre_h = $this->getCellHeight($this->FontSize
);
18883 if (isset($this->tagvspaces
[$tag['value']][1]['n'])) {
18884 $cn = $this->tagvspaces
[$tag['value']][1]['n'];
18885 } elseif (preg_match('/[h][0-9]/', $tag['value']) > 0) {
18890 if (isset($this->tagvspaces
[$tag['value']][1])) {
18891 $hbc = ($cn * $pre_h);
18895 switch($tag['value']) {
18899 $dom[$key]['rowspans'] = array();
18900 if (!isset($dom[$key]['attribute']['nested']) OR ($dom[$key]['attribute']['nested'] != 'true')) {
18901 $this->htmlvspace
= 0;
18902 // set table header
18903 if (!TCPDF_STATIC
::empty_string($dom[$key]['thead'])) {
18904 // set table header
18905 $this->thead
= $dom[$key]['thead'];
18906 if (!isset($this->theadMargins
) OR (empty($this->theadMargins
))) {
18907 $this->theadMargins
= array();
18908 $this->theadMargins
['cell_padding'] = $this->cell_padding
;
18909 $this->theadMargins
['lmargin'] = $this->lMargin
;
18910 $this->theadMargins
['rmargin'] = $this->rMargin
;
18911 $this->theadMargins
['page'] = $this->page
;
18912 $this->theadMargins
['cell'] = $cell;
18913 $this->theadMargins
['gvars'] = $this->getGraphicVars();
18917 // store current margins and page
18918 $dom[$key]['old_cell_padding'] = $this->cell_padding
;
18919 if (isset($tag['attribute']['cellpadding'])) {
18920 $pad = $this->getHTMLUnitToUnits($tag['attribute']['cellpadding'], 1, 'px');
18921 $this->setCellPadding($pad);
18922 } elseif (isset($tag['padding'])) {
18923 $this->cell_padding
= $tag['padding'];
18925 if (isset($tag['attribute']['cellspacing'])) {
18926 $cs = $this->getHTMLUnitToUnits($tag['attribute']['cellspacing'], 1, 'px');
18927 } elseif (isset($tag['border-spacing'])) {
18928 $cs = $tag['border-spacing']['V'];
18930 $prev_y = $this->y
;
18931 if ($this->checkPageBreak(((2 * $cp) +
(2 * $cs) +
$this->lasth
), '', false) OR ($this->y
< $prev_y)) {
18932 $this->inthead
= true;
18933 // add a page (or trig AcceptPageBreak() for multicolumn mode)
18934 $this->checkPageBreak($this->PageBreakTrigger +
1);
18939 // array of columns positions
18940 $dom[$key]['cellpos'] = array();
18944 if ((isset($tag['height'])) AND ($tag['height'] != '')) {
18945 $hrHeight = $this->getHTMLUnitToUnits($tag['height'], 1, 'px');
18947 $hrHeight = $this->GetLineWidth();
18949 $this->addHTMLVertSpace($hbz, max($hb, ($hrHeight / 2)), $cell, $firsttag);
18950 $x = $this->GetX();
18951 $y = $this->GetY();
18952 $wtmp = $this->w
- $this->lMargin
- $this->rMargin
;
18954 $wtmp -= ($this->cell_padding
['L'] +
$this->cell_padding
['R']);
18956 if ((isset($tag['width'])) AND ($tag['width'] != '')) {
18957 $hrWidth = $this->getHTMLUnitToUnits($tag['width'], $wtmp, 'px');
18961 $prevlinewidth = $this->GetLineWidth();
18962 $this->setLineWidth($hrHeight);
18964 $lineStyle = array();
18965 if (isset($tag['fgcolor'])) {
18966 $lineStyle['color'] = $tag['fgcolor'];
18969 if (isset($tag['fgcolor'])) {
18970 $lineStyle['color'] = $tag['fgcolor'];
18973 if (isset($tag['style']['cap'])) {
18974 $lineStyle['cap'] = $tag['style']['cap'];
18977 if (isset($tag['style']['join'])) {
18978 $lineStyle['join'] = $tag['style']['join'];
18981 if (isset($tag['style']['dash'])) {
18982 $lineStyle['dash'] = $tag['style']['dash'];
18985 if (isset($tag['style']['phase'])) {
18986 $lineStyle['phase'] = $tag['style']['phase'];
18989 $lineStyle = array_filter($lineStyle);
18991 $this->Line($x, $y, $x +
$hrWidth, $y, $lineStyle);
18992 $this->setLineWidth($prevlinewidth);
18993 $this->addHTMLVertSpace(max($hbc, ($hrHeight / 2)), 0, $cell, !isset($dom[($key +
1)]));
18997 if (array_key_exists('href', $tag['attribute'])) {
18998 $this->HREF
['url'] = $tag['attribute']['href'];
19003 if (empty($tag['attribute']['src'])) {
19006 $imgsrc = $tag['attribute']['src'];
19007 if ($imgsrc[0] === '@') {
19009 $imgsrc = '@'.base64_decode(substr($imgsrc, 1));
19011 } else if (preg_match('@^data:image/([^;]*);base64,(.*)@', $imgsrc, $reg)) {
19012 $imgsrc = '@'.base64_decode($reg[2]);
19014 } elseif ( $this->allowLocalFiles
&& substr($imgsrc, 0, 7) === 'file://') {
19015 // get image type from a local file path
19016 $imgsrc = substr($imgsrc, 7);
19017 $type = TCPDF_IMAGES
::getImageFileType($imgsrc);
19019 if (($imgsrc[0] === '/') AND !empty($_SERVER['DOCUMENT_ROOT']) AND ($_SERVER['DOCUMENT_ROOT'] != '/')) {
19021 $findroot = strpos($imgsrc, $_SERVER['DOCUMENT_ROOT']);
19022 if (($findroot === false) OR ($findroot > 1)) {
19023 if (substr($_SERVER['DOCUMENT_ROOT'], -1) == '/') {
19024 $imgsrc = substr($_SERVER['DOCUMENT_ROOT'], 0, -1).$imgsrc;
19026 $imgsrc = $_SERVER['DOCUMENT_ROOT'].$imgsrc;
19029 $imgsrc = urldecode($imgsrc);
19030 $testscrtype = @parse_url
($imgsrc);
19031 if (empty($testscrtype['query'])) {
19032 // convert URL to server path
19033 $imgsrc = str_replace(K_PATH_URL
, K_PATH_MAIN
, $imgsrc);
19034 } elseif (preg_match('|^https?://|', $imgsrc) !== 1) {
19035 // convert URL to server path
19036 $imgsrc = str_replace(K_PATH_MAIN
, K_PATH_URL
, $imgsrc);
19040 $type = TCPDF_IMAGES
::getImageFileType($imgsrc);
19042 if (!isset($tag['width'])) {
19045 if (!isset($tag['height'])) {
19046 $tag['height'] = 0;
19048 //if (!isset($tag['attribute']['align'])) {
19049 // the only alignment supported is "bottom"
19050 // further development is required for other modes.
19051 $tag['attribute']['align'] = 'bottom';
19053 switch($tag['attribute']['align']) {
19074 if (isset($this->HREF
['url']) AND !TCPDF_STATIC
::empty_string($this->HREF
['url'])) {
19075 $imglink = $this->HREF
['url'];
19076 if ($imglink[0] == '#') {
19077 // convert url to internal link
19078 $lnkdata = explode(',', $imglink);
19079 if (isset($lnkdata[0])) {
19080 $page = intval(substr($lnkdata[0], 1));
19081 if (empty($page) OR ($page <= 0)) {
19082 $page = $this->page
;
19084 if (isset($lnkdata[1]) AND (strlen($lnkdata[1]) > 0)) {
19085 $lnky = floatval($lnkdata[1]);
19089 $imglink = $this->AddLink();
19090 $this->setLink($imglink, $lnky, $page);
19095 if (isset($tag['border']) AND !empty($tag['border'])) {
19096 // currently only support 1 (frame) or a combination of 'LTRB'
19097 $border = $tag['border'];
19100 if (isset($tag['width'])) {
19101 $iw = $this->getHTMLUnitToUnits($tag['width'], ($tag['fontsize'] / $this->k
), 'px', false);
19104 if (isset($tag['height'])) {
19105 $ih = $this->getHTMLUnitToUnits($tag['height'], ($tag['fontsize'] / $this->k
), 'px', false);
19107 if (($type == 'eps') OR ($type == 'ai')) {
19108 $this->ImageEps($imgsrc, $xpos, $this->y
, $iw, $ih, $imglink, true, $align, '', $border, true);
19109 } elseif ($type == 'svg') {
19110 $this->ImageSVG($imgsrc, $xpos, $this->y
, $iw, $ih, $imglink, $align, '', $border, true);
19112 $this->Image($imgsrc, $xpos, $this->y
, $iw, $ih, '', $imglink, $align, false, 300, '', false, false, $border, false, false, true);
19120 $this->y
= (($this->img_rb_y +
$prevy - ($this->getCellHeight($tag['fontsize'] / $this->k
))) / 2);
19124 $this->y
= $this->img_rb_y
- ($this->getCellHeight($tag['fontsize'] / $this->k
) - ($this->getFontDescent($tag['fontname'], $tag['fontstyle'], $tag['fontsize']) * $this->cell_height_ratio
));
19132 if ($this->listnum
== 1) {
19133 $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
19135 $this->addHTMLVertSpace(0, 0, $cell, $firsttag);
19140 $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
19145 $this->rMargin +
= $this->listindent
;
19147 $this->lMargin +
= $this->listindent
;
19149 ++
$this->listindentlevel
;
19150 $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
19156 if ($tag['value'] == 'ol') {
19157 $this->listordered
[$this->listnum
] = true;
19159 $this->listordered
[$this->listnum
] = false;
19161 if (isset($tag['attribute']['start'])) {
19162 $this->listcount
[$this->listnum
] = intval($tag['attribute']['start']) - 1;
19164 $this->listcount
[$this->listnum
] = 0;
19167 $this->rMargin +
= $this->listindent
;
19168 $this->x
-= $this->listindent
;
19170 $this->lMargin +
= $this->listindent
;
19171 $this->x +
= $this->listindent
;
19173 ++
$this->listindentlevel
;
19174 if ($this->listnum
== 1) {
19176 $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
19179 $this->addHTMLVertSpace(0, 0, $cell, $firsttag);
19185 $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
19187 if ($this->listordered
[$this->listnum
]) {
19189 if (isset($parent['attribute']['type']) AND !TCPDF_STATIC
::empty_string($parent['attribute']['type'])) {
19190 $this->lispacer
= $parent['attribute']['type'];
19191 } elseif (isset($parent['listtype']) AND !TCPDF_STATIC
::empty_string($parent['listtype'])) {
19192 $this->lispacer
= $parent['listtype'];
19193 } elseif (isset($this->lisymbol
) AND !TCPDF_STATIC
::empty_string($this->lisymbol
)) {
19194 $this->lispacer
= $this->lisymbol
;
19196 $this->lispacer
= '#';
19198 ++
$this->listcount
[$this->listnum
];
19199 if (isset($tag['attribute']['value'])) {
19200 $this->listcount
[$this->listnum
] = intval($tag['attribute']['value']);
19204 if (isset($parent['attribute']['type']) AND !TCPDF_STATIC
::empty_string($parent['attribute']['type'])) {
19205 $this->lispacer
= $parent['attribute']['type'];
19206 } elseif (isset($parent['listtype']) AND !TCPDF_STATIC
::empty_string($parent['listtype'])) {
19207 $this->lispacer
= $parent['listtype'];
19208 } elseif (isset($this->lisymbol
) AND !TCPDF_STATIC
::empty_string($this->lisymbol
)) {
19209 $this->lispacer
= $this->lisymbol
;
19211 $this->lispacer
= '!';
19216 case 'blockquote': {
19218 $this->rMargin +
= $this->listindent
;
19220 $this->lMargin +
= $this->listindent
;
19222 ++
$this->listindentlevel
;
19223 $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
19227 $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
19231 $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
19235 $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
19239 $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
19240 $this->premode
= true;
19244 $this->setXY($this->GetX(), $this->GetY() - ((0.7 * $this->FontSizePt
) / $this->k
));
19248 $this->setXY($this->GetX(), $this->GetY() +
((0.3 * $this->FontSizePt
) / $this->k
));
19257 $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
19260 // Form fields (since 4.8.000 - 2009-09-07)
19262 if (isset($tag['attribute']['action'])) {
19263 $this->form_action
= $tag['attribute']['action'];
19265 $this->Error('Please explicitly set action attribute path!');
19267 if (isset($tag['attribute']['enctype'])) {
19268 $this->form_enctype
= $tag['attribute']['enctype'];
19270 $this->form_enctype
= 'application/x-www-form-urlencoded';
19272 if (isset($tag['attribute']['method'])) {
19273 $this->form_mode
= $tag['attribute']['method'];
19275 $this->form_mode
= 'post';
19280 if (isset($tag['attribute']['name']) AND !TCPDF_STATIC
::empty_string($tag['attribute']['name'])) {
19281 $name = $tag['attribute']['name'];
19287 if (isset($tag['attribute']['readonly']) AND !TCPDF_STATIC
::empty_string($tag['attribute']['readonly'])) {
19288 $prop['readonly'] = true;
19290 if (isset($tag['attribute']['value']) AND !TCPDF_STATIC
::empty_string($tag['attribute']['value'])) {
19291 $value = $tag['attribute']['value'];
19293 if (isset($tag['attribute']['maxlength']) AND !TCPDF_STATIC
::empty_string($tag['attribute']['maxlength'])) {
19294 $opt['maxlen'] = intval($tag['attribute']['maxlength']);
19296 $h = $this->getCellHeight($this->FontSize
);
19297 if (isset($tag['attribute']['size']) AND !TCPDF_STATIC
::empty_string($tag['attribute']['size'])) {
19298 $w = intval($tag['attribute']['size']) * $this->GetStringWidth(chr(32)) * 2;
19302 if (isset($tag['attribute']['checked']) AND (($tag['attribute']['checked'] == 'checked') OR ($tag['attribute']['checked'] == 'true'))) {
19307 if (isset($tag['align'])) {
19308 switch ($tag['align']) {
19323 switch ($tag['attribute']['type']) {
19325 if (isset($value)) {
19326 $opt['v'] = $value;
19328 $this->TextField($name, $w, $h, $prop, $opt, '', '', false);
19332 if (isset($value)) {
19333 $opt['v'] = $value;
19335 $prop['password'] = 'true';
19336 $this->TextField($name, $w, $h, $prop, $opt, '', '', false);
19340 if (!isset($value)) {
19343 $this->CheckBox($name, $w, $checked, $prop, $opt, $value, '', '', false);
19347 if (!isset($value)) {
19350 $this->RadioButton($name, $w, $prop, $opt, $value, $checked, '', '', false);
19354 if (!isset($value)) {
19357 $w = $this->GetStringWidth($value) * 1.5;
19359 $prop = array('lineWidth'=>1, 'borderStyle'=>'beveled', 'fillColor'=>array(196, 196, 196), 'strokeColor'=>array(255, 255, 255));
19361 $action['S'] = 'SubmitForm';
19362 $action['F'] = $this->form_action
;
19363 if ($this->form_enctype
!= 'FDF') {
19364 $action['Flags'] = array('ExportFormat');
19366 if ($this->form_mode
== 'get') {
19367 $action['Flags'] = array('GetMethod');
19369 $this->Button($name, $w, $h, $value, $action, $prop, $opt, '', '', false);
19373 if (!isset($value)) {
19376 $w = $this->GetStringWidth($value) * 1.5;
19378 $prop = array('lineWidth'=>1, 'borderStyle'=>'beveled', 'fillColor'=>array(196, 196, 196), 'strokeColor'=>array(255, 255, 255));
19379 $this->Button($name, $w, $h, $value, array('S'=>'ResetForm'), $prop, $opt, '', '', false);
19383 $prop['fileSelect'] = 'true';
19384 $this->TextField($name, $w, $h, $prop, $opt, '', '', false);
19385 if (!isset($value)) {
19388 $w = $this->GetStringWidth($value) * 2;
19390 $prop = array('lineWidth'=>1, 'borderStyle'=>'beveled', 'fillColor'=>array(196, 196, 196), 'strokeColor'=>array(255, 255, 255));
19391 $jsaction = 'var f=this.getField(\''.$name.'\'); f.browseForFileToSubmit();';
19392 $this->Button('FB_'.$name, $w, $h, $value, $jsaction, $prop, $opt, '', '', false);
19396 if (isset($value)) {
19397 $opt['v'] = $value;
19399 $opt['f'] = array('invisible', 'hidden');
19400 $this->TextField($name, 0, 0, $prop, $opt, '', '', false);
19404 // THIS TYPE MUST BE FIXED
19405 if (isset($tag['attribute']['src']) AND !TCPDF_STATIC
::empty_string($tag['attribute']['src'])) {
19406 $img = $tag['attribute']['src'];
19411 //$opt['mk'] = array('i'=>$img, 'tp'=>1, 'if'=>array('sw'=>'A', 's'=>'A', 'fb'=>false));
19412 if (isset($tag['attribute']['onclick']) AND !empty($tag['attribute']['onclick'])) {
19413 $jsaction = $tag['attribute']['onclick'];
19417 $this->Button($name, $w, $h, $value, $jsaction, $prop, $opt, '', '', false);
19421 if (!isset($value)) {
19424 $w = $this->GetStringWidth($value) * 1.5;
19426 $prop = array('lineWidth'=>1, 'borderStyle'=>'beveled', 'fillColor'=>array(196, 196, 196), 'strokeColor'=>array(255, 255, 255));
19427 if (isset($tag['attribute']['onclick']) AND !empty($tag['attribute']['onclick'])) {
19428 $jsaction = $tag['attribute']['onclick'];
19432 $this->Button($name, $w, $h, $value, $jsaction, $prop, $opt, '', '', false);
19441 if (isset($tag['attribute']['readonly']) AND !TCPDF_STATIC
::empty_string($tag['attribute']['readonly'])) {
19442 $prop['readonly'] = true;
19444 if (isset($tag['attribute']['name']) AND !TCPDF_STATIC
::empty_string($tag['attribute']['name'])) {
19445 $name = $tag['attribute']['name'];
19449 if (isset($tag['attribute']['value']) AND !TCPDF_STATIC
::empty_string($tag['attribute']['value'])) {
19450 $opt['v'] = $tag['attribute']['value'];
19452 if (isset($tag['attribute']['cols']) AND !TCPDF_STATIC
::empty_string($tag['attribute']['cols'])) {
19453 $w = intval($tag['attribute']['cols']) * $this->GetStringWidth(chr(32)) * 2;
19457 if (isset($tag['attribute']['rows']) AND !TCPDF_STATIC
::empty_string($tag['attribute']['rows'])) {
19458 $h = intval($tag['attribute']['rows']) * $this->getCellHeight($this->FontSize
);
19462 $prop['multiline'] = 'true';
19463 $this->TextField($name, $w, $h, $prop, $opt, '', '', false);
19467 $h = $this->getCellHeight($this->FontSize
);
19468 if (isset($tag['attribute']['size']) AND !TCPDF_STATIC
::empty_string($tag['attribute']['size'])) {
19469 $h *= ($tag['attribute']['size'] +
1);
19473 if (isset($tag['attribute']['name']) AND !TCPDF_STATIC
::empty_string($tag['attribute']['name'])) {
19474 $name = $tag['attribute']['name'];
19479 if (isset($tag['attribute']['opt']) AND !TCPDF_STATIC
::empty_string($tag['attribute']['opt'])) {
19480 $options = explode('#!NwL!#', $tag['attribute']['opt']);
19482 foreach ($options as $val) {
19483 if (strpos($val, '#!TaB!#') !== false) {
19484 $opts = explode('#!TaB!#', $val);
19486 $w = max($w, $this->GetStringWidth($opts[1]));
19489 $w = max($w, $this->GetStringWidth($val));
19496 if (isset($tag['attribute']['multiple']) AND ($tag['attribute']['multiple']='multiple')) {
19497 $prop['multipleSelection'] = 'true';
19498 $this->ListBox($name, $w, $h, $values, $prop, $opt, '', '', false);
19500 $this->ComboBox($name, $w, $h, $values, $prop, $opt, '', '', false);
19505 if (defined('K_TCPDF_CALLS_IN_HTML') AND (K_TCPDF_CALLS_IN_HTML
=== true)) {
19506 // Special tag used to call TCPDF methods
19507 if (isset($tag['attribute']['method'])) {
19508 $tcpdf_method = $tag['attribute']['method'];
19509 if (method_exists($this, $tcpdf_method)) {
19510 if (isset($tag['attribute']['params']) AND (!empty($tag['attribute']['params']))) {
19511 $params = $this->unserializeTCPDFtagParameters($tag['attribute']['params']);
19512 call_user_func_array(array($this, $tcpdf_method), $params);
19514 $this->$tcpdf_method();
19516 $this->newline
= true;
19526 // define tags that support borders and background colors
19527 $bordertags = array('blockquote','br','dd','dl','div','dt','h1','h2','h3','h4','h5','h6','hr','li','ol','p','pre','ul','tcpdf','table');
19528 if (in_array($tag['value'], $bordertags)) {
19530 $dom[$key]['borderposition'] = $this->getBorderStartPosition();
19532 if ($dom[$key]['self'] AND isset($dom[$key]['attribute']['pagebreakafter'])) {
19533 $pba = $dom[$key]['attribute']['pagebreakafter'];
19534 // check for pagebreak
19535 if (($pba == 'true') OR ($pba == 'left') OR ($pba == 'right')) {
19536 // add a page (or trig AcceptPageBreak() for multicolumn mode)
19537 $this->checkPageBreak($this->PageBreakTrigger +
1);
19539 if ((($pba == 'left') AND (((!$this->rtl
) AND (($this->page %
2) == 0)) OR (($this->rtl
) AND (($this->page %
2) != 0))))
19540 OR (($pba == 'right') AND (((!$this->rtl
) AND (($this->page %
2) != 0)) OR (($this->rtl
) AND (($this->page %
2) == 0))))) {
19541 // add a page (or trig AcceptPageBreak() for multicolumn mode)
19542 $this->checkPageBreak($this->PageBreakTrigger +
1);
19549 * Process closing tags.
19550 * @param array $dom html dom array
19551 * @param int $key current element id
19552 * @param boolean $cell if true add the default left (or right if RTL) padding to each new line (default false).
19553 * @param int $maxbottomliney maximum y value of current line
19554 * @return array $dom
19557 protected function closeHTMLTagHandler($dom, $key, $cell, $maxbottomliney=0) {
19559 $parent = $dom[($dom[$key]['parent'])];
19560 $lasttag = ((!isset($dom[($key +
1)])) OR ((!isset($dom[($key +
2)])) AND ($dom[($key +
1)]['value'] == 'marker')));
19561 $in_table_head = false;
19562 // maximum x position (used to draw borders)
19568 if ($tag['block']) {
19569 $hbz = 0; // distance from y to line bottom
19570 $hb = 0; // vertical space between block tags
19571 // calculate vertical space for block tags
19572 if (isset($this->tagvspaces
[$tag['value']][1]['h']) && !empty($this->tagvspaces
[$tag['value']][1]['h']) && ($this->tagvspaces
[$tag['value']][1]['h'] >= 0)) {
19573 $pre_h = $this->tagvspaces
[$tag['value']][1]['h'];
19574 } elseif (isset($parent['fontsize'])) {
19575 $pre_h = $this->getCellHeight($parent['fontsize'] / $this->k
);
19577 $pre_h = $this->getCellHeight($this->FontSize
);
19579 if (isset($this->tagvspaces
[$tag['value']][1]['n'])) {
19580 $cn = $this->tagvspaces
[$tag['value']][1]['n'];
19581 } elseif (preg_match('/[h][0-9]/', $tag['value']) > 0) {
19586 if ((!isset($this->tagvspaces
[$tag['value']])) AND ($tag['value'] == 'div')) {
19589 $hb = ($cn * $pre_h);
19591 if ($maxbottomliney > $this->PageBreakTrigger
) {
19592 $hbz = $this->getCellHeight($this->FontSize
);
19593 } elseif ($this->y
< $maxbottomliney) {
19594 $hbz = ($maxbottomliney - $this->y
);
19598 switch($tag['value']) {
19600 $table_el = $dom[($dom[$key]['parent'])]['parent'];
19601 if (!isset($parent['endy'])) {
19602 $dom[($dom[$key]['parent'])]['endy'] = $this->y
;
19603 $parent['endy'] = $this->y
;
19605 if (!isset($parent['endpage'])) {
19606 $dom[($dom[$key]['parent'])]['endpage'] = $this->page
;
19607 $parent['endpage'] = $this->page
;
19609 if (!isset($parent['endcolumn'])) {
19610 $dom[($dom[$key]['parent'])]['endcolumn'] = $this->current_column
;
19611 $parent['endcolumn'] = $this->current_column
;
19613 // update row-spanned cells
19614 if (isset($dom[$table_el]['rowspans'])) {
19615 foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
19616 $dom[$table_el]['rowspans'][$k]['rowspan'] -= 1;
19617 if ($dom[$table_el]['rowspans'][$k]['rowspan'] == 0) {
19618 if (($dom[$table_el]['rowspans'][$k]['endpage'] == $parent['endpage']) AND ($dom[$table_el]['rowspans'][$k]['endcolumn'] == $parent['endcolumn'])) {
19619 $dom[($dom[$key]['parent'])]['endy'] = max($dom[$table_el]['rowspans'][$k]['endy'], $parent['endy']);
19620 } elseif (($dom[$table_el]['rowspans'][$k]['endpage'] > $parent['endpage']) OR ($dom[$table_el]['rowspans'][$k]['endcolumn'] > $parent['endcolumn'])) {
19621 $dom[($dom[$key]['parent'])]['endy'] = $dom[$table_el]['rowspans'][$k]['endy'];
19622 $dom[($dom[$key]['parent'])]['endpage'] = $dom[$table_el]['rowspans'][$k]['endpage'];
19623 $dom[($dom[$key]['parent'])]['endcolumn'] = $dom[$table_el]['rowspans'][$k]['endcolumn'];
19627 // report new endy and endpage to the rowspanned cells
19628 foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
19629 if ($dom[$table_el]['rowspans'][$k]['rowspan'] == 0) {
19630 $dom[$table_el]['rowspans'][$k]['endpage'] = max($dom[$table_el]['rowspans'][$k]['endpage'], $dom[($dom[$key]['parent'])]['endpage']);
19631 $dom[($dom[$key]['parent'])]['endpage'] = $dom[$table_el]['rowspans'][$k]['endpage'];
19632 $dom[$table_el]['rowspans'][$k]['endcolumn'] = max($dom[$table_el]['rowspans'][$k]['endcolumn'], $dom[($dom[$key]['parent'])]['endcolumn']);
19633 $dom[($dom[$key]['parent'])]['endcolumn'] = $dom[$table_el]['rowspans'][$k]['endcolumn'];
19634 $dom[$table_el]['rowspans'][$k]['endy'] = max($dom[$table_el]['rowspans'][$k]['endy'], $dom[($dom[$key]['parent'])]['endy']);
19635 $dom[($dom[$key]['parent'])]['endy'] = $dom[$table_el]['rowspans'][$k]['endy'];
19638 // update remaining rowspanned cells
19639 foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
19640 if ($dom[$table_el]['rowspans'][$k]['rowspan'] == 0) {
19641 $dom[$table_el]['rowspans'][$k]['endpage'] = $dom[($dom[$key]['parent'])]['endpage'];
19642 $dom[$table_el]['rowspans'][$k]['endcolumn'] = $dom[($dom[$key]['parent'])]['endcolumn'];
19643 $dom[$table_el]['rowspans'][$k]['endy'] = $dom[($dom[$key]['parent'])]['endy'];
19647 $prev_page = $this->page
;
19648 $this->setPage($dom[($dom[$key]['parent'])]['endpage']);
19649 if ($this->num_columns
> 1) {
19650 if (($prev_page < $this->page
)
19651 AND ((($this->current_column
== 0) AND ($dom[($dom[$key]['parent'])]['endcolumn'] == ($this->num_columns
- 1)))
19652 OR ($this->current_column
== $dom[($dom[$key]['parent'])]['endcolumn']))) {
19654 $this->selectColumn(0);
19655 $dom[($dom[$key]['parent'])]['endcolumn'] = 0;
19656 $dom[($dom[$key]['parent'])]['endy'] = $this->y
;
19658 $this->selectColumn($dom[($dom[$key]['parent'])]['endcolumn']);
19659 $this->y
= $dom[($dom[$key]['parent'])]['endy'];
19662 $this->y
= $dom[($dom[$key]['parent'])]['endy'];
19664 if (isset($dom[$table_el]['attribute']['cellspacing'])) {
19665 $this->y +
= $this->getHTMLUnitToUnits($dom[$table_el]['attribute']['cellspacing'], 1, 'px');
19666 } elseif (isset($dom[$table_el]['border-spacing'])) {
19667 $this->y +
= $dom[$table_el]['border-spacing']['V'];
19669 $this->Ln(0, $cell);
19670 if ($this->current_column
== $parent['startcolumn']) {
19671 $this->x
= $parent['startx'];
19673 // account for booklet mode
19674 if ($this->page
> $parent['startpage']) {
19675 if (($this->rtl
) AND ($this->pagedim
[$this->page
]['orm'] != $this->pagedim
[$parent['startpage']]['orm'])) {
19676 $this->x
-= ($this->pagedim
[$this->page
]['orm'] - $this->pagedim
[$parent['startpage']]['orm']);
19677 } elseif ((!$this->rtl
) AND ($this->pagedim
[$this->page
]['olm'] != $this->pagedim
[$parent['startpage']]['olm'])) {
19678 $this->x +
= ($this->pagedim
[$this->page
]['olm'] - $this->pagedim
[$parent['startpage']]['olm']);
19684 // closing tag used for the thead part
19685 $in_table_head = true;
19686 $this->inthead
= false;
19688 $table_el = $parent;
19689 // set default border
19690 if (isset($table_el['attribute']['border']) AND ($table_el['attribute']['border'] > 0)) {
19691 // set default border
19692 $border = array('LTRB' => array('width' => $this->getCSSBorderWidth($table_el['attribute']['border']), 'cap'=>'square', 'join'=>'miter', 'dash'=> 0, 'color'=>array(0,0,0)));
19696 $default_border = $border;
19697 // fix bottom line alignment of last line before page break
19698 foreach ($dom[($dom[$key]['parent'])]['trids'] as $j => $trkey) {
19699 // update row-spanned cells
19700 if (isset($dom[($dom[$key]['parent'])]['rowspans'])) {
19701 foreach ($dom[($dom[$key]['parent'])]['rowspans'] as $k => $trwsp) {
19702 if (isset($prevtrkey) AND ($trwsp['trid'] == $prevtrkey) AND ($trwsp['mrowspan'] > 0)) {
19703 $dom[($dom[$key]['parent'])]['rowspans'][$k]['trid'] = $trkey;
19705 if ($dom[($dom[$key]['parent'])]['rowspans'][$k]['trid'] == $trkey) {
19706 $dom[($dom[$key]['parent'])]['rowspans'][$k]['mrowspan'] -= 1;
19710 if (isset($prevtrkey) AND ($dom[$trkey]['startpage'] > $dom[$prevtrkey]['endpage'])) {
19711 $pgendy = $this->pagedim
[$dom[$prevtrkey]['endpage']]['hk'] - $this->pagedim
[$dom[$prevtrkey]['endpage']]['bm'];
19712 $dom[$prevtrkey]['endy'] = $pgendy;
19713 // update row-spanned cells
19714 if (isset($dom[($dom[$key]['parent'])]['rowspans'])) {
19715 foreach ($dom[($dom[$key]['parent'])]['rowspans'] as $k => $trwsp) {
19716 if (($trwsp['trid'] == $prevtrkey) AND ($trwsp['mrowspan'] >= 0) AND ($trwsp['endpage'] == $dom[$prevtrkey]['endpage'])) {
19717 $dom[($dom[$key]['parent'])]['rowspans'][$k]['endy'] = $pgendy;
19718 $dom[($dom[$key]['parent'])]['rowspans'][$k]['mrowspan'] = -1;
19723 $prevtrkey = $trkey;
19724 $table_el = $dom[($dom[$key]['parent'])];
19727 if (!empty($table_el['trids'])) {
19730 foreach ($table_el['trids'] as $j => $trkey) {
19731 $parent = $dom[$trkey];
19732 if (!isset($xmax)) {
19733 $xmax = $parent['cellpos'][(count($parent['cellpos']) - 1)]['endx'];
19735 // for each cell on the row
19736 foreach ($parent['cellpos'] as $k => $cellpos) {
19737 if (isset($cellpos['rowspanid']) AND ($cellpos['rowspanid'] >= 0)) {
19738 $cellpos['startx'] = $table_el['rowspans'][($cellpos['rowspanid'])]['startx'];
19739 $cellpos['endx'] = $table_el['rowspans'][($cellpos['rowspanid'])]['endx'];
19740 $endy = $table_el['rowspans'][($cellpos['rowspanid'])]['endy'];
19741 $startpage = $table_el['rowspans'][($cellpos['rowspanid'])]['startpage'];
19742 $endpage = $table_el['rowspans'][($cellpos['rowspanid'])]['endpage'];
19743 $startcolumn = $table_el['rowspans'][($cellpos['rowspanid'])]['startcolumn'];
19744 $endcolumn = $table_el['rowspans'][($cellpos['rowspanid'])]['endcolumn'];
19746 $endy = $parent['endy'];
19747 $startpage = $parent['startpage'];
19748 $endpage = $parent['endpage'];
19749 $startcolumn = $parent['startcolumn'];
19750 $endcolumn = $parent['endcolumn'];
19752 if ($this->num_columns
== 0) {
19753 $this->num_columns
= 1;
19755 if (isset($cellpos['border'])) {
19756 $border = $cellpos['border'];
19758 if (isset($cellpos['bgcolor']) AND ($cellpos['bgcolor']) !== false) {
19759 $this->setFillColorArray($cellpos['bgcolor']);
19764 $x = $cellpos['startx'];
19765 $y = $parent['starty'];
19767 $w = abs($cellpos['endx'] - $cellpos['startx']);
19768 // get border modes
19769 $border_start = TCPDF_STATIC
::getBorderMode($border, $position='start', $this->opencell
);
19770 $border_end = TCPDF_STATIC
::getBorderMode($border, $position='end', $this->opencell
);
19771 $border_middle = TCPDF_STATIC
::getBorderMode($border, $position='middle', $this->opencell
);
19772 // design borders around HTML cells.
19773 for ($page = $startpage; $page <= $endpage; ++
$page) { // for each page
19775 $this->setPage($page);
19776 if ($this->num_columns
< 2) {
19777 // single-column mode
19779 $this->y
= $this->tMargin
;
19781 // account for margin changes
19782 if ($page > $startpage) {
19783 if (($this->rtl
) AND ($this->pagedim
[$page]['orm'] != $this->pagedim
[$startpage]['orm'])) {
19784 $this->x
-= ($this->pagedim
[$page]['orm'] - $this->pagedim
[$startpage]['orm']);
19785 } elseif ((!$this->rtl
) AND ($this->pagedim
[$page]['olm'] != $this->pagedim
[$startpage]['olm'])) {
19786 $this->x +
= ($this->pagedim
[$page]['olm'] - $this->pagedim
[$startpage]['olm']);
19789 if ($startpage == $endpage) { // single page
19792 for ($column = $startcolumn; $column <= $endcolumn; ++
$column) { // for each column
19793 $this->selectColumn($column);
19794 if ($startcolumn == $endcolumn) { // single column
19795 $cborder = $border;
19796 $h = $endy - $parent['starty'];
19799 } elseif ($column == $startcolumn) { // first column
19800 $cborder = $border_start;
19801 $this->y
= $starty;
19803 $h = $this->h
- $this->y
- $this->bMargin
;
19805 $deltacol = $this->x +
$this->rMargin
- $this->w
;
19807 $deltacol = $this->x
- $this->lMargin
;
19809 } elseif ($column == $endcolumn) { // end column
19810 $cborder = $border_end;
19811 if (isset($this->columns
[$column]['th']['\''.$page.'\''])) {
19812 $this->y
= $this->columns
[$column]['th']['\''.$page.'\''];
19814 $this->x +
= $deltacol;
19815 $h = $endy - $this->y
;
19816 } else { // middle column
19817 $cborder = $border_middle;
19818 if (isset($this->columns
[$column]['th']['\''.$page.'\''])) {
19819 $this->y
= $this->columns
[$column]['th']['\''.$page.'\''];
19821 $this->x +
= $deltacol;
19822 $h = $this->h
- $this->y
- $this->bMargin
;
19824 $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
19825 } // end for each column
19826 } elseif ($page == $startpage) { // first page
19829 for ($column = $startcolumn; $column < $this->num_columns
; ++
$column) { // for each column
19830 $this->selectColumn($column);
19831 if ($column == $startcolumn) { // first column
19832 $cborder = $border_start;
19833 $this->y
= $starty;
19835 $h = $this->h
- $this->y
- $this->bMargin
;
19837 $deltacol = $this->x +
$this->rMargin
- $this->w
;
19839 $deltacol = $this->x
- $this->lMargin
;
19841 } else { // middle column
19842 $cborder = $border_middle;
19843 if (isset($this->columns
[$column]['th']['\''.$page.'\''])) {
19844 $this->y
= $this->columns
[$column]['th']['\''.$page.'\''];
19846 $this->x +
= $deltacol;
19847 $h = $this->h
- $this->y
- $this->bMargin
;
19849 $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
19850 } // end for each column
19851 } elseif ($page == $endpage) { // last page
19854 for ($column = 0; $column <= $endcolumn; ++
$column) { // for each column
19855 $this->selectColumn($column);
19856 if ($column == $endcolumn) { // end column
19857 $cborder = $border_end;
19858 if (isset($this->columns
[$column]['th']['\''.$page.'\''])) {
19859 $this->y
= $this->columns
[$column]['th']['\''.$page.'\''];
19861 $this->x +
= $deltacol;
19862 $h = $endy - $this->y
;
19863 } else { // middle column
19864 $cborder = $border_middle;
19865 if (isset($this->columns
[$column]['th']['\''.$page.'\''])) {
19866 $this->y
= $this->columns
[$column]['th']['\''.$page.'\''];
19868 $this->x +
= $deltacol;
19869 $h = $this->h
- $this->y
- $this->bMargin
;
19871 $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
19872 } // end for each column
19873 } else { // middle page
19876 for ($column = 0; $column < $this->num_columns
; ++
$column) { // for each column
19877 $this->selectColumn($column);
19878 $cborder = $border_middle;
19879 if (isset($this->columns
[$column]['th']['\''.$page.'\''])) {
19880 $this->y
= $this->columns
[$column]['th']['\''.$page.'\''];
19882 $this->x +
= $deltacol;
19883 $h = $this->h
- $this->y
- $this->bMargin
;
19884 $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
19885 } // end for each column
19887 if (!empty($cborder) OR !empty($fill)) {
19888 $offsetlen = strlen($ccode);
19889 // draw border and fill
19890 if ($this->inxobj
) {
19891 // we are inside an XObject template
19892 if (end($this->xobjects
[$this->xobjid
]['transfmrk']) !== false) {
19893 $pagemarkkey = key($this->xobjects
[$this->xobjid
]['transfmrk']);
19894 $pagemark = $this->xobjects
[$this->xobjid
]['transfmrk'][$pagemarkkey];
19895 $this->xobjects
[$this->xobjid
]['transfmrk'][$pagemarkkey] +
= $offsetlen;
19897 $pagemark = $this->xobjects
[$this->xobjid
]['intmrk'];
19898 $this->xobjects
[$this->xobjid
]['intmrk'] +
= $offsetlen;
19900 $pagebuff = $this->xobjects
[$this->xobjid
]['outdata'];
19901 $pstart = substr($pagebuff, 0, $pagemark);
19902 $pend = substr($pagebuff, $pagemark);
19903 $this->xobjects
[$this->xobjid
]['outdata'] = $pstart.$ccode.$pend;
19905 // draw border and fill
19906 if (end($this->transfmrk
[$this->page
]) !== false) {
19907 $pagemarkkey = key($this->transfmrk
[$this->page
]);
19908 $pagemark = $this->transfmrk
[$this->page
][$pagemarkkey];
19909 } elseif ($this->InFooter
) {
19910 $pagemark = $this->footerpos
[$this->page
];
19912 $pagemark = $this->intmrk
[$this->page
];
19914 $pagebuff = $this->getPageBuffer($this->page
);
19915 $pstart = substr($pagebuff, 0, $pagemark);
19916 $pend = substr($pagebuff, $pagemark);
19917 $this->setPageBuffer($this->page
, $pstart.$ccode.$pend);
19920 } // end for each page
19921 // restore default border
19922 $border = $default_border;
19923 } // end for each cell on the row
19924 if (isset($table_el['attribute']['cellspacing'])) {
19925 $this->y +
= $this->getHTMLUnitToUnits($table_el['attribute']['cellspacing'], 1, 'px');
19926 } elseif (isset($table_el['border-spacing'])) {
19927 $this->y +
= $table_el['border-spacing']['V'];
19929 $this->Ln(0, $cell);
19930 $this->x
= $parent['startx'];
19931 if ($endpage > $startpage) {
19932 if (($this->rtl
) AND ($this->pagedim
[$endpage]['orm'] != $this->pagedim
[$startpage]['orm'])) {
19933 $this->x +
= ($this->pagedim
[$endpage]['orm'] - $this->pagedim
[$startpage]['orm']);
19934 } elseif ((!$this->rtl
) AND ($this->pagedim
[$endpage]['olm'] != $this->pagedim
[$startpage]['olm'])) {
19935 $this->x +
= ($this->pagedim
[$endpage]['olm'] - $this->pagedim
[$startpage]['olm']);
19939 if (!$in_table_head) { // we are not inside a thead section
19940 $this->cell_padding
= isset($table_el['old_cell_padding']) ?
$table_el['old_cell_padding'] : null;
19941 // reset row height
19942 $this->resetLastH();
19943 if (($this->page
== ($this->numpages
- 1)) AND ($this->pageopen
[$this->numpages
])) {
19944 $plendiff = ($this->pagelen
[$this->numpages
] - $this->emptypagemrk
[$this->numpages
]);
19945 if (($plendiff > 0) AND ($plendiff < 60)) {
19946 $pagediff = substr($this->getPageBuffer($this->numpages
), $this->emptypagemrk
[$this->numpages
], $plendiff);
19947 if (substr($pagediff, 0, 5) == 'BT /F') {
19948 // the difference is only a font setting
19952 if ($plendiff == 0) {
19953 // remove last blank page
19954 $this->deletePage($this->numpages
);
19957 if (isset($this->theadMargins
['top'])) {
19958 // restore top margin
19959 $this->tMargin
= $this->theadMargins
['top'];
19961 if (!isset($table_el['attribute']['nested']) OR ($table_el['attribute']['nested'] != 'true')) {
19962 // reset main table header
19964 $this->theadMargins
= array();
19965 $this->pagedim
[$this->page
]['tm'] = $this->tMargin
;
19968 $parent = $table_el;
19972 $this->HREF
= array();
19976 $this->setXY($this->GetX(), $this->GetY() +
((0.7 * $parent['fontsize']) / $this->k
));
19980 $this->setXY($this->GetX(), $this->GetY() - ((0.3 * $parent['fontsize']) / $this->k
));
19984 $this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
19987 case 'blockquote': {
19989 $this->rMargin
-= $this->listindent
;
19991 $this->lMargin
-= $this->listindent
;
19993 --$this->listindentlevel
;
19994 $this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
19998 $this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
20002 $this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
20003 $this->premode
= false;
20008 if ($this->listnum
<= 0) {
20009 $this->listnum
= 0;
20010 $this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
20012 $this->addHTMLVertSpace(0, 0, $cell, false, $lasttag);
20014 $this->resetLastH();
20018 $this->lispacer
= '';
20019 $this->addHTMLVertSpace(0, 0, $cell, false, $lasttag);
20023 $this->lispacer
= '';
20025 $this->rMargin
-= $this->listindent
;
20027 $this->lMargin
-= $this->listindent
;
20029 --$this->listindentlevel
;
20030 $this->addHTMLVertSpace(0, 0, $cell, false, $lasttag);
20036 $this->lispacer
= '';
20038 $this->rMargin
-= $this->listindent
;
20040 $this->lMargin
-= $this->listindent
;
20042 --$this->listindentlevel
;
20043 if ($this->listnum
<= 0) {
20044 $this->listnum
= 0;
20045 $this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
20047 $this->addHTMLVertSpace(0, 0, $cell, false, $lasttag);
20049 $this->resetLastH();
20053 $this->lispacer
= '';
20054 $this->addHTMLVertSpace(0, 0, $cell, false, $lasttag);
20063 $this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
20066 // Form fields (since 4.8.000 - 2009-09-07)
20068 $this->form_action
= '';
20069 $this->form_enctype
= 'application/x-www-form-urlencoded';
20076 // draw border and background (if any)
20077 $this->drawHTMLTagBorder($parent, $xmax);
20078 if (isset($dom[($dom[$key]['parent'])]['attribute']['pagebreakafter'])) {
20079 $pba = $dom[($dom[$key]['parent'])]['attribute']['pagebreakafter'];
20080 // check for pagebreak
20081 if (($pba == 'true') OR ($pba == 'left') OR ($pba == 'right')) {
20082 // add a page (or trig AcceptPageBreak() for multicolumn mode)
20083 $this->checkPageBreak($this->PageBreakTrigger +
1);
20085 if ((($pba == 'left') AND (((!$this->rtl
) AND (($this->page %
2) == 0)) OR (($this->rtl
) AND (($this->page %
2) != 0))))
20086 OR (($pba == 'right') AND (((!$this->rtl
) AND (($this->page %
2) != 0)) OR (($this->rtl
) AND (($this->page %
2) == 0))))) {
20087 // add a page (or trig AcceptPageBreak() for multicolumn mode)
20088 $this->checkPageBreak($this->PageBreakTrigger +
1);
20091 $this->tmprtl
= false;
20096 * Add vertical spaces if needed.
20097 * @param string $hbz Distance between current y and line bottom.
20098 * @param string $hb The height of the break.
20099 * @param boolean $cell if true add the default left (or right if RTL) padding to each new line (default false).
20100 * @param boolean $firsttag set to true when the tag is the first.
20101 * @param boolean $lasttag set to true when the tag is the last.
20104 protected function addHTMLVertSpace($hbz=0, $hb=0, $cell=false, $firsttag=false, $lasttag=false) {
20106 $this->Ln(0, $cell);
20107 $this->htmlvspace
= 0;
20111 $this->Ln($hbz, $cell);
20112 $this->htmlvspace
= 0;
20115 if ($hb < $this->htmlvspace
) {
20118 $hd = $hb - $this->htmlvspace
;
20119 $this->htmlvspace
= $hb;
20121 $this->Ln(($hbz +
$hd), $cell);
20125 * Return the starting coordinates to draw an html border
20126 * @return array containing top-left border coordinates
20128 * @since 5.7.000 (2010-08-03)
20130 protected function getBorderStartPosition() {
20132 $xmax = $this->lMargin
;
20134 $xmax = $this->w
- $this->rMargin
;
20136 return array('page' => $this->page
, 'column' => $this->current_column
, 'x' => $this->x
, 'y' => $this->y
, 'xmax' => $xmax);
20140 * Draw an HTML block border and fill
20141 * @param array $tag array of tag properties.
20142 * @param int $xmax end X coordinate for border.
20144 * @since 5.7.000 (2010-08-03)
20146 protected function drawHTMLTagBorder($tag, $xmax) {
20147 if (!isset($tag['borderposition'])) {
20151 $prev_x = $this->x
;
20152 $prev_y = $this->y
;
20153 $prev_lasth = $this->lasth
;
20157 if (isset($tag['border']) AND !empty($tag['border'])) {
20158 // get border style
20159 $border = $tag['border'];
20160 if (!TCPDF_STATIC
::empty_string($this->thead
) AND (!$this->inthead
)) {
20161 // border for table header
20162 $border = TCPDF_STATIC
::getBorderMode($border, $position='middle', $this->opencell
);
20165 if (isset($tag['bgcolor']) AND ($tag['bgcolor'] !== false)) {
20166 // get background color
20167 $old_bgcolor = $this->bgcolor
;
20168 $this->setFillColorArray($tag['bgcolor']);
20171 if (!$border AND !$fill) {
20175 if (isset($tag['attribute']['cellspacing'])) {
20176 $clsp = $this->getHTMLUnitToUnits($tag['attribute']['cellspacing'], 1, 'px');
20177 $cellspacing = array('H' => $clsp, 'V' => $clsp);
20178 } elseif (isset($tag['border-spacing'])) {
20179 $cellspacing = $tag['border-spacing'];
20181 $cellspacing = array('H' => 0, 'V' => 0);
20183 if (($tag['value'] != 'table') AND (is_array($border)) AND (!empty($border))) {
20184 // draw the border externally respect the sqare edge.
20185 $border['mode'] = 'ext';
20188 if ($xmax >= $tag['borderposition']['x']) {
20189 $xmax = $tag['borderposition']['xmax'];
20191 $w = ($tag['borderposition']['x'] - $xmax);
20193 if ($xmax <= $tag['borderposition']['x']) {
20194 $xmax = $tag['borderposition']['xmax'];
20196 $w = ($xmax - $tag['borderposition']['x']);
20201 $w +
= $cellspacing['H'];
20202 $startpage = $tag['borderposition']['page'];
20203 $startcolumn = $tag['borderposition']['column'];
20204 $x = $tag['borderposition']['x'];
20205 $y = $tag['borderposition']['y'];
20206 $endpage = $this->page
;
20207 $starty = $tag['borderposition']['y'] - $cellspacing['V'];
20208 $currentY = $this->y
;
20210 // get latest column
20211 $endcolumn = $this->current_column
;
20212 if ($this->num_columns
== 0) {
20213 $this->num_columns
= 1;
20215 // get border modes
20216 $border_start = TCPDF_STATIC
::getBorderMode($border, $position='start', $this->opencell
);
20217 $border_end = TCPDF_STATIC
::getBorderMode($border, $position='end', $this->opencell
);
20218 $border_middle = TCPDF_STATIC
::getBorderMode($border, $position='middle', $this->opencell
);
20219 // temporary disable page regions
20220 $temp_page_regions = $this->page_regions
;
20221 $this->page_regions
= array();
20222 // design borders around HTML cells.
20223 for ($page = $startpage; $page <= $endpage; ++
$page) { // for each page
20225 $this->setPage($page);
20226 if ($this->num_columns
< 2) {
20227 // single-column mode
20229 $this->y
= $this->tMargin
;
20231 // account for margin changes
20232 if ($page > $startpage) {
20233 if (($this->rtl
) AND ($this->pagedim
[$page]['orm'] != $this->pagedim
[$startpage]['orm'])) {
20234 $this->x
-= ($this->pagedim
[$page]['orm'] - $this->pagedim
[$startpage]['orm']);
20235 } elseif ((!$this->rtl
) AND ($this->pagedim
[$page]['olm'] != $this->pagedim
[$startpage]['olm'])) {
20236 $this->x +
= ($this->pagedim
[$page]['olm'] - $this->pagedim
[$startpage]['olm']);
20239 if ($startpage == $endpage) {
20241 for ($column = $startcolumn; $column <= $endcolumn; ++
$column) { // for each column
20242 $this->selectColumn($column);
20243 if ($startcolumn == $endcolumn) { // single column
20244 $cborder = $border;
20245 $h = ($currentY - $y) +
$cellspacing['V'];
20246 $this->y
= $starty;
20247 } elseif ($column == $startcolumn) { // first column
20248 $cborder = $border_start;
20249 $this->y
= $starty;
20250 $h = $this->h
- $this->y
- $this->bMargin
;
20251 } elseif ($column == $endcolumn) { // end column
20252 $cborder = $border_end;
20253 $h = $currentY - $this->y
;
20254 } else { // middle column
20255 $cborder = $border_middle;
20256 $h = $this->h
- $this->y
- $this->bMargin
;
20258 $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
20259 } // end for each column
20260 } elseif ($page == $startpage) { // first page
20261 for ($column = $startcolumn; $column < $this->num_columns
; ++
$column) { // for each column
20262 $this->selectColumn($column);
20263 if ($column == $startcolumn) { // first column
20264 $cborder = $border_start;
20265 $this->y
= $starty;
20266 $h = $this->h
- $this->y
- $this->bMargin
;
20267 } else { // middle column
20268 $cborder = $border_middle;
20269 $h = $this->h
- $this->y
- $this->bMargin
;
20271 $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
20272 } // end for each column
20273 } elseif ($page == $endpage) { // last page
20274 for ($column = 0; $column <= $endcolumn; ++
$column) { // for each column
20275 $this->selectColumn($column);
20276 if ($column == $endcolumn) {
20278 $cborder = $border_end;
20279 $h = $currentY - $this->y
;
20282 $cborder = $border_middle;
20283 $h = $this->h
- $this->y
- $this->bMargin
;
20285 $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
20286 } // end for each column
20287 } else { // middle page
20288 for ($column = 0; $column < $this->num_columns
; ++
$column) { // for each column
20289 $this->selectColumn($column);
20290 $cborder = $border_middle;
20291 $h = $this->h
- $this->y
- $this->bMargin
;
20292 $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
20293 } // end for each column
20295 if ($cborder OR $fill) {
20296 $offsetlen = strlen($ccode);
20297 // draw border and fill
20298 if ($this->inxobj
) {
20299 // we are inside an XObject template
20300 if (end($this->xobjects
[$this->xobjid
]['transfmrk']) !== false) {
20301 $pagemarkkey = key($this->xobjects
[$this->xobjid
]['transfmrk']);
20302 $pagemark = $this->xobjects
[$this->xobjid
]['transfmrk'][$pagemarkkey];
20303 $this->xobjects
[$this->xobjid
]['transfmrk'][$pagemarkkey] +
= $offsetlen;
20305 $pagemark = $this->xobjects
[$this->xobjid
]['intmrk'];
20306 $this->xobjects
[$this->xobjid
]['intmrk'] +
= $offsetlen;
20308 $pagebuff = $this->xobjects
[$this->xobjid
]['outdata'];
20309 $pstart = substr($pagebuff, 0, $pagemark);
20310 $pend = substr($pagebuff, $pagemark);
20311 $this->xobjects
[$this->xobjid
]['outdata'] = $pstart.$ccode.$pend;
20313 if (end($this->transfmrk
[$this->page
]) !== false) {
20314 $pagemarkkey = key($this->transfmrk
[$this->page
]);
20315 $pagemark = $this->transfmrk
[$this->page
][$pagemarkkey];
20316 } elseif ($this->InFooter
) {
20317 $pagemark = $this->footerpos
[$this->page
];
20319 $pagemark = $this->intmrk
[$this->page
];
20321 $pagebuff = $this->getPageBuffer($this->page
);
20322 $pstart = substr($pagebuff, 0, $pagemark);
20323 $pend = substr($pagebuff, $pagemark);
20324 $this->setPageBuffer($this->page
, $pstart.$ccode.$pend);
20325 $this->bordermrk
[$this->page
] +
= $offsetlen;
20326 $this->cntmrk
[$this->page
] +
= $offsetlen;
20329 } // end for each page
20330 // restore page regions
20331 $this->page_regions
= $temp_page_regions;
20332 if (isset($old_bgcolor)) {
20333 // restore background color
20334 $this->setFillColorArray($old_bgcolor);
20336 // restore pointer position
20337 $this->x
= $prev_x;
20338 $this->y
= $prev_y;
20339 $this->lasth
= $prev_lasth;
20343 * Set the default bullet to be used as LI bullet symbol
20344 * @param string $symbol 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')
20346 * @since 4.0.028 (2008-09-26)
20348 public function setLIsymbol($symbol='!') {
20349 // check for custom image symbol
20350 if (substr($symbol, 0, 4) == 'img|') {
20351 $this->lisymbol
= $symbol;
20354 $symbol = strtolower($symbol);
20355 $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');
20356 if (in_array($symbol, $valid_symbols)) {
20357 $this->lisymbol
= $symbol;
20359 $this->lisymbol
= '';
20364 * Set the booklet mode for double-sided pages.
20365 * @param boolean $booklet true set the booklet mode on, false otherwise.
20366 * @param float $inner Inner page margin.
20367 * @param float $outer Outer page margin.
20369 * @since 4.2.000 (2008-10-29)
20371 public function setBooklet($booklet=true, $inner=-1, $outer=-1) {
20372 $this->booklet
= $booklet;
20374 $this->lMargin
= $inner;
20377 $this->rMargin
= $outer;
20382 * Swap the left and right margins.
20383 * @param boolean $reverse if true swap left and right margins.
20385 * @since 4.2.000 (2008-10-29)
20387 protected function swapMargins($reverse=true) {
20389 // swap left and right margins
20390 $mtemp = $this->original_lMargin
;
20391 $this->original_lMargin
= $this->original_rMargin
;
20392 $this->original_rMargin
= $mtemp;
20393 $deltam = $this->original_lMargin
- $this->original_rMargin
;
20394 $this->lMargin +
= $deltam;
20395 $this->rMargin
-= $deltam;
20400 * Set the vertical spaces for HTML tags.
20401 * The array must have the following structure (example):
20402 * $tagvs = array('h1' => array(0 => array('h' => '', 'n' => 2), 1 => array('h' => 1.3, 'n' => 1)));
20403 * The first array level contains the tag names,
20404 * the second level contains 0 for opening tags or 1 for closing tags,
20405 * the third level contains the vertical space unit (h) and the number spaces to add (n).
20406 * If the h parameter is not specified, default values are used.
20407 * @param array $tagvs array of tags and relative vertical spaces.
20409 * @since 4.2.001 (2008-10-30)
20411 public function setHtmlVSpace($tagvs) {
20412 $this->tagvspaces
= $tagvs;
20416 * Set custom width for list indentation.
20417 * @param float $width width of the indentation. Use negative value to disable it.
20419 * @since 4.2.007 (2008-11-12)
20421 public function setListIndentWidth($width) {
20422 return $this->customlistindent
= floatval($width);
20426 * Set the top/bottom cell sides to be open or closed when the cell cross the page.
20427 * @param boolean $isopen if true keeps the top/bottom border open for the cell sides that cross the page.
20429 * @since 4.2.010 (2008-11-14)
20431 public function setOpenCell($isopen) {
20432 $this->opencell
= $isopen;
20436 * Set the color and font style for HTML links.
20437 * @param array $color RGB array of colors
20438 * @param string $fontstyle additional font styles to add
20440 * @since 4.4.003 (2008-12-09)
20442 public function setHtmlLinksStyle($color=array(0,0,255), $fontstyle='U') {
20443 $this->htmlLinkColorArray
= $color;
20444 $this->htmlLinkFontStyle
= $fontstyle;
20448 * Convert HTML string containing value and unit of measure to user's units or points.
20449 * @param string $htmlval String containing values and unit.
20450 * @param string $refsize Reference value in points.
20451 * @param string $defaultunit Default unit (can be one of the following: %, em, ex, px, in, mm, pc, pt).
20452 * @param boolean $points If true returns points, otherwise returns value in user's units.
20453 * @return float value in user's unit or point if $points=true
20455 * @since 4.4.004 (2008-12-10)
20457 public function getHTMLUnitToUnits($htmlval, $refsize=1, $defaultunit='px', $points=false) {
20458 $supportedunits = array('%', 'em', 'ex', 'px', 'in', 'cm', 'mm', 'pc', 'pt');
20467 if (in_array($defaultunit, $supportedunits)) {
20468 $unit = $defaultunit;
20470 if (is_numeric($htmlval)) {
20471 $value = floatval($htmlval);
20472 } elseif (preg_match('/([0-9\.\-\+]+)/', $htmlval, $mnum)) {
20473 $value = floatval($mnum[1]);
20474 if (preg_match('/([a-z%]+)/', $htmlval, $munit)) {
20475 if (in_array($munit[1], $supportedunits)) {
20483 $retval = (($value * $refsize) / 100);
20488 $retval = ($value * $refsize);
20491 // height of lower case 'x' (about half the font-size)
20493 $retval = ($value * ($refsize / 2));
20498 $retval = (($value * $this->dpi
) / $k);
20503 $retval = (($value / 2.54 * $this->dpi
) / $k);
20508 $retval = (($value / 25.4 * $this->dpi
) / $k);
20511 // one pica is 12 points
20513 $retval = (($value * 12) / $k);
20518 $retval = ($value / $k);
20523 $retval = $this->pixelsToUnits($value);
20525 $retval *= $this->k
;
20534 * Output an HTML list bullet or ordered item symbol
20535 * @param int $listdepth list nesting level
20536 * @param string $listtype type of list
20537 * @param float $size current font size
20539 * @since 4.4.004 (2008-12-10)
20541 protected function putHtmlListBullet($listdepth, $listtype='', $size=10) {
20542 if ($this->state
!= 2) {
20547 $bgcolor = $this->bgcolor
;
20548 $color = $this->fgcolor
;
20549 $strokecolor = $this->strokecolor
;
20553 $lspace = $this->GetStringWidth(' ');
20554 if ($listtype == '^') {
20555 // special symbol used for avoid justification of rect bullet
20556 $this->lispacer
= '';
20558 } elseif ($listtype == '!') {
20559 // set default list type for unordered list
20560 $deftypes = array('disc', 'circle', 'square');
20561 $listtype = $deftypes[($listdepth - 1) %
3];
20562 } elseif ($listtype == '#') {
20563 // set default list type for ordered list
20564 $listtype = 'decimal';
20565 } elseif (substr($listtype, 0, 4) == 'img|') {
20566 // custom image type ('img|type|width|height|image.ext')
20567 $img = explode('|', $listtype);
20570 switch ($listtype) {
20577 $lspace +
= (2 * $r);
20579 $this->x +
= $lspace;
20581 $this->x
-= $lspace;
20583 $this->Circle(($this->x +
$r), ($this->y +
($this->lasth
/ 2)), $r, 0, 360, 'F', array(), $color, 8);
20588 $lspace +
= (2 * $r);
20590 $this->x +
= $lspace;
20592 $this->x
-= $lspace;
20594 $prev_line_style = $this->linestyleWidth
.' '.$this->linestyleCap
.' '.$this->linestyleJoin
.' '.$this->linestyleDash
.' '.$this->DrawColor
;
20595 $new_line_style = array('width' => ($r / 3), 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'phase' => 0, 'color'=>$color);
20596 $this->Circle(($this->x +
$r), ($this->y +
($this->lasth
/ 2)), ($r * (1 - (1/6))), 0, 360, 'D', $new_line_style, array(), 8);
20597 $this->_out($prev_line_style); // restore line settings
20604 $this->x +
= $lspace;
20606 $this->x
-= $lspace;
20608 $this->Rect($this->x
, ($this->y +
(($this->lasth
- $l) / 2)), $l, $l, 'F', array(), $color);
20612 // 1=>type, 2=>width, 3=>height, 4=>image.ext
20613 $lspace +
= $img[2];
20615 $this->x +
= $lspace;
20617 $this->x
-= $lspace;
20619 $imgtype = strtolower($img[1]);
20620 $prev_y = $this->y
;
20621 switch ($imgtype) {
20623 $this->ImageSVG($img[4], $this->x
, ($this->y +
(($this->lasth
- $img[3]) / 2)), $img[2], $img[3], '', 'T', '', 0, false);
20628 $this->ImageEps($img[4], $this->x
, ($this->y +
(($this->lasth
- $img[3]) / 2)), $img[2], $img[3], '', true, 'T', '', 0, false);
20632 $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);
20636 $this->y
= $prev_y;
20640 // $this->listcount[$this->listnum];
20644 $textitem = $this->listcount
[$this->listnum
];
20647 case 'decimal-leading-zero': {
20648 $textitem = sprintf('%02d', $this->listcount
[$this->listnum
]);
20652 case 'lower-roman': {
20653 $textitem = strtolower(TCPDF_STATIC
::intToRoman($this->listcount
[$this->listnum
]));
20657 case 'upper-roman': {
20658 $textitem = TCPDF_STATIC
::intToRoman($this->listcount
[$this->listnum
]);
20662 case 'lower-alpha':
20663 case 'lower-latin': {
20664 $textitem = chr(97 +
$this->listcount
[$this->listnum
] - 1);
20668 case 'upper-alpha':
20669 case 'upper-latin': {
20670 $textitem = chr(65 +
$this->listcount
[$this->listnum
] - 1);
20673 case 'lower-greek': {
20674 $textitem = TCPDF_FONTS
::unichr((945 +
$this->listcount
[$this->listnum
] - 1), $this->isunicode
);
20678 // Types to be implemented (special handling)
20688 case 'cjk-ideographic': {
20697 case 'hiragana-iroha': {
20700 case 'katakana-iroha': {
20705 $textitem = $this->listcount
[$this->listnum
];
20708 if (!TCPDF_STATIC
::empty_string($textitem)) {
20709 // Check whether we need a new page or new column
20710 $prev_y = $this->y
;
20711 $h = $this->getCellHeight($this->FontSize
);
20712 if ($this->checkPageBreak($h) OR ($this->y
< $prev_y)) {
20715 // print ordered item
20717 $textitem = '.'.$textitem;
20719 $textitem = $textitem.'.';
20721 $lspace +
= $this->GetStringWidth($textitem);
20723 $this->x +
= $lspace;
20725 $this->x
-= $lspace;
20727 $this->Write($this->lasth
, $textitem, '', false, '', false, 0, false);
20730 $this->lispacer
= '^';
20732 $this->setFillColorArray($bgcolor);
20733 $this->setDrawColorArray($strokecolor);
20734 $this->settextColorArray($color);
20738 * Returns current graphic variables as array.
20739 * @return array of graphic variables
20741 * @since 4.2.010 (2008-11-14)
20743 protected function getGraphicVars() {
20745 'FontFamily' => $this->FontFamily
,
20746 'FontStyle' => $this->FontStyle
,
20747 'FontSizePt' => $this->FontSizePt
,
20748 'rMargin' => $this->rMargin
,
20749 'lMargin' => $this->lMargin
,
20750 'cell_padding' => $this->cell_padding
,
20751 'cell_margin' => $this->cell_margin
,
20752 'LineWidth' => $this->LineWidth
,
20753 'linestyleWidth' => $this->linestyleWidth
,
20754 'linestyleCap' => $this->linestyleCap
,
20755 'linestyleJoin' => $this->linestyleJoin
,
20756 'linestyleDash' => $this->linestyleDash
,
20757 'textrendermode' => $this->textrendermode
,
20758 'textstrokewidth' => $this->textstrokewidth
,
20759 'DrawColor' => $this->DrawColor
,
20760 'FillColor' => $this->FillColor
,
20761 'TextColor' => $this->TextColor
,
20762 'ColorFlag' => $this->ColorFlag
,
20763 'bgcolor' => $this->bgcolor
,
20764 'fgcolor' => $this->fgcolor
,
20765 'htmlvspace' => $this->htmlvspace
,
20766 'listindent' => $this->listindent
,
20767 'listindentlevel' => $this->listindentlevel
,
20768 'listnum' => $this->listnum
,
20769 'listordered' => $this->listordered
,
20770 'listcount' => $this->listcount
,
20771 'lispacer' => $this->lispacer
,
20772 'cell_height_ratio' => $this->cell_height_ratio
,
20773 'font_stretching' => $this->font_stretching
,
20774 'font_spacing' => $this->font_spacing
,
20775 'alpha' => $this->alpha
,
20777 'lasth' => $this->lasth
,
20778 'tMargin' => $this->tMargin
,
20779 'bMargin' => $this->bMargin
,
20780 'AutoPageBreak' => $this->AutoPageBreak
,
20781 'PageBreakTrigger' => $this->PageBreakTrigger
,
20786 'wPt' => $this->wPt
,
20787 'hPt' => $this->hPt
,
20788 'fwPt' => $this->fwPt
,
20789 'fhPt' => $this->fhPt
,
20790 'page' => $this->page
,
20791 'current_column' => $this->current_column
,
20792 'num_columns' => $this->num_columns
20798 * Set graphic variables.
20799 * @param array $gvars array of graphic variablesto restore
20800 * @param boolean $extended if true restore extended graphic variables
20802 * @since 4.2.010 (2008-11-14)
20804 protected function setGraphicVars($gvars, $extended=false) {
20805 if ($this->state
!= 2) {
20808 $this->FontFamily
= $gvars['FontFamily'];
20809 $this->FontStyle
= $gvars['FontStyle'];
20810 $this->FontSizePt
= $gvars['FontSizePt'];
20811 $this->rMargin
= $gvars['rMargin'];
20812 $this->lMargin
= $gvars['lMargin'];
20813 $this->cell_padding
= $gvars['cell_padding'];
20814 $this->cell_margin
= $gvars['cell_margin'];
20815 $this->LineWidth
= $gvars['LineWidth'];
20816 $this->linestyleWidth
= $gvars['linestyleWidth'];
20817 $this->linestyleCap
= $gvars['linestyleCap'];
20818 $this->linestyleJoin
= $gvars['linestyleJoin'];
20819 $this->linestyleDash
= $gvars['linestyleDash'];
20820 $this->textrendermode
= $gvars['textrendermode'];
20821 $this->textstrokewidth
= $gvars['textstrokewidth'];
20822 $this->DrawColor
= $gvars['DrawColor'];
20823 $this->FillColor
= $gvars['FillColor'];
20824 $this->TextColor
= $gvars['TextColor'];
20825 $this->ColorFlag
= $gvars['ColorFlag'];
20826 $this->bgcolor
= $gvars['bgcolor'];
20827 $this->fgcolor
= $gvars['fgcolor'];
20828 $this->htmlvspace
= $gvars['htmlvspace'];
20829 $this->listindent
= $gvars['listindent'];
20830 $this->listindentlevel
= $gvars['listindentlevel'];
20831 $this->listnum
= $gvars['listnum'];
20832 $this->listordered
= $gvars['listordered'];
20833 $this->listcount
= $gvars['listcount'];
20834 $this->lispacer
= $gvars['lispacer'];
20835 $this->cell_height_ratio
= $gvars['cell_height_ratio'];
20836 $this->font_stretching
= $gvars['font_stretching'];
20837 $this->font_spacing
= $gvars['font_spacing'];
20838 $this->alpha
= $gvars['alpha'];
20840 // restore extended values
20841 $this->lasth
= $gvars['lasth'];
20842 $this->tMargin
= $gvars['tMargin'];
20843 $this->bMargin
= $gvars['bMargin'];
20844 $this->AutoPageBreak
= $gvars['AutoPageBreak'];
20845 $this->PageBreakTrigger
= $gvars['PageBreakTrigger'];
20846 $this->x
= $gvars['x'];
20847 $this->y
= $gvars['y'];
20848 $this->w
= $gvars['w'];
20849 $this->h
= $gvars['h'];
20850 $this->wPt
= $gvars['wPt'];
20851 $this->hPt
= $gvars['hPt'];
20852 $this->fwPt
= $gvars['fwPt'];
20853 $this->fhPt
= $gvars['fhPt'];
20854 $this->page
= $gvars['page'];
20855 $this->current_column
= $gvars['current_column'];
20856 $this->num_columns
= $gvars['num_columns'];
20858 $this->_out(''.$this->linestyleWidth
.' '.$this->linestyleCap
.' '.$this->linestyleJoin
.' '.$this->linestyleDash
.' '.$this->DrawColor
.' '.$this->FillColor
.'');
20859 if (!TCPDF_STATIC
::empty_string($this->FontFamily
)) {
20860 $this->setFont($this->FontFamily
, $this->FontStyle
, $this->FontSizePt
);
20865 * Outputs the "save graphics state" operator 'q'
20868 protected function _outSaveGraphicsState() {
20873 * Outputs the "restore graphics state" operator 'Q'
20876 protected function _outRestoreGraphicsState() {
20881 * Set buffer content (always append data).
20882 * @param string $data data
20884 * @since 4.5.000 (2009-01-02)
20886 protected function setBuffer($data) {
20887 $this->bufferlen +
= strlen($data);
20888 $this->buffer
.= $data;
20892 * Replace the buffer content
20893 * @param string $data data
20895 * @since 5.5.000 (2010-06-22)
20897 protected function replaceBuffer($data) {
20898 $this->bufferlen
= strlen($data);
20899 $this->buffer
= $data;
20903 * Get buffer content.
20904 * @return string buffer content
20906 * @since 4.5.000 (2009-01-02)
20908 protected function getBuffer() {
20909 return $this->buffer
;
20913 * Set page buffer content.
20914 * @param int $page page number
20915 * @param string $data page data
20916 * @param boolean $append if true append data, false replace.
20918 * @since 4.5.000 (2008-12-31)
20920 protected function setPageBuffer($page, $data, $append=false) {
20922 $this->pages
[$page] .= $data;
20924 $this->pages
[$page] = $data;
20926 if ($append AND isset($this->pagelen
[$page])) {
20927 $this->pagelen
[$page] +
= strlen($data);
20929 $this->pagelen
[$page] = strlen($data);
20934 * Get page buffer content.
20935 * @param int $page page number
20936 * @return string page buffer content or false in case of error
20938 * @since 4.5.000 (2008-12-31)
20940 protected function getPageBuffer($page) {
20941 if (isset($this->pages
[$page])) {
20942 return $this->pages
[$page];
20948 * Set image buffer content.
20949 * @param string $image image key
20950 * @param array $data image data
20951 * @return int image index number
20953 * @since 4.5.000 (2008-12-31)
20955 protected function setImageBuffer($image, $data) {
20956 if (($data['i'] = array_search($image, $this->imagekeys
)) === FALSE) {
20957 $this->imagekeys
[$this->numimages
] = $image;
20958 $data['i'] = $this->numimages
;
20959 ++
$this->numimages
;
20961 $this->images
[$image] = $data;
20966 * Set image buffer content for a specified sub-key.
20967 * @param string $image image key
20968 * @param string $key image sub-key
20969 * @param array $data image data
20971 * @since 4.5.000 (2008-12-31)
20973 protected function setImageSubBuffer($image, $key, $data) {
20974 if (!isset($this->images
[$image])) {
20975 $this->setImageBuffer($image, array());
20977 $this->images
[$image][$key] = $data;
20981 * Get image buffer content.
20982 * @param string $image image key
20983 * @return string|false image buffer content or false in case of error
20985 * @since 4.5.000 (2008-12-31)
20987 protected function getImageBuffer($image) {
20988 if (isset($this->images
[$image])) {
20989 return $this->images
[$image];
20995 * Set font buffer content.
20996 * @param string $font font key
20997 * @param array $data font data
20999 * @since 4.5.000 (2009-01-02)
21001 protected function setFontBuffer($font, $data) {
21002 $this->fonts
[$font] = $data;
21003 if (!in_array($font, $this->fontkeys
)) {
21004 $this->fontkeys
[] = $font;
21005 // store object ID for current font
21007 $this->font_obj_ids
[$font] = $this->n
;
21008 $this->setFontSubBuffer($font, 'n', $this->n
);
21013 * Set font buffer content.
21014 * @param string $font font key
21015 * @param string $key font sub-key
21016 * @param mixed $data font data
21018 * @since 4.5.000 (2009-01-02)
21020 protected function setFontSubBuffer($font, $key, $data) {
21021 if (!isset($this->fonts
[$font])) {
21022 $this->setFontBuffer($font, array());
21024 $this->fonts
[$font][$key] = $data;
21028 * Get font buffer content.
21029 * @param string $font font key
21030 * @return string|false font buffer content or false in case of error
21032 * @since 4.5.000 (2009-01-02)
21034 protected function getFontBuffer($font) {
21035 if (isset($this->fonts
[$font])) {
21036 return $this->fonts
[$font];
21042 * Move a page to a previous position.
21043 * @param int $frompage number of the source page
21044 * @param int $topage number of the destination page (must be less than $frompage)
21045 * @return bool true in case of success, false in case of error.
21047 * @since 4.5.000 (2009-01-02)
21049 public function movePage($frompage, $topage) {
21050 if (($frompage > $this->numpages
) OR ($frompage <= $topage)) {
21053 if ($frompage == $this->page
) {
21054 // close the page before moving it
21057 // move all page-related states
21058 $tmppage = $this->getPageBuffer($frompage);
21059 $tmppagedim = $this->pagedim
[$frompage];
21060 $tmppagelen = $this->pagelen
[$frompage];
21061 $tmpintmrk = $this->intmrk
[$frompage];
21062 $tmpbordermrk = $this->bordermrk
[$frompage];
21063 $tmpcntmrk = $this->cntmrk
[$frompage];
21064 $tmppageobjects = $this->pageobjects
[$frompage];
21065 if (isset($this->footerpos
[$frompage])) {
21066 $tmpfooterpos = $this->footerpos
[$frompage];
21068 if (isset($this->footerlen
[$frompage])) {
21069 $tmpfooterlen = $this->footerlen
[$frompage];
21071 if (isset($this->transfmrk
[$frompage])) {
21072 $tmptransfmrk = $this->transfmrk
[$frompage];
21074 if (isset($this->PageAnnots
[$frompage])) {
21075 $tmpannots = $this->PageAnnots
[$frompage];
21077 if (isset($this->newpagegroup
) AND !empty($this->newpagegroup
)) {
21078 for ($i = $frompage; $i > $topage; --$i) {
21079 if (isset($this->newpagegroup
[$i]) AND (($i +
$this->pagegroups
[$this->newpagegroup
[$i]]) > $frompage)) {
21080 --$this->pagegroups
[$this->newpagegroup
[$i]];
21084 for ($i = $topage; $i > 0; --$i) {
21085 if (isset($this->newpagegroup
[$i]) AND (($i +
$this->pagegroups
[$this->newpagegroup
[$i]]) > $topage)) {
21086 ++
$this->pagegroups
[$this->newpagegroup
[$i]];
21091 for ($i = $frompage; $i > $topage; --$i) {
21093 // shift pages down
21094 $this->setPageBuffer($i, $this->getPageBuffer($j));
21095 $this->pagedim
[$i] = $this->pagedim
[$j];
21096 $this->pagelen
[$i] = $this->pagelen
[$j];
21097 $this->intmrk
[$i] = $this->intmrk
[$j];
21098 $this->bordermrk
[$i] = $this->bordermrk
[$j];
21099 $this->cntmrk
[$i] = $this->cntmrk
[$j];
21100 $this->pageobjects
[$i] = $this->pageobjects
[$j];
21101 if (isset($this->footerpos
[$j])) {
21102 $this->footerpos
[$i] = $this->footerpos
[$j];
21103 } elseif (isset($this->footerpos
[$i])) {
21104 unset($this->footerpos
[$i]);
21106 if (isset($this->footerlen
[$j])) {
21107 $this->footerlen
[$i] = $this->footerlen
[$j];
21108 } elseif (isset($this->footerlen
[$i])) {
21109 unset($this->footerlen
[$i]);
21111 if (isset($this->transfmrk
[$j])) {
21112 $this->transfmrk
[$i] = $this->transfmrk
[$j];
21113 } elseif (isset($this->transfmrk
[$i])) {
21114 unset($this->transfmrk
[$i]);
21116 if (isset($this->PageAnnots
[$j])) {
21117 $this->PageAnnots
[$i] = $this->PageAnnots
[$j];
21118 } elseif (isset($this->PageAnnots
[$i])) {
21119 unset($this->PageAnnots
[$i]);
21121 if (isset($this->newpagegroup
[$j])) {
21122 $this->newpagegroup
[$i] = $this->newpagegroup
[$j];
21123 unset($this->newpagegroup
[$j]);
21125 if ($this->currpagegroup
== $j) {
21126 $this->currpagegroup
= $i;
21129 $this->setPageBuffer($topage, $tmppage);
21130 $this->pagedim
[$topage] = $tmppagedim;
21131 $this->pagelen
[$topage] = $tmppagelen;
21132 $this->intmrk
[$topage] = $tmpintmrk;
21133 $this->bordermrk
[$topage] = $tmpbordermrk;
21134 $this->cntmrk
[$topage] = $tmpcntmrk;
21135 $this->pageobjects
[$topage] = $tmppageobjects;
21136 if (isset($tmpfooterpos)) {
21137 $this->footerpos
[$topage] = $tmpfooterpos;
21138 } elseif (isset($this->footerpos
[$topage])) {
21139 unset($this->footerpos
[$topage]);
21141 if (isset($tmpfooterlen)) {
21142 $this->footerlen
[$topage] = $tmpfooterlen;
21143 } elseif (isset($this->footerlen
[$topage])) {
21144 unset($this->footerlen
[$topage]);
21146 if (isset($tmptransfmrk)) {
21147 $this->transfmrk
[$topage] = $tmptransfmrk;
21148 } elseif (isset($this->transfmrk
[$topage])) {
21149 unset($this->transfmrk
[$topage]);
21151 if (isset($tmpannots)) {
21152 $this->PageAnnots
[$topage] = $tmpannots;
21153 } elseif (isset($this->PageAnnots
[$topage])) {
21154 unset($this->PageAnnots
[$topage]);
21157 $tmpoutlines = $this->outlines
;
21158 foreach ($tmpoutlines as $key => $outline) {
21159 if (!$outline['f']) {
21160 if (($outline['p'] >= $topage) AND ($outline['p'] < $frompage)) {
21161 $this->outlines
[$key]['p'] = ($outline['p'] +
1);
21162 } elseif ($outline['p'] == $frompage) {
21163 $this->outlines
[$key]['p'] = $topage;
21168 $tmpdests = $this->dests
;
21169 foreach ($tmpdests as $key => $dest) {
21171 if (($dest['p'] >= $topage) AND ($dest['p'] < $frompage)) {
21172 $this->dests
[$key]['p'] = ($dest['p'] +
1);
21173 } elseif ($dest['p'] == $frompage) {
21174 $this->dests
[$key]['p'] = $topage;
21179 $tmplinks = $this->links
;
21180 foreach ($tmplinks as $key => $link) {
21182 if (($link['p'] >= $topage) AND ($link['p'] < $frompage)) {
21183 $this->links
[$key]['p'] = ($link['p'] +
1);
21184 } elseif ($link['p'] == $frompage) {
21185 $this->links
[$key]['p'] = $topage;
21189 // adjust javascript
21190 $jfrompage = $frompage;
21191 $jtopage = $topage;
21192 if (preg_match_all('/this\.addField\(\'([^\']*)\',\'([^\']*)\',([0-9]+)/', $this->javascript
, $pamatch) > 0) {
21193 foreach($pamatch[0] as $pk => $pmatch) {
21194 $pagenum = intval($pamatch[3][$pk]) +
1;
21195 if (($pagenum >= $jtopage) AND ($pagenum < $jfrompage)) {
21196 $newpage = ($pagenum +
1);
21197 } elseif ($pagenum == $jfrompage) {
21198 $newpage = $jtopage;
21200 $newpage = $pagenum;
21203 $newjs = "this.addField(\'".$pamatch[1][$pk]."\',\'".$pamatch[2][$pk]."\',".$newpage;
21204 $this->javascript
= str_replace($pmatch, $newjs, $this->javascript
);
21208 // return to last page
21209 $this->lastPage(true);
21214 * Remove the specified page.
21215 * @param int $page page to remove
21216 * @return bool true in case of success, false in case of error.
21218 * @since 4.6.004 (2009-04-23)
21220 public function deletePage($page) {
21221 if (($page < 1) OR ($page > $this->numpages
)) {
21224 // delete current page
21225 unset($this->pages
[$page]);
21226 unset($this->pagedim
[$page]);
21227 unset($this->pagelen
[$page]);
21228 unset($this->intmrk
[$page]);
21229 unset($this->bordermrk
[$page]);
21230 unset($this->cntmrk
[$page]);
21231 foreach ($this->pageobjects
[$page] as $oid) {
21232 if (isset($this->offsets
[$oid])){
21233 unset($this->offsets
[$oid]);
21236 unset($this->pageobjects
[$page]);
21237 if (isset($this->footerpos
[$page])) {
21238 unset($this->footerpos
[$page]);
21240 if (isset($this->footerlen
[$page])) {
21241 unset($this->footerlen
[$page]);
21243 if (isset($this->transfmrk
[$page])) {
21244 unset($this->transfmrk
[$page]);
21246 if (isset($this->PageAnnots
[$page])) {
21247 unset($this->PageAnnots
[$page]);
21249 if (isset($this->newpagegroup
) AND !empty($this->newpagegroup
)) {
21250 for ($i = $page; $i > 0; --$i) {
21251 if (isset($this->newpagegroup
[$i]) AND (($i +
$this->pagegroups
[$this->newpagegroup
[$i]]) > $page)) {
21252 --$this->pagegroups
[$this->newpagegroup
[$i]];
21257 if (isset($this->pageopen
[$page])) {
21258 unset($this->pageopen
[$page]);
21260 if ($page < $this->numpages
) {
21261 // update remaining pages
21262 for ($i = $page; $i < $this->numpages
; ++
$i) {
21265 $this->setPageBuffer($i, $this->getPageBuffer($j));
21266 $this->pagedim
[$i] = $this->pagedim
[$j];
21267 $this->pagelen
[$i] = $this->pagelen
[$j];
21268 $this->intmrk
[$i] = $this->intmrk
[$j];
21269 $this->bordermrk
[$i] = $this->bordermrk
[$j];
21270 $this->cntmrk
[$i] = $this->cntmrk
[$j];
21271 $this->pageobjects
[$i] = $this->pageobjects
[$j];
21272 if (isset($this->footerpos
[$j])) {
21273 $this->footerpos
[$i] = $this->footerpos
[$j];
21274 } elseif (isset($this->footerpos
[$i])) {
21275 unset($this->footerpos
[$i]);
21277 if (isset($this->footerlen
[$j])) {
21278 $this->footerlen
[$i] = $this->footerlen
[$j];
21279 } elseif (isset($this->footerlen
[$i])) {
21280 unset($this->footerlen
[$i]);
21282 if (isset($this->transfmrk
[$j])) {
21283 $this->transfmrk
[$i] = $this->transfmrk
[$j];
21284 } elseif (isset($this->transfmrk
[$i])) {
21285 unset($this->transfmrk
[$i]);
21287 if (isset($this->PageAnnots
[$j])) {
21288 $this->PageAnnots
[$i] = $this->PageAnnots
[$j];
21289 } elseif (isset($this->PageAnnots
[$i])) {
21290 unset($this->PageAnnots
[$i]);
21292 if (isset($this->newpagegroup
[$j])) {
21293 $this->newpagegroup
[$i] = $this->newpagegroup
[$j];
21294 unset($this->newpagegroup
[$j]);
21296 if ($this->currpagegroup
== $j) {
21297 $this->currpagegroup
= $i;
21299 if (isset($this->pageopen
[$j])) {
21300 $this->pageopen
[$i] = $this->pageopen
[$j];
21301 } elseif (isset($this->pageopen
[$i])) {
21302 unset($this->pageopen
[$i]);
21305 // remove last page
21306 unset($this->pages
[$this->numpages
]);
21307 unset($this->pagedim
[$this->numpages
]);
21308 unset($this->pagelen
[$this->numpages
]);
21309 unset($this->intmrk
[$this->numpages
]);
21310 unset($this->bordermrk
[$this->numpages
]);
21311 unset($this->cntmrk
[$this->numpages
]);
21312 foreach ($this->pageobjects
[$this->numpages
] as $oid) {
21313 if (isset($this->offsets
[$oid])){
21314 unset($this->offsets
[$oid]);
21317 unset($this->pageobjects
[$this->numpages
]);
21318 if (isset($this->footerpos
[$this->numpages
])) {
21319 unset($this->footerpos
[$this->numpages
]);
21321 if (isset($this->footerlen
[$this->numpages
])) {
21322 unset($this->footerlen
[$this->numpages
]);
21324 if (isset($this->transfmrk
[$this->numpages
])) {
21325 unset($this->transfmrk
[$this->numpages
]);
21327 if (isset($this->PageAnnots
[$this->numpages
])) {
21328 unset($this->PageAnnots
[$this->numpages
]);
21330 if (isset($this->newpagegroup
[$this->numpages
])) {
21331 unset($this->newpagegroup
[$this->numpages
]);
21333 if ($this->currpagegroup
== $this->numpages
) {
21334 $this->currpagegroup
= ($this->numpages
- 1);
21336 if (isset($this->pagegroups
[$this->numpages
])) {
21337 unset($this->pagegroups
[$this->numpages
]);
21339 if (isset($this->pageopen
[$this->numpages
])) {
21340 unset($this->pageopen
[$this->numpages
]);
21344 $this->page
= $this->numpages
;
21346 $tmpoutlines = $this->outlines
;
21347 foreach ($tmpoutlines as $key => $outline) {
21348 if (!$outline['f']) {
21349 if ($outline['p'] > $page) {
21350 $this->outlines
[$key]['p'] = $outline['p'] - 1;
21351 } elseif ($outline['p'] == $page) {
21352 unset($this->outlines
[$key]);
21357 $tmpdests = $this->dests
;
21358 foreach ($tmpdests as $key => $dest) {
21360 if ($dest['p'] > $page) {
21361 $this->dests
[$key]['p'] = $dest['p'] - 1;
21362 } elseif ($dest['p'] == $page) {
21363 unset($this->dests
[$key]);
21368 $tmplinks = $this->links
;
21369 foreach ($tmplinks as $key => $link) {
21371 if ($link['p'] > $page) {
21372 $this->links
[$key]['p'] = $link['p'] - 1;
21373 } elseif ($link['p'] == $page) {
21374 unset($this->links
[$key]);
21378 // adjust javascript
21380 if (preg_match_all('/this\.addField\(\'([^\']*)\',\'([^\']*)\',([0-9]+)/', $this->javascript
, $pamatch) > 0) {
21381 foreach($pamatch[0] as $pk => $pmatch) {
21382 $pagenum = intval($pamatch[3][$pk]) +
1;
21383 if ($pagenum >= $jpage) {
21384 $newpage = ($pagenum - 1);
21385 } elseif ($pagenum == $jpage) {
21388 $newpage = $pagenum;
21391 $newjs = "this.addField(\'".$pamatch[1][$pk]."\',\'".$pamatch[2][$pk]."\',".$newpage;
21392 $this->javascript
= str_replace($pmatch, $newjs, $this->javascript
);
21396 // return to last page
21397 if ($this->numpages
> 0) {
21398 $this->lastPage(true);
21404 * Clone the specified page to a new page.
21405 * @param int $page number of page to copy (0 = current page)
21406 * @return bool true in case of success, false in case of error.
21408 * @since 4.9.015 (2010-04-20)
21410 public function copyPage($page=0) {
21413 $page = $this->page
;
21415 if (($page < 1) OR ($page > $this->numpages
)) {
21418 // close the last page
21420 // copy all page-related states
21422 $this->page
= $this->numpages
;
21423 $this->setPageBuffer($this->page
, $this->getPageBuffer($page));
21424 $this->pagedim
[$this->page
] = $this->pagedim
[$page];
21425 $this->pagelen
[$this->page
] = $this->pagelen
[$page];
21426 $this->intmrk
[$this->page
] = $this->intmrk
[$page];
21427 $this->bordermrk
[$this->page
] = $this->bordermrk
[$page];
21428 $this->cntmrk
[$this->page
] = $this->cntmrk
[$page];
21429 $this->pageobjects
[$this->page
] = $this->pageobjects
[$page];
21430 $this->pageopen
[$this->page
] = false;
21431 if (isset($this->footerpos
[$page])) {
21432 $this->footerpos
[$this->page
] = $this->footerpos
[$page];
21434 if (isset($this->footerlen
[$page])) {
21435 $this->footerlen
[$this->page
] = $this->footerlen
[$page];
21437 if (isset($this->transfmrk
[$page])) {
21438 $this->transfmrk
[$this->page
] = $this->transfmrk
[$page];
21440 if (isset($this->PageAnnots
[$page])) {
21441 $this->PageAnnots
[$this->page
] = $this->PageAnnots
[$page];
21443 if (isset($this->newpagegroup
[$page])) {
21444 // start a new group
21445 $this->newpagegroup
[$this->page
] = sizeof($this->newpagegroup
) +
1;
21446 $this->currpagegroup
= $this->newpagegroup
[$this->page
];
21447 $this->pagegroups
[$this->currpagegroup
] = 1;
21448 } elseif (isset($this->currpagegroup
) AND ($this->currpagegroup
> 0)) {
21449 ++
$this->pagegroups
[$this->currpagegroup
];
21452 $tmpoutlines = $this->outlines
;
21453 foreach ($tmpoutlines as $key => $outline) {
21454 if ($outline['p'] == $page) {
21455 $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']);
21459 $tmplinks = $this->links
;
21460 foreach ($tmplinks as $key => $link) {
21461 if ($link['p'] == $page) {
21462 $this->links
[] = array('p' => $this->page
, 'y' => $link['y'], 'f' => $link['f']);
21465 // return to last page
21466 $this->lastPage(true);
21471 * Output a Table of Content Index (TOC).
21472 * This method must be called after all Bookmarks were set.
21473 * Before calling this method you have to open the page using the addTOCPage() method.
21474 * After calling this method you have to call endTOCPage() to close the TOC page.
21475 * You can override this method to achieve different styles.
21476 * @param int|null $page page number where this TOC should be inserted (leave empty for current page).
21477 * @param string $numbersfont set the font for page numbers (please use monospaced font for better alignment).
21478 * @param string $filler string used to fill the space between text and page number.
21479 * @param string $toc_name name to use for TOC bookmark.
21480 * @param string $style Font style for title: B = Bold, I = Italic, BI = Bold + Italic.
21481 * @param array $color RGB color array for bookmark title (values from 0 to 255).
21483 * @author Nicola Asuni
21484 * @since 4.5.000 (2009-01-02)
21485 * @see addTOCPage(), endTOCPage(), addHTMLTOC()
21487 public function addTOC($page=null, $numbersfont='', $filler='.', $toc_name='TOC', $style='', $color=array(0,0,0)) {
21488 $fontsize = $this->FontSizePt
;
21489 $fontfamily = $this->FontFamily
;
21490 $fontstyle = $this->FontStyle
;
21491 $w = $this->w
- $this->lMargin
- $this->rMargin
;
21492 $spacer = $this->GetStringWidth(chr(32)) * 4;
21493 $lmargin = $this->lMargin
;
21494 $rmargin = $this->rMargin
;
21495 $x_start = $this->GetX();
21496 $page_first = $this->page
;
21497 $current_page = $this->page
;
21498 $page_fill_start = false;
21499 $page_fill_end = false;
21500 $current_column = $this->current_column
;
21501 if (TCPDF_STATIC
::empty_string($numbersfont)) {
21502 $numbersfont = $this->default_monospaced_font
;
21504 if (TCPDF_STATIC
::empty_string($filler)) {
21507 if (TCPDF_STATIC
::empty_string($page)) {
21515 $this->setFont($numbersfont, $fontstyle, $fontsize);
21516 $numwidth = $this->GetStringWidth('00000');
21517 $maxpage = 0; //used for pages on attached documents
21518 foreach ($this->outlines
as $key => $outline) {
21519 // check for extra pages (used for attachments)
21520 if (($this->page
> $page_first) AND ($outline['p'] >= $this->numpages
)) {
21521 $outline['p'] +
= ($this->page
- $page_first);
21530 if ($outline['l'] == 0) {
21531 $this->setFont($fontfamily, $outline['s'].'B', $fontsize);
21533 $this->setFont($fontfamily, $outline['s'], $fontsize - $outline['l']);
21535 $this->setTextColorArray($outline['c']);
21536 // check for page break
21537 $this->checkPageBreak(2 * $this->getCellHeight($this->FontSize
));
21538 // set margins and X position
21539 if (($this->page
== $current_page) AND ($this->current_column
== $current_column)) {
21540 $this->lMargin
= $lmargin;
21541 $this->rMargin
= $rmargin;
21543 if ($this->current_column
!= $current_column) {
21545 $x_start = $this->w
- $this->columns
[$this->current_column
]['x'];
21547 $x_start = $this->columns
[$this->current_column
]['x'];
21550 $lmargin = $this->lMargin
;
21551 $rmargin = $this->rMargin
;
21552 $current_page = $this->page
;
21553 $current_column = $this->current_column
;
21555 $this->setX($x_start);
21556 $indent = ($spacer * $outline['l']);
21558 $this->x
-= $indent;
21559 $this->rMargin
= $this->w
- $this->x
;
21561 $this->x +
= $indent;
21562 $this->lMargin
= $this->x
;
21564 $link = $this->AddLink();
21565 $this->setLink($link, $outline['y'], $outline['p']);
21568 $txt = ' '.$outline['t'];
21570 $txt = $outline['t'].' ';
21572 $this->Write(0, $txt, $link, false, $aligntext, false, 0, false, false, 0, $numwidth, '');
21574 $tw = $this->x
- $this->lMargin
;
21576 $tw = $this->w
- $this->rMargin
- $this->x
;
21578 $this->setFont($numbersfont, $fontstyle, $fontsize);
21579 if (TCPDF_STATIC
::empty_string($page)) {
21580 $pagenum = $outline['p'];
21582 // placemark to be replaced with the correct number
21583 $pagenum = '{#'.($outline['p']).'}';
21584 if ($this->isUnicodeFont()) {
21585 $pagenum = '{'.$pagenum.'}';
21587 $maxpage = max($maxpage, $outline['p']);
21589 $fw = ($tw - $this->GetStringWidth($pagenum.$filler));
21590 $wfiller = $this->GetStringWidth($filler);
21591 if ($wfiller > 0) {
21592 $numfills = floor($fw / $wfiller);
21596 if ($numfills > 0) {
21597 $rowfill = str_repeat($filler, $numfills);
21602 $pagenum = $pagenum.$gap.$rowfill;
21604 $pagenum = $rowfill.$gap.$pagenum;
21606 // write the number
21607 $this->Cell($tw, 0, $pagenum, 0, 1, $alignnum, 0, $link, 0);
21609 $page_last = $this->getPage();
21610 $numpages = ($page_last - $page_first +
1);
21611 // account for booklet mode
21612 if ($this->booklet
) {
21613 // check if a blank page is required before TOC
21614 $page_fill_start = ((($page_first %
2) == 0) XOR (($page %
2) == 0));
21615 $page_fill_end = (!((($numpages %
2) == 0) XOR ($page_fill_start)));
21616 if ($page_fill_start) {
21617 // add a page at the end (to be moved before TOC)
21622 if ($page_fill_end) {
21623 // add a page at the end
21629 $maxpage = max($maxpage, $page_last);
21630 if (!TCPDF_STATIC
::empty_string($page)) {
21631 for ($p = $page_first; $p <= $page_last; ++
$p) {
21633 $temppage = $this->getPageBuffer($p);
21634 for ($n = 1; $n <= $maxpage; ++
$n) {
21635 // update page numbers
21637 // get page number aliases
21638 $pnalias = $this->getInternalPageNumberAliases($a);
21639 // calculate replacement number
21640 if (($n >= $page) AND ($n <= $this->numpages
)) {
21641 $np = $n +
$numpages;
21645 $na = TCPDF_STATIC
::formatTOCPageNumber(($this->starting_page_number +
$np - 1));
21646 $nu = TCPDF_FONTS
::UTF8ToUTF16BE($na, false, $this->isunicode
, $this->CurrentFont
);
21647 // replace aliases with numbers
21648 foreach ($pnalias['u'] as $u) {
21649 $sfill = str_repeat($filler, max(0, (strlen($u) - strlen($nu.' '))));
21651 $nr = $nu.TCPDF_FONTS
::UTF8ToUTF16BE(' '.$sfill, false, $this->isunicode
, $this->CurrentFont
);
21653 $nr = TCPDF_FONTS
::UTF8ToUTF16BE($sfill.' ', false, $this->isunicode
, $this->CurrentFont
).$nu;
21655 $temppage = str_replace($u, $nr, $temppage);
21657 foreach ($pnalias['a'] as $a) {
21658 $sfill = str_repeat($filler, max(0, (strlen($a) - strlen($na.' '))));
21660 $nr = $na.' '.$sfill;
21662 $nr = $sfill.' '.$na;
21664 $temppage = str_replace($a, $nr, $temppage);
21668 $this->setPageBuffer($p, $temppage);
21671 $this->Bookmark($toc_name, 0, 0, $page_first, $style, $color);
21672 if ($page_fill_start) {
21673 $this->movePage($page_last, $page_first);
21675 for ($i = 0; $i < $numpages; ++
$i) {
21676 $this->movePage($page_last, $page);
21682 * Output a Table Of Content Index (TOC) using HTML templates.
21683 * This method must be called after all Bookmarks were set.
21684 * Before calling this method you have to open the page using the addTOCPage() method.
21685 * After calling this method you have to call endTOCPage() to close the TOC page.
21686 * @param int|null $page page number where this TOC should be inserted (leave empty for current page).
21687 * @param string $toc_name name to use for TOC bookmark.
21688 * @param array $templates array of html templates. Use: "#TOC_DESCRIPTION#" for bookmark title, "#TOC_PAGE_NUMBER#" for page number.
21689 * @param boolean $correct_align if true correct the number alignment (numbers must be in monospaced font like courier and right aligned on LTR, or left aligned on RTL)
21690 * @param string $style Font style for title: B = Bold, I = Italic, BI = Bold + Italic.
21691 * @param array $color RGB color array for title (values from 0 to 255).
21693 * @author Nicola Asuni
21694 * @since 5.0.001 (2010-05-06)
21695 * @see addTOCPage(), endTOCPage(), addTOC()
21697 public function addHTMLTOC($page=null, $toc_name='TOC', $templates=array(), $correct_align=true, $style='', $color=array(0,0,0)) {
21699 $prev_htmlLinkColorArray = $this->htmlLinkColorArray
;
21700 $prev_htmlLinkFontStyle = $this->htmlLinkFontStyle
;
21701 // set new style for link
21702 $this->htmlLinkColorArray
= array();
21703 $this->htmlLinkFontStyle
= '';
21704 $page_first = $this->getPage();
21705 $page_fill_start = false;
21706 $page_fill_end = false;
21707 // get the font type used for numbers in each template
21708 $current_font = $this->FontFamily
;
21709 foreach ($templates as $level => $html) {
21710 $dom = $this->getHtmlDomArray($html);
21711 foreach ($dom as $key => $value) {
21712 if ($value['value'] == '#TOC_PAGE_NUMBER#') {
21713 $this->setFont($dom[($key - 1)]['fontname']);
21714 $templates['F'.$level] = $this->isUnicodeFont();
21718 $this->setFont($current_font);
21719 $maxpage = 0; //used for pages on attached documents
21720 foreach ($this->outlines
as $key => $outline) {
21721 // get HTML template
21722 $row = $templates[$outline['l']];
21723 if (TCPDF_STATIC
::empty_string($page)) {
21724 $pagenum = $outline['p'];
21726 // placemark to be replaced with the correct number
21727 $pagenum = '{#'.($outline['p']).'}';
21728 if (isset($templates['F'.$outline['l']]) && $templates['F'.$outline['l']]) {
21729 $pagenum = '{'.$pagenum.'}';
21731 $maxpage = max($maxpage, $outline['p']);
21733 // replace templates with current values
21734 $row = str_replace('#TOC_DESCRIPTION#', $outline['t'], $row);
21735 $row = str_replace('#TOC_PAGE_NUMBER#', $pagenum, $row);
21736 // add link to page
21737 $row = '<a href="#'.$outline['p'].','.$outline['y'].'">'.$row.'</a>';
21738 // write bookmark entry
21739 $this->writeHTML($row, false, false, true, false, '');
21741 // restore link styles
21742 $this->htmlLinkColorArray
= $prev_htmlLinkColorArray;
21743 $this->htmlLinkFontStyle
= $prev_htmlLinkFontStyle;
21744 // move TOC page and replace numbers
21745 $page_last = $this->getPage();
21746 $numpages = ($page_last - $page_first +
1);
21747 // account for booklet mode
21748 if ($this->booklet
) {
21749 // check if a blank page is required before TOC
21750 $page_fill_start = ((($page_first %
2) == 0) XOR (($page %
2) == 0));
21751 $page_fill_end = (!((($numpages %
2) == 0) XOR ($page_fill_start)));
21752 if ($page_fill_start) {
21753 // add a page at the end (to be moved before TOC)
21758 if ($page_fill_end) {
21759 // add a page at the end
21765 $maxpage = max($maxpage, $page_last);
21766 if (!TCPDF_STATIC
::empty_string($page)) {
21767 for ($p = $page_first; $p <= $page_last; ++
$p) {
21769 $temppage = $this->getPageBuffer($p);
21770 for ($n = 1; $n <= $maxpage; ++
$n) {
21771 // update page numbers
21773 // get page number aliases
21774 $pnalias = $this->getInternalPageNumberAliases($a);
21775 // calculate replacement number
21777 $np = $n +
$numpages;
21781 $na = TCPDF_STATIC
::formatTOCPageNumber(($this->starting_page_number +
$np - 1));
21782 $nu = TCPDF_FONTS
::UTF8ToUTF16BE($na, false, $this->isunicode
, $this->CurrentFont
);
21783 // replace aliases with numbers
21784 foreach ($pnalias['u'] as $u) {
21785 if ($correct_align) {
21786 $sfill = str_repeat($filler, (strlen($u) - strlen($nu.' ')));
21788 $nr = $nu.TCPDF_FONTS
::UTF8ToUTF16BE(' '.$sfill, false, $this->isunicode
, $this->CurrentFont
);
21790 $nr = TCPDF_FONTS
::UTF8ToUTF16BE($sfill.' ', false, $this->isunicode
, $this->CurrentFont
).$nu;
21795 $temppage = str_replace($u, $nr, $temppage);
21797 foreach ($pnalias['a'] as $a) {
21798 if ($correct_align) {
21799 $sfill = str_repeat($filler, (strlen($a) - strlen($na.' ')));
21801 $nr = $na.' '.$sfill;
21803 $nr = $sfill.' '.$na;
21808 $temppage = str_replace($a, $nr, $temppage);
21812 $this->setPageBuffer($p, $temppage);
21815 $this->Bookmark($toc_name, 0, 0, $page_first, $style, $color);
21816 if ($page_fill_start) {
21817 $this->movePage($page_last, $page_first);
21819 for ($i = 0; $i < $numpages; ++
$i) {
21820 $this->movePage($page_last, $page);
21826 * Stores a copy of the current TCPDF object used for undo operation.
21828 * @since 4.5.029 (2009-03-19)
21830 public function startTransaction() {
21831 if (isset($this->objcopy
)) {
21832 // remove previous copy
21833 $this->commitTransaction();
21835 // record current page number and Y position
21836 $this->start_transaction_page
= $this->page
;
21837 $this->start_transaction_y
= $this->y
;
21838 // clone current object
21839 $this->objcopy
= TCPDF_STATIC
::objclone($this);
21843 * Delete the copy of the current TCPDF object used for undo operation.
21845 * @since 4.5.029 (2009-03-19)
21847 public function commitTransaction() {
21848 if (isset($this->objcopy
)) {
21849 $this->objcopy
->_destroy(true, true);
21850 /* The unique file_id should not be used during cleanup again */
21851 $this->objcopy
->file_id
= NULL;
21852 unset($this->objcopy
);
21857 * This method allows to undo the latest transaction by returning the latest saved TCPDF object with startTransaction().
21858 * @param boolean $self if true restores current class object to previous state without the need of reassignment via the returned value.
21859 * @return TCPDF object.
21861 * @since 4.5.029 (2009-03-19)
21863 public function rollbackTransaction($self=false) {
21864 if (isset($this->objcopy
)) {
21865 $objcopy = $this->objcopy
;
21866 $this->_destroy(true, true);
21868 $objvars = get_object_vars($objcopy);
21869 foreach ($objvars as $key => $value) {
21870 $this->$key = $value;
21872 $objcopy->_destroy(true, true);
21873 /* The unique file_id should not be used during cleanup again */
21874 $objcopy->file_id
= NULL;
21878 /* The unique file_id should not be used during cleanup again */
21879 $this->file_id
= NULL;
21885 // --- MULTI COLUMNS METHODS -----------------------
21888 * Set multiple columns of the same size
21889 * @param int $numcols number of columns (set to zero to disable columns mode)
21890 * @param int $width column width
21891 * @param int|null $y column starting Y position (leave empty for current Y position)
21893 * @since 4.9.001 (2010-03-28)
21895 public function setEqualColumns($numcols=0, $width=0, $y=null) {
21896 $this->columns
= array();
21897 if ($numcols < 2) {
21899 $this->columns
= array();
21901 // maximum column width
21902 $maxwidth = ($this->w
- $this->original_lMargin
- $this->original_rMargin
) / $numcols;
21903 if (($width == 0) OR ($width > $maxwidth)) {
21904 $width = $maxwidth;
21906 if (TCPDF_STATIC
::empty_string($y)) {
21909 // space between columns
21910 $space = (($this->w
- $this->original_lMargin
- $this->original_rMargin
- ($numcols * $width)) / ($numcols - 1));
21911 // fill the columns array (with, space, starting Y position)
21912 for ($i = 0; $i < $numcols; ++
$i) {
21913 $this->columns
[$i] = array('w' => $width, 's' => $space, 'y' => $y);
21916 $this->num_columns
= $numcols;
21917 $this->current_column
= 0;
21918 $this->column_start_page
= $this->page
;
21919 $this->selectColumn(0);
21923 * Remove columns and reset page margins.
21925 * @since 5.9.072 (2011-04-26)
21927 public function resetColumns() {
21928 $this->lMargin
= $this->original_lMargin
;
21929 $this->rMargin
= $this->original_rMargin
;
21930 $this->setEqualColumns();
21934 * Set columns array.
21935 * Each column is represented by an array of arrays with the following keys: (w = width, s = space between columns, y = column top position).
21936 * @param array $columns
21938 * @since 4.9.001 (2010-03-28)
21940 public function setColumnsArray($columns) {
21941 $this->columns
= $columns;
21942 $this->num_columns
= count($columns);
21943 $this->current_column
= 0;
21944 $this->column_start_page
= $this->page
;
21945 $this->selectColumn(0);
21949 * Set position at a given column
21950 * @param int|null $col column number (from 0 to getNumberOfColumns()-1); empty string = current column.
21952 * @since 4.9.001 (2010-03-28)
21954 public function selectColumn($col=null) {
21955 if (TCPDF_STATIC
::empty_string($col)) {
21956 $col = $this->current_column
;
21957 } elseif ($col >= $this->num_columns
) {
21960 $xshift = array('x' => 0, 's' => array('H' => 0, 'V' => 0), 'p' => array('L' => 0, 'T' => 0, 'R' => 0, 'B' => 0));
21961 $enable_thead = false;
21962 if ($this->num_columns
> 1) {
21963 if ($col != $this->current_column
) {
21964 // move Y pointer at the top of the column
21965 if ($this->column_start_page
== $this->page
) {
21966 $this->y
= $this->columns
[$col]['y'];
21968 $this->y
= $this->tMargin
;
21970 // Avoid to write table headers more than once
21971 if (($this->page
> $this->maxselcol
['page']) OR (($this->page
== $this->maxselcol
['page']) AND ($col > $this->maxselcol
['column']))) {
21972 $enable_thead = true;
21973 $this->maxselcol
['page'] = $this->page
;
21974 $this->maxselcol
['column'] = $col;
21977 $xshift = $this->colxshift
;
21978 // set X position of the current column by case
21979 $listindent = ($this->listindentlevel
* $this->listindent
);
21980 // calculate column X position
21982 for ($i = 0; $i < $col; ++
$i) {
21983 $colpos +
= ($this->columns
[$i]['w'] +
$this->columns
[$i]['s']);
21986 $x = $this->w
- $this->original_rMargin
- $colpos;
21987 $this->rMargin
= ($this->w
- $x +
$listindent);
21988 $this->lMargin
= ($x - $this->columns
[$col]['w']);
21989 $this->x
= $x - $listindent;
21991 $x = $this->original_lMargin +
$colpos;
21992 $this->lMargin
= ($x +
$listindent);
21993 $this->rMargin
= ($this->w
- $x - $this->columns
[$col]['w']);
21994 $this->x
= $x +
$listindent;
21996 $this->columns
[$col]['x'] = $x;
21998 $this->current_column
= $col;
21999 // fix for HTML mode
22000 $this->newline
= true;
22001 // print HTML table header (if any)
22002 if ((!TCPDF_STATIC
::empty_string($this->thead
)) AND (!$this->inthead
)) {
22003 if ($enable_thead) {
22004 // print table header
22005 $this->writeHTML($this->thead
, false, false, false, false, '');
22006 $this->y +
= $xshift['s']['V'];
22007 // store end of header position
22008 if (!isset($this->columns
[$col]['th'])) {
22009 $this->columns
[$col]['th'] = array();
22011 $this->columns
[$col]['th']['\''.$this->page
.'\''] = $this->y
;
22013 } elseif (isset($this->columns
[$col]['th']['\''.$this->page
.'\''])) {
22014 $this->y
= $this->columns
[$col]['th']['\''.$this->page
.'\''];
22017 // account for an html table cell over multiple columns
22019 $this->rMargin +
= $xshift['x'];
22020 $this->x
-= ($xshift['x'] +
$xshift['p']['R']);
22022 $this->lMargin +
= $xshift['x'];
22023 $this->x +
= $xshift['x'] +
$xshift['p']['L'];
22028 * Return the current column number
22029 * @return int current column number
22031 * @since 5.5.011 (2010-07-08)
22033 public function getColumn() {
22034 return $this->current_column
;
22038 * Return the current number of columns.
22039 * @return int number of columns
22041 * @since 5.8.018 (2010-08-25)
22043 public function getNumberOfColumns() {
22044 return $this->num_columns
;
22048 * Set Text rendering mode.
22049 * @param int $stroke outline size in user units (0 = disable).
22050 * @param boolean $fill if true fills the text (default).
22051 * @param boolean $clip if true activate clipping mode
22053 * @since 4.9.008 (2009-04-02)
22055 public function setTextRenderingMode($stroke=0, $fill=true, $clip=false) {
22056 // Ref.: PDF 32000-1:2008 - 9.3.6 Text Rendering Mode
22057 // convert text rendering parameters
22061 if ($fill === true) {
22063 if ($clip === true) {
22064 // Fill, then stroke text and add to path for clipping
22065 $textrendermode = 6;
22067 // Fill, then stroke text
22068 $textrendermode = 2;
22070 $textstrokewidth = $stroke;
22072 if ($clip === true) {
22073 // Fill text and add to path for clipping
22074 $textrendermode = 4;
22077 $textrendermode = 0;
22082 if ($clip === true) {
22083 // Stroke text and add to path for clipping
22084 $textrendermode = 5;
22087 $textrendermode = 1;
22089 $textstrokewidth = $stroke;
22091 if ($clip === true) {
22092 // Add text to path for clipping
22093 $textrendermode = 7;
22095 // Neither fill nor stroke text (invisible)
22096 $textrendermode = 3;
22100 $this->textrendermode
= $textrendermode;
22101 $this->textstrokewidth
= $stroke;
22105 * Set parameters for drop shadow effect for text.
22106 * @param array $params 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.
22107 * @since 5.9.174 (2012-07-25)
22110 public function setTextShadow($params=array('enabled'=>false, 'depth_w'=>0, 'depth_h'=>0, 'color'=>false, 'opacity'=>1, 'blend_mode'=>'Normal')) {
22111 if (isset($params['enabled'])) {
22112 $this->txtshadow
['enabled'] = $params['enabled']?
true:false;
22114 $this->txtshadow
['enabled'] = false;
22116 if (isset($params['depth_w'])) {
22117 $this->txtshadow
['depth_w'] = floatval($params['depth_w']);
22119 $this->txtshadow
['depth_w'] = 0;
22121 if (isset($params['depth_h'])) {
22122 $this->txtshadow
['depth_h'] = floatval($params['depth_h']);
22124 $this->txtshadow
['depth_h'] = 0;
22126 if (isset($params['color']) AND ($params['color'] !== false) AND is_array($params['color'])) {
22127 $this->txtshadow
['color'] = $params['color'];
22129 $this->txtshadow
['color'] = $this->strokecolor
;
22131 if (isset($params['opacity'])) {
22132 $this->txtshadow
['opacity'] = min(1, max(0, floatval($params['opacity'])));
22134 $this->txtshadow
['opacity'] = 1;
22136 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'))) {
22137 $this->txtshadow
['blend_mode'] = $params['blend_mode'];
22139 $this->txtshadow
['blend_mode'] = 'Normal';
22141 if ((($this->txtshadow
['depth_w'] == 0) AND ($this->txtshadow
['depth_h'] == 0)) OR ($this->txtshadow
['opacity'] == 0)) {
22142 $this->txtshadow
['enabled'] = false;
22147 * Return the text shadow parameters array.
22148 * @return array array of parameters.
22149 * @since 5.9.174 (2012-07-25)
22152 public function getTextShadow() {
22153 return $this->txtshadow
;
22157 * Returns an array of chars containing soft hyphens.
22158 * @param array $word array of chars
22159 * @param array $patterns Array of hypenation patterns.
22160 * @param array $dictionary Array of words to be returned without applying the hyphenation algorithm.
22161 * @param int $leftmin Minimum number of character to leave on the left of the word without applying the hyphens.
22162 * @param int $rightmin Minimum number of character to leave on the right of the word without applying the hyphens.
22163 * @param int $charmin Minimum word length to apply the hyphenation algorithm.
22164 * @param int $charmax Maximum length of broken piece of word.
22165 * @return array text with soft hyphens
22166 * @author Nicola Asuni
22167 * @since 4.9.012 (2010-04-12)
22170 protected function hyphenateWord($word, $patterns, $dictionary=array(), $leftmin=1, $rightmin=2, $charmin=1, $charmax=8) {
22171 $hyphenword = array(); // hyphens positions
22172 $numchars = count($word);
22173 if ($numchars <= $charmin) {
22176 $word_string = TCPDF_FONTS
::UTF8ArrSubString($word, '', '', $this->isunicode
);
22177 // some words will be returned as-is
22178 $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})(\]?)$/';
22179 if (preg_match($pattern, $word_string) > 0) {
22183 $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})(\]?)$/';
22184 if (preg_match($pattern, $word_string) > 0) {
22188 if (isset($dictionary[$word_string])) {
22189 return TCPDF_FONTS
::UTF8StringToArray($dictionary[$word_string], $this->isunicode
, $this->CurrentFont
);
22191 // surround word with '_' characters
22192 $tmpword = array_merge(array(46), $word, array(46));
22193 $tmpnumchars = $numchars +
2;
22194 $maxpos = $tmpnumchars - 1;
22195 for ($pos = 0; $pos < $maxpos; ++
$pos) {
22196 $imax = min(($tmpnumchars - $pos), $charmax);
22197 for ($i = 1; $i <= $imax; ++
$i) {
22198 $subword = strtolower(TCPDF_FONTS
::UTF8ArrSubString($tmpword, $pos, ($pos +
$i), $this->isunicode
));
22199 if (isset($patterns[$subword])) {
22200 $pattern = TCPDF_FONTS
::UTF8StringToArray($patterns[$subword], $this->isunicode
, $this->CurrentFont
);
22201 $pattern_length = count($pattern);
22203 for ($j = 0; $j < $pattern_length; ++
$j) {
22204 // check if $pattern[$j] is a number = hyphenation level (only numbers from 1 to 5 are valid)
22205 if (($pattern[$j] >= 48) AND ($pattern[$j] <= 57)) {
22209 $zero = $pos +
$j - $digits;
22211 // get hyphenation level
22212 $level = ($pattern[$j] - 48);
22213 // if two levels from two different patterns match at the same point, the higher one is selected.
22214 if (!isset($hyphenword[$zero]) OR ($hyphenword[$zero] < $level)) {
22215 $hyphenword[$zero] = $level;
22224 $maxpos = $numchars - $rightmin;
22225 for ($i = $leftmin; $i <= $maxpos; ++
$i) {
22226 // only odd levels indicate allowed hyphenation points
22227 if (isset($hyphenword[$i]) AND (($hyphenword[$i] %
2) != 0)) {
22228 // 173 = soft hyphen character
22229 array_splice($word, $i +
$inserted, 0, 173);
22237 * Returns text with soft hyphens.
22238 * @param string $text text to process
22239 * @param mixed $patterns 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/
22240 * @param array $dictionary Array of words to be returned without applying the hyphenation algorithm.
22241 * @param int $leftmin Minimum number of character to leave on the left of the word without applying the hyphens.
22242 * @param int $rightmin Minimum number of character to leave on the right of the word without applying the hyphens.
22243 * @param int $charmin Minimum word length to apply the hyphenation algorithm.
22244 * @param int $charmax Maximum length of broken piece of word.
22245 * @return string text with soft hyphens
22246 * @author Nicola Asuni
22247 * @since 4.9.012 (2010-04-12)
22250 public function hyphenateText($text, $patterns, $dictionary=array(), $leftmin=1, $rightmin=2, $charmin=1, $charmax=8) {
22251 $text = $this->unhtmlentities($text);
22252 $word = array(); // last word
22253 $txtarr = array(); // text to be returned
22254 $intag = false; // true if we are inside an HTML tag
22255 $skip = false; // true to skip hyphenation
22256 if (!is_array($patterns)) {
22257 $patterns = TCPDF_STATIC
::getHyphenPatternsFromTEX($patterns);
22259 // get array of characters
22260 $unichars = TCPDF_FONTS
::UTF8StringToArray($text, $this->isunicode
, $this->CurrentFont
);
22262 foreach ($unichars as $char) {
22263 if ((!$intag) AND (!$skip) AND TCPDF_FONT_DATA
::$uni_type[$char] == 'L') {
22264 // letter character
22267 // other type of character
22268 if (!TCPDF_STATIC
::empty_string($word)) {
22269 // hypenate the word
22270 $txtarr = array_merge($txtarr, $this->hyphenateWord($word, $patterns, $dictionary, $leftmin, $rightmin, $charmin, $charmax));
22274 if (chr($char) == '<') {
22275 // we are inside an HTML tag
22277 } elseif ($intag AND (chr($char) == '>')) {
22280 // check for style tag
22281 $expected = array(115, 116, 121, 108, 101); // = 'style'
22282 $current = array_slice($txtarr, -6, 5); // last 5 chars
22283 $compare = array_diff($expected, $current);
22284 if (empty($compare)) {
22285 // check if it is a closing tag
22286 $expected = array(47); // = '/'
22287 $current = array_slice($txtarr, -7, 1);
22288 $compare = array_diff($expected, $current);
22289 if (empty($compare)) {
22290 // closing style tag
22293 // opening style tag
22300 if (!TCPDF_STATIC
::empty_string($word)) {
22301 // hypenate the word
22302 $txtarr = array_merge($txtarr, $this->hyphenateWord($word, $patterns, $dictionary, $leftmin, $rightmin, $charmin, $charmax));
22304 // convert char array to string and return
22305 return TCPDF_FONTS
::UTF8ArrSubString($txtarr, '', '', $this->isunicode
);
22309 * Enable/disable rasterization of vector images using ImageMagick library.
22310 * @param boolean $mode if true enable rasterization, false otherwise.
22312 * @since 5.0.000 (2010-04-27)
22314 public function setRasterizeVectorImages($mode) {
22315 $this->rasterize_vector_images
= $mode;
22319 * Enable or disable default option for font subsetting.
22320 * @param boolean $enable if true enable font subsetting by default.
22321 * @author Nicola Asuni
22323 * @since 5.3.002 (2010-06-07)
22325 public function setFontSubsetting($enable=true) {
22326 if ($this->pdfa_mode
) {
22327 $this->font_subsetting
= false;
22329 $this->font_subsetting
= $enable ?
true : false;
22334 * Return the default option for font subsetting.
22335 * @return bool default font subsetting state.
22336 * @author Nicola Asuni
22338 * @since 5.3.002 (2010-06-07)
22340 public function getFontSubsetting() {
22341 return $this->font_subsetting
;
22345 * Left trim the input string
22346 * @param string $str string to trim
22347 * @param string $replace string that replace spaces.
22348 * @return string left trimmed string
22349 * @author Nicola Asuni
22351 * @since 5.8.000 (2010-08-11)
22353 public function stringLeftTrim($str, $replace='') {
22354 return preg_replace('/^'.$this->re_space
['p'].'+/'.$this->re_space
['m'], $replace, $str);
22358 * Right trim the input string
22359 * @param string $str string to trim
22360 * @param string $replace string that replace spaces.
22361 * @return string right trimmed string
22362 * @author Nicola Asuni
22364 * @since 5.8.000 (2010-08-11)
22366 public function stringRightTrim($str, $replace='') {
22367 return preg_replace('/'.$this->re_space
['p'].'+$/'.$this->re_space
['m'], $replace, $str);
22371 * Trim the input string
22372 * @param string $str string to trim
22373 * @param string $replace string that replace spaces.
22374 * @return string trimmed string
22375 * @author Nicola Asuni
22377 * @since 5.8.000 (2010-08-11)
22379 public function stringTrim($str, $replace='') {
22380 $str = $this->stringLeftTrim($str, $replace);
22381 $str = $this->stringRightTrim($str, $replace);
22386 * Return true if the current font is unicode type.
22387 * @return bool true for unicode font, false otherwise.
22388 * @author Nicola Asuni
22390 * @since 5.8.002 (2010-08-14)
22392 public function isUnicodeFont() {
22393 return (($this->CurrentFont
['type'] == 'TrueTypeUnicode') OR ($this->CurrentFont
['type'] == 'cidfont0'));
22397 * Return normalized font name
22398 * @param string $fontfamily property string containing font family names
22399 * @return string normalized font name
22400 * @author Nicola Asuni
22402 * @since 5.8.004 (2010-08-17)
22404 public function getFontFamilyName($fontfamily) {
22405 // remove spaces and symbols
22406 $fontfamily = preg_replace('/[^a-z0-9_\,]/', '', strtolower($fontfamily));
22407 // extract all font names
22408 $fontslist = preg_split('/[,]/', $fontfamily);
22409 // find first valid font name
22410 foreach ($fontslist as $font) {
22411 // replace font variations
22412 $font = preg_replace('/regular$/', '', $font);
22413 $font = preg_replace('/italic$/', 'I', $font);
22414 $font = preg_replace('/oblique$/', 'I', $font);
22415 $font = preg_replace('/bold([I]?)$/', 'B\\1', $font);
22416 // replace common family names and core fonts
22417 $pattern = array();
22418 $replacement = array();
22419 $pattern[] = '/^serif|^cursive|^fantasy|^timesnewroman/';
22420 $replacement[] = 'times';
22421 $pattern[] = '/^sansserif/';
22422 $replacement[] = 'helvetica';
22423 $pattern[] = '/^monospace/';
22424 $replacement[] = 'courier';
22425 $font = preg_replace($pattern, $replacement, $font);
22426 if (in_array(strtolower($font), $this->fontlist
) OR in_array($font, $this->fontkeys
)) {
22430 // return current font as default
22431 return $this->CurrentFont
['fontkey'];
22435 * Start a new XObject Template.
22436 * 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).
22437 * 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.
22438 * Note: X,Y coordinates will be reset to 0,0.
22439 * @param int $w Template width in user units (empty string or zero = page width less margins).
22440 * @param int $h Template height in user units (empty string or zero = page height less margins).
22441 * @param mixed $group 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).
22442 * @return string|false the XObject Template ID in case of success or false in case of error.
22443 * @author Nicola Asuni
22445 * @since 5.8.017 (2010-08-24)
22446 * @see endTemplate(), printTemplate()
22448 public function startTemplate($w=0, $h=0, $group=false) {
22449 if ($this->inxobj
) {
22450 // we are already inside an XObject template
22453 $this->inxobj
= true;
22456 $this->xobjid
= 'XT'.$this->n
;
22458 $this->xobjects
[$this->xobjid
] = array('n' => $this->n
);
22459 // store current graphic state
22460 $this->xobjects
[$this->xobjid
]['gvars'] = $this->getGraphicVars();
22462 $this->xobjects
[$this->xobjid
]['intmrk'] = 0;
22463 $this->xobjects
[$this->xobjid
]['transfmrk'] = array();
22464 $this->xobjects
[$this->xobjid
]['outdata'] = '';
22465 $this->xobjects
[$this->xobjid
]['xobjects'] = array();
22466 $this->xobjects
[$this->xobjid
]['images'] = array();
22467 $this->xobjects
[$this->xobjid
]['fonts'] = array();
22468 $this->xobjects
[$this->xobjid
]['annotations'] = array();
22469 $this->xobjects
[$this->xobjid
]['extgstates'] = array();
22470 $this->xobjects
[$this->xobjid
]['gradients'] = array();
22471 $this->xobjects
[$this->xobjid
]['spot_colors'] = array();
22472 // set new environment
22473 $this->num_columns
= 1;
22474 $this->current_column
= 0;
22475 $this->setAutoPageBreak(false);
22476 if (($w === '') OR ($w <= 0)) {
22477 $w = $this->w
- $this->lMargin
- $this->rMargin
;
22479 if (($h === '') OR ($h <= 0)) {
22480 $h = $this->h
- $this->tMargin
- $this->bMargin
;
22482 $this->xobjects
[$this->xobjid
]['x'] = 0;
22483 $this->xobjects
[$this->xobjid
]['y'] = 0;
22484 $this->xobjects
[$this->xobjid
]['w'] = $w;
22485 $this->xobjects
[$this->xobjid
]['h'] = $h;
22488 $this->wPt
= $this->w
* $this->k
;
22489 $this->hPt
= $this->h
* $this->k
;
22490 $this->fwPt
= $this->wPt
;
22491 $this->fhPt
= $this->hPt
;
22494 $this->lMargin
= 0;
22495 $this->rMargin
= 0;
22496 $this->tMargin
= 0;
22497 $this->bMargin
= 0;
22499 $this->xobjects
[$this->xobjid
]['group'] = $group;
22500 return $this->xobjid
;
22504 * End the current XObject Template started with startTemplate() and restore the previous graphic state.
22505 * 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).
22506 * 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.
22507 * @return string|false the XObject Template ID in case of success or false in case of error.
22508 * @author Nicola Asuni
22510 * @since 5.8.017 (2010-08-24)
22511 * @see startTemplate(), printTemplate()
22513 public function endTemplate() {
22514 if (!$this->inxobj
) {
22515 // we are not inside a template
22518 $this->inxobj
= false;
22519 // restore previous graphic state
22520 $this->setGraphicVars($this->xobjects
[$this->xobjid
]['gvars'], true);
22521 return $this->xobjid
;
22525 * Print an XObject Template.
22526 * You can print an XObject Template inside the currently opened Template.
22527 * 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).
22528 * 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.
22529 * @param string $id The ID of XObject Template to print.
22530 * @param float|null $x X position in user units (empty string = current x position)
22531 * @param float|null $y Y position in user units (empty string = current y position)
22532 * @param float $w Width in user units (zero = remaining page width)
22533 * @param float $h Height in user units (zero = remaining page height)
22534 * @param string $align 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>
22535 * @param string $palign 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>
22536 * @param boolean $fitonpage If true the template is resized to not exceed page dimensions.
22537 * @author Nicola Asuni
22539 * @since 5.8.017 (2010-08-24)
22540 * @see startTemplate(), endTemplate()
22542 public function printTemplate($id, $x=null, $y=null, $w=0, $h=0, $align='', $palign='', $fitonpage=false) {
22543 if ($this->state
!= 2) {
22546 if (!isset($this->xobjects
[$id])) {
22547 $this->Error('The XObject Template \''.$id.'\' doesn\'t exist!');
22549 if ($this->inxobj
) {
22550 if ($id == $this->xobjid
) {
22551 // close current template
22552 $this->endTemplate();
22554 // use the template as resource for the template currently opened
22555 $this->xobjects
[$this->xobjid
]['xobjects'][$id] = $this->xobjects
[$id];
22558 // set default values
22559 if (TCPDF_STATIC
::empty_string($x)) {
22562 if (TCPDF_STATIC
::empty_string($y)) {
22565 // check page for no-write regions and adapt page margins if necessary
22566 list($x, $y) = $this->checkPageRegions($h, $x, $y);
22567 $ow = $this->xobjects
[$id]['w'];
22571 $oh = $this->xobjects
[$id]['h'];
22575 // calculate template width and height on document
22576 if (($w <= 0) AND ($h <= 0)) {
22579 } elseif ($w <= 0) {
22580 $w = $h * $ow / $oh;
22581 } elseif ($h <= 0) {
22582 $h = $w * $oh / $ow;
22584 // fit the template on available space
22585 list($w, $h, $x, $y) = $this->fitBlock($w, $h, $x, $y, $fitonpage);
22586 // set page alignment
22590 if ($palign == 'L') {
22591 $xt = $this->lMargin
;
22592 } elseif ($palign == 'C') {
22593 $xt = ($this->w +
$this->lMargin
- $this->rMargin
- $w) / 2;
22594 } elseif ($palign == 'R') {
22595 $xt = $this->w
- $this->rMargin
- $w;
22601 if ($palign == 'L') {
22602 $xt = $this->lMargin
;
22603 } elseif ($palign == 'C') {
22604 $xt = ($this->w +
$this->lMargin
- $this->rMargin
- $w) / 2;
22605 } elseif ($palign == 'R') {
22606 $xt = $this->w
- $this->rMargin
- $w;
22612 // print XObject Template + Transformation matrix
22613 $this->StartTransform();
22614 // translate and scale
22622 $tm[4] = $xt * $this->k
;
22623 $tm[5] = ($this->h
- $h - $y) * $this->k
;
22624 $this->Transform($tm);
22626 $this->_out('/'.$id.' Do');
22627 $this->StopTransform();
22629 if (!empty($this->xobjects
[$id]['annotations'])) {
22630 foreach ($this->xobjects
[$id]['annotations'] as $annot) {
22631 // transform original coordinates
22632 $coordlt = TCPDF_STATIC
::getTransformationMatrixProduct($tm, array(1, 0, 0, 1, ($annot['x'] * $this->k
), (-$annot['y'] * $this->k
)));
22633 $ax = ($coordlt[4] / $this->k
);
22634 $ay = ($this->h
- $h - ($coordlt[5] / $this->k
));
22635 $coordrb = TCPDF_STATIC
::getTransformationMatrixProduct($tm, array(1, 0, 0, 1, (($annot['x'] +
$annot['w']) * $this->k
), ((-$annot['y'] - $annot['h']) * $this->k
)));
22636 $aw = ($coordrb[4] / $this->k
) - $ax;
22637 $ah = ($this->h
- $h - ($coordrb[5] / $this->k
)) - $ay;
22638 $this->Annotation($ax, $ay, $aw, $ah, $annot['text'], $annot['opt'], $annot['spaces']);
22641 // set pointer to align the next text/objects
22649 $this->y
= $y +
round($h/2);
22659 $this->setY($rb_y);
22669 * Set the percentage of character stretching.
22670 * @param int $perc percentage of stretching (100 = no stretching)
22671 * @author Nicola Asuni
22673 * @since 5.9.000 (2010-09-29)
22675 public function setFontStretching($perc=100) {
22676 $this->font_stretching
= $perc;
22680 * Get the percentage of character stretching.
22681 * @return float stretching value
22682 * @author Nicola Asuni
22684 * @since 5.9.000 (2010-09-29)
22686 public function getFontStretching() {
22687 return $this->font_stretching
;
22691 * Set the amount to increase or decrease the space between characters in a text.
22692 * @param float $spacing amount to increase or decrease the space between characters in a text (0 = default spacing)
22693 * @author Nicola Asuni
22695 * @since 5.9.000 (2010-09-29)
22697 public function setFontSpacing($spacing=0) {
22698 $this->font_spacing
= $spacing;
22702 * Get the amount to increase or decrease the space between characters in a text.
22703 * @return int font spacing (tracking) value
22704 * @author Nicola Asuni
22706 * @since 5.9.000 (2010-09-29)
22708 public function getFontSpacing() {
22709 return $this->font_spacing
;
22713 * Return an array of no-write page regions
22714 * @return array of no-write page regions
22715 * @author Nicola Asuni
22717 * @since 5.9.003 (2010-10-13)
22718 * @see setPageRegions(), addPageRegion()
22720 public function getPageRegions() {
22721 return $this->page_regions
;
22725 * Set no-write regions on page.
22726 * 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.
22727 * A region is always aligned on the left or right side of the page ad is defined using a vertical segment.
22728 * You can set multiple regions for the same page.
22729 * @param array $regions 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.
22730 * @author Nicola Asuni
22732 * @since 5.9.003 (2010-10-13)
22733 * @see addPageRegion(), getPageRegions()
22735 public function setPageRegions($regions=array()) {
22736 // empty current regions array
22737 $this->page_regions
= array();
22739 foreach ($regions as $data) {
22740 $this->addPageRegion($data);
22745 * Add a single no-write region on selected page.
22746 * 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.
22747 * A region is always aligned on the left or right side of the page ad is defined using a vertical segment.
22748 * You can set multiple regions for the same page.
22749 * @param array $region 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).
22750 * @author Nicola Asuni
22752 * @since 5.9.003 (2010-10-13)
22753 * @see setPageRegions(), getPageRegions()
22755 public function addPageRegion($region) {
22756 if (!isset($region['page']) OR empty($region['page'])) {
22757 $region['page'] = $this->page
;
22759 if (isset($region['xt']) AND isset($region['xb']) AND ($region['xt'] > 0) AND ($region['xb'] > 0)
22760 AND isset($region['yt']) AND isset($region['yb']) AND ($region['yt'] >= 0) AND ($region['yt'] < $region['yb'])
22761 AND isset($region['side']) AND (($region['side'] == 'L') OR ($region['side'] == 'R'))) {
22762 $this->page_regions
[] = $region;
22767 * Remove a single no-write region.
22768 * @param int $key region key
22769 * @author Nicola Asuni
22771 * @since 5.9.003 (2010-10-13)
22772 * @see setPageRegions(), getPageRegions()
22774 public function removePageRegion($key) {
22775 if (isset($this->page_regions
[$key])) {
22776 unset($this->page_regions
[$key]);
22781 * Check page for no-write regions and adapt current coordinates and page margins if necessary.
22782 * 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.
22783 * A region is always aligned on the left or right side of the page ad is defined using a vertical segment.
22784 * @param float $h height of the text/image/object to print in user units
22785 * @param float $x current X coordinate in user units
22786 * @param float $y current Y coordinate in user units
22787 * @return float[] array($x, $y)
22788 * @author Nicola Asuni
22790 * @since 5.9.003 (2010-10-13)
22792 protected function checkPageRegions($h, $x, $y) {
22793 // set default values
22800 if (!$this->check_page_regions
OR empty($this->page_regions
)) {
22801 // no page regions defined
22802 return array($x, $y);
22805 $h = $this->getCellHeight($this->FontSize
);
22807 // check for page break
22808 if ($this->checkPageBreak($h, $y)) {
22809 // the content will be printed on a new page
22813 if ($this->num_columns
> 1) {
22815 $this->lMargin
= ($this->columns
[$this->current_column
]['x'] - $this->columns
[$this->current_column
]['w']);
22817 $this->rMargin
= ($this->w
- $this->columns
[$this->current_column
]['x'] - $this->columns
[$this->current_column
]['w']);
22821 $this->lMargin
= max($this->clMargin
, $this->original_lMargin
);
22823 $this->rMargin
= max($this->crMargin
, $this->original_rMargin
);
22826 // adjust coordinates and page margins
22827 foreach ($this->page_regions
as $regid => $regdata) {
22828 if ($regdata['page'] == $this->page
) {
22829 // check region boundaries
22830 if (($y > ($regdata['yt'] - $h)) AND ($y <= $regdata['yb'])) {
22831 // Y is inside the region
22832 $minv = ($regdata['xb'] - $regdata['xt']) / ($regdata['yb'] - $regdata['yt']); // inverse of angular coefficient
22833 $yt = max($y, $regdata['yt']);
22834 $yb = min(($yt +
$h), $regdata['yb']);
22835 $xt = (($yt - $regdata['yt']) * $minv) +
$regdata['xt'];
22836 $xb = (($yb - $regdata['yt']) * $minv) +
$regdata['xt'];
22837 if ($regdata['side'] == 'L') { // left side
22838 $new_margin = max($xt, $xb);
22839 if ($this->lMargin
< $new_margin) {
22841 // adjust left page margin
22842 $this->lMargin
= max(0, $new_margin);
22844 if ($x < $new_margin) {
22845 // adjust x position
22847 if ($new_margin > ($this->w
- $this->rMargin
)) {
22848 // adjust y position
22849 $y = $regdata['yb'] - $h;
22853 } elseif ($regdata['side'] == 'R') { // right side
22854 $new_margin = min($xt, $xb);
22855 if (($this->w
- $this->rMargin
) > $new_margin) {
22857 // adjust right page margin
22858 $this->rMargin
= max(0, ($this->w
- $new_margin));
22860 if ($x > $new_margin) {
22861 // adjust x position
22863 if ($new_margin > $this->lMargin
) {
22864 // adjust y position
22865 $y = $regdata['yb'] - $h;
22873 return array($x, $y);
22876 // --- SVG METHODS ---------------------------------------------------------
22879 * Embedd a Scalable Vector Graphics (SVG) image.
22880 * NOTE: SVG standard is not yet fully implemented, use the setRasterizeVectorImages() method to enable/disable rasterization of vector images using ImageMagick library.
22881 * @param string $file Name of the SVG file or a '@' character followed by the SVG data string.
22882 * @param float|null $x Abscissa of the upper-left corner.
22883 * @param float|null $y Ordinate of the upper-left corner.
22884 * @param float $w Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
22885 * @param float $h Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
22886 * @param mixed $link URL or identifier returned by AddLink().
22887 * @param string $align Indicates the alignment of the pointer next to image insertion relative to image height. The value can be:<ul><li>T: top-right for LTR or top-left for RTL</li><li>M: middle-right for LTR or middle-left for RTL</li><li>B: bottom-right for LTR or bottom-left for RTL</li><li>N: next line</li></ul> If the alignment is an empty string, then the pointer will be restored on the starting SVG position.
22888 * @param string $palign Allows to center or align the image on the current line. Possible values are:<ul><li>L : left align</li><li>C : center</li><li>R : right align</li><li>'' : empty string : left for LTR or right for RTL</li></ul>
22889 * @param mixed $border 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)))
22890 * @param boolean $fitonpage if true the image is resized to not exceed page dimensions.
22891 * @author Nicola Asuni
22892 * @since 5.0.000 (2010-05-02)
22895 public function ImageSVG($file, $x=null, $y=null, $w=0, $h=0, $link='', $align='', $palign='', $border=0, $fitonpage=false) {
22896 if ($this->state
!= 2) {
22900 $this->svggradients
= array();
22901 $this->svggradientid
= 0;
22902 $this->svgdefsmode
= false;
22903 $this->svgdefs
= array();
22904 $this->svgclipmode
= false;
22905 $this->svgclippaths
= array();
22906 $this->svgcliptm
= array();
22907 $this->svgclipid
= 0;
22908 $this->svgtext
= '';
22909 $this->svgtextmode
= array();
22910 if ($this->rasterize_vector_images
AND ($w > 0) AND ($h > 0)) {
22911 // convert SVG to raster image using GD or ImageMagick libraries
22912 return $this->Image($file, $x, $y, $w, $h, 'SVG', $link, $align, true, 300, $palign, false, false, $border, false, false, false);
22914 if ($file[0] === '@') { // image from string
22915 $this->svgdir
= '';
22916 $svgdata = substr($file, 1);
22917 } else { // SVG file
22918 $this->svgdir
= dirname($file);
22919 $svgdata = $this->getCachedFileContents($file);
22921 if ($svgdata === FALSE) {
22922 $this->Error('SVG file not found: '.$file);
22924 if (TCPDF_STATIC
::empty_string($x)) {
22927 if (TCPDF_STATIC
::empty_string($y)) {
22930 // check page for no-write regions and adapt page margins if necessary
22931 list($x, $y) = $this->checkPageRegions($h, $x, $y);
22937 $aspect_ratio_align = 'xMidYMid';
22938 $aspect_ratio_ms = 'meet';
22940 // get original image width and height
22941 preg_match('/<svg([^\>]*)>/si', $svgdata, $regs);
22942 if (isset($regs[1]) AND !empty($regs[1])) {
22944 if (preg_match('/[\s]+x[\s]*=[\s]*"([^"]*)"/si', $regs[1], $tmp)) {
22945 $ox = $this->getHTMLUnitToUnits($tmp[1], 0, $this->svgunit
, false);
22948 if (preg_match('/[\s]+y[\s]*=[\s]*"([^"]*)"/si', $regs[1], $tmp)) {
22949 $oy = $this->getHTMLUnitToUnits($tmp[1], 0, $this->svgunit
, false);
22952 if (preg_match('/[\s]+width[\s]*=[\s]*"([^"]*)"/si', $regs[1], $tmp)) {
22953 $ow = $this->getHTMLUnitToUnits($tmp[1], 1, $this->svgunit
, false);
22956 if (preg_match('/[\s]+height[\s]*=[\s]*"([^"]*)"/si', $regs[1], $tmp)) {
22957 $oh = $this->getHTMLUnitToUnits($tmp[1], 1, $this->svgunit
, false);
22960 $view_box = array();
22961 if (preg_match('/[\s]+viewBox[\s]*=[\s]*"[\s]*([0-9\.\-]+)[\s]+([0-9\.\-]+)[\s]+([0-9\.]+)[\s]+([0-9\.]+)[\s]*"/si', $regs[1], $tmp)) {
22962 if (count($tmp) == 5) {
22964 foreach ($tmp as $key => $val) {
22965 $view_box[$key] = $this->getHTMLUnitToUnits($val, 0, $this->svgunit
, false);
22967 $ox = $view_box[0];
22968 $oy = $view_box[1];
22970 // get aspect ratio
22972 if (preg_match('/[\s]+preserveAspectRatio[\s]*=[\s]*"([^"]*)"/si', $regs[1], $tmp)) {
22973 $aspect_ratio = preg_split('/[\s]+/si', $tmp[1]);
22974 switch (count($aspect_ratio)) {
22976 $aspect_ratio_align = $aspect_ratio[1];
22977 $aspect_ratio_ms = $aspect_ratio[2];
22981 $aspect_ratio_align = $aspect_ratio[0];
22982 $aspect_ratio_ms = $aspect_ratio[1];
22986 $aspect_ratio_align = $aspect_ratio[0];
22987 $aspect_ratio_ms = 'meet';
23000 // calculate image width and height on document
23001 if (($w <= 0) AND ($h <= 0)) {
23002 // convert image size to document unit
23005 } elseif ($w <= 0) {
23006 $w = $h * $ow / $oh;
23007 } elseif ($h <= 0) {
23008 $h = $w * $oh / $ow;
23010 // fit the image on available space
23011 list($w, $h, $x, $y) = $this->fitBlock($w, $h, $x, $y, $fitonpage);
23012 if ($this->rasterize_vector_images
) {
23013 // convert SVG to raster image using GD or ImageMagick libraries
23014 return $this->Image($file, $x, $y, $w, $h, 'SVG', $link, $align, true, 300, $palign, false, false, $border, false, false, false);
23017 $this->img_rb_y
= $y +
$h;
23020 if ($palign == 'L') {
23021 $ximg = $this->lMargin
;
23022 } elseif ($palign == 'C') {
23023 $ximg = ($this->w +
$this->lMargin
- $this->rMargin
- $w) / 2;
23024 } elseif ($palign == 'R') {
23025 $ximg = $this->w
- $this->rMargin
- $w;
23029 $this->img_rb_x
= $ximg;
23031 if ($palign == 'L') {
23032 $ximg = $this->lMargin
;
23033 } elseif ($palign == 'C') {
23034 $ximg = ($this->w +
$this->lMargin
- $this->rMargin
- $w) / 2;
23035 } elseif ($palign == 'R') {
23036 $ximg = $this->w
- $this->rMargin
- $w;
23040 $this->img_rb_x
= $ximg +
$w;
23042 // store current graphic vars
23043 $gvars = $this->getGraphicVars();
23044 // store SVG position and scale factors
23045 $svgoffset_x = ($ximg - $ox) * $this->k
;
23046 $svgoffset_y = -($y - $oy) * $this->k
;
23047 if (isset($view_box[2]) AND ($view_box[2] > 0) AND ($view_box[3] > 0)) {
23048 $ow = $view_box[2];
23049 $oh = $view_box[3];
23058 $svgscale_x = $w / $ow;
23059 $svgscale_y = $h / $oh;
23060 // scaling and alignment
23061 if ($aspect_ratio_align != 'none') {
23062 // store current scaling values
23063 $svgscale_old_x = $svgscale_x;
23064 $svgscale_old_y = $svgscale_y;
23065 // force uniform scaling
23066 if ($aspect_ratio_ms == 'slice') {
23067 // the entire viewport is covered by the viewBox
23068 if ($svgscale_x > $svgscale_y) {
23069 $svgscale_y = $svgscale_x;
23070 } elseif ($svgscale_x < $svgscale_y) {
23071 $svgscale_x = $svgscale_y;
23074 // the entire viewBox is visible within the viewport
23075 if ($svgscale_x < $svgscale_y) {
23076 $svgscale_y = $svgscale_x;
23077 } elseif ($svgscale_x > $svgscale_y) {
23078 $svgscale_x = $svgscale_y;
23081 // correct X alignment
23082 switch (substr($aspect_ratio_align, 1, 3)) {
23088 $svgoffset_x +
= (($w * $this->k
) - ($ow * $this->k
* $svgscale_x));
23093 $svgoffset_x +
= ((($w * $this->k
) - ($ow * $this->k
* $svgscale_x)) / 2);
23097 // correct Y alignment
23098 switch (substr($aspect_ratio_align, 5)) {
23104 $svgoffset_y -= (($h * $this->k
) - ($oh * $this->k
* $svgscale_y));
23109 $svgoffset_y -= ((($h * $this->k
) - ($oh * $this->k
* $svgscale_y)) / 2);
23114 // store current page break mode
23115 $page_break_mode = $this->AutoPageBreak
;
23116 $page_break_margin = $this->getBreakMargin();
23117 $cell_padding = $this->cell_padding
;
23118 $this->setCellPadding(0);
23119 $this->setAutoPageBreak(false);
23120 // save the current graphic state
23121 $this->_out('q'.$this->epsmarker
);
23122 // set initial clipping mask
23123 $this->Rect($ximg, $y, $w, $h, 'CNZ', array(), array());
23124 // scale and translate
23125 $e = $ox * $this->k
* (1 - $svgscale_x);
23126 $f = ($this->h
- $oy) * $this->k
* (1 - $svgscale_y);
23127 $this->_out(sprintf('%F %F %F %F %F %F cm', $svgscale_x, 0, 0, $svgscale_y, ($e +
$svgoffset_x), ($f +
$svgoffset_y)));
23128 // creates a new XML parser to be used by the other XML functions
23129 $parser = xml_parser_create('UTF-8');
23130 // the following function allows to use parser inside object
23131 xml_set_object($parser, $this);
23132 // disable case-folding for this XML parser
23133 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING
, 0);
23134 // sets the element handler functions for the XML parser
23135 xml_set_element_handler($parser, 'startSVGElementHandler', 'endSVGElementHandler');
23136 // sets the character data handler function for the XML parser
23137 xml_set_character_data_handler($parser, 'segSVGContentHandler');
23138 // start parsing an XML document
23139 if (!xml_parse($parser, $svgdata)) {
23140 $error_message = sprintf('SVG Error: %s at line %d', xml_error_string(xml_get_error_code($parser)), xml_get_current_line_number($parser));
23141 $this->Error($error_message);
23143 // free this XML parser
23144 xml_parser_free($parser);
23146 // >= PHP 7.0.0 "explicitly unset the reference to parser to avoid memory leaks"
23149 // restore previous graphic state
23150 $this->_out($this->epsmarker
.'Q');
23151 // restore graphic vars
23152 $this->setGraphicVars($gvars);
23153 $this->lasth
= $gvars['lasth'];
23154 if (!empty($border)) {
23162 $this->Cell($w, $h, '', $border, 0, '', 0, '', 0, true);
23167 $this->Link($ximg, $y, $w, $h, $link, 0);
23169 // set pointer to align the next text/objects
23173 $this->x
= $this->img_rb_x
;
23177 $this->y
= $y +
round($h/2);
23178 $this->x
= $this->img_rb_x
;
23182 $this->y
= $this->img_rb_y
;
23183 $this->x
= $this->img_rb_x
;
23187 $this->setY($this->img_rb_y
);
23191 // restore pointer to starting position
23192 $this->x
= $gvars['x'];
23193 $this->y
= $gvars['y'];
23194 $this->page
= $gvars['page'];
23195 $this->current_column
= $gvars['current_column'];
23196 $this->tMargin
= $gvars['tMargin'];
23197 $this->bMargin
= $gvars['bMargin'];
23198 $this->w
= $gvars['w'];
23199 $this->h
= $gvars['h'];
23200 $this->wPt
= $gvars['wPt'];
23201 $this->hPt
= $gvars['hPt'];
23202 $this->fwPt
= $gvars['fwPt'];
23203 $this->fhPt
= $gvars['fhPt'];
23207 $this->endlinex
= $this->img_rb_x
;
23208 // restore page break
23209 $this->setAutoPageBreak($page_break_mode, $page_break_margin);
23210 $this->cell_padding
= $cell_padding;
23214 * Convert SVG transformation matrix to PDF.
23215 * @param array $tm original SVG transformation matrix
23216 * @return array transformation matrix
23218 * @since 5.0.000 (2010-05-02)
23220 protected function convertSVGtMatrix($tm) {
23225 $e = $this->getHTMLUnitToUnits($tm[4], 1, $this->svgunit
, false) * $this->k
;
23226 $f = -$this->getHTMLUnitToUnits($tm[5], 1, $this->svgunit
, false) * $this->k
;
23228 $y = $this->h
* $this->k
;
23229 $e = ($x * (1 - $a)) - ($y * $c) +
$e;
23230 $f = ($y * (1 - $d)) - ($x * $b) +
$f;
23231 return array($a, $b, $c, $d, $e, $f);
23235 * Apply SVG graphic transformation matrix.
23236 * @param array $tm original SVG transformation matrix
23238 * @since 5.0.000 (2010-05-02)
23240 protected function SVGTransform($tm) {
23241 $this->Transform($this->convertSVGtMatrix($tm));
23245 * Apply the requested SVG styles (*** TO BE COMPLETED ***)
23246 * @param array $svgstyle array of SVG styles to apply
23247 * @param array $prevsvgstyle array of previous SVG style
23248 * @param int $x X origin of the bounding box
23249 * @param int $y Y origin of the bounding box
23250 * @param int $w width of the bounding box
23251 * @param int $h height of the bounding box
23252 * @param string $clip_function clip function
23253 * @param array $clip_params array of parameters for clipping function
23254 * @return string style
23255 * @author Nicola Asuni
23256 * @since 5.0.000 (2010-05-02)
23259 protected function setSVGStyles($svgstyle, $prevsvgstyle, $x=0, $y=0, $w=1, $h=1, $clip_function='', $clip_params=array()) {
23260 if ($this->state
!= 2) {
23264 $minlen = (0.01 / $this->k
); // minimum acceptable length
23265 if (!isset($svgstyle['opacity'])) {
23270 if (preg_match('/url\([\s]*\#([^\)]*)\)/si', $svgstyle['clip-path'], $regs)) {
23271 $clip_path = $this->svgclippaths
[$regs[1]];
23272 foreach ($clip_path as $cp) {
23273 $this->startSVGElementHandler('clip-path', $cp['name'], $cp['attribs'], $cp['tm']);
23277 if ($svgstyle['opacity'] != 1) {
23278 $this->setAlpha($svgstyle['opacity'], 'Normal', $svgstyle['opacity'], false);
23281 $fill_color = TCPDF_COLORS
::convertHTMLColorToDec($svgstyle['color'], $this->spot_colors
);
23282 $this->setFillColorArray($fill_color);
23284 $text_color = TCPDF_COLORS
::convertHTMLColorToDec($svgstyle['text-color'], $this->spot_colors
);
23285 $this->setTextColorArray($text_color);
23287 if (preg_match('/rect\(([a-z0-9\-\.]*)[\s]*([a-z0-9\-\.]*)[\s]*([a-z0-9\-\.]*)[\s]*([a-z0-9\-\.]*)\)/si', $svgstyle['clip'], $regs)) {
23288 $top = (isset($regs[1])?
$this->getHTMLUnitToUnits($regs[1], 0, $this->svgunit
, false):0);
23289 $right = (isset($regs[2])?
$this->getHTMLUnitToUnits($regs[2], 0, $this->svgunit
, false):0);
23290 $bottom = (isset($regs[3])?
$this->getHTMLUnitToUnits($regs[3], 0, $this->svgunit
, false):0);
23291 $left = (isset($regs[4])?
$this->getHTMLUnitToUnits($regs[4], 0, $this->svgunit
, false):0);
23294 $cw = $w - $left - $right;
23295 $ch = $h - $top - $bottom;
23296 if ($svgstyle['clip-rule'] == 'evenodd') {
23297 $clip_rule = 'CNZ';
23299 $clip_rule = 'CEO';
23301 $this->Rect($cx, $cy, $cw, $ch, $clip_rule, array(), array());
23305 if (preg_match('/url\([\s]*\#([^\)]*)\)/si', $svgstyle['fill'], $regs)) {
23307 $gradient = $this->svggradients
[$regs[1]];
23308 if (isset($gradient['xref'])) {
23309 // reference to another gradient definition
23310 $newgradient = $this->svggradients
[$gradient['xref']];
23311 $newgradient['coords'] = $gradient['coords'];
23312 $newgradient['mode'] = $gradient['mode'];
23313 $newgradient['type'] = $gradient['type'];
23314 $newgradient['gradientUnits'] = $gradient['gradientUnits'];
23315 if (isset($gradient['gradientTransform'])) {
23316 $newgradient['gradientTransform'] = $gradient['gradientTransform'];
23318 $gradient = $newgradient;
23320 //save current Graphic State
23321 $this->_outSaveGraphicsState();
23322 //set clipping area
23323 if (!empty($clip_function) AND method_exists($this, $clip_function)) {
23324 $bbox = call_user_func_array(array($this, $clip_function), $clip_params);
23325 if ((!isset($gradient['type']) OR ($gradient['type'] != 3)) AND is_array($bbox) AND (count($bbox) == 4)) {
23326 list($x, $y, $w, $h) = $bbox;
23329 if ($gradient['mode'] == 'measure') {
23330 if (!isset($gradient['coords'][4])) {
23331 $gradient['coords'][4] = 0.5;
23333 if (isset($gradient['gradientTransform']) AND !empty($gradient['gradientTransform'])) {
23334 $gtm = $gradient['gradientTransform'];
23335 // apply transformation matrix
23336 $xa = ($gtm[0] * $gradient['coords'][0]) +
($gtm[2] * $gradient['coords'][1]) +
$gtm[4];
23337 $ya = ($gtm[1] * $gradient['coords'][0]) +
($gtm[3] * $gradient['coords'][1]) +
$gtm[5];
23338 $xb = ($gtm[0] * $gradient['coords'][2]) +
($gtm[2] * $gradient['coords'][3]) +
$gtm[4];
23339 $yb = ($gtm[1] * $gradient['coords'][2]) +
($gtm[3] * $gradient['coords'][3]) +
$gtm[5];
23340 $r = sqrt(pow(($gtm[0] * $gradient['coords'][4]), 2) +
pow(($gtm[1] * $gradient['coords'][4]), 2));
23341 $gradient['coords'][0] = $xa;
23342 $gradient['coords'][1] = $ya;
23343 $gradient['coords'][2] = $xb;
23344 $gradient['coords'][3] = $yb;
23345 $gradient['coords'][4] = $r;
23347 // convert SVG coordinates to user units
23348 $gradient['coords'][0] = $this->getHTMLUnitToUnits($gradient['coords'][0], 0, $this->svgunit
, false);
23349 $gradient['coords'][1] = $this->getHTMLUnitToUnits($gradient['coords'][1], 0, $this->svgunit
, false);
23350 $gradient['coords'][2] = $this->getHTMLUnitToUnits($gradient['coords'][2], 0, $this->svgunit
, false);
23351 $gradient['coords'][3] = $this->getHTMLUnitToUnits($gradient['coords'][3], 0, $this->svgunit
, false);
23352 $gradient['coords'][4] = $this->getHTMLUnitToUnits($gradient['coords'][4], 0, $this->svgunit
, false);
23353 if ($w <= $minlen) {
23356 if ($h <= $minlen) {
23360 if ($gradient['gradientUnits'] == 'objectBoundingBox') {
23361 // convert to SVG coordinate system
23362 $gradient['coords'][0] +
= $x;
23363 $gradient['coords'][1] +
= $y;
23364 $gradient['coords'][2] +
= $x;
23365 $gradient['coords'][3] +
= $y;
23367 // calculate percentages
23368 $gradient['coords'][0] = (($gradient['coords'][0] - $x) / $w);
23369 $gradient['coords'][1] = (($gradient['coords'][1] - $y) / $h);
23370 $gradient['coords'][2] = (($gradient['coords'][2] - $x) / $w);
23371 $gradient['coords'][3] = (($gradient['coords'][3] - $y) / $h);
23372 $gradient['coords'][4] /= $w;
23373 } elseif ($gradient['mode'] == 'percentage') {
23374 foreach($gradient['coords'] as $key => $val) {
23375 $gradient['coords'][$key] = (intval($val) / 100);
23377 $gradient['coords'][$key] = 0;
23378 } elseif ($val > 1) {
23379 $gradient['coords'][$key] = 1;
23383 if (($gradient['type'] == 2) AND ($gradient['coords'][0] == $gradient['coords'][2]) AND ($gradient['coords'][1] == $gradient['coords'][3])) {
23384 // single color (no shading)
23385 $gradient['coords'][0] = 1;
23386 $gradient['coords'][1] = 0;
23387 $gradient['coords'][2] = 0.999;
23388 $gradient['coords'][3] = 0;
23390 // swap Y coordinates
23391 $tmp = $gradient['coords'][1];
23392 $gradient['coords'][1] = $gradient['coords'][3];
23393 $gradient['coords'][3] = $tmp;
23394 // set transformation map for gradient
23395 $cy = ($this->h
- $y);
23396 if ($gradient['type'] == 3) {
23397 // circular gradient
23398 $cy -= ($gradient['coords'][1] * ($w +
$h));
23399 $h = $w = max($w, $h);
23403 $this->_out(sprintf('%F 0 0 %F %F %F cm', ($w * $this->k
), ($h * $this->k
), ($x * $this->k
), ($cy * $this->k
)));
23404 if (count($gradient['stops']) > 1) {
23405 $this->Gradient($gradient['type'], $gradient['coords'], $gradient['stops'], array(), false);
23407 } elseif ($svgstyle['fill'] != 'none') {
23408 $fill_color = TCPDF_COLORS
::convertHTMLColorToDec($svgstyle['fill'], $this->spot_colors
);
23409 if ($svgstyle['fill-opacity'] != 1) {
23410 $this->setAlpha($this->alpha
['CA'], 'Normal', $svgstyle['fill-opacity'], false);
23412 $this->setFillColorArray($fill_color);
23413 if ($svgstyle['fill-rule'] == 'evenodd') {
23420 if ($svgstyle['stroke'] != 'none') {
23421 if ($svgstyle['stroke-opacity'] != 1) {
23422 $this->setAlpha($svgstyle['stroke-opacity'], 'Normal', $this->alpha
['ca'], false);
23423 } elseif (preg_match('/rgba\(\d+%?,\s*\d+%?,\s*\d+%?,\s*(\d+(?:\.\d+)?)\)/i', $svgstyle['stroke'], $rgba_matches)) {
23424 $this->setAlpha($rgba_matches[1], 'Normal', $this->alpha
['ca'], false);
23426 $stroke_style = array(
23427 'color' => TCPDF_COLORS
::convertHTMLColorToDec($svgstyle['stroke'], $this->spot_colors
),
23428 'width' => $this->getHTMLUnitToUnits($svgstyle['stroke-width'], 0, $this->svgunit
, false),
23429 'cap' => $svgstyle['stroke-linecap'],
23430 'join' => $svgstyle['stroke-linejoin']
23432 if (isset($svgstyle['stroke-dasharray']) AND !empty($svgstyle['stroke-dasharray']) AND ($svgstyle['stroke-dasharray'] != 'none')) {
23433 $stroke_style['dash'] = $svgstyle['stroke-dasharray'];
23435 $this->setLineStyle($stroke_style);
23440 if (!empty($svgstyle['font'])) {
23441 if (preg_match('/font-family[\s]*:[\s]*([^\;\"]*)/si', $svgstyle['font'], $regs)) {
23442 $font_family = $this->getFontFamilyName($regs[1]);
23444 $font_family = $svgstyle['font-family'];
23446 if (preg_match('/font-size[\s]*:[\s]*([^\s\;\"]*)/si', $svgstyle['font'], $regs)) {
23447 $font_size = trim($regs[1]);
23449 $font_size = $svgstyle['font-size'];
23451 if (preg_match('/font-style[\s]*:[\s]*([^\s\;\"]*)/si', $svgstyle['font'], $regs)) {
23452 $font_style = trim($regs[1]);
23454 $font_style = $svgstyle['font-style'];
23456 if (preg_match('/font-weight[\s]*:[\s]*([^\s\;\"]*)/si', $svgstyle['font'], $regs)) {
23457 $font_weight = trim($regs[1]);
23459 $font_weight = $svgstyle['font-weight'];
23461 if (preg_match('/font-stretch[\s]*:[\s]*([^\s\;\"]*)/si', $svgstyle['font'], $regs)) {
23462 $font_stretch = trim($regs[1]);
23464 $font_stretch = $svgstyle['font-stretch'];
23466 if (preg_match('/letter-spacing[\s]*:[\s]*([^\s\;\"]*)/si', $svgstyle['font'], $regs)) {
23467 $font_spacing = trim($regs[1]);
23469 $font_spacing = $svgstyle['letter-spacing'];
23472 $font_family = $this->getFontFamilyName($svgstyle['font-family']);
23473 $font_size = $svgstyle['font-size'];
23474 $font_style = $svgstyle['font-style'];
23475 $font_weight = $svgstyle['font-weight'];
23476 $font_stretch = $svgstyle['font-stretch'];
23477 $font_spacing = $svgstyle['letter-spacing'];
23479 $font_size = $this->getHTMLFontUnits($font_size, $this->svgstyles
[0]['font-size'], $prevsvgstyle['font-size'], $this->svgunit
);
23480 $font_stretch = $this->getCSSFontStretching($font_stretch, $svgstyle['font-stretch']);
23481 $font_spacing = $this->getCSSFontSpacing($font_spacing, $svgstyle['letter-spacing']);
23482 switch ($font_style) {
23497 switch ($font_weight) {
23500 $font_style .= 'B';
23504 if ((substr($font_family, -1) == 'I') AND (substr($font_family, -2, 1) == 'B')) {
23505 $font_family = substr($font_family, 0, -2).'I';
23506 } elseif (substr($font_family, -1) == 'B') {
23507 $font_family = substr($font_family, 0, -1);
23512 switch ($svgstyle['text-decoration']) {
23513 case 'underline': {
23514 $font_style .= 'U';
23518 $font_style .= 'O';
23521 case 'line-through': {
23522 $font_style .= 'D';
23530 $this->setFont($font_family, $font_style, $font_size);
23531 $this->setFontStretching($font_stretch);
23532 $this->setFontSpacing($font_spacing);
23537 * Draws an SVG path
23538 * @param string $d attribute d of the path SVG element
23539 * @param string $style Style of rendering. Possible values are:
23541 * <li>D or empty string: Draw (default).</li>
23542 * <li>F: Fill.</li>
23543 * <li>F*: Fill using the even-odd rule to determine which regions lie inside the clipping path.</li>
23544 * <li>DF or FD: Draw and fill.</li>
23545 * <li>DF* or FD*: Draw and fill using the even-odd rule to determine which regions lie inside the clipping path.</li>
23546 * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
23547 * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
23549 * @return array of container box measures (x, y, w, h)
23550 * @author Nicola Asuni
23551 * @since 5.0.000 (2010-05-02)
23554 protected function SVGPath($d, $style='') {
23555 if ($this->state
!= 2) {
23558 // set fill/stroke style
23559 $op = TCPDF_STATIC
::getPathPaintOperator($style, '');
23564 $d = preg_replace('/([0-9ACHLMQSTVZ])([\-\+])/si', '\\1 \\2', $d);
23565 $d = preg_replace('/(\.[0-9]+)(\.)/s', '\\1 \\2', $d);
23566 preg_match_all('/([ACHLMQSTVZ])[\s]*([^ACHLMQSTVZ\"]*)/si', $d, $paths, PREG_SET_ORDER
);
23573 $xmin = 2147483647;
23575 $ymin = 2147483647;
23580 $minlen = (0.01 / $this->k
); // minimum acceptable length (3 point)
23581 $firstcmd = true; // used to print first point
23582 // draw curve pieces
23583 foreach ($paths as $key => $val) {
23585 $cmd = trim($val[1]);
23586 if (strtolower($cmd) == $cmd) {
23587 // use relative coordinated instead of absolute
23597 if (isset($val[2])) {
23598 // get curve parameters
23599 $rawparams = preg_split('/([\,\s]+)/si', trim($val[2]));
23601 foreach ($rawparams as $ck => $cp) {
23602 $params[$ck] = $this->getHTMLUnitToUnits($cp, 0, $this->svgunit
, false);
23603 if (abs($params[$ck]) < $minlen) {
23604 // approximate little values to zero
23609 // store current origin point
23612 switch (strtoupper($cmd)) {
23613 case 'M': { // moveto
23614 foreach ($params as $ck => $cp) {
23615 if (($ck %
2) == 0) {
23616 $x = $cp +
$xoffset;
23618 $y = $cp +
$yoffset;
23619 if ($firstcmd OR (abs($x0 - $x) >= $minlen) OR (abs($y0 - $y) >= $minlen)) {
23621 $this->_outPoint($x, $y);
23626 $this->_outLine($x, $y);
23631 $xmin = min($xmin, $x);
23632 $ymin = min($ymin, $y);
23633 $xmax = max($xmax, $x);
23634 $ymax = max($ymax, $y);
23643 case 'L': { // lineto
23644 foreach ($params as $ck => $cp) {
23645 if (($ck %
2) == 0) {
23646 $x = $cp +
$xoffset;
23648 $y = $cp +
$yoffset;
23649 if ((abs($x0 - $x) >= $minlen) OR (abs($y0 - $y) >= $minlen)) {
23650 $this->_outLine($x, $y);
23654 $xmin = min($xmin, $x);
23655 $ymin = min($ymin, $y);
23656 $xmax = max($xmax, $x);
23657 $ymax = max($ymax, $y);
23666 case 'H': { // horizontal lineto
23667 foreach ($params as $ck => $cp) {
23668 $x = $cp +
$xoffset;
23669 if ((abs($x0 - $x) >= $minlen) OR (abs($y0 - $y) >= $minlen)) {
23670 $this->_outLine($x, $y);
23674 $xmin = min($xmin, $x);
23675 $xmax = max($xmax, $x);
23682 case 'V': { // vertical lineto
23683 foreach ($params as $ck => $cp) {
23684 $y = $cp +
$yoffset;
23685 if ((abs($x0 - $x) >= $minlen) OR (abs($y0 - $y) >= $minlen)) {
23686 $this->_outLine($x, $y);
23690 $ymin = min($ymin, $y);
23691 $ymax = max($ymax, $y);
23698 case 'C': { // curveto
23699 foreach ($params as $ck => $cp) {
23700 $params[$ck] = $cp;
23701 if ((($ck +
1) %
6) == 0) {
23702 $x1 = $params[($ck - 5)] +
$xoffset;
23703 $y1 = $params[($ck - 4)] +
$yoffset;
23704 $x2 = $params[($ck - 3)] +
$xoffset;
23705 $y2 = $params[($ck - 2)] +
$yoffset;
23706 $x = $params[($ck - 1)] +
$xoffset;
23707 $y = $params[($ck)] +
$yoffset;
23708 $this->_outCurve($x1, $y1, $x2, $y2, $x, $y);
23709 $xmin = min($xmin, $x, $x1, $x2);
23710 $ymin = min($ymin, $y, $y1, $y2);
23711 $xmax = max($xmax, $x, $x1, $x2);
23712 $ymax = max($ymax, $y, $y1, $y2);
23721 case 'S': { // shorthand/smooth curveto
23722 foreach ($params as $ck => $cp) {
23723 $params[$ck] = $cp;
23724 if ((($ck +
1) %
4) == 0) {
23725 if (($key > 0) AND ((strtoupper($paths[($key - 1)][1]) == 'C') OR (strtoupper($paths[($key - 1)][1]) == 'S'))) {
23726 $x1 = (2 * $x) - $x2;
23727 $y1 = (2 * $y) - $y2;
23732 $x2 = $params[($ck - 3)] +
$xoffset;
23733 $y2 = $params[($ck - 2)] +
$yoffset;
23734 $x = $params[($ck - 1)] +
$xoffset;
23735 $y = $params[($ck)] +
$yoffset;
23736 $this->_outCurve($x1, $y1, $x2, $y2, $x, $y);
23737 $xmin = min($xmin, $x, $x1, $x2);
23738 $ymin = min($ymin, $y, $y1, $y2);
23739 $xmax = max($xmax, $x, $x1, $x2);
23740 $ymax = max($ymax, $y, $y1, $y2);
23749 case 'Q': { // quadratic Bezier curveto
23750 foreach ($params as $ck => $cp) {
23751 $params[$ck] = $cp;
23752 if ((($ck +
1) %
4) == 0) {
23753 // convert quadratic points to cubic points
23754 $x1 = $params[($ck - 3)] +
$xoffset;
23755 $y1 = $params[($ck - 2)] +
$yoffset;
23756 $xa = ($x +
(2 * $x1)) / 3;
23757 $ya = ($y +
(2 * $y1)) / 3;
23758 $x = $params[($ck - 1)] +
$xoffset;
23759 $y = $params[($ck)] +
$yoffset;
23760 $xb = ($x +
(2 * $x1)) / 3;
23761 $yb = ($y +
(2 * $y1)) / 3;
23762 $this->_outCurve($xa, $ya, $xb, $yb, $x, $y);
23763 $xmin = min($xmin, $x, $xa, $xb);
23764 $ymin = min($ymin, $y, $ya, $yb);
23765 $xmax = max($xmax, $x, $xa, $xb);
23766 $ymax = max($ymax, $y, $ya, $yb);
23775 case 'T': { // shorthand/smooth quadratic Bezier curveto
23776 foreach ($params as $ck => $cp) {
23777 $params[$ck] = $cp;
23778 if (($ck %
2) != 0) {
23779 if (($key > 0) AND ((strtoupper($paths[($key - 1)][1]) == 'Q') OR (strtoupper($paths[($key - 1)][1]) == 'T'))) {
23780 $x1 = (2 * $x) - $x1;
23781 $y1 = (2 * $y) - $y1;
23786 // convert quadratic points to cubic points
23787 $xa = ($x +
(2 * $x1)) / 3;
23788 $ya = ($y +
(2 * $y1)) / 3;
23789 $x = $params[($ck - 1)] +
$xoffset;
23790 $y = $params[($ck)] +
$yoffset;
23791 $xb = ($x +
(2 * $x1)) / 3;
23792 $yb = ($y +
(2 * $y1)) / 3;
23793 $this->_outCurve($xa, $ya, $xb, $yb, $x, $y);
23794 $xmin = min($xmin, $x, $xa, $xb);
23795 $ymin = min($ymin, $y, $ya, $yb);
23796 $xmax = max($xmax, $x, $xa, $xb);
23797 $ymax = max($ymax, $y, $ya, $yb);
23806 case 'A': { // elliptical arc
23807 foreach ($params as $ck => $cp) {
23808 $params[$ck] = $cp;
23809 if ((($ck +
1) %
7) == 0) {
23812 $rx = max(abs($params[($ck - 6)]), .000000001);
23813 $ry = max(abs($params[($ck - 5)]), .000000001);
23814 $ang = -$rawparams[($ck - 4)];
23815 $angle = deg2rad($ang);
23816 $fa = $rawparams[($ck - 3)]; // large-arc-flag
23817 $fs = $rawparams[($ck - 2)]; // sweep-flag
23818 $x = $params[($ck - 1)] +
$xoffset;
23819 $y = $params[$ck] +
$yoffset;
23820 if ((abs($x0 - $x) < $minlen) AND (abs($y0 - $y) < $minlen)) {
23821 // endpoints are almost identical
23822 $xmin = min($xmin, $x);
23823 $ymin = min($ymin, $y);
23824 $xmax = max($xmax, $x);
23825 $ymax = max($ymax, $y);
23827 $cos_ang = cos($angle);
23828 $sin_ang = sin($angle);
23829 $a = (($x0 - $x) / 2);
23830 $b = (($y0 - $y) / 2);
23831 $xa = ($a * $cos_ang) - ($b * $sin_ang);
23832 $ya = ($a * $sin_ang) +
($b * $cos_ang);
23837 $delta = ($xa2 / $rx2) +
($ya2 / $ry2);
23839 $rx *= sqrt($delta);
23840 $ry *= sqrt($delta);
23844 $numerator = (($rx2 * $ry2) - ($rx2 * $ya2) - ($ry2 * $xa2));
23845 if ($numerator < 0) {
23848 $root = sqrt($numerator / (($rx2 * $ya2) +
($ry2 * $xa2)));
23853 $cax = $root * (($rx * $ya) / $ry);
23854 $cay = -$root * (($ry * $xa) / $rx);
23855 // coordinates of ellipse center
23856 $cx = ($cax * $cos_ang) - ($cay * $sin_ang) +
(($x0 +
$x) / 2);
23857 $cy = ($cax * $sin_ang) +
($cay * $cos_ang) +
(($y0 +
$y) / 2);
23859 $angs = TCPDF_STATIC
::getVectorsAngle(1, 0, (($xa - $cax) / $rx), (($cay - $ya) / $ry));
23860 $dang = TCPDF_STATIC
::getVectorsAngle((($xa - $cax) / $rx), (($ya - $cay) / $ry), ((-$xa - $cax) / $rx), ((-$ya - $cay) / $ry));
23861 if (($fs == 0) AND ($dang > 0)) {
23862 $dang -= (2 * M_PI
);
23863 } elseif (($fs == 1) AND ($dang < 0)) {
23864 $dang +
= (2 * M_PI
);
23866 $angf = $angs - $dang;
23867 if ((($fs == 0) AND ($angs > $angf)) OR (($fs == 1) AND ($angs < $angf))) {
23873 $angs = round(rad2deg($angs), 6);
23874 $angf = round(rad2deg($angf), 6);
23875 // covent angles to positive values
23876 if (($angs < 0) AND ($angf < 0)) {
23881 if (($key == 0) AND (isset($paths[($key +
1)][1])) AND (trim($paths[($key +
1)][1]) == 'z')) {
23884 list($axmin, $aymin, $axmax, $aymax) = $this->_outellipticalarc($cx, $cy, $rx, $ry, $ang, $angs, $angf, $pie, 2, false, ($fs == 0), true);
23885 $xmin = min($xmin, $x, $axmin);
23886 $ymin = min($ymin, $y, $aymin);
23887 $xmax = max($xmax, $x, $axmax);
23888 $ymax = max($ymax, $y, $aymax);
23900 $x = $x0 = $xinitial;
23901 $y = $y0 = $yinitial;
23908 return array($xmin, $ymin, ($xmax - $xmin), ($ymax - $ymin));
23912 * Return the tag name without the namespace
23913 * @param string $name Tag name
23916 protected function removeTagNamespace($name) {
23917 if(strpos($name, ':') !== false) {
23918 $parts = explode(':', $name);
23919 return $parts[(sizeof($parts) - 1)];
23925 * Sets the opening SVG element handler function for the XML parser. (*** TO BE COMPLETED ***)
23926 * @param resource|string $parser The first parameter, parser, is a reference to the XML parser calling the handler.
23927 * @param string $name 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.
23928 * @param array $attribs 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.
23929 * @param array $ctm tranformation matrix for clipping mode (starting transformation matrix).
23930 * @author Nicola Asuni
23931 * @since 5.0.000 (2010-05-02)
23934 protected function startSVGElementHandler($parser, $name, $attribs, $ctm=array()) {
23935 $name = $this->removeTagNamespace($name);
23936 // check if we are in clip mode
23937 if ($this->svgclipmode
) {
23938 $this->svgclippaths
[$this->svgclipid
][] = array('name' => $name, 'attribs' => $attribs, 'tm' => $this->svgcliptm
[$this->svgclipid
]);
23941 if ($this->svgdefsmode
AND !in_array($name, array('clipPath', 'linearGradient', 'radialGradient', 'stop'))) {
23942 if (isset($attribs['id'])) {
23943 $attribs['child_elements'] = array();
23944 $this->svgdefs
[$attribs['id']] = array('name' => $name, 'attribs' => $attribs);
23947 if (end($this->svgdefs
) !== FALSE) {
23948 $last_svgdefs_id = key($this->svgdefs
);
23949 if (isset($this->svgdefs
[$last_svgdefs_id]['attribs']['child_elements'])) {
23950 $attribs['id'] = 'DF_'.(count($this->svgdefs
[$last_svgdefs_id]['attribs']['child_elements']) +
1);
23951 $this->svgdefs
[$last_svgdefs_id]['attribs']['child_elements'][$attribs['id']] = array('name' => $name, 'attribs' => $attribs);
23958 if ($parser == 'clip-path') {
23959 // set clipping mode
23962 // get styling properties
23963 $prev_svgstyle = $this->svgstyles
[max(0,(count($this->svgstyles
) - 1))]; // previous style
23964 $svgstyle = $this->svgstyles
[0]; // set default style
23965 if ($clipping AND !isset($attribs['fill']) AND (!isset($attribs['style']) OR (!preg_match('/[;\"\s]{1}fill[\s]*:[\s]*([^;\"]*)/si', $attribs['style'], $attrval)))) {
23966 // default fill attribute for clipping
23967 $attribs['fill'] = 'none';
23969 if (isset($attribs['style']) AND !TCPDF_STATIC
::empty_string($attribs['style']) AND ($attribs['style'][0] != ';')) {
23970 // fix style for regular expression
23971 $attribs['style'] = ';'.$attribs['style'];
23973 foreach ($prev_svgstyle as $key => $val) {
23974 if (in_array($key, TCPDF_IMAGES
::$svginheritprop)) {
23975 // inherit previous value
23976 $svgstyle[$key] = $val;
23978 if (isset($attribs[$key]) AND !TCPDF_STATIC
::empty_string($attribs[$key])) {
23979 // specific attribute settings
23980 if ($attribs[$key] == 'inherit') {
23981 $svgstyle[$key] = $val;
23983 $svgstyle[$key] = $attribs[$key];
23985 } elseif (isset($attribs['style']) AND !TCPDF_STATIC
::empty_string($attribs['style'])) {
23986 // CSS style syntax
23987 $attrval = array();
23988 if (preg_match('/[;\"\s]{1}'.$key.'[\s]*:[\s]*([^;\"]*)/si', $attribs['style'], $attrval) AND isset($attrval[1])) {
23989 if ($attrval[1] == 'inherit') {
23990 $svgstyle[$key] = $val;
23992 $svgstyle[$key] = $attrval[1];
23997 // transformation matrix
23998 if (!empty($ctm)) {
24001 $tm = array(1,0,0,1,0,0);
24003 if (isset($attribs['transform']) AND !empty($attribs['transform'])) {
24004 $tm = TCPDF_STATIC
::getTransformationMatrixProduct($tm, TCPDF_STATIC
::getSVGTransformMatrix($attribs['transform']));
24006 $svgstyle['transfmatrix'] = $tm;
24007 $invisible = false;
24008 if (($svgstyle['visibility'] == 'hidden') OR ($svgstyle['visibility'] == 'collapse') OR ($svgstyle['display'] == 'none')) {
24009 // the current graphics element is invisible (nothing is painted)
24015 $this->svgdefsmode
= true;
24023 $this->svgclipmode
= true;
24024 if (!isset($attribs['id'])) {
24025 $attribs['id'] = 'CP_'.(count($this->svgcliptm
) +
1);
24027 $this->svgclipid
= $attribs['id'];
24028 $this->svgclippaths
[$this->svgclipid
] = array();
24029 $this->svgcliptm
[$this->svgclipid
] = $tm;
24033 // start of SVG object
24034 if(++
$this->svg_tag_depth
<= 1) {
24038 array_push($this->svgstyles
, $svgstyle);
24039 $this->StartTransform();
24040 $svgX = (isset($attribs['x'])?
$attribs['x']:0);
24041 $svgY = (isset($attribs['y'])?
$attribs['y']:0);
24042 $svgW = (isset($attribs['width'])?
$attribs['width']:0);
24043 $svgH = (isset($attribs['height'])?
$attribs['height']:0);
24044 // set x, y position using transform matrix
24045 $tm = TCPDF_STATIC
::getTransformationMatrixProduct($tm, array( 1, 0, 0, 1, $svgX, $svgY));
24046 $this->SVGTransform($tm);
24047 // set clipping for width and height
24050 $w = (isset($attribs['width'])?
$this->getHTMLUnitToUnits($attribs['width'], 0, $this->svgunit
, false):$this->w
);
24051 $h = (isset($attribs['height'])?
$this->getHTMLUnitToUnits($attribs['height'], 0, $this->svgunit
, false):$this->h
);
24052 // draw clipping rect
24053 $this->Rect($x, $y, $w, $h, 'CNZ', array(), array());
24054 // parse viewbox, calculate extra transformation matrix
24055 if (isset($attribs['viewBox'])) {
24057 preg_match_all("/[0-9]+/", $attribs['viewBox'], $tmp);
24059 if (sizeof($tmp) == 4) {
24064 // get aspect ratio
24069 if (isset($attribs['preserveAspectRatio'])) {
24070 if($attribs['preserveAspectRatio'] == 'none') {
24073 preg_match_all('/[a-zA-Z]+/', $attribs['preserveAspectRatio'], $tmp);
24075 if ((sizeof($tmp) == 2) AND (strlen($tmp[0]) == 8) AND (in_array($tmp[1], array('meet', 'slice', 'none')))) {
24076 $aspectX = substr($tmp[0], 0, 4);
24077 $aspectY = substr($tmp[0], 4, 4);
24082 $wr = ($svgW / $vw);
24083 $hr = ($svgH / $vh);
24085 if ((($fit == 'meet') AND ($hr < $wr)) OR (($fit == 'slice') AND ($hr > $wr))) {
24086 if ($aspectX == 'xMax') {
24087 $ax = (($vw * ($wr / $hr)) - $vw);
24089 if ($aspectX == 'xMid') {
24090 $ax = ((($vw * ($wr / $hr)) - $vw) / 2);
24093 } elseif ((($fit == 'meet') AND ($hr > $wr)) OR (($fit == 'slice') AND ($hr < $wr))) {
24094 if ($aspectY == 'YMax') {
24095 $ay = (($vh * ($hr / $wr)) - $vh);
24097 if ($aspectY == 'YMid') {
24098 $ay = ((($vh * ($hr / $wr)) - $vh) / 2);
24102 $newtm = array($wr, 0, 0, $hr, (($wr * ($ax - $vx)) - $svgX), (($hr * ($ay - $vy)) - $svgY));
24103 $tm = TCPDF_STATIC
::getTransformationMatrixProduct($tm, $newtm);
24104 $this->SVGTransform($tm);
24107 $this->setSVGStyles($svgstyle, $prev_svgstyle);
24111 // group together related graphics elements
24112 array_push($this->svgstyles
, $svgstyle);
24113 $this->StartTransform();
24114 $x = (isset($attribs['x'])?
$attribs['x']:0);
24115 $y = (isset($attribs['y'])?
$attribs['y']:0);
24116 $w = 1;//(isset($attribs['width'])?$attribs['width']:1);
24117 $h = 1;//(isset($attribs['height'])?$attribs['height']:1);
24118 $tm = TCPDF_STATIC
::getTransformationMatrixProduct($tm, array($w, 0, 0, $h, $x, $y));
24119 $this->SVGTransform($tm);
24120 $this->setSVGStyles($svgstyle, $prev_svgstyle);
24123 case 'linearGradient': {
24124 if ($this->pdfa_mode
&& $this->pdfa_version
< 2) {
24127 if (!isset($attribs['id'])) {
24128 $attribs['id'] = 'GR_'.(count($this->svggradients
) +
1);
24130 $this->svggradientid
= $attribs['id'];
24131 $this->svggradients
[$this->svggradientid
] = array();
24132 $this->svggradients
[$this->svggradientid
]['type'] = 2;
24133 $this->svggradients
[$this->svggradientid
]['stops'] = array();
24134 if (isset($attribs['gradientUnits'])) {
24135 $this->svggradients
[$this->svggradientid
]['gradientUnits'] = $attribs['gradientUnits'];
24137 $this->svggradients
[$this->svggradientid
]['gradientUnits'] = 'objectBoundingBox';
24139 //$attribs['spreadMethod']
24140 if (((!isset($attribs['x1'])) AND (!isset($attribs['y1'])) AND (!isset($attribs['x2'])) AND (!isset($attribs['y2'])))
24141 OR ((isset($attribs['x1']) AND (substr($attribs['x1'], -1) == '%'))
24142 OR (isset($attribs['y1']) AND (substr($attribs['y1'], -1) == '%'))
24143 OR (isset($attribs['x2']) AND (substr($attribs['x2'], -1) == '%'))
24144 OR (isset($attribs['y2']) AND (substr($attribs['y2'], -1) == '%')))) {
24145 $this->svggradients
[$this->svggradientid
]['mode'] = 'percentage';
24147 $this->svggradients
[$this->svggradientid
]['mode'] = 'measure';
24149 $x1 = (isset($attribs['x1'])?
$attribs['x1']:'0');
24150 $y1 = (isset($attribs['y1'])?
$attribs['y1']:'0');
24151 $x2 = (isset($attribs['x2'])?
$attribs['x2']:'100');
24152 $y2 = (isset($attribs['y2'])?
$attribs['y2']:'0');
24153 if (isset($attribs['gradientTransform'])) {
24154 $this->svggradients
[$this->svggradientid
]['gradientTransform'] = TCPDF_STATIC
::getSVGTransformMatrix($attribs['gradientTransform']);
24156 $this->svggradients
[$this->svggradientid
]['coords'] = array($x1, $y1, $x2, $y2);
24157 if (isset($attribs['xlink:href']) AND !empty($attribs['xlink:href'])) {
24158 // gradient is defined on another place
24159 $this->svggradients
[$this->svggradientid
]['xref'] = substr($attribs['xlink:href'], 1);
24163 case 'radialGradient': {
24164 if ($this->pdfa_mode
&& $this->pdfa_version
< 2) {
24167 if (!isset($attribs['id'])) {
24168 $attribs['id'] = 'GR_'.(count($this->svggradients
) +
1);
24170 $this->svggradientid
= $attribs['id'];
24171 $this->svggradients
[$this->svggradientid
] = array();
24172 $this->svggradients
[$this->svggradientid
]['type'] = 3;
24173 $this->svggradients
[$this->svggradientid
]['stops'] = array();
24174 if (isset($attribs['gradientUnits'])) {
24175 $this->svggradients
[$this->svggradientid
]['gradientUnits'] = $attribs['gradientUnits'];
24177 $this->svggradients
[$this->svggradientid
]['gradientUnits'] = 'objectBoundingBox';
24179 //$attribs['spreadMethod']
24180 if (((!isset($attribs['cx'])) AND (!isset($attribs['cy'])))
24181 OR ((isset($attribs['cx']) AND (substr($attribs['cx'], -1) == '%'))
24182 OR (isset($attribs['cy']) AND (substr($attribs['cy'], -1) == '%')))) {
24183 $this->svggradients
[$this->svggradientid
]['mode'] = 'percentage';
24184 } elseif (isset($attribs['r']) AND is_numeric($attribs['r']) AND ($attribs['r']) <= 1) {
24185 $this->svggradients
[$this->svggradientid
]['mode'] = 'ratio';
24187 $this->svggradients
[$this->svggradientid
]['mode'] = 'measure';
24189 $cx = (isset($attribs['cx']) ?
$attribs['cx'] : 0.5);
24190 $cy = (isset($attribs['cy']) ?
$attribs['cy'] : 0.5);
24191 $fx = (isset($attribs['fx']) ?
$attribs['fx'] : $cx);
24192 $fy = (isset($attribs['fy']) ?
$attribs['fy'] : $cy);
24193 $r = (isset($attribs['r']) ?
$attribs['r'] : 0.5);
24194 if (isset($attribs['gradientTransform'])) {
24195 $this->svggradients
[$this->svggradientid
]['gradientTransform'] = TCPDF_STATIC
::getSVGTransformMatrix($attribs['gradientTransform']);
24197 $this->svggradients
[$this->svggradientid
]['coords'] = array($cx, $cy, $fx, $fy, $r);
24198 if (isset($attribs['xlink:href']) AND !empty($attribs['xlink:href'])) {
24199 // gradient is defined on another place
24200 $this->svggradients
[$this->svggradientid
]['xref'] = substr($attribs['xlink:href'], 1);
24206 if (substr($attribs['offset'], -1) == '%') {
24207 $offset = floatval(substr($attribs['offset'], 0, -1)) / 100;
24209 $offset = floatval($attribs['offset']);
24214 $stop_color = isset($svgstyle['stop-color'])?TCPDF_COLORS
::convertHTMLColorToDec($svgstyle['stop-color'], $this->spot_colors
):'black';
24215 $opacity = isset($svgstyle['stop-opacity'])?
$svgstyle['stop-opacity']:1;
24216 $this->svggradients
[$this->svggradientid
]['stops'][] = array('offset' => $offset, 'color' => $stop_color, 'opacity' => $opacity);
24224 if (isset($attribs['d'])) {
24225 $d = trim($attribs['d']);
24227 $x = (isset($attribs['x'])?
$attribs['x']:0);
24228 $y = (isset($attribs['y'])?
$attribs['y']:0);
24229 $w = (isset($attribs['width'])?
$attribs['width']:1);
24230 $h = (isset($attribs['height'])?
$attribs['height']:1);
24231 $tm = TCPDF_STATIC
::getTransformationMatrixProduct($tm, array($w, 0, 0, $h, $x, $y));
24233 $this->SVGTransform($tm);
24234 $this->SVGPath($d, 'CNZ');
24236 $this->StartTransform();
24237 $this->SVGTransform($tm);
24238 $obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h, 'SVGPath', array($d, 'CNZ'));
24239 if (!empty($obstyle)) {
24240 $this->SVGPath($d, $obstyle);
24242 $this->StopTransform();
24253 $x = (isset($attribs['x'])?
$this->getHTMLUnitToUnits($attribs['x'], 0, $this->svgunit
, false):0);
24254 $y = (isset($attribs['y'])?
$this->getHTMLUnitToUnits($attribs['y'], 0, $this->svgunit
, false):0);
24255 $w = (isset($attribs['width'])?
$this->getHTMLUnitToUnits($attribs['width'], 0, $this->svgunit
, false):0);
24256 $h = (isset($attribs['height'])?
$this->getHTMLUnitToUnits($attribs['height'], 0, $this->svgunit
, false):0);
24257 $rx = (isset($attribs['rx'])?
$this->getHTMLUnitToUnits($attribs['rx'], 0, $this->svgunit
, false):0);
24258 $ry = (isset($attribs['ry'])?
$this->getHTMLUnitToUnits($attribs['ry'], 0, $this->svgunit
, false):$rx);
24260 $this->SVGTransform($tm);
24261 $this->RoundedRectXY($x, $y, $w, $h, $rx, $ry, '1111', 'CNZ', array(), array());
24263 $this->StartTransform();
24264 $this->SVGTransform($tm);
24265 $obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h, 'RoundedRectXY', array($x, $y, $w, $h, $rx, $ry, '1111', 'CNZ'));
24266 if (!empty($obstyle)) {
24267 $this->RoundedRectXY($x, $y, $w, $h, $rx, $ry, '1111', $obstyle, array(), array());
24269 $this->StopTransform();
24277 $r = (isset($attribs['r']) ?
$this->getHTMLUnitToUnits($attribs['r'], 0, $this->svgunit
, false) : 0);
24278 $cx = (isset($attribs['cx']) ?
$this->getHTMLUnitToUnits($attribs['cx'], 0, $this->svgunit
, false) : (isset($attribs['x']) ?
$this->getHTMLUnitToUnits($attribs['x'], 0, $this->svgunit
, false) : 0));
24279 $cy = (isset($attribs['cy']) ?
$this->getHTMLUnitToUnits($attribs['cy'], 0, $this->svgunit
, false) : (isset($attribs['y']) ?
$this->getHTMLUnitToUnits($attribs['y'], 0, $this->svgunit
, false) : 0));
24285 $this->SVGTransform($tm);
24286 $this->Circle($cx, $cy, $r, 0, 360, 'CNZ', array(), array(), 8);
24288 $this->StartTransform();
24289 $this->SVGTransform($tm);
24290 $obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h, 'Circle', array($cx, $cy, $r, 0, 360, 'CNZ'));
24291 if (!empty($obstyle)) {
24292 $this->Circle($cx, $cy, $r, 0, 360, $obstyle, array(), array(), 8);
24294 $this->StopTransform();
24302 $rx = (isset($attribs['rx']) ?
$this->getHTMLUnitToUnits($attribs['rx'], 0, $this->svgunit
, false) : 0);
24303 $ry = (isset($attribs['ry']) ?
$this->getHTMLUnitToUnits($attribs['ry'], 0, $this->svgunit
, false) : 0);
24304 $cx = (isset($attribs['cx']) ?
$this->getHTMLUnitToUnits($attribs['cx'], 0, $this->svgunit
, false) : (isset($attribs['x']) ?
$this->getHTMLUnitToUnits($attribs['x'], 0, $this->svgunit
, false) : 0));
24305 $cy = (isset($attribs['cy']) ?
$this->getHTMLUnitToUnits($attribs['cy'], 0, $this->svgunit
, false) : (isset($attribs['y']) ?
$this->getHTMLUnitToUnits($attribs['y'], 0, $this->svgunit
, false) : 0));
24311 $this->SVGTransform($tm);
24312 $this->Ellipse($cx, $cy, $rx, $ry, 0, 0, 360, 'CNZ', array(), array(), 8);
24314 $this->StartTransform();
24315 $this->SVGTransform($tm);
24316 $obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h, 'Ellipse', array($cx, $cy, $rx, $ry, 0, 0, 360, 'CNZ'));
24317 if (!empty($obstyle)) {
24318 $this->Ellipse($cx, $cy, $rx, $ry, 0, 0, 360, $obstyle, array(), array(), 8);
24320 $this->StopTransform();
24328 $x1 = (isset($attribs['x1'])?
$this->getHTMLUnitToUnits($attribs['x1'], 0, $this->svgunit
, false):0);
24329 $y1 = (isset($attribs['y1'])?
$this->getHTMLUnitToUnits($attribs['y1'], 0, $this->svgunit
, false):0);
24330 $x2 = (isset($attribs['x2'])?
$this->getHTMLUnitToUnits($attribs['x2'], 0, $this->svgunit
, false):0);
24331 $y2 = (isset($attribs['y2'])?
$this->getHTMLUnitToUnits($attribs['y2'], 0, $this->svgunit
, false):0);
24334 $w = abs($x2 - $x1);
24335 $h = abs($y2 - $y1);
24337 $this->StartTransform();
24338 $this->SVGTransform($tm);
24339 $obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h, 'Line', array($x1, $y1, $x2, $y2));
24340 $this->Line($x1, $y1, $x2, $y2);
24341 $this->StopTransform();
24350 $points = (isset($attribs['points'])?
$attribs['points']:'0 0');
24351 $points = trim($points);
24352 // note that point may use a complex syntax not covered here
24353 $points = preg_split('/[\,\s]+/si', $points);
24354 if (count($points) < 4) {
24358 $xmin = 2147483647;
24360 $ymin = 2147483647;
24362 foreach ($points as $key => $val) {
24363 $p[$key] = $this->getHTMLUnitToUnits($val, 0, $this->svgunit
, false);
24364 if (($key %
2) == 0) {
24366 $xmin = min($xmin, $p[$key]);
24367 $xmax = max($xmax, $p[$key]);
24370 $ymin = min($ymin, $p[$key]);
24371 $ymax = max($ymax, $p[$key]);
24376 $w = ($xmax - $xmin);
24377 $h = ($ymax - $ymin);
24378 if ($name == 'polyline') {
24379 $this->StartTransform();
24380 $this->SVGTransform($tm);
24381 $obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h, 'PolyLine', array($p, 'CNZ'));
24382 if (!empty($obstyle)) {
24383 $this->PolyLine($p, $obstyle, array(), array());
24385 $this->StopTransform();
24386 } else { // polygon
24388 $this->SVGTransform($tm);
24389 $this->Polygon($p, 'CNZ', array(), array(), true);
24391 $this->StartTransform();
24392 $this->SVGTransform($tm);
24393 $obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h, 'Polygon', array($p, 'CNZ'));
24394 if (!empty($obstyle)) {
24395 $this->Polygon($p, $obstyle, array(), array(), true);
24397 $this->StopTransform();
24407 if (!isset($attribs['xlink:href']) OR empty($attribs['xlink:href'])) {
24410 $x = (isset($attribs['x'])?
$this->getHTMLUnitToUnits($attribs['x'], 0, $this->svgunit
, false):0);
24411 $y = (isset($attribs['y'])?
$this->getHTMLUnitToUnits($attribs['y'], 0, $this->svgunit
, false):0);
24412 $w = (isset($attribs['width'])?
$this->getHTMLUnitToUnits($attribs['width'], 0, $this->svgunit
, false):0);
24413 $h = (isset($attribs['height'])?
$this->getHTMLUnitToUnits($attribs['height'], 0, $this->svgunit
, false):0);
24414 $img = $attribs['xlink:href'];
24416 $this->StartTransform();
24417 $this->SVGTransform($tm);
24418 $obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h);
24419 if (preg_match('/^data:image\/[^;]+;base64,/', $img, $m) > 0) {
24420 // embedded image encoded as base64
24421 $img = '@'.base64_decode(substr($img, strlen($m[0])));
24424 if (!TCPDF_STATIC
::empty_string($this->svgdir
) AND (($img[0] == '.') OR (basename($img) == $img))) {
24425 // replace relative path with full server path
24426 $img = $this->svgdir
.'/'.$img;
24428 if (($img[0] == '/') AND !empty($_SERVER['DOCUMENT_ROOT']) AND ($_SERVER['DOCUMENT_ROOT'] != '/')) {
24429 $findroot = strpos($img, $_SERVER['DOCUMENT_ROOT']);
24430 if (($findroot === false) OR ($findroot > 1)) {
24431 if (substr($_SERVER['DOCUMENT_ROOT'], -1) == '/') {
24432 $img = substr($_SERVER['DOCUMENT_ROOT'], 0, -1).$img;
24434 $img = $_SERVER['DOCUMENT_ROOT'].$img;
24438 $img = urldecode($img);
24439 $testscrtype = @parse_url
($img);
24440 if (empty($testscrtype['query'])) {
24441 // convert URL to server path
24442 $img = str_replace(K_PATH_URL
, K_PATH_MAIN
, $img);
24443 } elseif (preg_match('|^https?://|', $img) !== 1) {
24444 // convert server path to URL
24445 $img = str_replace(K_PATH_MAIN
, K_PATH_URL
, $img);
24449 $imgtype = TCPDF_IMAGES
::getImageFileType($img);
24450 if (($imgtype == 'eps') OR ($imgtype == 'ai')) {
24451 $this->ImageEps($img, $x, $y, $w, $h);
24452 } elseif ($imgtype == 'svg') {
24454 $svggradients = $this->svggradients
;
24455 $svggradientid = $this->svggradientid
;
24456 $svgdefsmode = $this->svgdefsmode
;
24457 $svgdefs = $this->svgdefs
;
24458 $svgclipmode = $this->svgclipmode
;
24459 $svgclippaths = $this->svgclippaths
;
24460 $svgcliptm = $this->svgcliptm
;
24461 $svgclipid = $this->svgclipid
;
24462 $svgtext = $this->svgtext
;
24463 $svgtextmode = $this->svgtextmode
;
24464 $this->ImageSVG($img, $x, $y, $w, $h);
24465 // restore SVG vars
24466 $this->svggradients
= $svggradients;
24467 $this->svggradientid
= $svggradientid;
24468 $this->svgdefsmode
= $svgdefsmode;
24469 $this->svgdefs
= $svgdefs;
24470 $this->svgclipmode
= $svgclipmode;
24471 $this->svgclippaths
= $svgclippaths;
24472 $this->svgcliptm
= $svgcliptm;
24473 $this->svgclipid
= $svgclipid;
24474 $this->svgtext
= $svgtext;
24475 $this->svgtextmode
= $svgtextmode;
24477 $this->Image($img, $x, $y, $w, $h);
24479 $this->StopTransform();
24486 if (isset($this->svgtextmode
['text-anchor']) AND !empty($this->svgtext
)) {
24487 // @TODO: unsupported feature
24489 // only basic support - advanced features must be implemented
24490 $this->svgtextmode
['invisible'] = $invisible;
24494 array_push($this->svgstyles
, $svgstyle);
24495 if (isset($attribs['x'])) {
24496 $x = $this->getHTMLUnitToUnits($attribs['x'], 0, $this->svgunit
, false);
24497 } elseif ($name == 'tspan') {
24502 if (isset($attribs['dx'])) {
24503 $x +
= $this->getHTMLUnitToUnits($attribs['dx'], 0, $this->svgunit
, false);
24505 if (isset($attribs['y'])) {
24506 $y = $this->getHTMLUnitToUnits($attribs['y'], 0, $this->svgunit
, false);
24507 } elseif ($name == 'tspan') {
24512 if (isset($attribs['dy'])) {
24513 $y +
= $this->getHTMLUnitToUnits($attribs['dy'], 0, $this->svgunit
, false);
24515 $svgstyle['text-color'] = $svgstyle['fill'];
24516 $this->svgtext
= '';
24517 if (isset($svgstyle['text-anchor'])) {
24518 $this->svgtextmode
['text-anchor'] = $svgstyle['text-anchor'];
24520 $this->svgtextmode
['text-anchor'] = 'start';
24522 if (isset($svgstyle['direction'])) {
24523 if ($svgstyle['direction'] == 'rtl') {
24524 $this->svgtextmode
['rtl'] = true;
24526 $this->svgtextmode
['rtl'] = false;
24529 $this->svgtextmode
['rtl'] = false;
24531 if (isset($svgstyle['stroke']) AND ($svgstyle['stroke'] != 'none') AND isset($svgstyle['stroke-width']) AND ($svgstyle['stroke-width'] > 0)) {
24532 $this->svgtextmode
['stroke'] = $this->getHTMLUnitToUnits($svgstyle['stroke-width'], 0, $this->svgunit
, false);
24534 $this->svgtextmode
['stroke'] = false;
24536 $this->StartTransform();
24537 $this->SVGTransform($tm);
24538 $obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, 1, 1);
24545 if (isset($attribs['xlink:href']) AND !empty($attribs['xlink:href'])) {
24546 $svgdefid = substr($attribs['xlink:href'], 1);
24547 if (isset($this->svgdefs
[$svgdefid])) {
24548 $use = $this->svgdefs
[$svgdefid];
24549 if (isset($attribs['xlink:href'])) {
24550 unset($attribs['xlink:href']);
24552 if (isset($attribs['id'])) {
24553 unset($attribs['id']);
24555 if (isset($use['attribs']['x']) AND isset($attribs['x'])) {
24556 $attribs['x'] +
= $use['attribs']['x'];
24558 if (isset($use['attribs']['y']) AND isset($attribs['y'])) {
24559 $attribs['y'] +
= $use['attribs']['y'];
24561 if (empty($attribs['style'])) {
24562 $attribs['style'] = '';
24564 if (!empty($use['attribs']['style'])) {
24566 $attribs['style'] = str_replace(';;',';',';'.$use['attribs']['style'].$attribs['style']);
24568 $attribs = array_merge($use['attribs'], $attribs);
24569 $this->startSVGElementHandler($parser, $use['name'], $attribs);
24579 // process child elements
24580 if (!empty($attribs['child_elements'])) {
24581 $child_elements = $attribs['child_elements'];
24582 unset($attribs['child_elements']);
24583 foreach($child_elements as $child_element) {
24584 if (empty($child_element['attribs']['closing_tag'])) {
24585 $this->startSVGElementHandler('child-tag', $child_element['name'], $child_element['attribs']);
24587 if (isset($child_element['attribs']['content'])) {
24588 $this->svgtext
= $child_element['attribs']['content'];
24590 $this->endSVGElementHandler('child-tag', $child_element['name']);
24597 * Sets the closing SVG element handler function for the XML parser.
24598 * @param resource|string $parser The first parameter, parser, is a reference to the XML parser calling the handler.
24599 * @param string $name 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.
24600 * @author Nicola Asuni
24601 * @since 5.0.000 (2010-05-02)
24604 protected function endSVGElementHandler($parser, $name) {
24605 $name = $this->removeTagNamespace($name);
24606 if ($this->svgdefsmode
AND !in_array($name, array('defs', 'clipPath', 'linearGradient', 'radialGradient', 'stop'))) {;
24607 if (end($this->svgdefs
) !== FALSE) {
24608 $last_svgdefs_id = key($this->svgdefs
);
24609 if (isset($this->svgdefs
[$last_svgdefs_id]['attribs']['child_elements'])) {
24610 foreach($this->svgdefs
[$last_svgdefs_id]['attribs']['child_elements'] as $child_element) {
24611 if (isset($child_element['attribs']['id']) AND ($child_element['name'] == $name)) {
24612 $this->svgdefs
[$last_svgdefs_id]['attribs']['child_elements'][$child_element['attribs']['id'].'_CLOSE'] = array('name' => $name, 'attribs' => array('closing_tag' => TRUE, 'content' => $this->svgtext
));
24616 if ($this->svgdefs
[$last_svgdefs_id]['name'] == $name) {
24617 $this->svgdefs
[$last_svgdefs_id]['attribs']['child_elements'][$last_svgdefs_id.'_CLOSE'] = array('name' => $name, 'attribs' => array('closing_tag' => TRUE, 'content' => $this->svgtext
));
24626 $this->svgdefsmode
= false;
24631 $this->svgclipmode
= false;
24635 if (--$this->svg_tag_depth
<= 0) {
24640 // ungroup: remove last style from array
24641 array_pop($this->svgstyles
);
24642 $this->StopTransform();
24647 if ($this->svgtextmode
['invisible']) {
24648 // This implementation must be fixed to following the rule:
24649 // 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.
24653 $text = $this->svgtext
;
24654 //$text = $this->stringTrim($text);
24655 $textlen = $this->GetStringWidth($text);
24656 if ($this->svgtextmode
['text-anchor'] != 'start') {
24657 // check if string is RTL text
24658 if ($this->svgtextmode
['text-anchor'] == 'end') {
24659 if ($this->svgtextmode
['rtl']) {
24660 $this->x +
= $textlen;
24662 $this->x
-= $textlen;
24664 } elseif ($this->svgtextmode
['text-anchor'] == 'middle') {
24665 if ($this->svgtextmode
['rtl']) {
24666 $this->x +
= ($textlen / 2);
24668 $this->x
-= ($textlen / 2);
24672 $textrendermode = $this->textrendermode
;
24673 $textstrokewidth = $this->textstrokewidth
;
24674 $this->setTextRenderingMode($this->svgtextmode
['stroke'], true, false);
24675 if ($name == 'text') {
24676 // store current coordinates
24681 $this->Cell($textlen, 0, $text, 0, 0, '', false, '', 0, false, 'L', 'T');
24682 if ($name == 'text') {
24683 // restore coordinates
24687 // restore previous rendering mode
24688 $this->textrendermode
= $textrendermode;
24689 $this->textstrokewidth
= $textstrokewidth;
24690 $this->svgtext
= '';
24691 $this->StopTransform();
24692 if (!$this->svgdefsmode
) {
24693 array_pop($this->svgstyles
);
24704 * Sets the character data handler function for the XML parser.
24705 * @param resource $parser The first parameter, parser, is a reference to the XML parser calling the handler.
24706 * @param string $data The second parameter, data, contains the character data as a string.
24707 * @author Nicola Asuni
24708 * @since 5.0.000 (2010-05-02)
24711 protected function segSVGContentHandler($parser, $data) {
24712 $this->svgtext
.= $data;
24715 // --- END SVG METHODS -----------------------------------------------------
24718 * Keeps files in memory, so it doesn't need to downloaded everytime in a loop
24719 * @param string $file
24722 protected function getCachedFileContents($file)
24724 if (!isset($this->fileContentCache
[$file])) {
24725 $this->fileContentCache
[$file] = TCPDF_STATIC
::fileGetContents($file);
24727 return $this->fileContentCache
[$file];
24731 * Avoid multiple calls to an external server to see if a file exists
24732 * @param string $file
24735 protected function fileExists($file)
24737 if (isset($this->fileContentCache
[$file]) ||
false !== $this->getImageBuffer($file)) {
24741 return TCPDF_STATIC
::file_exists($file);
24744 } // END OF TCPDF CLASS
24746 //============================================================+
24748 //============================================================+