Advisor: mark that 'Rate of reading fixed position' may be wrong, requires further...
[phpmyadmin/thilanka.git] / libraries / tcpdf / tcpdf.php
bloba60c193840e5739d01f1d316e93b929be9ad2662
1 <?php
2 //============================================================+
3 // File name : tcpdf.php
4 // Version : 5.9.108
5 // Begin : 2002-08-03
6 // Last Update : 2011-08-09
7 // Author : Nicola Asuni - Tecnick.com S.r.l - Via Della Pace, 11 - 09044 - Quartucciu (CA) - ITALY - www.tecnick.com - info@tecnick.com
8 // License : http://www.tecnick.com/pagefiles/tcpdf/LICENSE.TXT GNU-LGPLv3 + YOU CAN'T REMOVE ANY TCPDF COPYRIGHT NOTICE OR LINK FROM THE GENERATED PDF DOCUMENTS.
9 // -------------------------------------------------------------------
10 // Copyright (C) 2002-2011 Nicola Asuni - Tecnick.com S.r.l.
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. Additionally,
18 // YOU CAN'T REMOVE ANY TCPDF COPYRIGHT NOTICE OR LINK FROM THE
19 // GENERATED PDF DOCUMENTS.
21 // TCPDF is distributed in the hope that it will be useful, but
22 // WITHOUT ANY WARRANTY; without even the implied warranty of
23 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
24 // See the GNU Lesser General Public License for more details.
26 // You should have received a copy of the License
27 // along with TCPDF. If not, see
28 // <http://www.tecnick.com/pagefiles/tcpdf/LICENSE.TXT>.
30 // See LICENSE.TXT file for more information.
31 // -------------------------------------------------------------------
33 // Description :
34 // This is a PHP class for generating PDF documents without requiring external extensions.
36 // NOTE:
37 // This class was originally derived in 2002 from the Public
38 // Domain FPDF class by Olivier Plathey (http://www.fpdf.org),
39 // but now is almost entirely rewritten and contains thousands of
40 // new lines of code and hundreds new features.
42 // Main features:
43 // * no external libraries are required for the basic functions;
44 // * all standard page formats, custom page formats, custom margins and units of measure;
45 // * UTF-8 Unicode and Right-To-Left languages;
46 // * TrueTypeUnicode, OpenTypeUnicode, TrueType, OpenType, Type1 and CID-0 fonts;
47 // * font subsetting;
48 // * methods to publish some XHTML + CSS code, Javascript and Forms;
49 // * images, graphic (geometric figures) and transformation methods;
50 // * 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 ImagMagick (http://www.imagemagick.org/www/formats.html)
51 // * 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 Extention, 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, QR-Code, PDF417;
52 // * JPEG and PNG ICC profiles, Grayscale, RGB, CMYK, Spot Colors and Transparencies;
53 // * automatic page header and footer management;
54 // * document encryption up to 256 bit and digital signature certifications;
55 // * transactions to UNDO commands;
56 // * PDF annotations, including links, text and file attachments;
57 // * text rendering modes (fill, stroke and clipping);
58 // * multiple columns mode;
59 // * no-write page regions;
60 // * bookmarks, named destinations and table of content;
61 // * text hyphenation;
62 // * text stretching and spacing (tracking/kerning);
63 // * automatic page break, line break and text alignments including justification;
64 // * automatic page numbering and page groups;
65 // * move and delete pages;
66 // * page compression (requires php-zlib extension);
67 // * XOBject Templates;
68 // * Layers and object visibility.
70 // -----------------------------------------------------------
71 // THANKS TO:
73 // Olivier Plathey (http://www.fpdf.org) for original FPDF.
74 // Efthimios Mavrogeorgiadis (emavro@yahoo.com) for suggestions on RTL language support.
75 // Klemen Vodopivec (http://www.fpdf.de/downloads/addons/37/) for Encryption algorithm.
76 // Warren Sherliker (wsherliker@gmail.com) for better image handling.
77 // dullus for text Justification.
78 // Bob Vincent (pillarsdotnet@users.sourceforge.net) for <li> value attribute.
79 // Patrick Benny for text stretch suggestion on Cell().
80 // Johannes Güntert for JavaScript support.
81 // Denis Van Nuffelen for Dynamic Form.
82 // Jacek Czekaj for multibyte justification
83 // Anthony Ferrara for the reintroduction of legacy image methods.
84 // Sourceforge user 1707880 (hucste) for line-trough mode.
85 // Larry Stanbery for page groups.
86 // Martin Hall-May for transparency.
87 // Aaron C. Spike for Polycurve method.
88 // Mohamad Ali Golkar, Saleh AlMatrafe, Charles Abbott for Arabic and Persian support.
89 // Moritz Wagner and Andreas Wurmser for graphic functions.
90 // Andrew Whitehead for core fonts support.
91 // Esteban Joël Marín for OpenType font conversion.
92 // Teus Hagen for several suggestions and fixes.
93 // Yukihiro Nakadaira for CID-0 CJK fonts fixes.
94 // Kosmas Papachristos for some CSS improvements.
95 // Marcel Partap for some fixes.
96 // Won Kyu Park for several suggestions, fixes and patches.
97 // Dominik Dzienia for QR-code support.
98 // Laurent Minguet for some suggestions.
99 // Christian Deligant for some suggestions and fixes.
100 // Anyone that has reported a bug or sent a suggestion.
101 //============================================================+
104 * @file
105 * This is a PHP class for generating PDF documents without requiring external extensions.<br>
106 * 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>
107 * <h3>TCPDF main features are:</h3>
108 * <ul>
109 * <li>no external libraries are required for the basic functions;</li>
110 * <li>all standard page formats, custom page formats, custom margins and units of measure;</li>
111 * <li>UTF-8 Unicode and Right-To-Left languages;</li>
112 * <li>TrueTypeUnicode, OpenTypeUnicode, TrueType, OpenType, Type1 and CID-0 fonts;</li>
113 * <li>font subsetting;</li>
114 * <li>methods to publish some XHTML + CSS code, Javascript and Forms;</li>
115 * <li>images, graphic (geometric figures) and transformation methods;
116 * <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 ImagMagick (http://www.imagemagick.org/www/formats.html)</li>
117 * <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 Extention, 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, QR-Code, PDF417;</li>
118 * <li>JPEG and PNG ICC profiles, Grayscale, RGB, CMYK, Spot Colors and Transparencies;</li>
119 * <li>automatic page header and footer management;</li>
120 * <li>document encryption up to 256 bit and digital signature certifications;</li>
121 * <li>transactions to UNDO commands;</li>
122 * <li>PDF annotations, including links, text and file attachments;</li>
123 * <li>text rendering modes (fill, stroke and clipping);</li>
124 * <li>multiple columns mode;</li>
125 * <li>no-write page regions;</li>
126 * <li>bookmarks, named destinations and table of content;</li>
127 * <li>text hyphenation;</li>
128 * <li>text stretching and spacing (tracking/kerning);</li>
129 * <li>automatic page break, line break and text alignments including justification;</li>
130 * <li>automatic page numbering and page groups;</li>
131 * <li>move and delete pages;</li>
132 * <li>page compression (requires php-zlib extension);</li>
133 * <li>XOBject Templates;</li>
134 * <li>Layers and object visibility;</li>
135 * </ul>
136 * Tools to encode your unicode fonts are on fonts/utils directory.</p>
137 * @package com.tecnick.tcpdf
138 * @author Nicola Asuni
139 * @version 5.9.108
142 // Main configuration file. Define the K_TCPDF_EXTERNAL_CONFIG constant to skip this file.
143 require_once(dirname(__FILE__).'/config/tcpdf_config.php');
146 * @class TCPDF
147 * PHP class for generating PDF documents without requiring external extensions.
148 * 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>
149 * @package com.tecnick.tcpdf
150 * @brief PHP class for generating PDF documents without requiring external extensions.
151 * @version 5.9.108
152 * @author Nicola Asuni - info@tecnick.com
154 class TCPDF {
156 // private properties
159 * Current TCPDF version.
160 * @private
162 private $tcpdf_version = '5.9.108';
164 // Protected properties
167 * Current page number.
168 * @protected
170 protected $page;
173 * Current object number.
174 * @protected
176 protected $n;
179 * Array of object offsets.
180 * @protected
182 protected $offsets;
185 * Buffer holding in-memory PDF.
186 * @protected
188 protected $buffer;
191 * Array containing pages.
192 * @protected
194 protected $pages = array();
197 * Current document state.
198 * @protected
200 protected $state;
203 * Compression flag.
204 * @protected
206 protected $compress;
209 * Current page orientation (P = Portrait, L = Landscape).
210 * @protected
212 protected $CurOrientation;
215 * Page dimensions.
216 * @protected
218 protected $pagedim = array();
221 * Scale factor (number of points in user unit).
222 * @protected
224 protected $k;
227 * Width of page format in points.
228 * @protected
230 protected $fwPt;
233 * Height of page format in points.
234 * @protected
236 protected $fhPt;
239 * Current width of page in points.
240 * @protected
242 protected $wPt;
245 * Current height of page in points.
246 * @protected
248 protected $hPt;
251 * Current width of page in user unit.
252 * @protected
254 protected $w;
257 * Current height of page in user unit.
258 * @protected
260 protected $h;
263 * Left margin.
264 * @protected
266 protected $lMargin;
269 * Top margin.
270 * @protected
272 protected $tMargin;
275 * Right margin.
276 * @protected
278 protected $rMargin;
281 * Page break margin.
282 * @protected
284 protected $bMargin;
287 * Array of cell internal paddings ('T' => top, 'R' => right, 'B' => bottom, 'L' => left).
288 * @since 5.9.000 (2010-10-03)
289 * @protected
291 protected $cell_padding = array('T' => 0, 'R' => 0, 'B' => 0, 'L' => 0);
294 * Array of cell margins ('T' => top, 'R' => right, 'B' => bottom, 'L' => left).
295 * @since 5.9.000 (2010-10-04)
296 * @protected
298 protected $cell_margin = array('T' => 0, 'R' => 0, 'B' => 0, 'L' => 0);
301 * Current horizontal position in user unit for cell positioning.
302 * @protected
304 protected $x;
307 * Current vertical position in user unit for cell positioning.
308 * @protected
310 protected $y;
313 * Height of last cell printed.
314 * @protected
316 protected $lasth;
319 * Line width in user unit.
320 * @protected
322 protected $LineWidth;
325 * Array of standard font names.
326 * @protected
328 protected $CoreFonts;
331 * Array of used fonts.
332 * @protected
334 protected $fonts = array();
337 * Array of font files.
338 * @protected
340 protected $FontFiles = array();
343 * Array of encoding differences.
344 * @protected
346 protected $diffs = array();
349 * Array of used images.
350 * @protected
352 protected $images = array();
355 * Array of Annotations in pages.
356 * @protected
358 protected $PageAnnots = array();
361 * Array of internal links.
362 * @protected
364 protected $links = array();
367 * Current font family.
368 * @protected
370 protected $FontFamily;
373 * Current font style.
374 * @protected
376 protected $FontStyle;
379 * Current font ascent (distance between font top and baseline).
380 * @protected
381 * @since 2.8.000 (2007-03-29)
383 protected $FontAscent;
386 * Current font descent (distance between font bottom and baseline).
387 * @protected
388 * @since 2.8.000 (2007-03-29)
390 protected $FontDescent;
393 * Underlining flag.
394 * @protected
396 protected $underline;
399 * Overlining flag.
400 * @protected
402 protected $overline;
405 * Current font info.
406 * @protected
408 protected $CurrentFont;
411 * Current font size in points.
412 * @protected
414 protected $FontSizePt;
417 * Current font size in user unit.
418 * @protected
420 protected $FontSize;
423 * Commands for drawing color.
424 * @protected
426 protected $DrawColor;
429 * Commands for filling color.
430 * @protected
432 protected $FillColor;
435 * Commands for text color.
436 * @protected
438 protected $TextColor;
441 * Indicates whether fill and text colors are different.
442 * @protected
444 protected $ColorFlag;
447 * Automatic page breaking.
448 * @protected
450 protected $AutoPageBreak;
453 * Threshold used to trigger page breaks.
454 * @protected
456 protected $PageBreakTrigger;
459 * Flag set when processing page header.
460 * @protected
462 protected $InHeader = false;
465 * Flag set when processing page footer.
466 * @protected
468 protected $InFooter = false;
471 * Zoom display mode.
472 * @protected
474 protected $ZoomMode;
477 * Layout display mode.
478 * @protected
480 protected $LayoutMode;
483 * If true set the document information dictionary in Unicode.
484 * @protected
486 protected $docinfounicode = true;
489 * Document title.
490 * @protected
492 protected $title = '';
495 * Document subject.
496 * @protected
498 protected $subject = '';
501 * Document author.
502 * @protected
504 protected $author = '';
507 * Document keywords.
508 * @protected
510 protected $keywords = '';
513 * Document creator.
514 * @protected
516 protected $creator = '';
519 * Starting page number.
520 * @protected
522 protected $starting_page_number = 1;
525 * String alias for total number of pages.
526 * @protected
528 protected $alias_tot_pages = '{:ptp:}';
531 * String alias for page number.
532 * @protected
534 protected $alias_num_page = '{:pnp:}';
537 * String alias for total number of pages in a single group.
538 * @protected
540 protected $alias_group_tot_pages = '{:ptg:}';
543 * String alias for group page number.
544 * @protected
546 protected $alias_group_num_page = '{:png:}';
549 * String alias for right shift compensation used to correctly align page numbers on the right.
550 * @protected
552 protected $alias_right_shift = '{rsc:';
555 * The right-bottom (or left-bottom for RTL) corner X coordinate of last inserted image.
556 * @since 2002-07-31
557 * @author Nicola Asuni
558 * @protected
560 protected $img_rb_x;
563 * The right-bottom corner Y coordinate of last inserted image.
564 * @since 2002-07-31
565 * @author Nicola Asuni
566 * @protected
568 protected $img_rb_y;
571 * Adjusting factor to convert pixels to user units.
572 * @since 2004-06-14
573 * @author Nicola Asuni
574 * @protected
576 protected $imgscale = 1;
579 * Boolean flag set to true when the input text is unicode (require unicode fonts).
580 * @since 2005-01-02
581 * @author Nicola Asuni
582 * @protected
584 protected $isunicode = false;
587 * Object containing unicode data.
588 * @since 5.9.004 (2010-10-18)
589 * @author Nicola Asuni
590 * @protected
592 protected $unicode;
595 * PDF version.
596 * @since 1.5.3
597 * @protected
599 protected $PDFVersion = '1.7';
602 * ID of the stored default header template (-1 = not set).
603 * @protected
605 protected $header_xobjid = -1;
608 * If true reset the Header Xobject template at each page
609 * @protected
611 protected $header_xobj_autoreset = false;
614 * Minimum distance between header and top page margin.
615 * @protected
617 protected $header_margin;
620 * Minimum distance between footer and bottom page margin.
621 * @protected
623 protected $footer_margin;
626 * Original left margin value.
627 * @protected
628 * @since 1.53.0.TC013
630 protected $original_lMargin;
633 * Original right margin value.
634 * @protected
635 * @since 1.53.0.TC013
637 protected $original_rMargin;
640 * Default font used on page header.
641 * @protected
643 protected $header_font;
646 * Default font used on page footer.
647 * @protected
649 protected $footer_font;
652 * Language templates.
653 * @protected
655 protected $l;
658 * Barcode to print on page footer (only if set).
659 * @protected
661 protected $barcode = false;
664 * Boolean flag to print/hide page header.
665 * @protected
667 protected $print_header = true;
670 * Boolean flag to print/hide page footer.
671 * @protected
673 protected $print_footer = true;
676 * Header image logo.
677 * @protected
679 protected $header_logo = '';
682 * Width of header image logo in user units.
683 * @protected
685 protected $header_logo_width = 30;
688 * Title to be printed on default page header.
689 * @protected
691 protected $header_title = '';
694 * String to pring on page header after title.
695 * @protected
697 protected $header_string = '';
700 * Default number of columns for html table.
701 * @protected
703 protected $default_table_columns = 4;
705 // variables for html parser
708 * HTML PARSER: array to store current link and rendering styles.
709 * @protected
711 protected $HREF = array();
714 * List of available fonts on filesystem.
715 * @protected
717 protected $fontlist = array();
720 * Current foreground color.
721 * @protected
723 protected $fgcolor;
726 * HTML PARSER: array of boolean values, true in case of ordered list (OL), false otherwise.
727 * @protected
729 protected $listordered = array();
732 * HTML PARSER: array count list items on nested lists.
733 * @protected
735 protected $listcount = array();
738 * HTML PARSER: current list nesting level.
739 * @protected
741 protected $listnum = 0;
744 * HTML PARSER: indent amount for lists.
745 * @protected
747 protected $listindent = 0;
750 * HTML PARSER: current list indententation level.
751 * @protected
753 protected $listindentlevel = 0;
756 * Current background color.
757 * @protected
759 protected $bgcolor;
762 * Temporary font size in points.
763 * @protected
765 protected $tempfontsize = 10;
768 * Spacer string for LI tags.
769 * @protected
771 protected $lispacer = '';
774 * Default encoding.
775 * @protected
776 * @since 1.53.0.TC010
778 protected $encoding = 'UTF-8';
781 * PHP internal encoding.
782 * @protected
783 * @since 1.53.0.TC016
785 protected $internal_encoding;
788 * Boolean flag to indicate if the document language is Right-To-Left.
789 * @protected
790 * @since 2.0.000
792 protected $rtl = false;
795 * Boolean flag used to force RTL or LTR string direction.
796 * @protected
797 * @since 2.0.000
799 protected $tmprtl = false;
801 // --- Variables used for document encryption:
804 * IBoolean flag indicating whether document is protected.
805 * @protected
806 * @since 2.0.000 (2008-01-02)
808 protected $encrypted;
811 * Array containing encryption settings.
812 * @protected
813 * @since 5.0.005 (2010-05-11)
815 protected $encryptdata = array();
818 * Last RC4 key encrypted (cached for optimisation).
819 * @protected
820 * @since 2.0.000 (2008-01-02)
822 protected $last_enc_key;
825 * Last RC4 computed key.
826 * @protected
827 * @since 2.0.000 (2008-01-02)
829 protected $last_enc_key_c;
832 * Encryption padding string.
833 * @protected
835 protected $enc_padding = "\x28\xBF\x4E\x5E\x4E\x75\x8A\x41\x64\x00\x4E\x56\xFF\xFA\x01\x08\x2E\x2E\x00\xB6\xD0\x68\x3E\x80\x2F\x0C\xA9\xFE\x64\x53\x69\x7A";
838 * File ID (used on document trailer).
839 * @protected
840 * @since 5.0.005 (2010-05-12)
842 protected $file_id;
844 // --- bookmark ---
847 * Outlines for bookmark.
848 * @protected
849 * @since 2.1.002 (2008-02-12)
851 protected $outlines = array();
854 * Outline root for bookmark.
855 * @protected
856 * @since 2.1.002 (2008-02-12)
858 protected $OutlineRoot;
860 // --- javascript and form ---
863 * Javascript code.
864 * @protected
865 * @since 2.1.002 (2008-02-12)
867 protected $javascript = '';
870 * Javascript counter.
871 * @protected
872 * @since 2.1.002 (2008-02-12)
874 protected $n_js;
877 * line trough state
878 * @protected
879 * @since 2.8.000 (2008-03-19)
881 protected $linethrough;
884 * Array with additional document-wide usage rights for the document.
885 * @protected
886 * @since 5.8.014 (2010-08-23)
888 protected $ur = array();
891 * DPI (Dot Per Inch) Document Resolution (do not change).
892 * @protected
893 * @since 3.0.000 (2008-03-27)
895 protected $dpi = 72;
898 * Array of page numbers were a new page group was started (the page numbers are the keys of the array).
899 * @protected
900 * @since 3.0.000 (2008-03-27)
902 protected $newpagegroup = array();
905 * Array that contains the number of pages in each page group.
906 * @protected
907 * @since 3.0.000 (2008-03-27)
909 protected $pagegroups = array();
912 * Current page group number.
913 * @protected
914 * @since 3.0.000 (2008-03-27)
916 protected $currpagegroup = 0;
919 * Array of transparency objects and parameters.
920 * @protected
921 * @since 3.0.000 (2008-03-27)
923 protected $extgstates;
926 * Set the default JPEG compression quality (1-100).
927 * @protected
928 * @since 3.0.000 (2008-03-27)
930 protected $jpeg_quality;
933 * Default cell height ratio.
934 * @protected
935 * @since 3.0.014 (2008-05-23)
937 protected $cell_height_ratio = K_CELL_HEIGHT_RATIO;
940 * PDF viewer preferences.
941 * @protected
942 * @since 3.1.000 (2008-06-09)
944 protected $viewer_preferences;
947 * A name object specifying how the document should be displayed when opened.
948 * @protected
949 * @since 3.1.000 (2008-06-09)
951 protected $PageMode;
954 * Array for storing gradient information.
955 * @protected
956 * @since 3.1.000 (2008-06-09)
958 protected $gradients = array();
961 * Array used to store positions inside the pages buffer (keys are the page numbers).
962 * @protected
963 * @since 3.2.000 (2008-06-26)
965 protected $intmrk = array();
968 * Array used to store positions inside the pages buffer (keys are the page numbers).
969 * @protected
970 * @since 5.7.000 (2010-08-03)
972 protected $bordermrk = array();
975 * Array used to store page positions to track empty pages (keys are the page numbers).
976 * @protected
977 * @since 5.8.007 (2010-08-18)
979 protected $emptypagemrk = array();
982 * Array used to store content positions inside the pages buffer (keys are the page numbers).
983 * @protected
984 * @since 4.6.021 (2009-07-20)
986 protected $cntmrk = array();
989 * Array used to store footer positions of each page.
990 * @protected
991 * @since 3.2.000 (2008-07-01)
993 protected $footerpos = array();
996 * Array used to store footer length of each page.
997 * @protected
998 * @since 4.0.014 (2008-07-29)
1000 protected $footerlen = array();
1003 * Boolean flag to indicate if a new line is created.
1004 * @protected
1005 * @since 3.2.000 (2008-07-01)
1007 protected $newline = true;
1010 * End position of the latest inserted line.
1011 * @protected
1012 * @since 3.2.000 (2008-07-01)
1014 protected $endlinex = 0;
1017 * PDF string for width value of the last line.
1018 * @protected
1019 * @since 4.0.006 (2008-07-16)
1021 protected $linestyleWidth = '';
1024 * PDF string for CAP value of the last line.
1025 * @protected
1026 * @since 4.0.006 (2008-07-16)
1028 protected $linestyleCap = '0 J';
1031 * PDF string for join value of the last line.
1032 * @protected
1033 * @since 4.0.006 (2008-07-16)
1035 protected $linestyleJoin = '0 j';
1038 * PDF string for dash value of the last line.
1039 * @protected
1040 * @since 4.0.006 (2008-07-16)
1042 protected $linestyleDash = '[] 0 d';
1045 * Boolean flag to indicate if marked-content sequence is open.
1046 * @protected
1047 * @since 4.0.013 (2008-07-28)
1049 protected $openMarkedContent = false;
1052 * Count the latest inserted vertical spaces on HTML.
1053 * @protected
1054 * @since 4.0.021 (2008-08-24)
1056 protected $htmlvspace = 0;
1059 * Array of Spot colors.
1060 * @protected
1061 * @since 4.0.024 (2008-09-12)
1063 protected $spot_colors = array();
1066 * Symbol used for HTML unordered list items.
1067 * @protected
1068 * @since 4.0.028 (2008-09-26)
1070 protected $lisymbol = '';
1073 * String used to mark the beginning and end of EPS image blocks.
1074 * @protected
1075 * @since 4.1.000 (2008-10-18)
1077 protected $epsmarker = 'x#!#EPS#!#x';
1080 * Array of transformation matrix.
1081 * @protected
1082 * @since 4.2.000 (2008-10-29)
1084 protected $transfmatrix = array();
1087 * Current key for transformation matrix.
1088 * @protected
1089 * @since 4.8.005 (2009-09-17)
1091 protected $transfmatrix_key = 0;
1094 * Booklet mode for double-sided pages.
1095 * @protected
1096 * @since 4.2.000 (2008-10-29)
1098 protected $booklet = false;
1101 * Epsilon value used for float calculations.
1102 * @protected
1103 * @since 4.2.000 (2008-10-29)
1105 protected $feps = 0.005;
1108 * Array used for custom vertical spaces for HTML tags.
1109 * @protected
1110 * @since 4.2.001 (2008-10-30)
1112 protected $tagvspaces = array();
1115 * HTML PARSER: custom indent amount for lists. Negative value means disabled.
1116 * @protected
1117 * @since 4.2.007 (2008-11-12)
1119 protected $customlistindent = -1;
1122 * Boolean flag to indicate if the border of the cell sides that cross the page should be removed.
1123 * @protected
1124 * @since 4.2.010 (2008-11-14)
1126 protected $opencell = true;
1129 * Array of files to embedd.
1130 * @protected
1131 * @since 4.4.000 (2008-12-07)
1133 protected $embeddedfiles = array();
1136 * Boolean flag to indicate if we are inside a PRE tag.
1137 * @protected
1138 * @since 4.4.001 (2008-12-08)
1140 protected $premode = false;
1143 * Array used to store positions of graphics transformation blocks inside the page buffer.
1144 * keys are the page numbers
1145 * @protected
1146 * @since 4.4.002 (2008-12-09)
1148 protected $transfmrk = array();
1151 * Default color for html links.
1152 * @protected
1153 * @since 4.4.003 (2008-12-09)
1155 protected $htmlLinkColorArray = array(0, 0, 255);
1158 * Default font style to add to html links.
1159 * @protected
1160 * @since 4.4.003 (2008-12-09)
1162 protected $htmlLinkFontStyle = 'U';
1165 * Counts the number of pages.
1166 * @protected
1167 * @since 4.5.000 (2008-12-31)
1169 protected $numpages = 0;
1172 * Array containing page lengths in bytes.
1173 * @protected
1174 * @since 4.5.000 (2008-12-31)
1176 protected $pagelen = array();
1179 * Counts the number of pages.
1180 * @protected
1181 * @since 4.5.000 (2008-12-31)
1183 protected $numimages = 0;
1186 * Store the image keys.
1187 * @protected
1188 * @since 4.5.000 (2008-12-31)
1190 protected $imagekeys = array();
1193 * Length of the buffer in bytes.
1194 * @protected
1195 * @since 4.5.000 (2008-12-31)
1197 protected $bufferlen = 0;
1200 * If true enables disk caching.
1201 * @protected
1202 * @since 4.5.000 (2008-12-31)
1204 protected $diskcache = false;
1207 * Counts the number of fonts.
1208 * @protected
1209 * @since 4.5.000 (2009-01-02)
1211 protected $numfonts = 0;
1214 * Store the font keys.
1215 * @protected
1216 * @since 4.5.000 (2009-01-02)
1218 protected $fontkeys = array();
1221 * Store the font object IDs.
1222 * @protected
1223 * @since 4.8.001 (2009-09-09)
1225 protected $font_obj_ids = array();
1228 * Store the fage status (true when opened, false when closed).
1229 * @protected
1230 * @since 4.5.000 (2009-01-02)
1232 protected $pageopen = array();
1235 * Default monospace font.
1236 * @protected
1237 * @since 4.5.025 (2009-03-10)
1239 protected $default_monospaced_font = 'courier';
1242 * Cloned copy of the current class object.
1243 * @protected
1244 * @since 4.5.029 (2009-03-19)
1246 protected $objcopy;
1249 * Array used to store the lengths of cache files.
1250 * @protected
1251 * @since 4.5.029 (2009-03-19)
1253 protected $cache_file_length = array();
1256 * Table header content to be repeated on each new page.
1257 * @protected
1258 * @since 4.5.030 (2009-03-20)
1260 protected $thead = '';
1263 * Margins used for table header.
1264 * @protected
1265 * @since 4.5.030 (2009-03-20)
1267 protected $theadMargins = array();
1270 * Cache array for UTF8StringToArray() method.
1271 * @protected
1272 * @since 4.5.037 (2009-04-07)
1274 protected $cache_UTF8StringToArray = array();
1277 * Maximum size of cache array used for UTF8StringToArray() method.
1278 * @protected
1279 * @since 4.5.037 (2009-04-07)
1281 protected $cache_maxsize_UTF8StringToArray = 8;
1284 * Current size of cache array used for UTF8StringToArray() method.
1285 * @protected
1286 * @since 4.5.037 (2009-04-07)
1288 protected $cache_size_UTF8StringToArray = 0;
1291 * Boolean flag to enable document digital signature.
1292 * @protected
1293 * @since 4.6.005 (2009-04-24)
1295 protected $sign = false;
1298 * Digital signature data.
1299 * @protected
1300 * @since 4.6.005 (2009-04-24)
1302 protected $signature_data = array();
1305 * Digital signature max length.
1306 * @protected
1307 * @since 4.6.005 (2009-04-24)
1309 protected $signature_max_length = 11742;
1312 * Data for digital signature appearance.
1313 * @protected
1314 * @since 5.3.011 (2010-06-16)
1316 protected $signature_appearance = array('page' => 1, 'rect' => '0 0 0 0');
1319 * Array of empty digital signature appearances.
1320 * @protected
1321 * @since 5.9.101 (2011-07-06)
1323 protected $empty_signature_appearance = array();
1326 * Regular expression used to find blank characters (required for word-wrapping).
1327 * @protected
1328 * @since 4.6.006 (2009-04-28)
1330 protected $re_spaces = '/[^\S\xa0]/';
1333 * Array of $re_spaces parts.
1334 * @protected
1335 * @since 5.5.011 (2010-07-09)
1337 protected $re_space = array('p' => '[^\S\xa0]', 'm' => '');
1340 * Digital signature object ID.
1341 * @protected
1342 * @since 4.6.022 (2009-06-23)
1344 protected $sig_obj_id = 0;
1347 * ByteRange placemark used during digital signature process.
1348 * @protected
1349 * @since 4.6.028 (2009-08-25)
1351 protected $byterange_string = '/ByteRange[0 ********** ********** **********]';
1354 * Placemark used during digital signature process.
1355 * @protected
1356 * @since 4.6.028 (2009-08-25)
1358 protected $sig_annot_ref = '***SIGANNREF*** 0 R';
1361 * ID of page objects.
1362 * @protected
1363 * @since 4.7.000 (2009-08-29)
1365 protected $page_obj_id = array();
1368 * List of form annotations IDs.
1369 * @protected
1370 * @since 4.8.000 (2009-09-07)
1372 protected $form_obj_id = array();
1375 * 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.
1376 * @protected
1377 * @since 4.8.000 (2009-09-07)
1379 protected $default_form_prop = array('lineWidth'=>1, 'borderStyle'=>'solid', 'fillColor'=>array(255, 255, 255), 'strokeColor'=>array(128, 128, 128));
1382 * Javascript objects array.
1383 * @protected
1384 * @since 4.8.000 (2009-09-07)
1386 protected $js_objects = array();
1389 * Current form action (used during XHTML rendering).
1390 * @protected
1391 * @since 4.8.000 (2009-09-07)
1393 protected $form_action = '';
1396 * Current form encryption type (used during XHTML rendering).
1397 * @protected
1398 * @since 4.8.000 (2009-09-07)
1400 protected $form_enctype = 'application/x-www-form-urlencoded';
1403 * Current method to submit forms.
1404 * @protected
1405 * @since 4.8.000 (2009-09-07)
1407 protected $form_mode = 'post';
1410 * List of fonts used on form fields (fontname => fontkey).
1411 * @protected
1412 * @since 4.8.001 (2009-09-09)
1414 protected $annotation_fonts = array();
1417 * List of radio buttons parent objects.
1418 * @protected
1419 * @since 4.8.001 (2009-09-09)
1421 protected $radiobutton_groups = array();
1424 * List of radio group objects IDs.
1425 * @protected
1426 * @since 4.8.001 (2009-09-09)
1428 protected $radio_groups = array();
1431 * Text indentation value (used for text-indent CSS attribute).
1432 * @protected
1433 * @since 4.8.006 (2009-09-23)
1435 protected $textindent = 0;
1438 * Store page number when startTransaction() is called.
1439 * @protected
1440 * @since 4.8.006 (2009-09-23)
1442 protected $start_transaction_page = 0;
1445 * Store Y position when startTransaction() is called.
1446 * @protected
1447 * @since 4.9.001 (2010-03-28)
1449 protected $start_transaction_y = 0;
1452 * True when we are printing the thead section on a new page.
1453 * @protected
1454 * @since 4.8.027 (2010-01-25)
1456 protected $inthead = false;
1459 * Array of column measures (width, space, starting Y position).
1460 * @protected
1461 * @since 4.9.001 (2010-03-28)
1463 protected $columns = array();
1466 * Number of colums.
1467 * @protected
1468 * @since 4.9.001 (2010-03-28)
1470 protected $num_columns = 1;
1473 * Current column number.
1474 * @protected
1475 * @since 4.9.001 (2010-03-28)
1477 protected $current_column = 0;
1480 * Starting page for columns.
1481 * @protected
1482 * @since 4.9.001 (2010-03-28)
1484 protected $column_start_page = 0;
1487 * Maximum page and column selected.
1488 * @protected
1489 * @since 5.8.000 (2010-08-11)
1491 protected $maxselcol = array('page' => 0, 'column' => 0);
1494 * Array of: X difference between table cell x start and starting page margin, cellspacing, cellpadding.
1495 * @protected
1496 * @since 5.8.000 (2010-08-11)
1498 protected $colxshift = array('x' => 0, 's' => array('H' => 0, 'V' => 0), 'p' => array('L' => 0, 'T' => 0, 'R' => 0, 'B' => 0));
1501 * 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.
1502 * @protected
1503 * @since 4.9.008 (2010-04-03)
1505 protected $textrendermode = 0;
1508 * Text stroke width in doc units.
1509 * @protected
1510 * @since 4.9.008 (2010-04-03)
1512 protected $textstrokewidth = 0;
1515 * Current stroke color.
1516 * @protected
1517 * @since 4.9.008 (2010-04-03)
1519 protected $strokecolor;
1522 * Default unit of measure for document.
1523 * @protected
1524 * @since 5.0.000 (2010-04-22)
1526 protected $pdfunit = 'mm';
1529 * Boolean flag true when we are on TOC (Table Of Content) page.
1530 * @protected
1532 protected $tocpage = false;
1535 * Boolean flag: if true convert vector images (SVG, EPS) to raster image using GD or ImageMagick library.
1536 * @protected
1537 * @since 5.0.000 (2010-04-26)
1539 protected $rasterize_vector_images = false;
1542 * Boolean flag: if true enables font subsetting by default.
1543 * @protected
1544 * @since 5.3.002 (2010-06-07)
1546 protected $font_subsetting = true;
1549 * Array of default graphic settings.
1550 * @protected
1551 * @since 5.5.008 (2010-07-02)
1553 protected $default_graphic_vars = array();
1556 * Array of XObjects.
1557 * @protected
1558 * @since 5.8.014 (2010-08-23)
1560 protected $xobjects = array();
1563 * Boolean value true when we are inside an XObject.
1564 * @protected
1565 * @since 5.8.017 (2010-08-24)
1567 protected $inxobj = false;
1570 * Current XObject ID.
1571 * @protected
1572 * @since 5.8.017 (2010-08-24)
1574 protected $xobjid = '';
1577 * Percentage of character stretching.
1578 * @protected
1579 * @since 5.9.000 (2010-09-29)
1581 protected $font_stretching = 100;
1584 * Increases or decreases the space between characters in a text by the specified amount (tracking/kerning).
1585 * @protected
1586 * @since 5.9.000 (2010-09-29)
1588 protected $font_spacing = 0;
1591 * Array of no-write regions.
1592 * ('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)
1593 * @protected
1594 * @since 5.9.003 (2010-10-14)
1596 protected $page_regions = array();
1599 * Array containing HTML color names and values.
1600 * @protected
1601 * @since 5.9.004 (2010-10-18)
1603 protected $webcolor = array();
1606 * Array containing spot color names and values.
1607 * @protected
1608 * @since 5.9.012 (2010-11-11)
1610 protected $spotcolor = array();
1613 * Array of PDF layers data.
1614 * @protected
1615 * @since 5.9.102 (2011-07-13)
1617 protected $pdflayers = array();
1620 * A dictionary of names and corresponding destinations (Dests key on document Catalog).
1621 * @protected
1622 * @since 5.9.097 (2011-06-23)
1624 protected $dests = array();
1627 * Object ID for Named Destinations
1628 * @protected
1629 * @since 5.9.097 (2011-06-23)
1631 protected $n_dests;
1634 * Directory used for the last SVG image.
1635 * @protected
1636 * @since 5.0.000 (2010-05-05)
1638 protected $svgdir = '';
1641 * Deafult unit of measure for SVG.
1642 * @protected
1643 * @since 5.0.000 (2010-05-02)
1645 protected $svgunit = 'px';
1648 * Array of SVG gradients.
1649 * @protected
1650 * @since 5.0.000 (2010-05-02)
1652 protected $svggradients = array();
1655 * ID of last SVG gradient.
1656 * @protected
1657 * @since 5.0.000 (2010-05-02)
1659 protected $svggradientid = 0;
1662 * Boolean value true when in SVG defs group.
1663 * @protected
1664 * @since 5.0.000 (2010-05-02)
1666 protected $svgdefsmode = false;
1669 * Array of SVG defs.
1670 * @protected
1671 * @since 5.0.000 (2010-05-02)
1673 protected $svgdefs = array();
1676 * Boolean value true when in SVG clipPath tag.
1677 * @protected
1678 * @since 5.0.000 (2010-04-26)
1680 protected $svgclipmode = false;
1683 * Array of SVG clipPath commands.
1684 * @protected
1685 * @since 5.0.000 (2010-05-02)
1687 protected $svgclippaths = array();
1690 * Array of SVG clipPath tranformation matrix.
1691 * @protected
1692 * @since 5.8.022 (2010-08-31)
1694 protected $svgcliptm = array();
1697 * ID of last SVG clipPath.
1698 * @protected
1699 * @since 5.0.000 (2010-05-02)
1701 protected $svgclipid = 0;
1704 * SVG text.
1705 * @protected
1706 * @since 5.0.000 (2010-05-02)
1708 protected $svgtext = '';
1711 * SVG text properties.
1712 * @protected
1713 * @since 5.8.013 (2010-08-23)
1715 protected $svgtextmode = array();
1718 * Array of hinheritable SVG properties.
1719 * @protected
1720 * @since 5.0.000 (2010-05-02)
1722 protected $svginheritprop = array('clip-rule', 'color', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'cursor', 'direction', 'fill', 'fill-opacity', 'fill-rule', 'font', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'glyph-orientation-horizontal', 'glyph-orientation-vertical', 'image-rendering', 'kerning', 'letter-spacing', 'marker', 'marker-end', 'marker-mid', 'marker-start', 'pointer-events', 'shape-rendering', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'text-anchor', 'text-rendering', 'visibility', 'word-spacing', 'writing-mode');
1725 * Array of SVG properties.
1726 * @protected
1727 * @since 5.0.000 (2010-05-02)
1729 protected $svgstyles = array(array(
1730 'alignment-baseline' => 'auto',
1731 'baseline-shift' => 'baseline',
1732 'clip' => 'auto',
1733 'clip-path' => 'none',
1734 'clip-rule' => 'nonzero',
1735 'color' => 'black',
1736 'color-interpolation' => 'sRGB',
1737 'color-interpolation-filters' => 'linearRGB',
1738 'color-profile' => 'auto',
1739 'color-rendering' => 'auto',
1740 'cursor' => 'auto',
1741 'direction' => 'ltr',
1742 'display' => 'inline',
1743 'dominant-baseline' => 'auto',
1744 'enable-background' => 'accumulate',
1745 'fill' => 'black',
1746 'fill-opacity' => 1,
1747 'fill-rule' => 'nonzero',
1748 'filter' => 'none',
1749 'flood-color' => 'black',
1750 'flood-opacity' => 1,
1751 'font' => '',
1752 'font-family' => 'helvetica',
1753 'font-size' => 'medium',
1754 'font-size-adjust' => 'none',
1755 'font-stretch' => 'normal',
1756 'font-style' => 'normal',
1757 'font-variant' => 'normal',
1758 'font-weight' => 'normal',
1759 'glyph-orientation-horizontal' => '0deg',
1760 'glyph-orientation-vertical' => 'auto',
1761 'image-rendering' => 'auto',
1762 'kerning' => 'auto',
1763 'letter-spacing' => 'normal',
1764 'lighting-color' => 'white',
1765 'marker' => '',
1766 'marker-end' => 'none',
1767 'marker-mid' => 'none',
1768 'marker-start' => 'none',
1769 'mask' => 'none',
1770 'opacity' => 1,
1771 'overflow' => 'auto',
1772 'pointer-events' => 'visiblePainted',
1773 'shape-rendering' => 'auto',
1774 'stop-color' => 'black',
1775 'stop-opacity' => 1,
1776 'stroke' => 'none',
1777 'stroke-dasharray' => 'none',
1778 'stroke-dashoffset' => 0,
1779 'stroke-linecap' => 'butt',
1780 'stroke-linejoin' => 'miter',
1781 'stroke-miterlimit' => 4,
1782 'stroke-opacity' => 1,
1783 'stroke-width' => 1,
1784 'text-anchor' => 'start',
1785 'text-decoration' => 'none',
1786 'text-rendering' => 'auto',
1787 'unicode-bidi' => 'normal',
1788 'visibility' => 'visible',
1789 'word-spacing' => 'normal',
1790 'writing-mode' => 'lr-tb',
1791 'text-color' => 'black',
1792 'transfmatrix' => array(1, 0, 0, 1, 0, 0)
1795 //------------------------------------------------------------
1796 // METHODS
1797 //------------------------------------------------------------
1800 * This is the class constructor.
1801 * It allows to set up the page format, the orientation and the measure unit used in all the methods (except for the font sizes).
1802 * @param $orientation (string) page orientation. Possible values are (case insensitive):<ul><li>P or Portrait (default)</li><li>L or Landscape</li><li>'' (empty string) for automatic orientation</li></ul>
1803 * @param $unit (string) User measure unit. Possible values are:<ul><li>pt: point</li><li>mm: millimeter (default)</li><li>cm: centimeter</li><li>in: inch</li></ul><br />A point equals 1/72 of inch, that is to say about 0.35 mm (an inch being 2.54 cm). This is a very common unit in typography; font sizes are expressed in that unit.
1804 * @param $format (mixed) The format used for pages. It can be either: one of the string values specified at getPageSizeFromFormat() or an array of parameters specified at setPageFormat().
1805 * @param $unicode (boolean) TRUE means that the input text is unicode (default = true)
1806 * @param $diskcache (boolean) if TRUE reduce the RAM memory usage by caching temporary data on filesystem (slower).
1807 * @param $encoding (string) charset encoding; default is UTF-8
1808 * @public
1809 * @see getPageSizeFromFormat(), setPageFormat()
1811 public function __construct($orientation='P', $unit='mm', $format='A4', $unicode=true, $encoding='UTF-8', $diskcache=false) {
1812 /* Set internal character encoding to ASCII */
1813 if (function_exists('mb_internal_encoding') AND mb_internal_encoding()) {
1814 $this->internal_encoding = mb_internal_encoding();
1815 mb_internal_encoding('ASCII');
1817 // get array of HTML colors
1818 require(dirname(__FILE__).'/htmlcolors.php');
1819 $this->webcolor = $webcolor;
1820 // get array of custom spot colors
1821 if (file_exists(dirname(__FILE__).'/spotcolors.php')) {
1822 require(dirname(__FILE__).'/spotcolors.php');
1823 $this->spotcolor = $spotcolor;
1824 } else {
1825 $this->spotcolor = array();
1827 require_once(dirname(__FILE__).'/unicode_data.php');
1828 $this->unicode = new TCPDF_UNICODE_DATA();
1829 $this->font_obj_ids = array();
1830 $this->page_obj_id = array();
1831 $this->form_obj_id = array();
1832 // set disk caching
1833 $this->diskcache = $diskcache ? true : false;
1834 // set language direction
1835 $this->rtl = false;
1836 $this->tmprtl = false;
1837 // some checks
1838 $this->_dochecks();
1839 // initialization of properties
1840 $this->isunicode = $unicode;
1841 $this->page = 0;
1842 $this->transfmrk[0] = array();
1843 $this->pagedim = array();
1844 $this->n = 2;
1845 $this->buffer = '';
1846 $this->pages = array();
1847 $this->state = 0;
1848 $this->fonts = array();
1849 $this->FontFiles = array();
1850 $this->diffs = array();
1851 $this->images = array();
1852 $this->links = array();
1853 $this->gradients = array();
1854 $this->InFooter = false;
1855 $this->lasth = 0;
1856 $this->FontFamily = 'helvetica';
1857 $this->FontStyle = '';
1858 $this->FontSizePt = 12;
1859 $this->underline = false;
1860 $this->overline = false;
1861 $this->linethrough = false;
1862 $this->DrawColor = '0 G';
1863 $this->FillColor = '0 g';
1864 $this->TextColor = '0 g';
1865 $this->ColorFlag = false;
1866 $this->pdflayers = array();
1867 // encryption values
1868 $this->encrypted = false;
1869 $this->last_enc_key = '';
1870 // standard Unicode fonts
1871 $this->CoreFonts = array(
1872 'courier'=>'Courier',
1873 'courierB'=>'Courier-Bold',
1874 'courierI'=>'Courier-Oblique',
1875 'courierBI'=>'Courier-BoldOblique',
1876 'helvetica'=>'Helvetica',
1877 'helveticaB'=>'Helvetica-Bold',
1878 'helveticaI'=>'Helvetica-Oblique',
1879 'helveticaBI'=>'Helvetica-BoldOblique',
1880 'times'=>'Times-Roman',
1881 'timesB'=>'Times-Bold',
1882 'timesI'=>'Times-Italic',
1883 'timesBI'=>'Times-BoldItalic',
1884 'symbol'=>'Symbol',
1885 'zapfdingbats'=>'ZapfDingbats'
1887 // set scale factor
1888 $this->setPageUnit($unit);
1889 // set page format and orientation
1890 $this->setPageFormat($format, $orientation);
1891 // page margins (1 cm)
1892 $margin = 28.35 / $this->k;
1893 $this->SetMargins($margin, $margin);
1894 // internal cell padding
1895 $cpadding = $margin / 10;
1896 $this->setCellPaddings($cpadding, 0, $cpadding, 0);
1897 // cell margins
1898 $this->setCellMargins(0, 0, 0, 0);
1899 // line width (0.2 mm)
1900 $this->LineWidth = 0.57 / $this->k;
1901 $this->linestyleWidth = sprintf('%.2F w', ($this->LineWidth * $this->k));
1902 $this->linestyleCap = '0 J';
1903 $this->linestyleJoin = '0 j';
1904 $this->linestyleDash = '[] 0 d';
1905 // automatic page break
1906 $this->SetAutoPageBreak(true, (2 * $margin));
1907 // full width display mode
1908 $this->SetDisplayMode('fullwidth');
1909 // compression
1910 $this->SetCompression(true);
1911 // set default PDF version number
1912 $this->PDFVersion = '1.7';
1913 $this->encoding = $encoding;
1914 $this->HREF = array();
1915 $this->getFontsList();
1916 $this->fgcolor = array('R' => 0, 'G' => 0, 'B' => 0);
1917 $this->strokecolor = array('R' => 0, 'G' => 0, 'B' => 0);
1918 $this->bgcolor = array('R' => 255, 'G' => 255, 'B' => 255);
1919 $this->extgstates = array();
1920 // user's rights
1921 $this->sign = false;
1922 $this->ur['enabled'] = false;
1923 $this->ur['document'] = '/FullSave';
1924 $this->ur['annots'] = '/Create/Delete/Modify/Copy/Import/Export';
1925 $this->ur['form'] = '/Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate';
1926 $this->ur['signature'] = '/Modify';
1927 $this->ur['ef'] = '/Create/Delete/Modify/Import';
1928 $this->ur['formex'] = '';
1929 $this->signature_appearance = array('page' => 1, 'rect' => '0 0 0 0');
1930 $this->empty_signature_appearance = array();
1931 // set default JPEG quality
1932 $this->jpeg_quality = 75;
1933 // initialize some settings
1934 $this->utf8Bidi(array(''), '');
1935 // set default font
1936 $this->SetFont($this->FontFamily, $this->FontStyle, $this->FontSizePt);
1937 // check if PCRE Unicode support is enabled
1938 if ($this->isunicode AND (@preg_match('/\pL/u', 'a') == 1)) {
1939 // PCRE unicode support is turned ON
1940 // \p{Z} or \p{Separator}: any kind of Unicode whitespace or invisible separator.
1941 // \p{Lo} or \p{Other_Letter}: a Unicode letter or ideograph that does not have lowercase and uppercase variants.
1942 // \p{Lo} is needed because Chinese characters are packed next to each other without spaces in between.
1943 //$this->setSpacesRE('/[^\S\P{Z}\P{Lo}\xa0]/u');
1944 $this->setSpacesRE('/[^\S\P{Z}\xa0]/u');
1945 } else {
1946 // PCRE unicode support is turned OFF
1947 $this->setSpacesRE('/[^\S\xa0]/');
1949 $this->default_form_prop = array('lineWidth'=>1, 'borderStyle'=>'solid', 'fillColor'=>array(255, 255, 255), 'strokeColor'=>array(128, 128, 128));
1950 // set file ID for trailer
1951 $this->file_id = md5($this->getRandomSeed('TCPDF'.$orientation.$unit.$format.$encoding));
1952 // get default graphic vars
1953 $this->default_graphic_vars = $this->getGraphicVars();
1954 $this->header_xobj_autoreset = false;
1958 * Default destructor.
1959 * @public
1960 * @since 1.53.0.TC016
1962 public function __destruct() {
1963 // restore internal encoding
1964 if (isset($this->internal_encoding) AND !empty($this->internal_encoding)) {
1965 mb_internal_encoding($this->internal_encoding);
1967 // unset all class variables
1968 $this->_destroy(true);
1972 * Return the current TCPDF version.
1973 * @return TCPDF version string
1974 * @public
1975 * @since 5.9.012 (2010-11-10)
1977 public function getTCPDFVersion() {
1978 return $this->tcpdf_version;
1982 * Set the units of measure for the document.
1983 * @param $unit (string) User measure unit. Possible values are:<ul><li>pt: point</li><li>mm: millimeter (default)</li><li>cm: centimeter</li><li>in: inch</li></ul><br />A point equals 1/72 of inch, that is to say about 0.35 mm (an inch being 2.54 cm). This is a very common unit in typography; font sizes are expressed in that unit.
1984 * @public
1985 * @since 3.0.015 (2008-06-06)
1987 public function setPageUnit($unit) {
1988 $unit = strtolower($unit);
1989 //Set scale factor
1990 switch ($unit) {
1991 // points
1992 case 'px':
1993 case 'pt': {
1994 $this->k = 1;
1995 break;
1997 // millimeters
1998 case 'mm': {
1999 $this->k = $this->dpi / 25.4;
2000 break;
2002 // centimeters
2003 case 'cm': {
2004 $this->k = $this->dpi / 2.54;
2005 break;
2007 // inches
2008 case 'in': {
2009 $this->k = $this->dpi;
2010 break;
2012 // unsupported unit
2013 default : {
2014 $this->Error('Incorrect unit: '.$unit);
2015 break;
2018 $this->pdfunit = $unit;
2019 if (isset($this->CurOrientation)) {
2020 $this->setPageOrientation($this->CurOrientation);
2025 * Get page dimensions from format name.
2026 * @param $format (mixed) The format name. It can be: <ul>
2027 * <li><b>ISO 216 A Series + 2 SIS 014711 extensions</b></li>
2028 * <li>A0 (841x1189 mm ; 33.11x46.81 in)</li>
2029 * <li>A1 (594x841 mm ; 23.39x33.11 in)</li>
2030 * <li>A2 (420x594 mm ; 16.54x23.39 in)</li>
2031 * <li>A3 (297x420 mm ; 11.69x16.54 in)</li>
2032 * <li>A4 (210x297 mm ; 8.27x11.69 in)</li>
2033 * <li>A5 (148x210 mm ; 5.83x8.27 in)</li>
2034 * <li>A6 (105x148 mm ; 4.13x5.83 in)</li>
2035 * <li>A7 (74x105 mm ; 2.91x4.13 in)</li>
2036 * <li>A8 (52x74 mm ; 2.05x2.91 in)</li>
2037 * <li>A9 (37x52 mm ; 1.46x2.05 in)</li>
2038 * <li>A10 (26x37 mm ; 1.02x1.46 in)</li>
2039 * <li>A11 (18x26 mm ; 0.71x1.02 in)</li>
2040 * <li>A12 (13x18 mm ; 0.51x0.71 in)</li>
2041 * <li><b>ISO 216 B Series + 2 SIS 014711 extensions</b></li>
2042 * <li>B0 (1000x1414 mm ; 39.37x55.67 in)</li>
2043 * <li>B1 (707x1000 mm ; 27.83x39.37 in)</li>
2044 * <li>B2 (500x707 mm ; 19.69x27.83 in)</li>
2045 * <li>B3 (353x500 mm ; 13.90x19.69 in)</li>
2046 * <li>B4 (250x353 mm ; 9.84x13.90 in)</li>
2047 * <li>B5 (176x250 mm ; 6.93x9.84 in)</li>
2048 * <li>B6 (125x176 mm ; 4.92x6.93 in)</li>
2049 * <li>B7 (88x125 mm ; 3.46x4.92 in)</li>
2050 * <li>B8 (62x88 mm ; 2.44x3.46 in)</li>
2051 * <li>B9 (44x62 mm ; 1.73x2.44 in)</li>
2052 * <li>B10 (31x44 mm ; 1.22x1.73 in)</li>
2053 * <li>B11 (22x31 mm ; 0.87x1.22 in)</li>
2054 * <li>B12 (15x22 mm ; 0.59x0.87 in)</li>
2055 * <li><b>ISO 216 C Series + 2 SIS 014711 extensions + 2 EXTENSION</b></li>
2056 * <li>C0 (917x1297 mm ; 36.10x51.06 in)</li>
2057 * <li>C1 (648x917 mm ; 25.51x36.10 in)</li>
2058 * <li>C2 (458x648 mm ; 18.03x25.51 in)</li>
2059 * <li>C3 (324x458 mm ; 12.76x18.03 in)</li>
2060 * <li>C4 (229x324 mm ; 9.02x12.76 in)</li>
2061 * <li>C5 (162x229 mm ; 6.38x9.02 in)</li>
2062 * <li>C6 (114x162 mm ; 4.49x6.38 in)</li>
2063 * <li>C7 (81x114 mm ; 3.19x4.49 in)</li>
2064 * <li>C8 (57x81 mm ; 2.24x3.19 in)</li>
2065 * <li>C9 (40x57 mm ; 1.57x2.24 in)</li>
2066 * <li>C10 (28x40 mm ; 1.10x1.57 in)</li>
2067 * <li>C11 (20x28 mm ; 0.79x1.10 in)</li>
2068 * <li>C12 (14x20 mm ; 0.55x0.79 in)</li>
2069 * <li>C76 (81x162 mm ; 3.19x6.38 in)</li>
2070 * <li>DL (110x220 mm ; 4.33x8.66 in)</li>
2071 * <li><b>SIS 014711 E Series</b></li>
2072 * <li>E0 (879x1241 mm ; 34.61x48.86 in)</li>
2073 * <li>E1 (620x879 mm ; 24.41x34.61 in)</li>
2074 * <li>E2 (440x620 mm ; 17.32x24.41 in)</li>
2075 * <li>E3 (310x440 mm ; 12.20x17.32 in)</li>
2076 * <li>E4 (220x310 mm ; 8.66x12.20 in)</li>
2077 * <li>E5 (155x220 mm ; 6.10x8.66 in)</li>
2078 * <li>E6 (110x155 mm ; 4.33x6.10 in)</li>
2079 * <li>E7 (78x110 mm ; 3.07x4.33 in)</li>
2080 * <li>E8 (55x78 mm ; 2.17x3.07 in)</li>
2081 * <li>E9 (39x55 mm ; 1.54x2.17 in)</li>
2082 * <li>E10 (27x39 mm ; 1.06x1.54 in)</li>
2083 * <li>E11 (19x27 mm ; 0.75x1.06 in)</li>
2084 * <li>E12 (13x19 mm ; 0.51x0.75 in)</li>
2085 * <li><b>SIS 014711 G Series</b></li>
2086 * <li>G0 (958x1354 mm ; 37.72x53.31 in)</li>
2087 * <li>G1 (677x958 mm ; 26.65x37.72 in)</li>
2088 * <li>G2 (479x677 mm ; 18.86x26.65 in)</li>
2089 * <li>G3 (338x479 mm ; 13.31x18.86 in)</li>
2090 * <li>G4 (239x338 mm ; 9.41x13.31 in)</li>
2091 * <li>G5 (169x239 mm ; 6.65x9.41 in)</li>
2092 * <li>G6 (119x169 mm ; 4.69x6.65 in)</li>
2093 * <li>G7 (84x119 mm ; 3.31x4.69 in)</li>
2094 * <li>G8 (59x84 mm ; 2.32x3.31 in)</li>
2095 * <li>G9 (42x59 mm ; 1.65x2.32 in)</li>
2096 * <li>G10 (29x42 mm ; 1.14x1.65 in)</li>
2097 * <li>G11 (21x29 mm ; 0.83x1.14 in)</li>
2098 * <li>G12 (14x21 mm ; 0.55x0.83 in)</li>
2099 * <li><b>ISO Press</b></li>
2100 * <li>RA0 (860x1220 mm ; 33.86x48.03 in)</li>
2101 * <li>RA1 (610x860 mm ; 24.02x33.86 in)</li>
2102 * <li>RA2 (430x610 mm ; 16.93x24.02 in)</li>
2103 * <li>RA3 (305x430 mm ; 12.01x16.93 in)</li>
2104 * <li>RA4 (215x305 mm ; 8.46x12.01 in)</li>
2105 * <li>SRA0 (900x1280 mm ; 35.43x50.39 in)</li>
2106 * <li>SRA1 (640x900 mm ; 25.20x35.43 in)</li>
2107 * <li>SRA2 (450x640 mm ; 17.72x25.20 in)</li>
2108 * <li>SRA3 (320x450 mm ; 12.60x17.72 in)</li>
2109 * <li>SRA4 (225x320 mm ; 8.86x12.60 in)</li>
2110 * <li><b>German DIN 476</b></li>
2111 * <li>4A0 (1682x2378 mm ; 66.22x93.62 in)</li>
2112 * <li>2A0 (1189x1682 mm ; 46.81x66.22 in)</li>
2113 * <li><b>Variations on the ISO Standard</b></li>
2114 * <li>A2_EXTRA (445x619 mm ; 17.52x24.37 in)</li>
2115 * <li>A3+ (329x483 mm ; 12.95x19.02 in)</li>
2116 * <li>A3_EXTRA (322x445 mm ; 12.68x17.52 in)</li>
2117 * <li>A3_SUPER (305x508 mm ; 12.01x20.00 in)</li>
2118 * <li>SUPER_A3 (305x487 mm ; 12.01x19.17 in)</li>
2119 * <li>A4_EXTRA (235x322 mm ; 9.25x12.68 in)</li>
2120 * <li>A4_SUPER (229x322 mm ; 9.02x12.68 in)</li>
2121 * <li>SUPER_A4 (227x356 mm ; 8.94x14.02 in)</li>
2122 * <li>A4_LONG (210x348 mm ; 8.27x13.70 in)</li>
2123 * <li>F4 (210x330 mm ; 8.27x12.99 in)</li>
2124 * <li>SO_B5_EXTRA (202x276 mm ; 7.95x10.87 in)</li>
2125 * <li>A5_EXTRA (173x235 mm ; 6.81x9.25 in)</li>
2126 * <li><b>ANSI Series</b></li>
2127 * <li>ANSI_E (864x1118 mm ; 34.00x44.00 in)</li>
2128 * <li>ANSI_D (559x864 mm ; 22.00x34.00 in)</li>
2129 * <li>ANSI_C (432x559 mm ; 17.00x22.00 in)</li>
2130 * <li>ANSI_B (279x432 mm ; 11.00x17.00 in)</li>
2131 * <li>ANSI_A (216x279 mm ; 8.50x11.00 in)</li>
2132 * <li><b>Traditional 'Loose' North American Paper Sizes</b></li>
2133 * <li>LEDGER, USLEDGER (432x279 mm ; 17.00x11.00 in)</li>
2134 * <li>TABLOID, USTABLOID, BIBLE, ORGANIZERK (279x432 mm ; 11.00x17.00 in)</li>
2135 * <li>LETTER, USLETTER, ORGANIZERM (216x279 mm ; 8.50x11.00 in)</li>
2136 * <li>LEGAL, USLEGAL (216x356 mm ; 8.50x14.00 in)</li>
2137 * <li>GLETTER, GOVERNMENTLETTER (203x267 mm ; 8.00x10.50 in)</li>
2138 * <li>JLEGAL, JUNIORLEGAL (203x127 mm ; 8.00x5.00 in)</li>
2139 * <li><b>Other North American Paper Sizes</b></li>
2140 * <li>QUADDEMY (889x1143 mm ; 35.00x45.00 in)</li>
2141 * <li>SUPER_B (330x483 mm ; 13.00x19.00 in)</li>
2142 * <li>QUARTO (229x279 mm ; 9.00x11.00 in)</li>
2143 * <li>FOLIO, GOVERNMENTLEGAL (216x330 mm ; 8.50x13.00 in)</li>
2144 * <li>EXECUTIVE, MONARCH (184x267 mm ; 7.25x10.50 in)</li>
2145 * <li>MEMO, STATEMENT, ORGANIZERL (140x216 mm ; 5.50x8.50 in)</li>
2146 * <li>FOOLSCAP (210x330 mm ; 8.27x13.00 in)</li>
2147 * <li>COMPACT (108x171 mm ; 4.25x6.75 in)</li>
2148 * <li>ORGANIZERJ (70x127 mm ; 2.75x5.00 in)</li>
2149 * <li><b>Canadian standard CAN 2-9.60M</b></li>
2150 * <li>P1 (560x860 mm ; 22.05x33.86 in)</li>
2151 * <li>P2 (430x560 mm ; 16.93x22.05 in)</li>
2152 * <li>P3 (280x430 mm ; 11.02x16.93 in)</li>
2153 * <li>P4 (215x280 mm ; 8.46x11.02 in)</li>
2154 * <li>P5 (140x215 mm ; 5.51x8.46 in)</li>
2155 * <li>P6 (107x140 mm ; 4.21x5.51 in)</li>
2156 * <li><b>North American Architectural Sizes</b></li>
2157 * <li>ARCH_E (914x1219 mm ; 36.00x48.00 in)</li>
2158 * <li>ARCH_E1 (762x1067 mm ; 30.00x42.00 in)</li>
2159 * <li>ARCH_D (610x914 mm ; 24.00x36.00 in)</li>
2160 * <li>ARCH_C, BROADSHEET (457x610 mm ; 18.00x24.00 in)</li>
2161 * <li>ARCH_B (305x457 mm ; 12.00x18.00 in)</li>
2162 * <li>ARCH_A (229x305 mm ; 9.00x12.00 in)</li>
2163 * <li><b>Announcement Envelopes</b></li>
2164 * <li>ANNENV_A2 (111x146 mm ; 4.37x5.75 in)</li>
2165 * <li>ANNENV_A6 (121x165 mm ; 4.75x6.50 in)</li>
2166 * <li>ANNENV_A7 (133x184 mm ; 5.25x7.25 in)</li>
2167 * <li>ANNENV_A8 (140x206 mm ; 5.50x8.12 in)</li>
2168 * <li>ANNENV_A10 (159x244 mm ; 6.25x9.62 in)</li>
2169 * <li>ANNENV_SLIM (98x225 mm ; 3.87x8.87 in)</li>
2170 * <li><b>Commercial Envelopes</b></li>
2171 * <li>COMMENV_N6_1/4 (89x152 mm ; 3.50x6.00 in)</li>
2172 * <li>COMMENV_N6_3/4 (92x165 mm ; 3.62x6.50 in)</li>
2173 * <li>COMMENV_N8 (98x191 mm ; 3.87x7.50 in)</li>
2174 * <li>COMMENV_N9 (98x225 mm ; 3.87x8.87 in)</li>
2175 * <li>COMMENV_N10 (105x241 mm ; 4.12x9.50 in)</li>
2176 * <li>COMMENV_N11 (114x263 mm ; 4.50x10.37 in)</li>
2177 * <li>COMMENV_N12 (121x279 mm ; 4.75x11.00 in)</li>
2178 * <li>COMMENV_N14 (127x292 mm ; 5.00x11.50 in)</li>
2179 * <li><b>Catalogue Envelopes</b></li>
2180 * <li>CATENV_N1 (152x229 mm ; 6.00x9.00 in)</li>
2181 * <li>CATENV_N1_3/4 (165x241 mm ; 6.50x9.50 in)</li>
2182 * <li>CATENV_N2 (165x254 mm ; 6.50x10.00 in)</li>
2183 * <li>CATENV_N3 (178x254 mm ; 7.00x10.00 in)</li>
2184 * <li>CATENV_N6 (191x267 mm ; 7.50x10.50 in)</li>
2185 * <li>CATENV_N7 (203x279 mm ; 8.00x11.00 in)</li>
2186 * <li>CATENV_N8 (210x286 mm ; 8.25x11.25 in)</li>
2187 * <li>CATENV_N9_1/2 (216x267 mm ; 8.50x10.50 in)</li>
2188 * <li>CATENV_N9_3/4 (222x286 mm ; 8.75x11.25 in)</li>
2189 * <li>CATENV_N10_1/2 (229x305 mm ; 9.00x12.00 in)</li>
2190 * <li>CATENV_N12_1/2 (241x318 mm ; 9.50x12.50 in)</li>
2191 * <li>CATENV_N13_1/2 (254x330 mm ; 10.00x13.00 in)</li>
2192 * <li>CATENV_N14_1/4 (286x311 mm ; 11.25x12.25 in)</li>
2193 * <li>CATENV_N14_1/2 (292x368 mm ; 11.50x14.50 in)</li>
2194 * <li><b>Japanese (JIS P 0138-61) Standard B-Series</b></li>
2195 * <li>JIS_B0 (1030x1456 mm ; 40.55x57.32 in)</li>
2196 * <li>JIS_B1 (728x1030 mm ; 28.66x40.55 in)</li>
2197 * <li>JIS_B2 (515x728 mm ; 20.28x28.66 in)</li>
2198 * <li>JIS_B3 (364x515 mm ; 14.33x20.28 in)</li>
2199 * <li>JIS_B4 (257x364 mm ; 10.12x14.33 in)</li>
2200 * <li>JIS_B5 (182x257 mm ; 7.17x10.12 in)</li>
2201 * <li>JIS_B6 (128x182 mm ; 5.04x7.17 in)</li>
2202 * <li>JIS_B7 (91x128 mm ; 3.58x5.04 in)</li>
2203 * <li>JIS_B8 (64x91 mm ; 2.52x3.58 in)</li>
2204 * <li>JIS_B9 (45x64 mm ; 1.77x2.52 in)</li>
2205 * <li>JIS_B10 (32x45 mm ; 1.26x1.77 in)</li>
2206 * <li>JIS_B11 (22x32 mm ; 0.87x1.26 in)</li>
2207 * <li>JIS_B12 (16x22 mm ; 0.63x0.87 in)</li>
2208 * <li><b>PA Series</b></li>
2209 * <li>PA0 (840x1120 mm ; 33.07x44.09 in)</li>
2210 * <li>PA1 (560x840 mm ; 22.05x33.07 in)</li>
2211 * <li>PA2 (420x560 mm ; 16.54x22.05 in)</li>
2212 * <li>PA3 (280x420 mm ; 11.02x16.54 in)</li>
2213 * <li>PA4 (210x280 mm ; 8.27x11.02 in)</li>
2214 * <li>PA5 (140x210 mm ; 5.51x8.27 in)</li>
2215 * <li>PA6 (105x140 mm ; 4.13x5.51 in)</li>
2216 * <li>PA7 (70x105 mm ; 2.76x4.13 in)</li>
2217 * <li>PA8 (52x70 mm ; 2.05x2.76 in)</li>
2218 * <li>PA9 (35x52 mm ; 1.38x2.05 in)</li>
2219 * <li>PA10 (26x35 mm ; 1.02x1.38 in)</li>
2220 * <li><b>Standard Photographic Print Sizes</b></li>
2221 * <li>PASSPORT_PHOTO (35x45 mm ; 1.38x1.77 in)</li>
2222 * <li>E (82x120 mm ; 3.25x4.72 in)</li>
2223 * <li>3R, L (89x127 mm ; 3.50x5.00 in)</li>
2224 * <li>4R, KG (102x152 mm ; 4.02x5.98 in)</li>
2225 * <li>4D (120x152 mm ; 4.72x5.98 in)</li>
2226 * <li>5R, 2L (127x178 mm ; 5.00x7.01 in)</li>
2227 * <li>6R, 8P (152x203 mm ; 5.98x7.99 in)</li>
2228 * <li>8R, 6P (203x254 mm ; 7.99x10.00 in)</li>
2229 * <li>S8R, 6PW (203x305 mm ; 7.99x12.01 in)</li>
2230 * <li>10R, 4P (254x305 mm ; 10.00x12.01 in)</li>
2231 * <li>S10R, 4PW (254x381 mm ; 10.00x15.00 in)</li>
2232 * <li>11R (279x356 mm ; 10.98x14.02 in)</li>
2233 * <li>S11R (279x432 mm ; 10.98x17.01 in)</li>
2234 * <li>12R (305x381 mm ; 12.01x15.00 in)</li>
2235 * <li>S12R (305x456 mm ; 12.01x17.95 in)</li>
2236 * <li><b>Common Newspaper Sizes</b></li>
2237 * <li>NEWSPAPER_BROADSHEET (750x600 mm ; 29.53x23.62 in)</li>
2238 * <li>NEWSPAPER_BERLINER (470x315 mm ; 18.50x12.40 in)</li>
2239 * <li>NEWSPAPER_COMPACT, NEWSPAPER_TABLOID (430x280 mm ; 16.93x11.02 in)</li>
2240 * <li><b>Business Cards</b></li>
2241 * <li>CREDIT_CARD, BUSINESS_CARD, BUSINESS_CARD_ISO7810 (54x86 mm ; 2.13x3.37 in)</li>
2242 * <li>BUSINESS_CARD_ISO216 (52x74 mm ; 2.05x2.91 in)</li>
2243 * <li>BUSINESS_CARD_IT, BUSINESS_CARD_UK, BUSINESS_CARD_FR, BUSINESS_CARD_DE, BUSINESS_CARD_ES (55x85 mm ; 2.17x3.35 in)</li>
2244 * <li>BUSINESS_CARD_US, BUSINESS_CARD_CA (51x89 mm ; 2.01x3.50 in)</li>
2245 * <li>BUSINESS_CARD_JP (55x91 mm ; 2.17x3.58 in)</li>
2246 * <li>BUSINESS_CARD_HK (54x90 mm ; 2.13x3.54 in)</li>
2247 * <li>BUSINESS_CARD_AU, BUSINESS_CARD_DK, BUSINESS_CARD_SE (55x90 mm ; 2.17x3.54 in)</li>
2248 * <li>BUSINESS_CARD_RU, BUSINESS_CARD_CZ, BUSINESS_CARD_FI, BUSINESS_CARD_HU, BUSINESS_CARD_IL (50x90 mm ; 1.97x3.54 in)</li>
2249 * <li><b>Billboards</b></li>
2250 * <li>4SHEET (1016x1524 mm ; 40.00x60.00 in)</li>
2251 * <li>6SHEET (1200x1800 mm ; 47.24x70.87 in)</li>
2252 * <li>12SHEET (3048x1524 mm ; 120.00x60.00 in)</li>
2253 * <li>16SHEET (2032x3048 mm ; 80.00x120.00 in)</li>
2254 * <li>32SHEET (4064x3048 mm ; 160.00x120.00 in)</li>
2255 * <li>48SHEET (6096x3048 mm ; 240.00x120.00 in)</li>
2256 * <li>64SHEET (8128x3048 mm ; 320.00x120.00 in)</li>
2257 * <li>96SHEET (12192x3048 mm ; 480.00x120.00 in)</li>
2258 * <li><b>Old Imperial English (some are still used in USA)</b></li>
2259 * <li>EN_EMPEROR (1219x1829 mm ; 48.00x72.00 in)</li>
2260 * <li>EN_ANTIQUARIAN (787x1346 mm ; 31.00x53.00 in)</li>
2261 * <li>EN_GRAND_EAGLE (730x1067 mm ; 28.75x42.00 in)</li>
2262 * <li>EN_DOUBLE_ELEPHANT (679x1016 mm ; 26.75x40.00 in)</li>
2263 * <li>EN_ATLAS (660x864 mm ; 26.00x34.00 in)</li>
2264 * <li>EN_COLOMBIER (597x876 mm ; 23.50x34.50 in)</li>
2265 * <li>EN_ELEPHANT (584x711 mm ; 23.00x28.00 in)</li>
2266 * <li>EN_DOUBLE_DEMY (572x902 mm ; 22.50x35.50 in)</li>
2267 * <li>EN_IMPERIAL (559x762 mm ; 22.00x30.00 in)</li>
2268 * <li>EN_PRINCESS (546x711 mm ; 21.50x28.00 in)</li>
2269 * <li>EN_CARTRIDGE (533x660 mm ; 21.00x26.00 in)</li>
2270 * <li>EN_DOUBLE_LARGE_POST (533x838 mm ; 21.00x33.00 in)</li>
2271 * <li>EN_ROYAL (508x635 mm ; 20.00x25.00 in)</li>
2272 * <li>EN_SHEET, EN_HALF_POST (495x597 mm ; 19.50x23.50 in)</li>
2273 * <li>EN_SUPER_ROYAL (483x686 mm ; 19.00x27.00 in)</li>
2274 * <li>EN_DOUBLE_POST (483x775 mm ; 19.00x30.50 in)</li>
2275 * <li>EN_MEDIUM (445x584 mm ; 17.50x23.00 in)</li>
2276 * <li>EN_DEMY (445x572 mm ; 17.50x22.50 in)</li>
2277 * <li>EN_LARGE_POST (419x533 mm ; 16.50x21.00 in)</li>
2278 * <li>EN_COPY_DRAUGHT (406x508 mm ; 16.00x20.00 in)</li>
2279 * <li>EN_POST (394x489 mm ; 15.50x19.25 in)</li>
2280 * <li>EN_CROWN (381x508 mm ; 15.00x20.00 in)</li>
2281 * <li>EN_PINCHED_POST (375x470 mm ; 14.75x18.50 in)</li>
2282 * <li>EN_BRIEF (343x406 mm ; 13.50x16.00 in)</li>
2283 * <li>EN_FOOLSCAP (343x432 mm ; 13.50x17.00 in)</li>
2284 * <li>EN_SMALL_FOOLSCAP (337x419 mm ; 13.25x16.50 in)</li>
2285 * <li>EN_POTT (318x381 mm ; 12.50x15.00 in)</li>
2286 * <li><b>Old Imperial Belgian</b></li>
2287 * <li>BE_GRAND_AIGLE (700x1040 mm ; 27.56x40.94 in)</li>
2288 * <li>BE_COLOMBIER (620x850 mm ; 24.41x33.46 in)</li>
2289 * <li>BE_DOUBLE_CARRE (620x920 mm ; 24.41x36.22 in)</li>
2290 * <li>BE_ELEPHANT (616x770 mm ; 24.25x30.31 in)</li>
2291 * <li>BE_PETIT_AIGLE (600x840 mm ; 23.62x33.07 in)</li>
2292 * <li>BE_GRAND_JESUS (550x730 mm ; 21.65x28.74 in)</li>
2293 * <li>BE_JESUS (540x730 mm ; 21.26x28.74 in)</li>
2294 * <li>BE_RAISIN (500x650 mm ; 19.69x25.59 in)</li>
2295 * <li>BE_GRAND_MEDIAN (460x605 mm ; 18.11x23.82 in)</li>
2296 * <li>BE_DOUBLE_POSTE (435x565 mm ; 17.13x22.24 in)</li>
2297 * <li>BE_COQUILLE (430x560 mm ; 16.93x22.05 in)</li>
2298 * <li>BE_PETIT_MEDIAN (415x530 mm ; 16.34x20.87 in)</li>
2299 * <li>BE_RUCHE (360x460 mm ; 14.17x18.11 in)</li>
2300 * <li>BE_PROPATRIA (345x430 mm ; 13.58x16.93 in)</li>
2301 * <li>BE_LYS (317x397 mm ; 12.48x15.63 in)</li>
2302 * <li>BE_POT (307x384 mm ; 12.09x15.12 in)</li>
2303 * <li>BE_ROSETTE (270x347 mm ; 10.63x13.66 in)</li>
2304 * <li><b>Old Imperial French</b></li>
2305 * <li>FR_UNIVERS (1000x1300 mm ; 39.37x51.18 in)</li>
2306 * <li>FR_DOUBLE_COLOMBIER (900x1260 mm ; 35.43x49.61 in)</li>
2307 * <li>FR_GRANDE_MONDE (900x1260 mm ; 35.43x49.61 in)</li>
2308 * <li>FR_DOUBLE_SOLEIL (800x1200 mm ; 31.50x47.24 in)</li>
2309 * <li>FR_DOUBLE_JESUS (760x1120 mm ; 29.92x44.09 in)</li>
2310 * <li>FR_GRAND_AIGLE (750x1060 mm ; 29.53x41.73 in)</li>
2311 * <li>FR_PETIT_AIGLE (700x940 mm ; 27.56x37.01 in)</li>
2312 * <li>FR_DOUBLE_RAISIN (650x1000 mm ; 25.59x39.37 in)</li>
2313 * <li>FR_JOURNAL (650x940 mm ; 25.59x37.01 in)</li>
2314 * <li>FR_COLOMBIER_AFFICHE (630x900 mm ; 24.80x35.43 in)</li>
2315 * <li>FR_DOUBLE_CAVALIER (620x920 mm ; 24.41x36.22 in)</li>
2316 * <li>FR_CLOCHE (600x800 mm ; 23.62x31.50 in)</li>
2317 * <li>FR_SOLEIL (600x800 mm ; 23.62x31.50 in)</li>
2318 * <li>FR_DOUBLE_CARRE (560x900 mm ; 22.05x35.43 in)</li>
2319 * <li>FR_DOUBLE_COQUILLE (560x880 mm ; 22.05x34.65 in)</li>
2320 * <li>FR_JESUS (560x760 mm ; 22.05x29.92 in)</li>
2321 * <li>FR_RAISIN (500x650 mm ; 19.69x25.59 in)</li>
2322 * <li>FR_CAVALIER (460x620 mm ; 18.11x24.41 in)</li>
2323 * <li>FR_DOUBLE_COURONNE (460x720 mm ; 18.11x28.35 in)</li>
2324 * <li>FR_CARRE (450x560 mm ; 17.72x22.05 in)</li>
2325 * <li>FR_COQUILLE (440x560 mm ; 17.32x22.05 in)</li>
2326 * <li>FR_DOUBLE_TELLIERE (440x680 mm ; 17.32x26.77 in)</li>
2327 * <li>FR_DOUBLE_CLOCHE (400x600 mm ; 15.75x23.62 in)</li>
2328 * <li>FR_DOUBLE_POT (400x620 mm ; 15.75x24.41 in)</li>
2329 * <li>FR_ECU (400x520 mm ; 15.75x20.47 in)</li>
2330 * <li>FR_COURONNE (360x460 mm ; 14.17x18.11 in)</li>
2331 * <li>FR_TELLIERE (340x440 mm ; 13.39x17.32 in)</li>
2332 * <li>FR_POT (310x400 mm ; 12.20x15.75 in)</li>
2333 * </ul>
2334 * @return array containing page width and height in points
2335 * @public
2336 * @since 5.0.010 (2010-05-17)
2338 public function getPageSizeFromFormat($format) {
2339 // Paper cordinates are calculated in this way: (inches * 72) where (1 inch = 25.4 mm)
2340 switch (strtoupper($format)) {
2341 // ISO 216 A Series + 2 SIS 014711 extensions
2342 case 'A0' : {$pf = array( 2383.937, 3370.394); break;}
2343 case 'A1' : {$pf = array( 1683.780, 2383.937); break;}
2344 case 'A2' : {$pf = array( 1190.551, 1683.780); break;}
2345 case 'A3' : {$pf = array( 841.890, 1190.551); break;}
2346 case 'A4' : {$pf = array( 595.276, 841.890); break;}
2347 case 'A5' : {$pf = array( 419.528, 595.276); break;}
2348 case 'A6' : {$pf = array( 297.638, 419.528); break;}
2349 case 'A7' : {$pf = array( 209.764, 297.638); break;}
2350 case 'A8' : {$pf = array( 147.402, 209.764); break;}
2351 case 'A9' : {$pf = array( 104.882, 147.402); break;}
2352 case 'A10': {$pf = array( 73.701, 104.882); break;}
2353 case 'A11': {$pf = array( 51.024, 73.701); break;}
2354 case 'A12': {$pf = array( 36.850, 51.024); break;}
2355 // ISO 216 B Series + 2 SIS 014711 extensions
2356 case 'B0' : {$pf = array( 2834.646, 4008.189); break;}
2357 case 'B1' : {$pf = array( 2004.094, 2834.646); break;}
2358 case 'B2' : {$pf = array( 1417.323, 2004.094); break;}
2359 case 'B3' : {$pf = array( 1000.630, 1417.323); break;}
2360 case 'B4' : {$pf = array( 708.661, 1000.630); break;}
2361 case 'B5' : {$pf = array( 498.898, 708.661); break;}
2362 case 'B6' : {$pf = array( 354.331, 498.898); break;}
2363 case 'B7' : {$pf = array( 249.449, 354.331); break;}
2364 case 'B8' : {$pf = array( 175.748, 249.449); break;}
2365 case 'B9' : {$pf = array( 124.724, 175.748); break;}
2366 case 'B10': {$pf = array( 87.874, 124.724); break;}
2367 case 'B11': {$pf = array( 62.362, 87.874); break;}
2368 case 'B12': {$pf = array( 42.520, 62.362); break;}
2369 // ISO 216 C Series + 2 SIS 014711 extensions + 2 EXTENSION
2370 case 'C0' : {$pf = array( 2599.370, 3676.535); break;}
2371 case 'C1' : {$pf = array( 1836.850, 2599.370); break;}
2372 case 'C2' : {$pf = array( 1298.268, 1836.850); break;}
2373 case 'C3' : {$pf = array( 918.425, 1298.268); break;}
2374 case 'C4' : {$pf = array( 649.134, 918.425); break;}
2375 case 'C5' : {$pf = array( 459.213, 649.134); break;}
2376 case 'C6' : {$pf = array( 323.150, 459.213); break;}
2377 case 'C7' : {$pf = array( 229.606, 323.150); break;}
2378 case 'C8' : {$pf = array( 161.575, 229.606); break;}
2379 case 'C9' : {$pf = array( 113.386, 161.575); break;}
2380 case 'C10': {$pf = array( 79.370, 113.386); break;}
2381 case 'C11': {$pf = array( 56.693, 79.370); break;}
2382 case 'C12': {$pf = array( 39.685, 56.693); break;}
2383 case 'C76': {$pf = array( 229.606, 459.213); break;}
2384 case 'DL' : {$pf = array( 311.811, 623.622); break;}
2385 // SIS 014711 E Series
2386 case 'E0' : {$pf = array( 2491.654, 3517.795); break;}
2387 case 'E1' : {$pf = array( 1757.480, 2491.654); break;}
2388 case 'E2' : {$pf = array( 1247.244, 1757.480); break;}
2389 case 'E3' : {$pf = array( 878.740, 1247.244); break;}
2390 case 'E4' : {$pf = array( 623.622, 878.740); break;}
2391 case 'E5' : {$pf = array( 439.370, 623.622); break;}
2392 case 'E6' : {$pf = array( 311.811, 439.370); break;}
2393 case 'E7' : {$pf = array( 221.102, 311.811); break;}
2394 case 'E8' : {$pf = array( 155.906, 221.102); break;}
2395 case 'E9' : {$pf = array( 110.551, 155.906); break;}
2396 case 'E10': {$pf = array( 76.535, 110.551); break;}
2397 case 'E11': {$pf = array( 53.858, 76.535); break;}
2398 case 'E12': {$pf = array( 36.850, 53.858); break;}
2399 // SIS 014711 G Series
2400 case 'G0' : {$pf = array( 2715.591, 3838.110); break;}
2401 case 'G1' : {$pf = array( 1919.055, 2715.591); break;}
2402 case 'G2' : {$pf = array( 1357.795, 1919.055); break;}
2403 case 'G3' : {$pf = array( 958.110, 1357.795); break;}
2404 case 'G4' : {$pf = array( 677.480, 958.110); break;}
2405 case 'G5' : {$pf = array( 479.055, 677.480); break;}
2406 case 'G6' : {$pf = array( 337.323, 479.055); break;}
2407 case 'G7' : {$pf = array( 238.110, 337.323); break;}
2408 case 'G8' : {$pf = array( 167.244, 238.110); break;}
2409 case 'G9' : {$pf = array( 119.055, 167.244); break;}
2410 case 'G10': {$pf = array( 82.205, 119.055); break;}
2411 case 'G11': {$pf = array( 59.528, 82.205); break;}
2412 case 'G12': {$pf = array( 39.685, 59.528); break;}
2413 // ISO Press
2414 case 'RA0': {$pf = array( 2437.795, 3458.268); break;}
2415 case 'RA1': {$pf = array( 1729.134, 2437.795); break;}
2416 case 'RA2': {$pf = array( 1218.898, 1729.134); break;}
2417 case 'RA3': {$pf = array( 864.567, 1218.898); break;}
2418 case 'RA4': {$pf = array( 609.449, 864.567); break;}
2419 case 'SRA0': {$pf = array( 2551.181, 3628.346); break;}
2420 case 'SRA1': {$pf = array( 1814.173, 2551.181); break;}
2421 case 'SRA2': {$pf = array( 1275.591, 1814.173); break;}
2422 case 'SRA3': {$pf = array( 907.087, 1275.591); break;}
2423 case 'SRA4': {$pf = array( 637.795, 907.087); break;}
2424 // German DIN 476
2425 case '4A0': {$pf = array( 4767.874, 6740.787); break;}
2426 case '2A0': {$pf = array( 3370.394, 4767.874); break;}
2427 // Variations on the ISO Standard
2428 case 'A2_EXTRA' : {$pf = array( 1261.417, 1754.646); break;}
2429 case 'A3+' : {$pf = array( 932.598, 1369.134); break;}
2430 case 'A3_EXTRA' : {$pf = array( 912.756, 1261.417); break;}
2431 case 'A3_SUPER' : {$pf = array( 864.567, 1440.000); break;}
2432 case 'SUPER_A3' : {$pf = array( 864.567, 1380.472); break;}
2433 case 'A4_EXTRA' : {$pf = array( 666.142, 912.756); break;}
2434 case 'A4_SUPER' : {$pf = array( 649.134, 912.756); break;}
2435 case 'SUPER_A4' : {$pf = array( 643.465, 1009.134); break;}
2436 case 'A4_LONG' : {$pf = array( 595.276, 986.457); break;}
2437 case 'F4' : {$pf = array( 595.276, 935.433); break;}
2438 case 'SO_B5_EXTRA': {$pf = array( 572.598, 782.362); break;}
2439 case 'A5_EXTRA' : {$pf = array( 490.394, 666.142); break;}
2440 // ANSI Series
2441 case 'ANSI_E': {$pf = array( 2448.000, 3168.000); break;}
2442 case 'ANSI_D': {$pf = array( 1584.000, 2448.000); break;}
2443 case 'ANSI_C': {$pf = array( 1224.000, 1584.000); break;}
2444 case 'ANSI_B': {$pf = array( 792.000, 1224.000); break;}
2445 case 'ANSI_A': {$pf = array( 612.000, 792.000); break;}
2446 // Traditional 'Loose' North American Paper Sizes
2447 case 'USLEDGER':
2448 case 'LEDGER' : {$pf = array( 1224.000, 792.000); break;}
2449 case 'ORGANIZERK':
2450 case 'BIBLE':
2451 case 'USTABLOID':
2452 case 'TABLOID': {$pf = array( 792.000, 1224.000); break;}
2453 case 'ORGANIZERM':
2454 case 'USLETTER':
2455 case 'LETTER' : {$pf = array( 612.000, 792.000); break;}
2456 case 'USLEGAL':
2457 case 'LEGAL' : {$pf = array( 612.000, 1008.000); break;}
2458 case 'GOVERNMENTLETTER':
2459 case 'GLETTER': {$pf = array( 576.000, 756.000); break;}
2460 case 'JUNIORLEGAL':
2461 case 'JLEGAL' : {$pf = array( 576.000, 360.000); break;}
2462 // Other North American Paper Sizes
2463 case 'QUADDEMY': {$pf = array( 2520.000, 3240.000); break;}
2464 case 'SUPER_B': {$pf = array( 936.000, 1368.000); break;}
2465 case 'QUARTO': {$pf = array( 648.000, 792.000); break;}
2466 case 'GOVERNMENTLEGAL':
2467 case 'FOLIO': {$pf = array( 612.000, 936.000); break;}
2468 case 'MONARCH':
2469 case 'EXECUTIVE': {$pf = array( 522.000, 756.000); break;}
2470 case 'ORGANIZERL':
2471 case 'STATEMENT':
2472 case 'MEMO': {$pf = array( 396.000, 612.000); break;}
2473 case 'FOOLSCAP': {$pf = array( 595.440, 936.000); break;}
2474 case 'COMPACT': {$pf = array( 306.000, 486.000); break;}
2475 case 'ORGANIZERJ': {$pf = array( 198.000, 360.000); break;}
2476 // Canadian standard CAN 2-9.60M
2477 case 'P1': {$pf = array( 1587.402, 2437.795); break;}
2478 case 'P2': {$pf = array( 1218.898, 1587.402); break;}
2479 case 'P3': {$pf = array( 793.701, 1218.898); break;}
2480 case 'P4': {$pf = array( 609.449, 793.701); break;}
2481 case 'P5': {$pf = array( 396.850, 609.449); break;}
2482 case 'P6': {$pf = array( 303.307, 396.850); break;}
2483 // North American Architectural Sizes
2484 case 'ARCH_E' : {$pf = array( 2592.000, 3456.000); break;}
2485 case 'ARCH_E1': {$pf = array( 2160.000, 3024.000); break;}
2486 case 'ARCH_D' : {$pf = array( 1728.000, 2592.000); break;}
2487 case 'BROADSHEET':
2488 case 'ARCH_C' : {$pf = array( 1296.000, 1728.000); break;}
2489 case 'ARCH_B' : {$pf = array( 864.000, 1296.000); break;}
2490 case 'ARCH_A' : {$pf = array( 648.000, 864.000); break;}
2491 // --- North American Envelope Sizes ---
2492 // - Announcement Envelopes
2493 case 'ANNENV_A2' : {$pf = array( 314.640, 414.000); break;}
2494 case 'ANNENV_A6' : {$pf = array( 342.000, 468.000); break;}
2495 case 'ANNENV_A7' : {$pf = array( 378.000, 522.000); break;}
2496 case 'ANNENV_A8' : {$pf = array( 396.000, 584.640); break;}
2497 case 'ANNENV_A10' : {$pf = array( 450.000, 692.640); break;}
2498 case 'ANNENV_SLIM': {$pf = array( 278.640, 638.640); break;}
2499 // - Commercial Envelopes
2500 case 'COMMENV_N6_1/4': {$pf = array( 252.000, 432.000); break;}
2501 case 'COMMENV_N6_3/4': {$pf = array( 260.640, 468.000); break;}
2502 case 'COMMENV_N8' : {$pf = array( 278.640, 540.000); break;}
2503 case 'COMMENV_N9' : {$pf = array( 278.640, 638.640); break;}
2504 case 'COMMENV_N10' : {$pf = array( 296.640, 684.000); break;}
2505 case 'COMMENV_N11' : {$pf = array( 324.000, 746.640); break;}
2506 case 'COMMENV_N12' : {$pf = array( 342.000, 792.000); break;}
2507 case 'COMMENV_N14' : {$pf = array( 360.000, 828.000); break;}
2508 // - Catalogue Envelopes
2509 case 'CATENV_N1' : {$pf = array( 432.000, 648.000); break;}
2510 case 'CATENV_N1_3/4' : {$pf = array( 468.000, 684.000); break;}
2511 case 'CATENV_N2' : {$pf = array( 468.000, 720.000); break;}
2512 case 'CATENV_N3' : {$pf = array( 504.000, 720.000); break;}
2513 case 'CATENV_N6' : {$pf = array( 540.000, 756.000); break;}
2514 case 'CATENV_N7' : {$pf = array( 576.000, 792.000); break;}
2515 case 'CATENV_N8' : {$pf = array( 594.000, 810.000); break;}
2516 case 'CATENV_N9_1/2' : {$pf = array( 612.000, 756.000); break;}
2517 case 'CATENV_N9_3/4' : {$pf = array( 630.000, 810.000); break;}
2518 case 'CATENV_N10_1/2': {$pf = array( 648.000, 864.000); break;}
2519 case 'CATENV_N12_1/2': {$pf = array( 684.000, 900.000); break;}
2520 case 'CATENV_N13_1/2': {$pf = array( 720.000, 936.000); break;}
2521 case 'CATENV_N14_1/4': {$pf = array( 810.000, 882.000); break;}
2522 case 'CATENV_N14_1/2': {$pf = array( 828.000, 1044.000); break;}
2523 // Japanese (JIS P 0138-61) Standard B-Series
2524 case 'JIS_B0' : {$pf = array( 2919.685, 4127.244); break;}
2525 case 'JIS_B1' : {$pf = array( 2063.622, 2919.685); break;}
2526 case 'JIS_B2' : {$pf = array( 1459.843, 2063.622); break;}
2527 case 'JIS_B3' : {$pf = array( 1031.811, 1459.843); break;}
2528 case 'JIS_B4' : {$pf = array( 728.504, 1031.811); break;}
2529 case 'JIS_B5' : {$pf = array( 515.906, 728.504); break;}
2530 case 'JIS_B6' : {$pf = array( 362.835, 515.906); break;}
2531 case 'JIS_B7' : {$pf = array( 257.953, 362.835); break;}
2532 case 'JIS_B8' : {$pf = array( 181.417, 257.953); break;}
2533 case 'JIS_B9' : {$pf = array( 127.559, 181.417); break;}
2534 case 'JIS_B10': {$pf = array( 90.709, 127.559); break;}
2535 case 'JIS_B11': {$pf = array( 62.362, 90.709); break;}
2536 case 'JIS_B12': {$pf = array( 45.354, 62.362); break;}
2537 // PA Series
2538 case 'PA0' : {$pf = array( 2381.102, 3174.803,); break;}
2539 case 'PA1' : {$pf = array( 1587.402, 2381.102); break;}
2540 case 'PA2' : {$pf = array( 1190.551, 1587.402); break;}
2541 case 'PA3' : {$pf = array( 793.701, 1190.551); break;}
2542 case 'PA4' : {$pf = array( 595.276, 793.701); break;}
2543 case 'PA5' : {$pf = array( 396.850, 595.276); break;}
2544 case 'PA6' : {$pf = array( 297.638, 396.850); break;}
2545 case 'PA7' : {$pf = array( 198.425, 297.638); break;}
2546 case 'PA8' : {$pf = array( 147.402, 198.425); break;}
2547 case 'PA9' : {$pf = array( 99.213, 147.402); break;}
2548 case 'PA10': {$pf = array( 73.701, 99.213); break;}
2549 // Standard Photographic Print Sizes
2550 case 'PASSPORT_PHOTO': {$pf = array( 99.213, 127.559); break;}
2551 case 'E' : {$pf = array( 233.858, 340.157); break;}
2552 case 'L':
2553 case '3R' : {$pf = array( 252.283, 360.000); break;}
2554 case 'KG':
2555 case '4R' : {$pf = array( 289.134, 430.866); break;}
2556 case '4D' : {$pf = array( 340.157, 430.866); break;}
2557 case '2L':
2558 case '5R' : {$pf = array( 360.000, 504.567); break;}
2559 case '8P':
2560 case '6R' : {$pf = array( 430.866, 575.433); break;}
2561 case '6P':
2562 case '8R' : {$pf = array( 575.433, 720.000); break;}
2563 case '6PW':
2564 case 'S8R' : {$pf = array( 575.433, 864.567); break;}
2565 case '4P':
2566 case '10R' : {$pf = array( 720.000, 864.567); break;}
2567 case '4PW':
2568 case 'S10R': {$pf = array( 720.000, 1080.000); break;}
2569 case '11R' : {$pf = array( 790.866, 1009.134); break;}
2570 case 'S11R': {$pf = array( 790.866, 1224.567); break;}
2571 case '12R' : {$pf = array( 864.567, 1080.000); break;}
2572 case 'S12R': {$pf = array( 864.567, 1292.598); break;}
2573 // Common Newspaper Sizes
2574 case 'NEWSPAPER_BROADSHEET': {$pf = array( 2125.984, 1700.787); break;}
2575 case 'NEWSPAPER_BERLINER' : {$pf = array( 1332.283, 892.913); break;}
2576 case 'NEWSPAPER_TABLOID':
2577 case 'NEWSPAPER_COMPACT' : {$pf = array( 1218.898, 793.701); break;}
2578 // Business Cards
2579 case 'CREDIT_CARD':
2580 case 'BUSINESS_CARD':
2581 case 'BUSINESS_CARD_ISO7810': {$pf = array( 153.014, 242.646); break;}
2582 case 'BUSINESS_CARD_ISO216' : {$pf = array( 147.402, 209.764); break;}
2583 case 'BUSINESS_CARD_IT':
2584 case 'BUSINESS_CARD_UK':
2585 case 'BUSINESS_CARD_FR':
2586 case 'BUSINESS_CARD_DE':
2587 case 'BUSINESS_CARD_ES' : {$pf = array( 155.906, 240.945); break;}
2588 case 'BUSINESS_CARD_CA':
2589 case 'BUSINESS_CARD_US' : {$pf = array( 144.567, 252.283); break;}
2590 case 'BUSINESS_CARD_JP' : {$pf = array( 155.906, 257.953); break;}
2591 case 'BUSINESS_CARD_HK' : {$pf = array( 153.071, 255.118); break;}
2592 case 'BUSINESS_CARD_AU':
2593 case 'BUSINESS_CARD_DK':
2594 case 'BUSINESS_CARD_SE' : {$pf = array( 155.906, 255.118); break;}
2595 case 'BUSINESS_CARD_RU':
2596 case 'BUSINESS_CARD_CZ':
2597 case 'BUSINESS_CARD_FI':
2598 case 'BUSINESS_CARD_HU':
2599 case 'BUSINESS_CARD_IL' : {$pf = array( 141.732, 255.118); break;}
2600 // Billboards
2601 case '4SHEET' : {$pf = array( 2880.000, 4320.000); break;}
2602 case '6SHEET' : {$pf = array( 3401.575, 5102.362); break;}
2603 case '12SHEET': {$pf = array( 8640.000, 4320.000); break;}
2604 case '16SHEET': {$pf = array( 5760.000, 8640.000); break;}
2605 case '32SHEET': {$pf = array(11520.000, 8640.000); break;}
2606 case '48SHEET': {$pf = array(17280.000, 8640.000); break;}
2607 case '64SHEET': {$pf = array(23040.000, 8640.000); break;}
2608 case '96SHEET': {$pf = array(34560.000, 8640.000); break;}
2609 // Old European Sizes
2610 // - Old Imperial English Sizes
2611 case 'EN_EMPEROR' : {$pf = array( 3456.000, 5184.000); break;}
2612 case 'EN_ANTIQUARIAN' : {$pf = array( 2232.000, 3816.000); break;}
2613 case 'EN_GRAND_EAGLE' : {$pf = array( 2070.000, 3024.000); break;}
2614 case 'EN_DOUBLE_ELEPHANT' : {$pf = array( 1926.000, 2880.000); break;}
2615 case 'EN_ATLAS' : {$pf = array( 1872.000, 2448.000); break;}
2616 case 'EN_COLOMBIER' : {$pf = array( 1692.000, 2484.000); break;}
2617 case 'EN_ELEPHANT' : {$pf = array( 1656.000, 2016.000); break;}
2618 case 'EN_DOUBLE_DEMY' : {$pf = array( 1620.000, 2556.000); break;}
2619 case 'EN_IMPERIAL' : {$pf = array( 1584.000, 2160.000); break;}
2620 case 'EN_PRINCESS' : {$pf = array( 1548.000, 2016.000); break;}
2621 case 'EN_CARTRIDGE' : {$pf = array( 1512.000, 1872.000); break;}
2622 case 'EN_DOUBLE_LARGE_POST': {$pf = array( 1512.000, 2376.000); break;}
2623 case 'EN_ROYAL' : {$pf = array( 1440.000, 1800.000); break;}
2624 case 'EN_SHEET':
2625 case 'EN_HALF_POST' : {$pf = array( 1404.000, 1692.000); break;}
2626 case 'EN_SUPER_ROYAL' : {$pf = array( 1368.000, 1944.000); break;}
2627 case 'EN_DOUBLE_POST' : {$pf = array( 1368.000, 2196.000); break;}
2628 case 'EN_MEDIUM' : {$pf = array( 1260.000, 1656.000); break;}
2629 case 'EN_DEMY' : {$pf = array( 1260.000, 1620.000); break;}
2630 case 'EN_LARGE_POST' : {$pf = array( 1188.000, 1512.000); break;}
2631 case 'EN_COPY_DRAUGHT' : {$pf = array( 1152.000, 1440.000); break;}
2632 case 'EN_POST' : {$pf = array( 1116.000, 1386.000); break;}
2633 case 'EN_CROWN' : {$pf = array( 1080.000, 1440.000); break;}
2634 case 'EN_PINCHED_POST' : {$pf = array( 1062.000, 1332.000); break;}
2635 case 'EN_BRIEF' : {$pf = array( 972.000, 1152.000); break;}
2636 case 'EN_FOOLSCAP' : {$pf = array( 972.000, 1224.000); break;}
2637 case 'EN_SMALL_FOOLSCAP' : {$pf = array( 954.000, 1188.000); break;}
2638 case 'EN_POTT' : {$pf = array( 900.000, 1080.000); break;}
2639 // - Old Imperial Belgian Sizes
2640 case 'BE_GRAND_AIGLE' : {$pf = array( 1984.252, 2948.031); break;}
2641 case 'BE_COLOMBIER' : {$pf = array( 1757.480, 2409.449); break;}
2642 case 'BE_DOUBLE_CARRE': {$pf = array( 1757.480, 2607.874); break;}
2643 case 'BE_ELEPHANT' : {$pf = array( 1746.142, 2182.677); break;}
2644 case 'BE_PETIT_AIGLE' : {$pf = array( 1700.787, 2381.102); break;}
2645 case 'BE_GRAND_JESUS' : {$pf = array( 1559.055, 2069.291); break;}
2646 case 'BE_JESUS' : {$pf = array( 1530.709, 2069.291); break;}
2647 case 'BE_RAISIN' : {$pf = array( 1417.323, 1842.520); break;}
2648 case 'BE_GRAND_MEDIAN': {$pf = array( 1303.937, 1714.961); break;}
2649 case 'BE_DOUBLE_POSTE': {$pf = array( 1233.071, 1601.575); break;}
2650 case 'BE_COQUILLE' : {$pf = array( 1218.898, 1587.402); break;}
2651 case 'BE_PETIT_MEDIAN': {$pf = array( 1176.378, 1502.362); break;}
2652 case 'BE_RUCHE' : {$pf = array( 1020.472, 1303.937); break;}
2653 case 'BE_PROPATRIA' : {$pf = array( 977.953, 1218.898); break;}
2654 case 'BE_LYS' : {$pf = array( 898.583, 1125.354); break;}
2655 case 'BE_POT' : {$pf = array( 870.236, 1088.504); break;}
2656 case 'BE_ROSETTE' : {$pf = array( 765.354, 983.622); break;}
2657 // - Old Imperial French Sizes
2658 case 'FR_UNIVERS' : {$pf = array( 2834.646, 3685.039); break;}
2659 case 'FR_DOUBLE_COLOMBIER' : {$pf = array( 2551.181, 3571.654); break;}
2660 case 'FR_GRANDE_MONDE' : {$pf = array( 2551.181, 3571.654); break;}
2661 case 'FR_DOUBLE_SOLEIL' : {$pf = array( 2267.717, 3401.575); break;}
2662 case 'FR_DOUBLE_JESUS' : {$pf = array( 2154.331, 3174.803); break;}
2663 case 'FR_GRAND_AIGLE' : {$pf = array( 2125.984, 3004.724); break;}
2664 case 'FR_PETIT_AIGLE' : {$pf = array( 1984.252, 2664.567); break;}
2665 case 'FR_DOUBLE_RAISIN' : {$pf = array( 1842.520, 2834.646); break;}
2666 case 'FR_JOURNAL' : {$pf = array( 1842.520, 2664.567); break;}
2667 case 'FR_COLOMBIER_AFFICHE': {$pf = array( 1785.827, 2551.181); break;}
2668 case 'FR_DOUBLE_CAVALIER' : {$pf = array( 1757.480, 2607.874); break;}
2669 case 'FR_CLOCHE' : {$pf = array( 1700.787, 2267.717); break;}
2670 case 'FR_SOLEIL' : {$pf = array( 1700.787, 2267.717); break;}
2671 case 'FR_DOUBLE_CARRE' : {$pf = array( 1587.402, 2551.181); break;}
2672 case 'FR_DOUBLE_COQUILLE' : {$pf = array( 1587.402, 2494.488); break;}
2673 case 'FR_JESUS' : {$pf = array( 1587.402, 2154.331); break;}
2674 case 'FR_RAISIN' : {$pf = array( 1417.323, 1842.520); break;}
2675 case 'FR_CAVALIER' : {$pf = array( 1303.937, 1757.480); break;}
2676 case 'FR_DOUBLE_COURONNE' : {$pf = array( 1303.937, 2040.945); break;}
2677 case 'FR_CARRE' : {$pf = array( 1275.591, 1587.402); break;}
2678 case 'FR_COQUILLE' : {$pf = array( 1247.244, 1587.402); break;}
2679 case 'FR_DOUBLE_TELLIERE' : {$pf = array( 1247.244, 1927.559); break;}
2680 case 'FR_DOUBLE_CLOCHE' : {$pf = array( 1133.858, 1700.787); break;}
2681 case 'FR_DOUBLE_POT' : {$pf = array( 1133.858, 1757.480); break;}
2682 case 'FR_ECU' : {$pf = array( 1133.858, 1474.016); break;}
2683 case 'FR_COURONNE' : {$pf = array( 1020.472, 1303.937); break;}
2684 case 'FR_TELLIERE' : {$pf = array( 963.780, 1247.244); break;}
2685 case 'FR_POT' : {$pf = array( 878.740, 1133.858); break;}
2686 // DEFAULT ISO A4
2687 default: {$pf = array( 595.276, 841.890); break;}
2689 return $pf;
2693 * Change the format of the current page
2694 * @param $format (mixed) The format used for pages. It can be either: one of the string values specified at getPageSizeFromFormat() documentation or an array of two numners (width, height) or an array containing the following measures and options:<ul>
2695 * <li>['format'] = page format name (one of the above);</li>
2696 * <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>
2697 * <li>['PZ'] : The page's preferred zoom (magnification) factor.</li>
2698 * <li>['MediaBox'] : the boundaries of the physical medium on which the page shall be displayed or printed:</li>
2699 * <li>['MediaBox']['llx'] : lower-left x coordinate in points</li>
2700 * <li>['MediaBox']['lly'] : lower-left y coordinate in points</li>
2701 * <li>['MediaBox']['urx'] : upper-right x coordinate in points</li>
2702 * <li>['MediaBox']['ury'] : upper-right y coordinate in points</li>
2703 * <li>['CropBox'] : the visible region of default user space:</li>
2704 * <li>['CropBox']['llx'] : lower-left x coordinate in points</li>
2705 * <li>['CropBox']['lly'] : lower-left y coordinate in points</li>
2706 * <li>['CropBox']['urx'] : upper-right x coordinate in points</li>
2707 * <li>['CropBox']['ury'] : upper-right y coordinate in points</li>
2708 * <li>['BleedBox'] : the region to which the contents of the page shall be clipped when output in a production environment:</li>
2709 * <li>['BleedBox']['llx'] : lower-left x coordinate in points</li>
2710 * <li>['BleedBox']['lly'] : lower-left y coordinate in points</li>
2711 * <li>['BleedBox']['urx'] : upper-right x coordinate in points</li>
2712 * <li>['BleedBox']['ury'] : upper-right y coordinate in points</li>
2713 * <li>['TrimBox'] : the intended dimensions of the finished page after trimming:</li>
2714 * <li>['TrimBox']['llx'] : lower-left x coordinate in points</li>
2715 * <li>['TrimBox']['lly'] : lower-left y coordinate in points</li>
2716 * <li>['TrimBox']['urx'] : upper-right x coordinate in points</li>
2717 * <li>['TrimBox']['ury'] : upper-right y coordinate in points</li>
2718 * <li>['ArtBox'] : the extent of the page's meaningful content:</li>
2719 * <li>['ArtBox']['llx'] : lower-left x coordinate in points</li>
2720 * <li>['ArtBox']['lly'] : lower-left y coordinate in points</li>
2721 * <li>['ArtBox']['urx'] : upper-right x coordinate in points</li>
2722 * <li>['ArtBox']['ury'] : upper-right y coordinate in points</li>
2723 * <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>
2724 * <li>['BoxColorInfo'][BOXTYPE]['C'] : an array of three numbers in the range 0-255, representing the components in the DeviceRGB colour space.</li>
2725 * <li>['BoxColorInfo'][BOXTYPE]['W'] : the guideline width in default user units</li>
2726 * <li>['BoxColorInfo'][BOXTYPE]['S'] : the guideline style: S = Solid; D = Dashed</li>
2727 * <li>['BoxColorInfo'][BOXTYPE]['D'] : dash array defining a pattern of dashes and gaps to be used in drawing dashed guidelines</li>
2728 * <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>
2729 * <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>
2730 * <li>['trans']['S'] : transition style : Split, Blinds, Box, Wipe, Dissolve, Glitter, R, Fly, Push, Cover, Uncover, Fade</li>
2731 * <li>['trans']['D'] : The duration of the transition effect, in seconds.</li>
2732 * <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>
2733 * <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>
2734 * <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>
2735 * <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>
2736 * <li>['trans']['B'] : (Fly transition style only) If true, the area that shall be flown in is rectangular and opaque. Default: false.</li>
2737 * </ul>
2738 * @param $orientation (string) page orientation. Possible values are (case insensitive):<ul>
2739 * <li>P or Portrait (default)</li>
2740 * <li>L or Landscape</li>
2741 * <li>'' (empty string) for automatic orientation</li>
2742 * </ul>
2743 * @protected
2744 * @since 3.0.015 (2008-06-06)
2745 * @see getPageSizeFromFormat()
2747 protected function setPageFormat($format, $orientation='P') {
2748 if (!empty($format) AND isset($this->pagedim[$this->page])) {
2749 // remove inherited values
2750 unset($this->pagedim[$this->page]);
2752 if (is_string($format)) {
2753 // get page measures from format name
2754 $pf = $this->getPageSizeFromFormat($format);
2755 $this->fwPt = $pf[0];
2756 $this->fhPt = $pf[1];
2757 } else {
2758 // the boundaries of the physical medium on which the page shall be displayed or printed
2759 if (isset($format['MediaBox'])) {
2760 $this->setPageBoxes($this->page, 'MediaBox', $format['MediaBox']['llx'], $format['MediaBox']['lly'], $format['MediaBox']['urx'], $format['MediaBox']['ury'], false);
2761 $this->fwPt = (($format['MediaBox']['urx'] - $format['MediaBox']['llx']) * $this->k);
2762 $this->fhPt = (($format['MediaBox']['ury'] - $format['MediaBox']['lly']) * $this->k);
2763 } else {
2764 if (isset($format[0]) AND is_numeric($format[0]) AND isset($format[1]) AND is_numeric($format[1])) {
2765 $pf = array(($format[0] * $this->k), ($format[1] * $this->k));
2766 } else {
2767 if (!isset($format['format'])) {
2768 // default value
2769 $format['format'] = 'A4';
2771 $pf = $this->getPageSizeFromFormat($format['format']);
2773 $this->fwPt = $pf[0];
2774 $this->fhPt = $pf[1];
2775 $this->setPageBoxes($this->page, 'MediaBox', 0, 0, $this->fwPt, $this->fhPt, true);
2777 // the visible region of default user space
2778 if (isset($format['CropBox'])) {
2779 $this->setPageBoxes($this->page, 'CropBox', $format['CropBox']['llx'], $format['CropBox']['lly'], $format['CropBox']['urx'], $format['CropBox']['ury'], false);
2781 // the region to which the contents of the page shall be clipped when output in a production environment
2782 if (isset($format['BleedBox'])) {
2783 $this->setPageBoxes($this->page, 'BleedBox', $format['BleedBox']['llx'], $format['BleedBox']['lly'], $format['BleedBox']['urx'], $format['BleedBox']['ury'], false);
2785 // the intended dimensions of the finished page after trimming
2786 if (isset($format['TrimBox'])) {
2787 $this->setPageBoxes($this->page, 'TrimBox', $format['TrimBox']['llx'], $format['TrimBox']['lly'], $format['TrimBox']['urx'], $format['TrimBox']['ury'], false);
2789 // the page's meaningful content (including potential white space)
2790 if (isset($format['ArtBox'])) {
2791 $this->setPageBoxes($this->page, 'ArtBox', $format['ArtBox']['llx'], $format['ArtBox']['lly'], $format['ArtBox']['urx'], $format['ArtBox']['ury'], false);
2793 // specify the colours and other visual characteristics that should be used in displaying guidelines on the screen for the various page boundaries
2794 if (isset($format['BoxColorInfo'])) {
2795 $this->pagedim[$this->page]['BoxColorInfo'] = $format['BoxColorInfo'];
2797 if (isset($format['Rotate']) AND (($format['Rotate'] % 90) == 0)) {
2798 // The number of degrees by which the page shall be rotated clockwise when displayed or printed. The value shall be a multiple of 90.
2799 $this->pagedim[$this->page]['Rotate'] = intval($format['Rotate']);
2801 if (isset($format['PZ'])) {
2802 // The page's preferred zoom (magnification) factor
2803 $this->pagedim[$this->page]['PZ'] = floatval($format['PZ']);
2805 if (isset($format['trans'])) {
2806 // The style and duration of the visual transition to use when moving from another page to the given page during a presentation
2807 if (isset($format['trans']['Dur'])) {
2808 // The page's display duration
2809 $this->pagedim[$this->page]['trans']['Dur'] = floatval($format['trans']['Dur']);
2811 $stansition_styles = array('Split', 'Blinds', 'Box', 'Wipe', 'Dissolve', 'Glitter', 'R', 'Fly', 'Push', 'Cover', 'Uncover', 'Fade');
2812 if (isset($format['trans']['S']) AND in_array($format['trans']['S'], $stansition_styles)) {
2813 // The transition style that shall be used when moving to this page from another during a presentation
2814 $this->pagedim[$this->page]['trans']['S'] = $format['trans']['S'];
2815 $valid_effect = array('Split', 'Blinds');
2816 $valid_vals = array('H', 'V');
2817 if (isset($format['trans']['Dm']) AND in_array($format['trans']['S'], $valid_effect) AND in_array($format['trans']['Dm'], $valid_vals)) {
2818 $this->pagedim[$this->page]['trans']['Dm'] = $format['trans']['Dm'];
2820 $valid_effect = array('Split', 'Box', 'Fly');
2821 $valid_vals = array('I', 'O');
2822 if (isset($format['trans']['M']) AND in_array($format['trans']['S'], $valid_effect) AND in_array($format['trans']['M'], $valid_vals)) {
2823 $this->pagedim[$this->page]['trans']['M'] = $format['trans']['M'];
2825 $valid_effect = array('Wipe', 'Glitter', 'Fly', 'Cover', 'Uncover', 'Push');
2826 if (isset($format['trans']['Di']) AND in_array($format['trans']['S'], $valid_effect)) {
2827 if (((($format['trans']['Di'] == 90) OR ($format['trans']['Di'] == 180)) AND ($format['trans']['S'] == 'Wipe'))
2828 OR (($format['trans']['Di'] == 315) AND ($format['trans']['S'] == 'Glitter'))
2829 OR (($format['trans']['Di'] == 0) OR ($format['trans']['Di'] == 270))) {
2830 $this->pagedim[$this->page]['trans']['Di'] = intval($format['trans']['Di']);
2833 if (isset($format['trans']['SS']) AND ($format['trans']['S'] == 'Fly')) {
2834 $this->pagedim[$this->page]['trans']['SS'] = floatval($format['trans']['SS']);
2836 if (isset($format['trans']['B']) AND ($format['trans']['B'] === true) AND ($format['trans']['S'] == 'Fly')) {
2837 $this->pagedim[$this->page]['trans']['B'] = 'true';
2839 } else {
2840 $this->pagedim[$this->page]['trans']['S'] = 'R';
2842 if (isset($format['trans']['D'])) {
2843 // The duration of the transition effect, in seconds
2844 $this->pagedim[$this->page]['trans']['D'] = floatval($format['trans']['D']);
2845 } else {
2846 $this->pagedim[$this->page]['trans']['D'] = 1;
2850 $this->setPageOrientation($orientation);
2854 * Set page boundaries.
2855 * @param $page (int) page number
2856 * @param $type (string) valid values are: <ul><li>'MediaBox' : the boundaries of the physical medium on which the page shall be displayed or printed;</li><li>'CropBox' : the visible region of default user space;</li><li>'BleedBox' : the region to which the contents of the page shall be clipped when output in a production environment;</li><li>'TrimBox' : the intended dimensions of the finished page after trimming;</li><li>'ArtBox' : the page's meaningful content (including potential white space).</li></ul>
2857 * @param $llx (float) lower-left x coordinate in user units
2858 * @param $lly (float) lower-left y coordinate in user units
2859 * @param $urx (float) upper-right x coordinate in user units
2860 * @param $ury (float) upper-right y coordinate in user units
2861 * @param $points (boolean) if true uses user units as unit of measure, otherwise uses PDF points
2862 * @public
2863 * @since 5.0.010 (2010-05-17)
2865 public function setPageBoxes($page, $type, $llx, $lly, $urx, $ury, $points=false) {
2866 if (!isset($this->pagedim[$page])) {
2867 // initialize array
2868 $this->pagedim[$page] = array();
2870 $pageboxes = array('MediaBox', 'CropBox', 'BleedBox', 'TrimBox', 'ArtBox');
2871 if (!in_array($type, $pageboxes)) {
2872 return;
2874 if ($points) {
2875 $k = 1;
2876 } else {
2877 $k = $this->k;
2879 $this->pagedim[$page][$type]['llx'] = ($llx * $k);
2880 $this->pagedim[$page][$type]['lly'] = ($lly * $k);
2881 $this->pagedim[$page][$type]['urx'] = ($urx * $k);
2882 $this->pagedim[$page][$type]['ury'] = ($ury * $k);
2886 * Swap X and Y coordinates of page boxes (change page boxes orientation).
2887 * @param $page (int) page number
2888 * @protected
2889 * @since 5.0.010 (2010-05-17)
2891 protected function swapPageBoxCoordinates($page) {
2892 $pageboxes = array('MediaBox', 'CropBox', 'BleedBox', 'TrimBox', 'ArtBox');
2893 foreach ($pageboxes as $type) {
2894 // swap X and Y coordinates
2895 if (isset($this->pagedim[$page][$type])) {
2896 $tmp = $this->pagedim[$page][$type]['llx'];
2897 $this->pagedim[$page][$type]['llx'] = $this->pagedim[$page][$type]['lly'];
2898 $this->pagedim[$page][$type]['lly'] = $tmp;
2899 $tmp = $this->pagedim[$page][$type]['urx'];
2900 $this->pagedim[$page][$type]['urx'] = $this->pagedim[$page][$type]['ury'];
2901 $this->pagedim[$page][$type]['ury'] = $tmp;
2907 * Set page orientation.
2908 * @param $orientation (string) page orientation. Possible values are (case insensitive):<ul><li>P or Portrait (default)</li><li>L or Landscape</li><li>'' (empty string) for automatic orientation</li></ul>
2909 * @param $autopagebreak (boolean) Boolean indicating if auto-page-break mode should be on or off.
2910 * @param $bottommargin (float) bottom margin of the page.
2911 * @public
2912 * @since 3.0.015 (2008-06-06)
2914 public function setPageOrientation($orientation, $autopagebreak='', $bottommargin='') {
2915 if (!isset($this->pagedim[$this->page]['MediaBox'])) {
2916 // the boundaries of the physical medium on which the page shall be displayed or printed
2917 $this->setPageBoxes($this->page, 'MediaBox', 0, 0, $this->fwPt, $this->fhPt, true);
2919 if (!isset($this->pagedim[$this->page]['CropBox'])) {
2920 // the visible region of default user space
2921 $this->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);
2923 if (!isset($this->pagedim[$this->page]['BleedBox'])) {
2924 // the region to which the contents of the page shall be clipped when output in a production environment
2925 $this->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);
2927 if (!isset($this->pagedim[$this->page]['TrimBox'])) {
2928 // the intended dimensions of the finished page after trimming
2929 $this->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);
2931 if (!isset($this->pagedim[$this->page]['ArtBox'])) {
2932 // the page's meaningful content (including potential white space)
2933 $this->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);
2935 if (!isset($this->pagedim[$this->page]['Rotate'])) {
2936 // The number of degrees by which the page shall be rotated clockwise when displayed or printed. The value shall be a multiple of 90.
2937 $this->pagedim[$this->page]['Rotate'] = 0;
2939 if (!isset($this->pagedim[$this->page]['PZ'])) {
2940 // The page's preferred zoom (magnification) factor
2941 $this->pagedim[$this->page]['PZ'] = 1;
2943 if ($this->fwPt > $this->fhPt) {
2944 // landscape
2945 $default_orientation = 'L';
2946 } else {
2947 // portrait
2948 $default_orientation = 'P';
2950 $valid_orientations = array('P', 'L');
2951 if (empty($orientation)) {
2952 $orientation = $default_orientation;
2953 } else {
2954 $orientation = strtoupper($orientation{0});
2956 if (in_array($orientation, $valid_orientations) AND ($orientation != $default_orientation)) {
2957 $this->CurOrientation = $orientation;
2958 $this->wPt = $this->fhPt;
2959 $this->hPt = $this->fwPt;
2960 } else {
2961 $this->CurOrientation = $default_orientation;
2962 $this->wPt = $this->fwPt;
2963 $this->hPt = $this->fhPt;
2965 if ((abs($this->pagedim[$this->page]['MediaBox']['urx'] - $this->hPt) < $this->feps) AND (abs($this->pagedim[$this->page]['MediaBox']['ury'] - $this->wPt) < $this->feps)){
2966 // swap X and Y coordinates (change page orientation)
2967 $this->swapPageBoxCoordinates($this->page);
2969 $this->w = $this->wPt / $this->k;
2970 $this->h = $this->hPt / $this->k;
2971 if ($this->empty_string($autopagebreak)) {
2972 if (isset($this->AutoPageBreak)) {
2973 $autopagebreak = $this->AutoPageBreak;
2974 } else {
2975 $autopagebreak = true;
2978 if ($this->empty_string($bottommargin)) {
2979 if (isset($this->bMargin)) {
2980 $bottommargin = $this->bMargin;
2981 } else {
2982 // default value = 2 cm
2983 $bottommargin = 2 * 28.35 / $this->k;
2986 $this->SetAutoPageBreak($autopagebreak, $bottommargin);
2987 // store page dimensions
2988 $this->pagedim[$this->page]['w'] = $this->wPt;
2989 $this->pagedim[$this->page]['h'] = $this->hPt;
2990 $this->pagedim[$this->page]['wk'] = $this->w;
2991 $this->pagedim[$this->page]['hk'] = $this->h;
2992 $this->pagedim[$this->page]['tm'] = $this->tMargin;
2993 $this->pagedim[$this->page]['bm'] = $bottommargin;
2994 $this->pagedim[$this->page]['lm'] = $this->lMargin;
2995 $this->pagedim[$this->page]['rm'] = $this->rMargin;
2996 $this->pagedim[$this->page]['pb'] = $autopagebreak;
2997 $this->pagedim[$this->page]['or'] = $this->CurOrientation;
2998 $this->pagedim[$this->page]['olm'] = $this->original_lMargin;
2999 $this->pagedim[$this->page]['orm'] = $this->original_rMargin;
3003 * Set regular expression to detect withespaces or word separators.
3004 * The pattern delimiter must be the forward-slash character "/".
3005 * Some example patterns are:
3006 * <pre>
3007 * Non-Unicode or missing PCRE unicode support: "/[^\S\xa0]/"
3008 * Unicode and PCRE unicode support: "/[^\S\P{Z}\xa0]/u"
3009 * Unicode and PCRE unicode support in Chinese mode: "/[^\S\P{Z}\P{Lo}\xa0]/u"
3010 * if PCRE unicode support is turned ON ("\P" is the negate class of "\p"):
3011 * "\p{Z}" or "\p{Separator}": any kind of Unicode whitespace or invisible separator.
3012 * "\p{Lo}" or "\p{Other_Letter}": a Unicode letter or ideograph that does not have lowercase and uppercase variants.
3013 * "\p{Lo}" is needed for Chinese characters because are packed next to each other without spaces in between.
3014 * </pre>
3015 * @param $re (string) regular expression (leave empty for default).
3016 * @public
3017 * @since 4.6.016 (2009-06-15)
3019 public function setSpacesRE($re='/[^\S\xa0]/') {
3020 $this->re_spaces = $re;
3021 $re_parts = explode('/', $re);
3022 // get pattern parts
3023 $this->re_space = array();
3024 if (isset($re_parts[1]) AND !empty($re_parts[1])) {
3025 $this->re_space['p'] = $re_parts[1];
3026 } else {
3027 $this->re_space['p'] = '[\s]';
3029 // set pattern modifiers
3030 if (isset($re_parts[2]) AND !empty($re_parts[2])) {
3031 $this->re_space['m'] = $re_parts[2];
3032 } else {
3033 $this->re_space['m'] = '';
3038 * Enable or disable Right-To-Left language mode
3039 * @param $enable (Boolean) if true enable Right-To-Left language mode.
3040 * @param $resetx (Boolean) if true reset the X position on direction change.
3041 * @public
3042 * @since 2.0.000 (2008-01-03)
3044 public function setRTL($enable, $resetx=true) {
3045 $enable = $enable ? true : false;
3046 $resetx = ($resetx AND ($enable != $this->rtl));
3047 $this->rtl = $enable;
3048 $this->tmprtl = false;
3049 if ($resetx) {
3050 $this->Ln(0);
3055 * Return the RTL status
3056 * @return boolean
3057 * @public
3058 * @since 4.0.012 (2008-07-24)
3060 public function getRTL() {
3061 return $this->rtl;
3065 * Force temporary RTL language direction
3066 * @param $mode (mixed) can be false, 'L' for LTR or 'R' for RTL
3067 * @public
3068 * @since 2.1.000 (2008-01-09)
3070 public function setTempRTL($mode) {
3071 $newmode = false;
3072 switch (strtoupper($mode)) {
3073 case 'LTR':
3074 case 'L': {
3075 if ($this->rtl) {
3076 $newmode = 'L';
3078 break;
3080 case 'RTL':
3081 case 'R': {
3082 if (!$this->rtl) {
3083 $newmode = 'R';
3085 break;
3087 case false:
3088 default: {
3089 $newmode = false;
3090 break;
3093 $this->tmprtl = $newmode;
3097 * Return the current temporary RTL status
3098 * @return boolean
3099 * @public
3100 * @since 4.8.014 (2009-11-04)
3102 public function isRTLTextDir() {
3103 return ($this->rtl OR ($this->tmprtl == 'R'));
3107 * Set the last cell height.
3108 * @param $h (float) cell height.
3109 * @author Nicola Asuni
3110 * @public
3111 * @since 1.53.0.TC034
3113 public function setLastH($h) {
3114 $this->lasth = $h;
3118 * Reset the last cell height.
3119 * @public
3120 * @since 5.9.000 (2010-10-03)
3122 public function resetLastH() {
3123 $this->lasth = ($this->FontSize * $this->cell_height_ratio) + $this->cell_padding['T'] + $this->cell_padding['B'];
3127 * Get the last cell height.
3128 * @return last cell height
3129 * @public
3130 * @since 4.0.017 (2008-08-05)
3132 public function getLastH() {
3133 return $this->lasth;
3137 * Set the adjusting factor to convert pixels to user units.
3138 * @param $scale (float) adjusting factor to convert pixels to user units.
3139 * @author Nicola Asuni
3140 * @public
3141 * @since 1.5.2
3143 public function setImageScale($scale) {
3144 $this->imgscale = $scale;
3148 * Returns the adjusting factor to convert pixels to user units.
3149 * @return float adjusting factor to convert pixels to user units.
3150 * @author Nicola Asuni
3151 * @public
3152 * @since 1.5.2
3154 public function getImageScale() {
3155 return $this->imgscale;
3159 * Returns an array of page dimensions:
3160 * <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>
3161 * @param $pagenum (int) page number (empty = current page)
3162 * @return array of page dimensions.
3163 * @author Nicola Asuni
3164 * @public
3165 * @since 4.5.027 (2009-03-16)
3167 public function getPageDimensions($pagenum='') {
3168 if (empty($pagenum)) {
3169 $pagenum = $this->page;
3171 return $this->pagedim[$pagenum];
3175 * Returns the page width in units.
3176 * @param $pagenum (int) page number (empty = current page)
3177 * @return int page width.
3178 * @author Nicola Asuni
3179 * @public
3180 * @since 1.5.2
3181 * @see getPageDimensions()
3183 public function getPageWidth($pagenum='') {
3184 if (empty($pagenum)) {
3185 return $this->w;
3187 return $this->pagedim[$pagenum]['w'];
3191 * Returns the page height in units.
3192 * @param $pagenum (int) page number (empty = current page)
3193 * @return int page height.
3194 * @author Nicola Asuni
3195 * @public
3196 * @since 1.5.2
3197 * @see getPageDimensions()
3199 public function getPageHeight($pagenum='') {
3200 if (empty($pagenum)) {
3201 return $this->h;
3203 return $this->pagedim[$pagenum]['h'];
3207 * Returns the page break margin.
3208 * @param $pagenum (int) page number (empty = current page)
3209 * @return int page break margin.
3210 * @author Nicola Asuni
3211 * @public
3212 * @since 1.5.2
3213 * @see getPageDimensions()
3215 public function getBreakMargin($pagenum='') {
3216 if (empty($pagenum)) {
3217 return $this->bMargin;
3219 return $this->pagedim[$pagenum]['bm'];
3223 * Returns the scale factor (number of points in user unit).
3224 * @return int scale factor.
3225 * @author Nicola Asuni
3226 * @public
3227 * @since 1.5.2
3229 public function getScaleFactor() {
3230 return $this->k;
3234 * Defines the left, top and right margins.
3235 * @param $left (float) Left margin.
3236 * @param $top (float) Top margin.
3237 * @param $right (float) Right margin. Default value is the left one.
3238 * @param $keepmargins (boolean) if true overwrites the default page margins
3239 * @public
3240 * @since 1.0
3241 * @see SetLeftMargin(), SetTopMargin(), SetRightMargin(), SetAutoPageBreak()
3243 public function SetMargins($left, $top, $right=-1, $keepmargins=false) {
3244 //Set left, top and right margins
3245 $this->lMargin = $left;
3246 $this->tMargin = $top;
3247 if ($right == -1) {
3248 $right = $left;
3250 $this->rMargin = $right;
3251 if ($keepmargins) {
3252 // overwrite original values
3253 $this->original_lMargin = $this->lMargin;
3254 $this->original_rMargin = $this->rMargin;
3259 * 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.
3260 * @param $margin (float) The margin.
3261 * @public
3262 * @since 1.4
3263 * @see SetTopMargin(), SetRightMargin(), SetAutoPageBreak(), SetMargins()
3265 public function SetLeftMargin($margin) {
3266 //Set left margin
3267 $this->lMargin = $margin;
3268 if (($this->page > 0) AND ($this->x < $margin)) {
3269 $this->x = $margin;
3274 * Defines the top margin. The method can be called before creating the first page.
3275 * @param $margin (float) The margin.
3276 * @public
3277 * @since 1.5
3278 * @see SetLeftMargin(), SetRightMargin(), SetAutoPageBreak(), SetMargins()
3280 public function SetTopMargin($margin) {
3281 //Set top margin
3282 $this->tMargin = $margin;
3283 if (($this->page > 0) AND ($this->y < $margin)) {
3284 $this->y = $margin;
3289 * Defines the right margin. The method can be called before creating the first page.
3290 * @param $margin (float) The margin.
3291 * @public
3292 * @since 1.5
3293 * @see SetLeftMargin(), SetTopMargin(), SetAutoPageBreak(), SetMargins()
3295 public function SetRightMargin($margin) {
3296 $this->rMargin = $margin;
3297 if (($this->page > 0) AND ($this->x > ($this->w - $margin))) {
3298 $this->x = $this->w - $margin;
3303 * Set the same internal Cell padding for top, right, bottom, left-
3304 * @param $pad (float) internal padding.
3305 * @public
3306 * @since 2.1.000 (2008-01-09)
3307 * @see getCellPaddings(), setCellPaddings()
3309 public function SetCellPadding($pad) {
3310 if ($pad >= 0) {
3311 $this->cell_padding['L'] = $pad;
3312 $this->cell_padding['T'] = $pad;
3313 $this->cell_padding['R'] = $pad;
3314 $this->cell_padding['B'] = $pad;
3319 * Set the internal Cell paddings.
3320 * @param $left (float) left padding
3321 * @param $top (float) top padding
3322 * @param $right (float) right padding
3323 * @param $bottom (float) bottom padding
3324 * @public
3325 * @since 5.9.000 (2010-10-03)
3326 * @see getCellPaddings(), SetCellPadding()
3328 public function setCellPaddings($left='', $top='', $right='', $bottom='') {
3329 if (($left !== '') AND ($left >= 0)) {
3330 $this->cell_padding['L'] = $left;
3332 if (($top !== '') AND ($top >= 0)) {
3333 $this->cell_padding['T'] = $top;
3335 if (($right !== '') AND ($right >= 0)) {
3336 $this->cell_padding['R'] = $right;
3338 if (($bottom !== '') AND ($bottom >= 0)) {
3339 $this->cell_padding['B'] = $bottom;
3344 * Get the internal Cell padding array.
3345 * @return array of padding values
3346 * @public
3347 * @since 5.9.000 (2010-10-03)
3348 * @see setCellPaddings(), SetCellPadding()
3350 public function getCellPaddings() {
3351 return $this->cell_padding;
3355 * Set the internal Cell margins.
3356 * @param $left (float) left margin
3357 * @param $top (float) top margin
3358 * @param $right (float) right margin
3359 * @param $bottom (float) bottom margin
3360 * @public
3361 * @since 5.9.000 (2010-10-03)
3362 * @see getCellMargins()
3364 public function setCellMargins($left='', $top='', $right='', $bottom='') {
3365 if (($left !== '') AND ($left >= 0)) {
3366 $this->cell_margin['L'] = $left;
3368 if (($top !== '') AND ($top >= 0)) {
3369 $this->cell_margin['T'] = $top;
3371 if (($right !== '') AND ($right >= 0)) {
3372 $this->cell_margin['R'] = $right;
3374 if (($bottom !== '') AND ($bottom >= 0)) {
3375 $this->cell_margin['B'] = $bottom;
3380 * Get the internal Cell margin array.
3381 * @return array of margin values
3382 * @public
3383 * @since 5.9.000 (2010-10-03)
3384 * @see setCellMargins()
3386 public function getCellMargins() {
3387 return $this->cell_margin;
3391 * Adjust the internal Cell padding array to take account of the line width.
3392 * @param $brd (mixed) Indicates if borders must be drawn around the cell. The value can be a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul> or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul> or an array of line styles for each border group - for example: array('LTRB' => array('width' => 2, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0)))
3393 * @return array of adjustments
3394 * @public
3395 * @since 5.9.000 (2010-10-03)
3397 protected function adjustCellPadding($brd=0) {
3398 if (empty($brd)) {
3399 return;
3401 if (is_string($brd)) {
3402 // convert string to array
3403 $slen = strlen($brd);
3404 $newbrd = array();
3405 for ($i = 0; $i < $slen; ++$i) {
3406 $newbrd[$brd{$i}] = true;
3408 $brd = $newbrd;
3409 } elseif (($brd === 1) OR ($brd === true) OR (is_numeric($brd) AND (intval($brd) > 0))) {
3410 $brd = array('LRTB' => true);
3412 if (!is_array($brd)) {
3413 return;
3415 // store current cell padding
3416 $cp = $this->cell_padding;
3417 // select border mode
3418 if (isset($brd['mode'])) {
3419 $mode = $brd['mode'];
3420 unset($brd['mode']);
3421 } else {
3422 $mode = 'normal';
3424 // process borders
3425 foreach ($brd as $border => $style) {
3426 $line_width = $this->LineWidth;
3427 if (is_array($style) AND isset($style['width'])) {
3428 // get border width
3429 $line_width = $style['width'];
3431 $adj = 0; // line width inside the cell
3432 switch ($mode) {
3433 case 'ext': {
3434 $adj = 0;
3435 break;
3437 case 'int': {
3438 $adj = $line_width;
3439 break;
3441 case 'normal':
3442 default: {
3443 $adj = ($line_width / 2);
3444 break;
3447 // correct internal cell padding if required to avoid overlap between text and lines
3448 if ((strpos($border,'T') !== false) AND ($this->cell_padding['T'] < $adj)) {
3449 $this->cell_padding['T'] = $adj;
3451 if ((strpos($border,'R') !== false) AND ($this->cell_padding['R'] < $adj)) {
3452 $this->cell_padding['R'] = $adj;
3454 if ((strpos($border,'B') !== false) AND ($this->cell_padding['B'] < $adj)) {
3455 $this->cell_padding['B'] = $adj;
3457 if ((strpos($border,'L') !== false) AND ($this->cell_padding['L'] < $adj)) {
3458 $this->cell_padding['L'] = $adj;
3461 return array('T' => ($this->cell_padding['T'] - $cp['T']), 'R' => ($this->cell_padding['R'] - $cp['R']), 'B' => ($this->cell_padding['B'] - $cp['B']), 'L' => ($this->cell_padding['L'] - $cp['L']));
3465 * 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.
3466 * @param $auto (boolean) Boolean indicating if mode should be on or off.
3467 * @param $margin (float) Distance from the bottom of the page.
3468 * @public
3469 * @since 1.0
3470 * @see Cell(), MultiCell(), AcceptPageBreak()
3472 public function SetAutoPageBreak($auto, $margin=0) {
3473 $this->AutoPageBreak = $auto;
3474 $this->bMargin = $margin;
3475 $this->PageBreakTrigger = $this->h - $margin;
3479 * Return the auto-page-break mode (true or false).
3480 * @return boolean auto-page-break mode
3481 * @public
3482 * @since 5.9.088
3484 public function getAutoPageBreak() {
3485 return $this->AutoPageBreak;
3489 * Defines the way the document is to be displayed by the viewer.
3490 * @param $zoom (mixed) The zoom to use. It can be one of the following string values or a number indicating the zooming factor to use. <ul><li>fullpage: displays the entire page on screen </li><li>fullwidth: uses maximum width of window</li><li>real: uses real size (equivalent to 100% zoom)</li><li>default: uses viewer default mode</li></ul>
3491 * @param $layout (string) The page layout. Possible values are:<ul><li>SinglePage Display one page at a time</li><li>OneColumn Display the pages in one column</li><li>TwoColumnLeft Display the pages in two columns, with odd-numbered pages on the left</li><li>TwoColumnRight Display the pages in two columns, with odd-numbered pages on the right</li><li>TwoPageLeft (PDF 1.5) Display the pages two at a time, with odd-numbered pages on the left</li><li>TwoPageRight (PDF 1.5) Display the pages two at a time, with odd-numbered pages on the right</li></ul>
3492 * @param $mode (string) A name object specifying how the document should be displayed when opened:<ul><li>UseNone Neither document outline nor thumbnail images visible</li><li>UseOutlines Document outline visible</li><li>UseThumbs Thumbnail images visible</li><li>FullScreen Full-screen mode, with no menu bar, window controls, or any other window visible</li><li>UseOC (PDF 1.5) Optional content group panel visible</li><li>UseAttachments (PDF 1.6) Attachments panel visible</li></ul>
3493 * @public
3494 * @since 1.2
3496 public function SetDisplayMode($zoom, $layout='SinglePage', $mode='UseNone') {
3497 if (($zoom == 'fullpage') OR ($zoom == 'fullwidth') OR ($zoom == 'real') OR ($zoom == 'default') OR (!is_string($zoom))) {
3498 $this->ZoomMode = $zoom;
3499 } else {
3500 $this->Error('Incorrect zoom display mode: '.$zoom);
3502 switch ($layout) {
3503 case 'default':
3504 case 'single':
3505 case 'SinglePage': {
3506 $this->LayoutMode = 'SinglePage';
3507 break;
3509 case 'continuous':
3510 case 'OneColumn': {
3511 $this->LayoutMode = 'OneColumn';
3512 break;
3514 case 'two':
3515 case 'TwoColumnLeft': {
3516 $this->LayoutMode = 'TwoColumnLeft';
3517 break;
3519 case 'TwoColumnRight': {
3520 $this->LayoutMode = 'TwoColumnRight';
3521 break;
3523 case 'TwoPageLeft': {
3524 $this->LayoutMode = 'TwoPageLeft';
3525 break;
3527 case 'TwoPageRight': {
3528 $this->LayoutMode = 'TwoPageRight';
3529 break;
3531 default: {
3532 $this->LayoutMode = 'SinglePage';
3535 switch ($mode) {
3536 case 'UseNone': {
3537 $this->PageMode = 'UseNone';
3538 break;
3540 case 'UseOutlines': {
3541 $this->PageMode = 'UseOutlines';
3542 break;
3544 case 'UseThumbs': {
3545 $this->PageMode = 'UseThumbs';
3546 break;
3548 case 'FullScreen': {
3549 $this->PageMode = 'FullScreen';
3550 break;
3552 case 'UseOC': {
3553 $this->PageMode = 'UseOC';
3554 break;
3556 case '': {
3557 $this->PageMode = 'UseAttachments';
3558 break;
3560 default: {
3561 $this->PageMode = 'UseNone';
3567 * 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.
3568 * Note: the Zlib extension is required for this feature. If not present, compression will be turned off.
3569 * @param $compress (boolean) Boolean indicating if compression must be enabled.
3570 * @public
3571 * @since 1.4
3573 public function SetCompression($compress) {
3574 if (function_exists('gzcompress')) {
3575 $this->compress = $compress ? true : false;
3576 } else {
3577 $this->compress = false;
3582 * Turn on/off Unicode mode for document information dictionary (meta tags).
3583 * This has effect only when unicode mode is set to false.
3584 * @param $unicode (boolean) if true set the meta information in Unicode
3585 * @since 5.9.027 (2010-12-01)
3586 * @public
3588 public function SetDocInfoUnicode($unicode=true) {
3589 $this->docinfounicode = $unicode ? true : false;
3593 * Defines the title of the document.
3594 * @param $title (string) The title.
3595 * @public
3596 * @since 1.2
3597 * @see SetAuthor(), SetCreator(), SetKeywords(), SetSubject()
3599 public function SetTitle($title) {
3600 $this->title = $title;
3604 * Defines the subject of the document.
3605 * @param $subject (string) The subject.
3606 * @public
3607 * @since 1.2
3608 * @see SetAuthor(), SetCreator(), SetKeywords(), SetTitle()
3610 public function SetSubject($subject) {
3611 $this->subject = $subject;
3615 * Defines the author of the document.
3616 * @param $author (string) The name of the author.
3617 * @public
3618 * @since 1.2
3619 * @see SetCreator(), SetKeywords(), SetSubject(), SetTitle()
3621 public function SetAuthor($author) {
3622 $this->author = $author;
3626 * Associates keywords with the document, generally in the form 'keyword1 keyword2 ...'.
3627 * @param $keywords (string) The list of keywords.
3628 * @public
3629 * @since 1.2
3630 * @see SetAuthor(), SetCreator(), SetSubject(), SetTitle()
3632 public function SetKeywords($keywords) {
3633 $this->keywords = $keywords;
3637 * Defines the creator of the document. This is typically the name of the application that generates the PDF.
3638 * @param $creator (string) The name of the creator.
3639 * @public
3640 * @since 1.2
3641 * @see SetAuthor(), SetKeywords(), SetSubject(), SetTitle()
3643 public function SetCreator($creator) {
3644 $this->creator = $creator;
3648 * This method is automatically called in case of fatal error; it simply outputs the message and halts the execution. An inherited class may override it to customize the error handling but should always halt the script, or the resulting document would probably be invalid.
3649 * 2004-06-11 :: Nicola Asuni : changed bold tag with strong
3650 * @param $msg (string) The error message
3651 * @public
3652 * @since 1.0
3654 public function Error($msg) {
3655 // unset all class variables
3656 $this->_destroy(true);
3657 // exit program and print error
3658 die('<strong>TCPDF ERROR: </strong>'.$msg);
3662 * This method begins the generation of the PDF document.
3663 * It is not necessary to call it explicitly because AddPage() does it automatically.
3664 * Note: no page is created by this method
3665 * @public
3666 * @since 1.0
3667 * @see AddPage(), Close()
3669 public function Open() {
3670 $this->state = 1;
3674 * Terminates the PDF document.
3675 * It is not necessary to call this method explicitly because Output() does it automatically.
3676 * If the document contains no page, AddPage() is called to prevent from getting an invalid document.
3677 * @public
3678 * @since 1.0
3679 * @see Open(), Output()
3681 public function Close() {
3682 if ($this->state == 3) {
3683 return;
3685 if ($this->page == 0) {
3686 $this->AddPage();
3688 $this->endLayer();
3689 // save current graphic settings
3690 $gvars = $this->getGraphicVars();
3691 $this->setEqualColumns();
3692 $this->lastpage(true);
3693 $this->SetAutoPageBreak(false);
3694 $this->x = 0;
3695 $this->y = $this->h - (1 / $this->k);
3696 $this->lMargin = 0;
3697 $this->_out('q');
3698 $this->SetFont('helvetica', '', 1);
3699 $this->setTextRenderingMode(0, false, false);
3700 $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";
3701 $lnk = "\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x74\x63\x70\x64\x66\x2e\x6f\x72\x67";
3702 $this->Cell(0, 0, $msg, 0, 0, 'L', 0, $lnk, 0, false, 'D', 'B');
3703 $this->_out('Q');
3704 // restore graphic settings
3705 $this->setGraphicVars($gvars);
3706 // close page
3707 $this->endPage();
3708 // close document
3709 $this->_enddoc();
3710 // unset all class variables (except critical ones)
3711 $this->_destroy(false);
3715 * Move pointer at the specified document page and update page dimensions.
3716 * @param $pnum (int) page number (1 ... numpages)
3717 * @param $resetmargins (boolean) if true reset left, right, top margins and Y position.
3718 * @public
3719 * @since 2.1.000 (2008-01-07)
3720 * @see getPage(), lastpage(), getNumPages()
3722 public function setPage($pnum, $resetmargins=false) {
3723 if (($pnum == $this->page) AND ($this->state == 2)) {
3724 return;
3726 if (($pnum > 0) AND ($pnum <= $this->numpages)) {
3727 $this->state = 2;
3728 // save current graphic settings
3729 //$gvars = $this->getGraphicVars();
3730 $oldpage = $this->page;
3731 $this->page = $pnum;
3732 $this->wPt = $this->pagedim[$this->page]['w'];
3733 $this->hPt = $this->pagedim[$this->page]['h'];
3734 $this->w = $this->pagedim[$this->page]['wk'];
3735 $this->h = $this->pagedim[$this->page]['hk'];
3736 $this->tMargin = $this->pagedim[$this->page]['tm'];
3737 $this->bMargin = $this->pagedim[$this->page]['bm'];
3738 $this->original_lMargin = $this->pagedim[$this->page]['olm'];
3739 $this->original_rMargin = $this->pagedim[$this->page]['orm'];
3740 $this->AutoPageBreak = $this->pagedim[$this->page]['pb'];
3741 $this->CurOrientation = $this->pagedim[$this->page]['or'];
3742 $this->SetAutoPageBreak($this->AutoPageBreak, $this->bMargin);
3743 // restore graphic settings
3744 //$this->setGraphicVars($gvars);
3745 if ($resetmargins) {
3746 $this->lMargin = $this->pagedim[$this->page]['olm'];
3747 $this->rMargin = $this->pagedim[$this->page]['orm'];
3748 $this->SetY($this->tMargin);
3749 } else {
3750 // account for booklet mode
3751 if ($this->pagedim[$this->page]['olm'] != $this->pagedim[$oldpage]['olm']) {
3752 $deltam = $this->pagedim[$this->page]['olm'] - $this->pagedim[$this->page]['orm'];
3753 $this->lMargin += $deltam;
3754 $this->rMargin -= $deltam;
3757 } else {
3758 $this->Error('Wrong page number on setPage() function: '.$pnum);
3763 * Reset pointer to the last document page.
3764 * @param $resetmargins (boolean) if true reset left, right, top margins and Y position.
3765 * @public
3766 * @since 2.0.000 (2008-01-04)
3767 * @see setPage(), getPage(), getNumPages()
3769 public function lastPage($resetmargins=false) {
3770 $this->setPage($this->getNumPages(), $resetmargins);
3774 * Get current document page number.
3775 * @return int page number
3776 * @public
3777 * @since 2.1.000 (2008-01-07)
3778 * @see setPage(), lastpage(), getNumPages()
3780 public function getPage() {
3781 return $this->page;
3785 * Get the total number of insered pages.
3786 * @return int number of pages
3787 * @public
3788 * @since 2.1.000 (2008-01-07)
3789 * @see setPage(), getPage(), lastpage()
3791 public function getNumPages() {
3792 return $this->numpages;
3796 * Adds a new TOC (Table Of Content) page to the document.
3797 * @param $orientation (string) page orientation.
3798 * @param $format (mixed) The format used for pages. It can be either: one of the string values specified at getPageSizeFromFormat() or an array of parameters specified at setPageFormat().
3799 * @param $keepmargins (boolean) if true overwrites the default page margins with the current margins
3800 * @public
3801 * @since 5.0.001 (2010-05-06)
3802 * @see AddPage(), startPage(), endPage(), endTOCPage()
3804 public function addTOCPage($orientation='', $format='', $keepmargins=false) {
3805 $this->AddPage($orientation, $format, $keepmargins, true);
3809 * Terminate the current TOC (Table Of Content) page
3810 * @public
3811 * @since 5.0.001 (2010-05-06)
3812 * @see AddPage(), startPage(), endPage(), addTOCPage()
3814 public function endTOCPage() {
3815 $this->endPage(true);
3819 * 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).
3820 * The origin of the coordinate system is at the top-left corner (or top-right for RTL) and increasing ordinates go downwards.
3821 * @param $orientation (string) page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
3822 * @param $format (mixed) The format used for pages. It can be either: one of the string values specified at getPageSizeFromFormat() or an array of parameters specified at setPageFormat().
3823 * @param $keepmargins (boolean) if true overwrites the default page margins with the current margins
3824 * @param $tocpage (boolean) if true set the tocpage state to true (the added page will be used to display Table Of Content).
3825 * @public
3826 * @since 1.0
3827 * @see startPage(), endPage(), addTOCPage(), endTOCPage(), getPageSizeFromFormat(), setPageFormat()
3829 public function AddPage($orientation='', $format='', $keepmargins=false, $tocpage=false) {
3830 if ($this->inxobj) {
3831 // we are inside an XObject template
3832 return;
3834 if (!isset($this->original_lMargin) OR $keepmargins) {
3835 $this->original_lMargin = $this->lMargin;
3837 if (!isset($this->original_rMargin) OR $keepmargins) {
3838 $this->original_rMargin = $this->rMargin;
3840 // terminate previous page
3841 $this->endPage();
3842 // start new page
3843 $this->startPage($orientation, $format, $tocpage);
3847 * Terminate the current page
3848 * @param $tocpage (boolean) if true set the tocpage state to false (end the page used to display Table Of Content).
3849 * @public
3850 * @since 4.2.010 (2008-11-14)
3851 * @see AddPage(), startPage(), addTOCPage(), endTOCPage()
3853 public function endPage($tocpage=false) {
3854 // check if page is already closed
3855 if (($this->page == 0) OR ($this->numpages > $this->page) OR (!$this->pageopen[$this->page])) {
3856 return;
3858 // print page footer
3859 $this->setFooter();
3860 // close page
3861 $this->_endpage();
3862 // mark page as closed
3863 $this->pageopen[$this->page] = false;
3864 if ($tocpage) {
3865 $this->tocpage = false;
3870 * Starts a new page to the document. The page must be closed using the endPage() function.
3871 * The origin of the coordinate system is at the top-left corner and increasing ordinates go downwards.
3872 * @param $orientation (string) page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
3873 * @param $format (mixed) The format used for pages. It can be either: one of the string values specified at getPageSizeFromFormat() or an array of parameters specified at setPageFormat().
3874 * @param $tocpage (boolean) if true the page is designated to contain the Table-Of-Content.
3875 * @since 4.2.010 (2008-11-14)
3876 * @see AddPage(), endPage(), addTOCPage(), endTOCPage(), getPageSizeFromFormat(), setPageFormat()
3877 * @public
3879 public function startPage($orientation='', $format='', $tocpage=false) {
3880 if ($tocpage) {
3881 $this->tocpage = true;
3883 if ($this->numpages > $this->page) {
3884 // this page has been already added
3885 $this->setPage($this->page + 1);
3886 $this->SetY($this->tMargin);
3887 return;
3889 // start a new page
3890 if ($this->state == 0) {
3891 $this->Open();
3893 ++$this->numpages;
3894 $this->swapMargins($this->booklet);
3895 // save current graphic settings
3896 $gvars = $this->getGraphicVars();
3897 // start new page
3898 $this->_beginpage($orientation, $format);
3899 // mark page as open
3900 $this->pageopen[$this->page] = true;
3901 // restore graphic settings
3902 $this->setGraphicVars($gvars);
3903 // mark this point
3904 $this->setPageMark();
3905 // print page header
3906 $this->setHeader();
3907 // restore graphic settings
3908 $this->setGraphicVars($gvars);
3909 // mark this point
3910 $this->setPageMark();
3911 // print table header (if any)
3912 $this->setTableHeader();
3913 // set mark for empty page check
3914 $this->emptypagemrk[$this->page]= $this->pagelen[$this->page];
3918 * Set start-writing mark on current page stream used to put borders and fills.
3919 * Borders and fills are always created after content and inserted on the position marked by this method.
3920 * This function must be called after calling Image() function for a background image.
3921 * Background images must be always inserted before calling Multicell() or WriteHTMLCell() or WriteHTML() functions.
3922 * @public
3923 * @since 4.0.016 (2008-07-30)
3925 public function setPageMark() {
3926 $this->intmrk[$this->page] = $this->pagelen[$this->page];
3927 $this->bordermrk[$this->page] = $this->intmrk[$this->page];
3928 $this->setContentMark();
3932 * Set start-writing mark on selected page.
3933 * Borders and fills are always created after content and inserted on the position marked by this method.
3934 * @param $page (int) page number (default is the current page)
3935 * @protected
3936 * @since 4.6.021 (2009-07-20)
3938 protected function setContentMark($page=0) {
3939 if ($page <= 0) {
3940 $page = $this->page;
3942 if (isset($this->footerlen[$page])) {
3943 $this->cntmrk[$page] = $this->pagelen[$page] - $this->footerlen[$page];
3944 } else {
3945 $this->cntmrk[$page] = $this->pagelen[$page];
3950 * Set header data.
3951 * @param $ln (string) header image logo
3952 * @param $lw (string) header image logo width in mm
3953 * @param $ht (string) string to print as title on document header
3954 * @param $hs (string) string to print on document header
3955 * @public
3957 public function setHeaderData($ln='', $lw=0, $ht='', $hs='') {
3958 $this->header_logo = $ln;
3959 $this->header_logo_width = $lw;
3960 $this->header_title = $ht;
3961 $this->header_string = $hs;
3965 * Returns header data:
3966 * <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>
3967 * @return array()
3968 * @public
3969 * @since 4.0.012 (2008-07-24)
3971 public function getHeaderData() {
3972 $ret = array();
3973 $ret['logo'] = $this->header_logo;
3974 $ret['logo_width'] = $this->header_logo_width;
3975 $ret['title'] = $this->header_title;
3976 $ret['string'] = $this->header_string;
3977 return $ret;
3981 * Set header margin.
3982 * (minimum distance between header and top page margin)
3983 * @param $hm (int) distance in user units
3984 * @public
3986 public function setHeaderMargin($hm=10) {
3987 $this->header_margin = $hm;
3991 * Returns header margin in user units.
3992 * @return float
3993 * @since 4.0.012 (2008-07-24)
3994 * @public
3996 public function getHeaderMargin() {
3997 return $this->header_margin;
4001 * Set footer margin.
4002 * (minimum distance between footer and bottom page margin)
4003 * @param $fm (int) distance in user units
4004 * @public
4006 public function setFooterMargin($fm=10) {
4007 $this->footer_margin = $fm;
4011 * Returns footer margin in user units.
4012 * @return float
4013 * @since 4.0.012 (2008-07-24)
4014 * @public
4016 public function getFooterMargin() {
4017 return $this->footer_margin;
4020 * Set a flag to print page header.
4021 * @param $val (boolean) set to true to print the page header (default), false otherwise.
4022 * @public
4024 public function setPrintHeader($val=true) {
4025 $this->print_header = $val;
4029 * Set a flag to print page footer.
4030 * @param $val (boolean) set to true to print the page footer (default), false otherwise.
4031 * @public
4033 public function setPrintFooter($val=true) {
4034 $this->print_footer = $val;
4038 * Return the right-bottom (or left-bottom for RTL) corner X coordinate of last inserted image
4039 * @return float
4040 * @public
4042 public function getImageRBX() {
4043 return $this->img_rb_x;
4047 * Return the right-bottom (or left-bottom for RTL) corner Y coordinate of last inserted image
4048 * @return float
4049 * @public
4051 public function getImageRBY() {
4052 return $this->img_rb_y;
4056 * Reset the xobject template used by Header() method.
4057 * @public
4059 public function resetHeaderTemplate() {
4060 $this->header_xobjid = -1;
4064 * Set a flag to automatically reset the xobject template used by Header() method at each page.
4065 * @param $val (boolean) set to true to reset Header xobject template at each page, false otherwise.
4066 * @public
4068 public function setHeaderTemplateAutoreset($val=true) {
4069 $this->header_xobj_autoreset = $val;
4073 * This method is used to render the page header.
4074 * It is automatically called by AddPage() and could be overwritten in your own inherited class.
4075 * @public
4077 public function Header() {
4078 if ($this->header_xobjid < 0) {
4079 // start a new XObject Template
4080 $this->header_xobjid = $this->startTemplate($this->w, $this->tMargin);
4081 $headerfont = $this->getHeaderFont();
4082 $headerdata = $this->getHeaderData();
4083 $this->y = $this->header_margin;
4084 if ($this->rtl) {
4085 $this->x = $this->w - $this->original_rMargin;
4086 } else {
4087 $this->x = $this->original_lMargin;
4089 if (($headerdata['logo']) AND ($headerdata['logo'] != K_BLANK_IMAGE)) {
4090 $imgtype = $this->getImageFileType(K_PATH_IMAGES.$headerdata['logo']);
4091 if (($imgtype == 'eps') OR ($imgtype == 'ai')) {
4092 $this->ImageEps(K_PATH_IMAGES.$headerdata['logo'], '', '', $headerdata['logo_width']);
4093 } elseif ($imgtype == 'svg') {
4094 $this->ImageSVG(K_PATH_IMAGES.$headerdata['logo'], '', '', $headerdata['logo_width']);
4095 } else {
4096 $this->Image(K_PATH_IMAGES.$headerdata['logo'], '', '', $headerdata['logo_width']);
4098 $imgy = $this->getImageRBY();
4099 } else {
4100 $imgy = $this->y;
4102 $cell_height = round(($this->cell_height_ratio * $headerfont[2]) / $this->k, 2);
4103 // set starting margin for text data cell
4104 if ($this->getRTL()) {
4105 $header_x = $this->original_rMargin + ($headerdata['logo_width'] * 1.1);
4106 } else {
4107 $header_x = $this->original_lMargin + ($headerdata['logo_width'] * 1.1);
4109 $cw = $this->w - $this->original_lMargin - $this->original_rMargin - ($headerdata['logo_width'] * 1.1);
4110 $this->SetTextColor(0, 0, 0);
4111 // header title
4112 $this->SetFont($headerfont[0], 'B', $headerfont[2] + 1);
4113 $this->SetX($header_x);
4114 $this->Cell($cw, $cell_height, $headerdata['title'], 0, 1, '', 0, '', 0);
4115 // header string
4116 $this->SetFont($headerfont[0], $headerfont[1], $headerfont[2]);
4117 $this->SetX($header_x);
4118 $this->MultiCell($cw, $cell_height, $headerdata['string'], 0, '', 0, 1, '', '', true, 0, false, true, 0, 'T', false);
4119 // print an ending header line
4120 $this->SetLineStyle(array('width' => 0.85 / $this->k, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0)));
4121 $this->SetY((2.835 / $this->k) + max($imgy, $this->y));
4122 if ($this->rtl) {
4123 $this->SetX($this->original_rMargin);
4124 } else {
4125 $this->SetX($this->original_lMargin);
4127 $this->Cell(($this->w - $this->original_lMargin - $this->original_rMargin), 0, '', 'T', 0, 'C');
4128 $this->endTemplate();
4130 // print header template
4131 $x = 0;
4132 $dx = 0;
4133 if ($this->booklet AND (($this->page % 2) == 0)) {
4134 // adjust margins for booklet mode
4135 $dx = ($this->original_lMargin - $this->original_rMargin);
4137 if ($this->rtl) {
4138 $x = $this->w + $dx;
4139 } else {
4140 $x = 0 + $dx;
4142 $this->printTemplate($this->header_xobjid, $x, 0, 0, 0, '', '', false);
4143 if ($this->header_xobj_autoreset) {
4144 // reset header xobject template at each page
4145 $this->header_xobjid = -1;
4150 * This method is used to render the page footer.
4151 * It is automatically called by AddPage() and could be overwritten in your own inherited class.
4152 * @public
4154 public function Footer() {
4155 $cur_y = $this->y;
4156 $this->SetTextColor(0, 0, 0);
4157 //set style for cell border
4158 $line_width = 0.85 / $this->k;
4159 $this->SetLineStyle(array('width' => $line_width, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0)));
4160 //print document barcode
4161 $barcode = $this->getBarcode();
4162 if (!empty($barcode)) {
4163 $this->Ln($line_width);
4164 $barcode_width = round(($this->w - $this->original_lMargin - $this->original_rMargin) / 3);
4165 $style = array(
4166 'position' => $this->rtl?'R':'L',
4167 'align' => $this->rtl?'R':'L',
4168 'stretch' => false,
4169 'fitwidth' => true,
4170 'cellfitalign' => '',
4171 'border' => false,
4172 'padding' => 0,
4173 'fgcolor' => array(0,0,0),
4174 'bgcolor' => false,
4175 'text' => false
4177 $this->write1DBarcode($barcode, 'C128', '', $cur_y + $line_width, '', (($this->footer_margin / 3) - $line_width), 0.3, $style, '');
4179 if (empty($this->pagegroups)) {
4180 $pagenumtxt = $this->l['w_page'].' '.$this->getAliasNumPage().' / '.$this->getAliasNbPages();
4181 } else {
4182 $pagenumtxt = $this->l['w_page'].' '.$this->getPageNumGroupAlias().' / '.$this->getPageGroupAlias();
4184 $this->SetY($cur_y);
4185 //Print page number
4186 if ($this->getRTL()) {
4187 $this->SetX($this->original_rMargin);
4188 $this->Cell(0, 0, $pagenumtxt, 'T', 0, 'L');
4189 } else {
4190 $this->SetX($this->original_lMargin);
4191 $this->Cell(0, 0, $this->getAliasRightShift().$pagenumtxt, 'T', 0, 'R');
4196 * This method is used to render the page header.
4197 * @protected
4198 * @since 4.0.012 (2008-07-24)
4200 protected function setHeader() {
4201 if (!$this->print_header) {
4202 return;
4204 $this->InHeader = true;
4205 $this->setGraphicVars($this->default_graphic_vars);
4206 $temp_thead = $this->thead;
4207 $temp_theadMargins = $this->theadMargins;
4208 $lasth = $this->lasth;
4209 $this->_out('q');
4210 $this->rMargin = $this->original_rMargin;
4211 $this->lMargin = $this->original_lMargin;
4212 $this->SetCellPadding(0);
4213 //set current position
4214 if ($this->rtl) {
4215 $this->SetXY($this->original_rMargin, $this->header_margin);
4216 } else {
4217 $this->SetXY($this->original_lMargin, $this->header_margin);
4219 $this->SetFont($this->header_font[0], $this->header_font[1], $this->header_font[2]);
4220 $this->Header();
4221 //restore position
4222 if ($this->rtl) {
4223 $this->SetXY($this->original_rMargin, $this->tMargin);
4224 } else {
4225 $this->SetXY($this->original_lMargin, $this->tMargin);
4227 $this->_out('Q');
4228 $this->lasth = $lasth;
4229 $this->thead = $temp_thead;
4230 $this->theadMargins = $temp_theadMargins;
4231 $this->newline = false;
4232 $this->InHeader = false;
4236 * This method is used to render the page footer.
4237 * @protected
4238 * @since 4.0.012 (2008-07-24)
4240 protected function setFooter() {
4241 //Page footer
4242 $this->InFooter = true;
4243 // save current graphic settings
4244 $gvars = $this->getGraphicVars();
4245 // mark this point
4246 $this->footerpos[$this->page] = $this->pagelen[$this->page];
4247 $this->_out("\n");
4248 if ($this->print_footer) {
4249 $this->setGraphicVars($this->default_graphic_vars);
4250 $this->current_column = 0;
4251 $this->num_columns = 1;
4252 $temp_thead = $this->thead;
4253 $temp_theadMargins = $this->theadMargins;
4254 $lasth = $this->lasth;
4255 $this->_out('q');
4256 $this->rMargin = $this->original_rMargin;
4257 $this->lMargin = $this->original_lMargin;
4258 $this->SetCellPadding(0);
4259 //set current position
4260 $footer_y = $this->h - $this->footer_margin;
4261 if ($this->rtl) {
4262 $this->SetXY($this->original_rMargin, $footer_y);
4263 } else {
4264 $this->SetXY($this->original_lMargin, $footer_y);
4266 $this->SetFont($this->footer_font[0], $this->footer_font[1], $this->footer_font[2]);
4267 $this->Footer();
4268 //restore position
4269 if ($this->rtl) {
4270 $this->SetXY($this->original_rMargin, $this->tMargin);
4271 } else {
4272 $this->SetXY($this->original_lMargin, $this->tMargin);
4274 $this->_out('Q');
4275 $this->lasth = $lasth;
4276 $this->thead = $temp_thead;
4277 $this->theadMargins = $temp_theadMargins;
4279 // restore graphic settings
4280 $this->setGraphicVars($gvars);
4281 $this->current_column = $gvars['current_column'];
4282 $this->num_columns = $gvars['num_columns'];
4283 // calculate footer length
4284 $this->footerlen[$this->page] = $this->pagelen[$this->page] - $this->footerpos[$this->page] + 1;
4285 $this->InFooter = false;
4289 * Check if we are on the page body (excluding page header and footer).
4290 * @return true if we are not in page header nor in page footer, false otherwise.
4291 * @protected
4292 * @since 5.9.091 (2011-06-15)
4294 protected function inPageBody() {
4295 return (($this->InHeader === false) AND ($this->InFooter === false));
4299 * This method is used to render the table header on new page (if any).
4300 * @protected
4301 * @since 4.5.030 (2009-03-25)
4303 protected function setTableHeader() {
4304 if ($this->num_columns > 1) {
4305 // multi column mode
4306 return;
4308 if (isset($this->theadMargins['top'])) {
4309 // restore the original top-margin
4310 $this->tMargin = $this->theadMargins['top'];
4311 $this->pagedim[$this->page]['tm'] = $this->tMargin;
4312 $this->y = $this->tMargin;
4314 if (!$this->empty_string($this->thead) AND (!$this->inthead)) {
4315 // set margins
4316 $prev_lMargin = $this->lMargin;
4317 $prev_rMargin = $this->rMargin;
4318 $prev_cell_padding = $this->cell_padding;
4319 $this->lMargin = $this->theadMargins['lmargin'] + ($this->pagedim[$this->page]['olm'] - $this->pagedim[$this->theadMargins['page']]['olm']);
4320 $this->rMargin = $this->theadMargins['rmargin'] + ($this->pagedim[$this->page]['orm'] - $this->pagedim[$this->theadMargins['page']]['orm']);
4321 $this->cell_padding = $this->theadMargins['cell_padding'];
4322 if ($this->rtl) {
4323 $this->x = $this->w - $this->rMargin;
4324 } else {
4325 $this->x = $this->lMargin;
4327 // account for special "cell" mode
4328 if ($this->theadMargins['cell']) {
4329 if ($this->rtl) {
4330 $this->x -= $this->cell_padding['R'];
4331 } else {
4332 $this->x += $this->cell_padding['L'];
4335 // print table header
4336 $this->writeHTML($this->thead, false, false, false, false, '');
4337 // set new top margin to skip the table headers
4338 if (!isset($this->theadMargins['top'])) {
4339 $this->theadMargins['top'] = $this->tMargin;
4341 // store end of header position
4342 if (!isset($this->columns[0]['th'])) {
4343 $this->columns[0]['th'] = array();
4345 $this->columns[0]['th']['\''.$this->page.'\''] = $this->y;
4346 $this->tMargin = $this->y;
4347 $this->pagedim[$this->page]['tm'] = $this->tMargin;
4348 $this->lasth = 0;
4349 $this->lMargin = $prev_lMargin;
4350 $this->rMargin = $prev_rMargin;
4351 $this->cell_padding = $prev_cell_padding;
4356 * Returns the current page number.
4357 * @return int page number
4358 * @public
4359 * @since 1.0
4360 * @see getAliasNbPages()
4362 public function PageNo() {
4363 return $this->page;
4367 * Defines a new spot color.
4368 * It can be expressed in RGB components or gray scale.
4369 * The method can be called before the first page is created and the value is retained from page to page.
4370 * @param $name (string) name of the spot color
4371 * @param $c (int) Cyan color for CMYK. Value between 0 and 100
4372 * @param $m (int) Magenta color for CMYK. Value between 0 and 100
4373 * @param $y (int) Yellow color for CMYK. Value between 0 and 100
4374 * @param $k (int) Key (Black) color for CMYK. Value between 0 and 100
4375 * @public
4376 * @since 4.0.024 (2008-09-12)
4377 * @see SetDrawSpotColor(), SetFillSpotColor(), SetTextSpotColor()
4379 public function AddSpotColor($name, $c, $m, $y, $k) {
4380 if (!isset($this->spot_colors[$name])) {
4381 $i = 1 + count($this->spot_colors);
4382 $this->spot_colors[$name] = array('i' => $i, 'c' => $c, 'm' => $m, 'y' => $y, 'k' => $k);
4384 $color = preg_replace('/[\s]*/', '', $name); // remove extra spaces
4385 $color = strtolower($color);
4386 if (!isset($this->spotcolor[$color])) {
4387 $this->spotcolor[$color] = array($c, $m, $y, $k, $name);
4392 * Defines the color used for all drawing operations (lines, rectangles and cell borders).
4393 * It can be expressed in RGB, CMYK or GRAY SCALE components.
4394 * The method can be called before the first page is created and the value is retained from page to page.
4395 * @param $color (array) array of colors
4396 * @param $ret (boolean) if true do not send the PDF command.
4397 * @return string the PDF command
4398 * @public
4399 * @since 3.1.000 (2008-06-11)
4400 * @see SetDrawColor()
4402 public function SetDrawColorArray($color, $ret=false) {
4403 if (is_array($color)) {
4404 $color = array_values($color);
4405 $r = isset($color[0]) ? $color[0] : -1;
4406 $g = isset($color[1]) ? $color[1] : -1;
4407 $b = isset($color[2]) ? $color[2] : -1;
4408 $k = isset($color[3]) ? $color[3] : -1;
4409 $name = isset($color[4]) ? $color[4] : ''; // spot color name
4410 if ($r >= 0) {
4411 return $this->SetDrawColor($r, $g, $b, $k, $ret, $name);
4414 return '';
4418 * 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.
4419 * @param $col1 (int) GRAY level for single color, or Red color for RGB (0-255), or CYAN color for CMYK (0-100).
4420 * @param $col2 (int) GREEN color for RGB (0-255), or MAGENTA color for CMYK (0-100).
4421 * @param $col3 (int) BLUE color for RGB (0-255), or YELLOW color for CMYK (0-100).
4422 * @param $col4 (int) KEY (BLACK) color for CMYK (0-100).
4423 * @param $ret (boolean) if true do not send the command.
4424 * @param $name (string) spot color name (if any)
4425 * @return string the PDF command
4426 * @public
4427 * @since 1.3
4428 * @see SetDrawColorArray(), SetFillColor(), SetTextColor(), Line(), Rect(), Cell(), MultiCell()
4430 public function SetDrawColor($col1=0, $col2=-1, $col3=-1, $col4=-1, $ret=false, $name='') {
4431 // set default values
4432 if (!is_numeric($col1)) {
4433 $col1 = 0;
4435 if (!is_numeric($col2)) {
4436 $col2 = -1;
4438 if (!is_numeric($col3)) {
4439 $col3 = -1;
4441 if (!is_numeric($col4)) {
4442 $col4 = -1;
4444 //Set color for all stroking operations
4445 if (($col2 == -1) AND ($col3 == -1) AND ($col4 == -1)) {
4446 // Grey scale
4447 $this->DrawColor = sprintf('%.3F G', ($col1 / 255));
4448 $this->strokecolor = array('G' => $col1);
4449 } elseif ($col4 == -1) {
4450 // RGB
4451 $this->DrawColor = sprintf('%.3F %.3F %.3F RG', ($col1 / 255), ($col2 / 255), ($col3 / 255));
4452 $this->strokecolor = array('R' => $col1, 'G' => $col2, 'B' => $col3);
4453 } elseif (empty($name)) {
4454 // CMYK
4455 $this->DrawColor = sprintf('%.3F %.3F %.3F %.3F K', ($col1 / 100), ($col2 / 100), ($col3 / 100), ($col4 / 100));
4456 $this->strokecolor = array('C' => $col1, 'M' => $col2, 'Y' => $col3, 'K' => $col4);
4457 } else {
4458 // SPOT COLOR
4459 $this->AddSpotColor($name, $col1, $col2, $col3, $col4);
4460 $this->DrawColor = sprintf('/CS%d CS %.3F SCN', $this->spot_colors[$name]['i'], 1);
4461 $this->strokecolor = array('C' => $col1, 'M' => $col2, 'Y' => $col3, 'K' => $col4, 'name' => $name);
4463 if ($this->page > 0) {
4464 if (!$ret) {
4465 $this->_out($this->DrawColor);
4467 return $this->DrawColor;
4469 return '';
4473 * Defines the spot color used for all drawing operations (lines, rectangles and cell borders).
4474 * @param $name (string) name of the spot color
4475 * @param $tint (int) the intensity of the color (from 0 to 100 ; 100 = full intensity by default).
4476 * @public
4477 * @since 4.0.024 (2008-09-12)
4478 * @see AddSpotColor(), SetFillSpotColor(), SetTextSpotColor()
4480 public function SetDrawSpotColor($name, $tint=100) {
4481 if (!isset($this->spot_colors[$name])) {
4482 $this->Error('Undefined spot color: '.$name);
4484 $this->DrawColor = sprintf('/CS%d CS %.3F SCN', $this->spot_colors[$name]['i'], ($tint / 100));
4485 $this->strokecolor = array('C' => $this->spot_colors[$name]['c'], 'M' => $this->spot_colors[$name]['m'], 'Y' => $this->spot_colors[$name]['y'], 'K' => $this->spot_colors[$name]['k'], 'name' => $name);
4486 if ($this->page > 0) {
4487 $this->_out($this->DrawColor);
4492 * Defines the color used for all filling operations (filled rectangles and cell backgrounds).
4493 * It can be expressed in RGB, CMYK or GRAY SCALE components.
4494 * The method can be called before the first page is created and the value is retained from page to page.
4495 * @param $color (array) array of colors
4496 * @param $ret (boolean) if true do not send the PDF command.
4497 * @public
4498 * @since 3.1.000 (2008-6-11)
4499 * @see SetFillColor()
4501 public function SetFillColorArray($color, $ret=false) {
4502 if (is_array($color)) {
4503 $color = array_values($color);
4504 $r = isset($color[0]) ? $color[0] : -1;
4505 $g = isset($color[1]) ? $color[1] : -1;
4506 $b = isset($color[2]) ? $color[2] : -1;
4507 $k = isset($color[3]) ? $color[3] : -1;
4508 $name = isset($color[4]) ? $color[4] : ''; // spot color name
4509 if ($r >= 0) {
4510 $this->SetFillColor($r, $g, $b, $k, $ret, $name);
4516 * 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.
4517 * @param $col1 (int) GRAY level for single color, or Red color for RGB (0-255), or CYAN color for CMYK (0-100).
4518 * @param $col2 (int) GREEN color for RGB (0-255), or MAGENTA color for CMYK (0-100).
4519 * @param $col3 (int) BLUE color for RGB (0-255), or YELLOW color for CMYK (0-100).
4520 * @param $col4 (int) KEY (BLACK) color for CMYK (0-100).
4521 * @param $ret (boolean) if true do not send the command.
4522 * @param $name (string) spot color name (if any)
4523 * @return string the PDF command
4524 * @public
4525 * @since 1.3
4526 * @see SetFillColorArray(), SetDrawColor(), SetTextColor(), Rect(), Cell(), MultiCell()
4528 public function SetFillColor($col1=0, $col2=-1, $col3=-1, $col4=-1, $ret=false, $name='') {
4529 // set default values
4530 if (!is_numeric($col1)) {
4531 $col1 = 0;
4533 if (!is_numeric($col2)) {
4534 $col2 = -1;
4536 if (!is_numeric($col3)) {
4537 $col3 = -1;
4539 if (!is_numeric($col4)) {
4540 $col4 = -1;
4542 //Set color for all filling operations
4543 if (($col2 == -1) AND ($col3 == -1) AND ($col4 == -1)) {
4544 // Grey scale
4545 $this->FillColor = sprintf('%.3F g', ($col1 / 255));
4546 $this->bgcolor = array('G' => $col1);
4547 } elseif ($col4 == -1) {
4548 // RGB
4549 $this->FillColor = sprintf('%.3F %.3F %.3F rg', ($col1 / 255), ($col2 / 255), ($col3 / 255));
4550 $this->bgcolor = array('R' => $col1, 'G' => $col2, 'B' => $col3);
4551 } elseif (empty($name)) {
4552 // CMYK
4553 $this->FillColor = sprintf('%.3F %.3F %.3F %.3F k', ($col1 / 100), ($col2 / 100), ($col3 / 100), ($col4 / 100));
4554 $this->bgcolor = array('C' => $col1, 'M' => $col2, 'Y' => $col3, 'K' => $col4);
4555 } else {
4556 // SPOT COLOR
4557 $this->AddSpotColor($name, $col1, $col2, $col3, $col4);
4558 $this->FillColor = sprintf('/CS%d cs %.3F scn', $this->spot_colors[$name]['i'], 1);
4559 $this->bgcolor = array('C' => $col1, 'M' => $col2, 'Y' => $col3, 'K' => $col4, 'name' => $name);
4561 $this->ColorFlag = ($this->FillColor != $this->TextColor);
4562 if ($this->page > 0) {
4563 if (!$ret) {
4564 $this->_out($this->FillColor);
4566 return $this->FillColor;
4568 return '';
4572 * Defines the spot color used for all filling operations (filled rectangles and cell backgrounds).
4573 * @param $name (string) name of the spot color
4574 * @param $tint (int) the intensity of the color (from 0 to 100 ; 100 = full intensity by default).
4575 * @public
4576 * @since 4.0.024 (2008-09-12)
4577 * @see AddSpotColor(), SetDrawSpotColor(), SetTextSpotColor()
4579 public function SetFillSpotColor($name, $tint=100) {
4580 if (!isset($this->spot_colors[$name])) {
4581 $this->Error('Undefined spot color: '.$name);
4583 $this->FillColor = sprintf('/CS%d cs %.3F scn', $this->spot_colors[$name]['i'], ($tint / 100));
4584 $this->bgcolor = array('C' => $this->spot_colors[$name]['c'], 'M' => $this->spot_colors[$name]['m'], 'Y' => $this->spot_colors[$name]['y'], 'K' => $this->spot_colors[$name]['k'], 'name' => $name);
4585 $this->ColorFlag = ($this->FillColor != $this->TextColor);
4586 if ($this->page > 0) {
4587 $this->_out($this->FillColor);
4592 * Defines the color used for text. It can be expressed in RGB components or gray scale.
4593 * The method can be called before the first page is created and the value is retained from page to page.
4594 * @param $color (array) array of colors
4595 * @param $ret (boolean) if true do not send the PDF command.
4596 * @public
4597 * @since 3.1.000 (2008-6-11)
4598 * @see SetFillColor()
4600 public function SetTextColorArray($color, $ret=false) {
4601 if (is_array($color)) {
4602 $color = array_values($color);
4603 $r = isset($color[0]) ? $color[0] : -1;
4604 $g = isset($color[1]) ? $color[1] : -1;
4605 $b = isset($color[2]) ? $color[2] : -1;
4606 $k = isset($color[3]) ? $color[3] : -1;
4607 $name = isset($color[4]) ? $color[4] : ''; // spot color name
4608 if ($r >= 0) {
4609 $this->SetTextColor($r, $g, $b, $k, $ret, $name);
4615 * 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.
4616 * @param $col1 (int) GRAY level for single color, or Red color for RGB (0-255), or CYAN color for CMYK (0-100).
4617 * @param $col2 (int) GREEN color for RGB (0-255), or MAGENTA color for CMYK (0-100).
4618 * @param $col3 (int) BLUE color for RGB (0-255), or YELLOW color for CMYK (0-100).
4619 * @param $col4 (int) KEY (BLACK) color for CMYK (0-100).
4620 * @param $ret (boolean) if true do not send the command.
4621 * @param $name (string) spot color name (if any)
4622 * @public
4623 * @since 1.3
4624 * @see SetTextColorArray(), SetDrawColor(), SetFillColor(), Text(), Cell(), MultiCell()
4626 public function SetTextColor($col1=0, $col2=-1, $col3=-1, $col4=-1, $ret=false, $name='') {
4627 // set default values
4628 if (!is_numeric($col1)) {
4629 $col1 = 0;
4631 if (!is_numeric($col2)) {
4632 $col2 = -1;
4634 if (!is_numeric($col3)) {
4635 $col3 = -1;
4637 if (!is_numeric($col4)) {
4638 $col4 = -1;
4640 //Set color for text
4641 if (($col2 == -1) AND ($col3 == -1) AND ($col4 == -1)) {
4642 // Grey scale
4643 $this->TextColor = sprintf('%.3F g', ($col1 / 255));
4644 $this->fgcolor = array('G' => $col1);
4645 } elseif ($col4 == -1) {
4646 // RGB
4647 $this->TextColor = sprintf('%.3F %.3F %.3F rg', ($col1 / 255), ($col2 / 255), ($col3 / 255));
4648 $this->fgcolor = array('R' => $col1, 'G' => $col2, 'B' => $col3);
4649 } elseif (empty($name)) {
4650 // CMYK
4651 $this->TextColor = sprintf('%.3F %.3F %.3F %.3F k', ($col1 / 100), ($col2 / 100), ($col3 / 100), ($col4 / 100));
4652 $this->fgcolor = array('C' => $col1, 'M' => $col2, 'Y' => $col3, 'K' => $col4);
4653 } else {
4654 // SPOT COLOR
4655 $this->AddSpotColor($name, $col1, $col2, $col3, $col4);
4656 $this->TextColor = sprintf('/CS%d cs %.3F scn', $this->spot_colors[$name]['i'], 1);
4657 $this->fgcolor = array('C' => $col1, 'M' => $col2, 'Y' => $col3, 'K' => $col4, 'name' => $name);
4659 $this->ColorFlag = ($this->FillColor != $this->TextColor);
4663 * Defines the spot color used for text.
4664 * @param $name (string) name of the spot color
4665 * @param $tint (int) the intensity of the color (from 0 to 100 ; 100 = full intensity by default).
4666 * @public
4667 * @since 4.0.024 (2008-09-12)
4668 * @see AddSpotColor(), SetDrawSpotColor(), SetFillSpotColor()
4670 public function SetTextSpotColor($name, $tint=100) {
4671 if (!isset($this->spot_colors[$name])) {
4672 $this->Error('Undefined spot color: '.$name);
4674 $this->TextColor = sprintf('/CS%d cs %.3F scn', $this->spot_colors[$name]['i'], ($tint / 100));
4675 $this->fgcolor = array('C' => $this->spot_colors[$name]['c'], 'M' => $this->spot_colors[$name]['m'], 'Y' => $this->spot_colors[$name]['y'], 'K' => $this->spot_colors[$name]['k'], 'name' => $name);
4676 $this->ColorFlag = ($this->FillColor != $this->TextColor);
4677 if ($this->page > 0) {
4678 $this->_out($this->TextColor);
4683 * Returns the length of a string in user unit. A font must be selected.<br>
4684 * @param $s (string) The string whose length is to be computed
4685 * @param $fontname (string) Family font. It can be either a name defined by AddFont() or one of the standard families. It is also possible to pass an empty string, in that case, the current family is retained.
4686 * @param $fontstyle (string) Font style. Possible values are (case insensitive):<ul><li>empty string: regular</li><li>B: bold</li><li>I: italic</li><li>U: underline</li><li>D: line-trough</li><li>O: overline</li></ul> or any combination. The default value is regular.
4687 * @param $fontsize (float) Font size in points. The default value is the current size.
4688 * @param $getarray (boolean) if true returns an array of characters widths, if false returns the total length.
4689 * @return mixed int total string length or array of characted widths
4690 * @author Nicola Asuni
4691 * @public
4692 * @since 1.2
4694 public function GetStringWidth($s, $fontname='', $fontstyle='', $fontsize=0, $getarray=false) {
4695 return $this->GetArrStringWidth($this->utf8Bidi($this->UTF8StringToArray($s), $s, $this->tmprtl), $fontname, $fontstyle, $fontsize, $getarray);
4699 * Returns the string length of an array of chars in user unit or an array of characters widths. A font must be selected.<br>
4700 * @param $sa (string) The array of chars whose total length is to be computed
4701 * @param $fontname (string) Family font. It can be either a name defined by AddFont() or one of the standard families. It is also possible to pass an empty string, in that case, the current family is retained.
4702 * @param $fontstyle (string) Font style. Possible values are (case insensitive):<ul><li>empty string: regular</li><li>B: bold</li><li>I: italic</li><li>U: underline</li><li>D: line trough</li><li>O: overline</li></ul> or any combination. The default value is regular.
4703 * @param $fontsize (float) Font size in points. The default value is the current size.
4704 * @param $getarray (boolean) if true returns an array of characters widths, if false returns the total length.
4705 * @return mixed int total string length or array of characted widths
4706 * @author Nicola Asuni
4707 * @public
4708 * @since 2.4.000 (2008-03-06)
4710 public function GetArrStringWidth($sa, $fontname='', $fontstyle='', $fontsize=0, $getarray=false) {
4711 // store current values
4712 if (!$this->empty_string($fontname)) {
4713 $prev_FontFamily = $this->FontFamily;
4714 $prev_FontStyle = $this->FontStyle;
4715 $prev_FontSizePt = $this->FontSizePt;
4716 $this->SetFont($fontname, $fontstyle, $fontsize);
4718 // convert UTF-8 array to Latin1 if required
4719 $sa = $this->UTF8ArrToLatin1($sa);
4720 $w = 0; // total width
4721 $wa = array(); // array of characters widths
4722 foreach ($sa as $ck => $char) {
4723 // character width
4724 $cw = $this->GetCharWidth($char, isset($sa[($ck + 1)]));
4725 $wa[] = $cw;
4726 $w += $cw;
4728 // restore previous values
4729 if (!$this->empty_string($fontname)) {
4730 $this->SetFont($prev_FontFamily, $prev_FontStyle, $prev_FontSizePt);
4732 if ($getarray) {
4733 return $wa;
4735 return $w;
4739 * Returns the length of the char in user unit for the current font considering current stretching and spacing (tracking/kerning).
4740 * @param $char (int) The char code whose length is to be returned
4741 * @param $notlast (boolean) set to false for the latest character on string, true otherwise (default)
4742 * @return float char width
4743 * @author Nicola Asuni
4744 * @public
4745 * @since 2.4.000 (2008-03-06)
4747 public function GetCharWidth($char, $notlast=true) {
4748 // get raw width
4749 $chw = $this->getRawCharWidth($char);
4750 if (($this->font_spacing != 0) AND $notlast) {
4751 // increase/decrease font spacing
4752 $chw += $this->font_spacing;
4754 if ($this->font_stretching != 100) {
4755 // fixed stretching mode
4756 $chw *= ($this->font_stretching / 100);
4758 return $chw;
4762 * Returns the length of the char in user unit for the current font.
4763 * @param $char (int) The char code whose length is to be returned
4764 * @return float char width
4765 * @author Nicola Asuni
4766 * @public
4767 * @since 5.9.000 (2010-09-28)
4769 public function getRawCharWidth($char) {
4770 if ($char == 173) {
4771 // SHY character will not be printed
4772 return (0);
4774 if (isset($this->CurrentFont['cw'][$char])) {
4775 $w = $this->CurrentFont['cw'][$char];
4776 } elseif (isset($this->CurrentFont['dw'])) {
4777 // default width
4778 $w = $this->CurrentFont['dw'];
4779 } elseif (isset($this->CurrentFont['cw'][32])) {
4780 // default width
4781 $w = $this->CurrentFont['cw'][32];
4782 } else {
4783 $w = 600;
4785 return ($w * $this->FontSize / 1000);
4789 * Returns the numbero of characters in a string.
4790 * @param $s (string) The input string.
4791 * @return int number of characters
4792 * @public
4793 * @since 2.0.0001 (2008-01-07)
4795 public function GetNumChars($s) {
4796 if ($this->isUnicodeFont()) {
4797 return count($this->UTF8StringToArray($s));
4799 return strlen($s);
4803 * Fill the list of available fonts ($this->fontlist).
4804 * @protected
4805 * @since 4.0.013 (2008-07-28)
4807 protected function getFontsList() {
4808 $fontsdir = opendir($this->_getfontpath());
4809 while (($file = readdir($fontsdir)) !== false) {
4810 if (substr($file, -4) == '.php') {
4811 array_push($this->fontlist, strtolower(basename($file, '.php')));
4814 closedir($fontsdir);
4818 * Imports a TrueType, Type1, core, or CID0 font and makes it available.
4819 * It is necessary to generate a font definition file first (read /fonts/utils/README.TXT).
4820 * 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.
4821 * @param $family (string) Font family. The name can be chosen arbitrarily. If it is a standard family name, it will override the corresponding font.
4822 * @param $style (string) Font style. Possible values are (case insensitive):<ul><li>empty string: regular (default)</li><li>B: bold</li><li>I: italic</li><li>BI or IB: bold italic</li></ul>
4823 * @param $fontfile (string) The font definition file. By default, the name is built from the family and style, in lower case with no spaces.
4824 * @return array containing the font data, or false in case of error.
4825 * @param $subset (mixed) if true embedd only a subset of the font (stores only the information related to the used characters); if false embedd full font; if 'default' uses the default value set using setFontSubsetting(). This option is valid only for TrueTypeUnicode fonts. If you want to enable users to change the document, set this parameter to false. If you subset the font, the person who receives your PDF would need to have your same font in order to make changes to your PDF. The file size of the PDF would also be smaller because you are embedding only part of a font.
4826 * @public
4827 * @since 1.5
4828 * @see SetFont(), setFontSubsetting()
4830 public function AddFont($family, $style='', $fontfile='', $subset='default') {
4831 if ($subset === 'default') {
4832 $subset = $this->font_subsetting;
4834 if ($this->empty_string($family)) {
4835 if (!$this->empty_string($this->FontFamily)) {
4836 $family = $this->FontFamily;
4837 } else {
4838 $this->Error('Empty font family');
4841 // move embedded styles on $style
4842 if (substr($family, -1) == 'I') {
4843 $style .= 'I';
4844 $family = substr($family, 0, -1);
4846 if (substr($family, -1) == 'B') {
4847 $style .= 'B';
4848 $family = substr($family, 0, -1);
4850 // normalize family name
4851 $family = strtolower($family);
4852 if ((!$this->isunicode) AND ($family == 'arial')) {
4853 $family = 'helvetica';
4855 if (($family == 'symbol') OR ($family == 'zapfdingbats')) {
4856 $style = '';
4858 $tempstyle = strtoupper($style);
4859 $style = '';
4860 // underline
4861 if (strpos($tempstyle, 'U') !== false) {
4862 $this->underline = true;
4863 } else {
4864 $this->underline = false;
4866 // line-through (deleted)
4867 if (strpos($tempstyle, 'D') !== false) {
4868 $this->linethrough = true;
4869 } else {
4870 $this->linethrough = false;
4872 // overline
4873 if (strpos($tempstyle, 'O') !== false) {
4874 $this->overline = true;
4875 } else {
4876 $this->overline = false;
4878 // bold
4879 if (strpos($tempstyle, 'B') !== false) {
4880 $style .= 'B';
4882 // oblique
4883 if (strpos($tempstyle, 'I') !== false) {
4884 $style .= 'I';
4886 $bistyle = $style;
4887 $fontkey = $family.$style;
4888 $font_style = $style.($this->underline ? 'U' : '').($this->linethrough ? 'D' : '').($this->overline ? 'O' : '');
4889 $fontdata = array('fontkey' => $fontkey, 'family' => $family, 'style' => $font_style);
4890 // check if the font has been already added
4891 $fb = $this->getFontBuffer($fontkey);
4892 if ($fb !== false) {
4893 if ($this->inxobj) {
4894 // we are inside an XObject template
4895 $this->xobjects[$this->xobjid]['fonts'][$fontkey] = $fb['i'];
4897 return $fontdata;
4899 if (isset($type)) {
4900 unset($type);
4902 if (isset($cw)) {
4903 unset($cw);
4905 // get specified font directory (if any)
4906 $fontdir = false;
4907 if (!$this->empty_string($fontfile)) {
4908 $fontdir = dirname($fontfile);
4909 if ($this->empty_string($fontdir) OR ($fontdir == '.')) {
4910 $fontdir = '';
4911 } else {
4912 $fontdir .= '/';
4915 $missing_style = false; // true when the font style variation is missing
4916 // search and include font file
4917 if ($this->empty_string($fontfile) OR (!file_exists($fontfile))) {
4918 // build a standard filenames for specified font
4919 $tmp_fontfile = str_replace(' ', '', $family).strtolower($style).'.php';
4920 // search files on various directories
4921 if (($fontdir !== false) AND file_exists($fontdir.$tmp_fontfile)) {
4922 $fontfile = $fontdir.$tmp_fontfile;
4923 } elseif (file_exists($this->_getfontpath().$tmp_fontfile)) {
4924 $fontfile = $this->_getfontpath().$tmp_fontfile;
4925 } elseif (file_exists($tmp_fontfile)) {
4926 $fontfile = $tmp_fontfile;
4927 } elseif (!$this->empty_string($style)) {
4928 $missing_style = true;
4929 // try to remove the style part
4930 $tmp_fontfile = str_replace(' ', '', $family).'.php';
4931 if (($fontdir !== false) AND file_exists($fontdir.$tmp_fontfile)) {
4932 $fontfile = $fontdir.$tmp_fontfile;
4933 } elseif (file_exists($this->_getfontpath().$tmp_fontfile)) {
4934 $fontfile = $this->_getfontpath().$tmp_fontfile;
4935 } else {
4936 $fontfile = $tmp_fontfile;
4940 // include font file
4941 if (file_exists($fontfile)) {
4942 include($fontfile);
4943 } else {
4944 $this->Error('Could not include font definition file: '.$fontfile);
4946 // check font parameters
4947 if ((!isset($type)) OR (!isset($cw))) {
4948 $this->Error('The font definition file has a bad format: '.$fontfile.'');
4950 // SET default parameters
4951 if (!isset($file) OR $this->empty_string($file)) {
4952 $file = '';
4954 if (!isset($enc) OR $this->empty_string($enc)) {
4955 $enc = '';
4957 if (!isset($cidinfo) OR $this->empty_string($cidinfo)) {
4958 $cidinfo = array('Registry'=>'Adobe', 'Ordering'=>'Identity', 'Supplement'=>0);
4959 $cidinfo['uni2cid'] = array();
4961 if (!isset($ctg) OR $this->empty_string($ctg)) {
4962 $ctg = '';
4964 if (!isset($desc) OR $this->empty_string($desc)) {
4965 $desc = array();
4967 if (!isset($up) OR $this->empty_string($up)) {
4968 $up = -100;
4970 if (!isset($ut) OR $this->empty_string($ut)) {
4971 $ut = 50;
4973 if (!isset($cw) OR $this->empty_string($cw)) {
4974 $cw = array();
4976 if (!isset($dw) OR $this->empty_string($dw)) {
4977 // set default width
4978 if (isset($desc['MissingWidth']) AND ($desc['MissingWidth'] > 0)) {
4979 $dw = $desc['MissingWidth'];
4980 } elseif (isset($cw[32])) {
4981 $dw = $cw[32];
4982 } else {
4983 $dw = 600;
4986 ++$this->numfonts;
4987 if ($type == 'core') {
4988 $name = $this->CoreFonts[$fontkey];
4989 $subset = false;
4990 } elseif (($type == 'TrueType') OR ($type == 'Type1')) {
4991 $subset = false;
4992 } elseif ($type == 'TrueTypeUnicode') {
4993 $enc = 'Identity-H';
4994 } elseif ($type != 'cidfont0') {
4995 $this->Error('Unknow font type: '.$type.'');
4997 // set name if unset
4998 if (!isset($name) OR empty($name)) {
4999 $name = $fontkey;
5001 // create artificial font style variations if missing (only works with non-embedded fonts)
5002 if (($type != 'core') AND $missing_style) {
5003 // style variations
5004 $styles = array('' => '', 'B' => ',Bold', 'I' => ',Italic', 'BI' => ',BoldItalic');
5005 $name .= $styles[$bistyle];
5006 // artificial bold
5007 if (strpos($bistyle, 'B') !== false) {
5008 if (isset($desc['StemV'])) {
5009 $desc['StemV'] *= 2;
5010 } else {
5011 $desc['StemV'] = 120;
5014 // artificial italic
5015 if (strpos($bistyle, 'I') !== false) {
5016 if (isset($desc['ItalicAngle'])) {
5017 $desc['ItalicAngle'] -= 11;
5018 } else {
5019 $desc['ItalicAngle'] = -11;
5021 if (isset($desc['Flags'])) {
5022 $desc['Flags'] |= 128; //bit 7
5023 } else {
5024 $desc['Flags'] = 128;
5028 // initialize subsetchars to contain default ASCII values (0-255)
5029 $subsetchars = array_fill(0, 256, true);
5030 $this->setFontBuffer($fontkey, array('fontkey' => $fontkey, 'i' => $this->numfonts, 'type' => $type, 'name' => $name, 'desc' => $desc, 'up' => $up, 'ut' => $ut, 'cw' => $cw, 'dw' => $dw, 'enc' => $enc, 'cidinfo' => $cidinfo, 'file' => $file, 'ctg' => $ctg, 'subset' => $subset, 'subsetchars' => $subsetchars));
5031 if ($this->inxobj) {
5032 // we are inside an XObject template
5033 $this->xobjects[$this->xobjid]['fonts'][$fontkey] = $this->numfonts;
5035 if (isset($diff) AND (!empty($diff))) {
5036 //Search existing encodings
5037 $d = 0;
5038 $nb = count($this->diffs);
5039 for ($i=1; $i <= $nb; ++$i) {
5040 if ($this->diffs[$i] == $diff) {
5041 $d = $i;
5042 break;
5045 if ($d == 0) {
5046 $d = $nb + 1;
5047 $this->diffs[$d] = $diff;
5049 $this->setFontSubBuffer($fontkey, 'diff', $d);
5051 if (!$this->empty_string($file)) {
5052 if (!isset($this->FontFiles[$file])) {
5053 if ((strcasecmp($type,'TrueType') == 0) OR (strcasecmp($type, 'TrueTypeUnicode') == 0)) {
5054 $this->FontFiles[$file] = array('length1' => $originalsize, 'fontdir' => $fontdir, 'subset' => $subset, 'fontkeys' => array($fontkey));
5055 } elseif ($type != 'core') {
5056 $this->FontFiles[$file] = array('length1' => $size1, 'length2' => $size2, 'fontdir' => $fontdir, 'subset' => $subset, 'fontkeys' => array($fontkey));
5058 } else {
5059 // update fontkeys that are sharing this font file
5060 $this->FontFiles[$file]['subset'] = ($this->FontFiles[$file]['subset'] AND $subset);
5061 if (!in_array($fontkey, $this->FontFiles[$file]['fontkeys'])) {
5062 $this->FontFiles[$file]['fontkeys'][] = $fontkey;
5066 return $fontdata;
5070 * Sets the font used to print character strings.
5071 * The font can be either a standard one or a font added via the AddFont() method. Standard fonts use Windows encoding cp1252 (Western Europe).
5072 * The method can be called before the first page is created and the font is retained from page to page.
5073 * If you just wish to change the current font size, it is simpler to call SetFontSize().
5074 * 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 />
5075 * @param $family (string) Family font. It can be either a name defined by AddFont() or one of the standard Type1 families (case insensitive):<ul><li>times (Times-Roman)</li><li>timesb (Times-Bold)</li><li>timesi (Times-Italic)</li><li>timesbi (Times-BoldItalic)</li><li>helvetica (Helvetica)</li><li>helveticab (Helvetica-Bold)</li><li>helveticai (Helvetica-Oblique)</li><li>helveticabi (Helvetica-BoldOblique)</li><li>courier (Courier)</li><li>courierb (Courier-Bold)</li><li>courieri (Courier-Oblique)</li><li>courierbi (Courier-BoldOblique)</li><li>symbol (Symbol)</li><li>zapfdingbats (ZapfDingbats)</li></ul> It is also possible to pass an empty string. In that case, the current family is retained.
5076 * @param $style (string) Font style. Possible values are (case insensitive):<ul><li>empty string: regular</li><li>B: bold</li><li>I: italic</li><li>U: underline</li><li>D: line trough</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.
5077 * @param $size (float) Font size in points. The default value is the current size. If no size has been specified since the beginning of the document, the value taken is 12
5078 * @param $fontfile (string) The font definition file. By default, the name is built from the family and style, in lower case with no spaces.
5079 * @param $subset (mixed) if true embedd only a subset of the font (stores only the information related to the used characters); if false embedd full font; if 'default' uses the default value set using setFontSubsetting(). This option is valid only for TrueTypeUnicode fonts. If you want to enable users to change the document, set this parameter to false. If you subset the font, the person who receives your PDF would need to have your same font in order to make changes to your PDF. The file size of the PDF would also be smaller because you are embedding only part of a font.
5080 * @author Nicola Asuni
5081 * @public
5082 * @since 1.0
5083 * @see AddFont(), SetFontSize()
5085 public function SetFont($family, $style='', $size=0, $fontfile='', $subset='default') {
5086 //Select a font; size given in points
5087 if ($size == 0) {
5088 $size = $this->FontSizePt;
5090 // try to add font (if not already added)
5091 $fontdata = $this->AddFont($family, $style, $fontfile, $subset);
5092 $this->FontFamily = $fontdata['family'];
5093 $this->FontStyle = $fontdata['style'];
5094 $this->CurrentFont = $this->getFontBuffer($fontdata['fontkey']);
5095 $this->SetFontSize($size);
5099 * Defines the size of the current font.
5100 * @param $size (float) The size (in points)
5101 * @param $out (boolean) if true output the font size command, otherwise only set the font properties.
5102 * @public
5103 * @since 1.0
5104 * @see SetFont()
5106 public function SetFontSize($size, $out=true) {
5107 // font size in points
5108 $this->FontSizePt = $size;
5109 // font size in user units
5110 $this->FontSize = $size / $this->k;
5111 // calculate some font metrics
5112 if (isset($this->CurrentFont['desc']['FontBBox'])) {
5113 $bbox = explode(' ', substr($this->CurrentFont['desc']['FontBBox'], 1, -1));
5114 $font_height = ((intval($bbox[3]) - intval($bbox[1])) * $size / 1000);
5115 } else {
5116 $font_height = $size * 1.219;
5118 if (isset($this->CurrentFont['desc']['Ascent']) AND ($this->CurrentFont['desc']['Ascent'] > 0)) {
5119 $font_ascent = ($this->CurrentFont['desc']['Ascent'] * $size / 1000);
5121 if (isset($this->CurrentFont['desc']['Descent']) AND ($this->CurrentFont['desc']['Descent'] <= 0)) {
5122 $font_descent = (- $this->CurrentFont['desc']['Descent'] * $size / 1000);
5124 if (!isset($font_ascent) AND !isset($font_descent)) {
5125 // core font
5126 $font_ascent = 0.76 * $font_height;
5127 $font_descent = $font_height - $font_ascent;
5128 } elseif (!isset($font_descent)) {
5129 $font_descent = $font_height - $font_ascent;
5130 } elseif (!isset($font_ascent)) {
5131 $font_ascent = $font_height - $font_descent;
5133 $this->FontAscent = $font_ascent / $this->k;
5134 $this->FontDescent = $font_descent / $this->k;
5135 if ($out AND ($this->page > 0) AND (isset($this->CurrentFont['i']))) {
5136 $this->_out(sprintf('BT /F%d %.2F Tf ET', $this->CurrentFont['i'], $this->FontSizePt));
5141 * Return the font descent value
5142 * @param $font (string) font name
5143 * @param $style (string) font style
5144 * @param $size (float) The size (in points)
5145 * @return int font descent
5146 * @public
5147 * @author Nicola Asuni
5148 * @since 4.9.003 (2010-03-30)
5150 public function getFontDescent($font, $style='', $size=0) {
5151 $fontdata = $this->AddFont($font, $style);
5152 $fontinfo = $this->getFontBuffer($fontdata['fontkey']);
5153 if (isset($fontinfo['desc']['Descent']) AND ($fontinfo['desc']['Descent'] <= 0)) {
5154 $descent = (- $fontinfo['desc']['Descent'] * $size / 1000);
5155 } else {
5156 $descent = 1.219 * 0.24 * $size;
5158 return ($descent / $this->k);
5162 * Return the font ascent value
5163 * @param $font (string) font name
5164 * @param $style (string) font style
5165 * @param $size (float) The size (in points)
5166 * @return int font ascent
5167 * @public
5168 * @author Nicola Asuni
5169 * @since 4.9.003 (2010-03-30)
5171 public function getFontAscent($font, $style='', $size=0) {
5172 $fontdata = $this->AddFont($font, $style);
5173 $fontinfo = $this->getFontBuffer($fontdata['fontkey']);
5174 if (isset($fontinfo['desc']['Ascent']) AND ($fontinfo['desc']['Ascent'] > 0)) {
5175 $ascent = ($fontinfo['desc']['Ascent'] * $size / 1000);
5176 } else {
5177 $ascent = 1.219 * 0.76 * $size;
5179 return ($ascent / $this->k);
5183 * Defines the default monospaced font.
5184 * @param $font (string) Font name.
5185 * @public
5186 * @since 4.5.025
5188 public function SetDefaultMonospacedFont($font) {
5189 $this->default_monospaced_font = $font;
5193 * 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 />
5194 * The identifier can then be passed to Cell(), Write(), Image() or Link(). The destination is defined with SetLink().
5195 * @public
5196 * @since 1.5
5197 * @see Cell(), Write(), Image(), Link(), SetLink()
5199 public function AddLink() {
5200 //Create a new internal link
5201 $n = count($this->links) + 1;
5202 $this->links[$n] = array(0, 0);
5203 return $n;
5207 * Defines the page and position a link points to.
5208 * @param $link (int) The link identifier returned by AddLink()
5209 * @param $y (float) Ordinate of target position; -1 indicates the current position. The default value is 0 (top of page)
5210 * @param $page (int) Number of target page; -1 indicates the current page. This is the default value
5211 * @public
5212 * @since 1.5
5213 * @see AddLink()
5215 public function SetLink($link, $y=0, $page=-1) {
5216 if ($y == -1) {
5217 $y = $this->y;
5219 if ($page == -1) {
5220 $page = $this->page;
5222 $this->links[$link] = array($page, $y);
5226 * Puts a link on a rectangular area of the page.
5227 * 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.
5228 * @param $x (float) Abscissa of the upper-left corner of the rectangle
5229 * @param $y (float) Ordinate of the upper-left corner of the rectangle
5230 * @param $w (float) Width of the rectangle
5231 * @param $h (float) Height of the rectangle
5232 * @param $link (mixed) URL or identifier returned by AddLink()
5233 * @param $spaces (int) number of spaces on the text to link
5234 * @public
5235 * @since 1.5
5236 * @see AddLink(), Annotation(), Cell(), Write(), Image()
5238 public function Link($x, $y, $w, $h, $link, $spaces=0) {
5239 $this->Annotation($x, $y, $w, $h, $link, array('Subtype'=>'Link'), $spaces);
5243 * Puts a markup annotation on a rectangular area of the page.
5244 * !!!!THE ANNOTATION SUPPORT IS NOT YET FULLY IMPLEMENTED !!!!
5245 * @param $x (float) Abscissa of the upper-left corner of the rectangle
5246 * @param $y (float) Ordinate of the upper-left corner of the rectangle
5247 * @param $w (float) Width of the rectangle
5248 * @param $h (float) Height of the rectangle
5249 * @param $text (string) annotation text or alternate content
5250 * @param $opt (array) array of options (see section 8.4 of PDF reference 1.7).
5251 * @param $spaces (int) number of spaces on the text to link
5252 * @public
5253 * @since 4.0.018 (2008-08-06)
5255 public function Annotation($x, $y, $w, $h, $text, $opt=array('Subtype'=>'Text'), $spaces=0) {
5256 if ($this->inxobj) {
5257 // store parameters for later use on template
5258 $this->xobjects[$this->xobjid]['annotations'][] = array('x' => $x, 'y' => $y, 'w' => $w, 'h' => $h, 'text' => $text, 'opt' => $opt, 'spaces' => $spaces);
5259 return;
5261 if ($x === '') {
5262 $x = $this->x;
5264 if ($y === '') {
5265 $y = $this->y;
5267 // check page for no-write regions and adapt page margins if necessary
5268 list($x, $y) = $this->checkPageRegions($h, $x, $y);
5269 // recalculate coordinates to account for graphic transformations
5270 if (isset($this->transfmatrix) AND !empty($this->transfmatrix)) {
5271 for ($i=$this->transfmatrix_key; $i > 0; --$i) {
5272 $maxid = count($this->transfmatrix[$i]) - 1;
5273 for ($j=$maxid; $j >= 0; --$j) {
5274 $ctm = $this->transfmatrix[$i][$j];
5275 if (isset($ctm['a'])) {
5276 $x = $x * $this->k;
5277 $y = ($this->h - $y) * $this->k;
5278 $w = $w * $this->k;
5279 $h = $h * $this->k;
5280 // top left
5281 $xt = $x;
5282 $yt = $y;
5283 $x1 = ($ctm['a'] * $xt) + ($ctm['c'] * $yt) + $ctm['e'];
5284 $y1 = ($ctm['b'] * $xt) + ($ctm['d'] * $yt) + $ctm['f'];
5285 // top right
5286 $xt = $x + $w;
5287 $yt = $y;
5288 $x2 = ($ctm['a'] * $xt) + ($ctm['c'] * $yt) + $ctm['e'];
5289 $y2 = ($ctm['b'] * $xt) + ($ctm['d'] * $yt) + $ctm['f'];
5290 // bottom left
5291 $xt = $x;
5292 $yt = $y - $h;
5293 $x3 = ($ctm['a'] * $xt) + ($ctm['c'] * $yt) + $ctm['e'];
5294 $y3 = ($ctm['b'] * $xt) + ($ctm['d'] * $yt) + $ctm['f'];
5295 // bottom right
5296 $xt = $x + $w;
5297 $yt = $y - $h;
5298 $x4 = ($ctm['a'] * $xt) + ($ctm['c'] * $yt) + $ctm['e'];
5299 $y4 = ($ctm['b'] * $xt) + ($ctm['d'] * $yt) + $ctm['f'];
5300 // new coordinates (rectangle area)
5301 $x = min($x1, $x2, $x3, $x4);
5302 $y = max($y1, $y2, $y3, $y4);
5303 $w = (max($x1, $x2, $x3, $x4) - $x) / $this->k;
5304 $h = ($y - min($y1, $y2, $y3, $y4)) / $this->k;
5305 $x = $x / $this->k;
5306 $y = $this->h - ($y / $this->k);
5311 if ($this->page <= 0) {
5312 $page = 1;
5313 } else {
5314 $page = $this->page;
5316 if (!isset($this->PageAnnots[$page])) {
5317 $this->PageAnnots[$page] = array();
5319 ++$this->n;
5320 $this->PageAnnots[$page][] = array('n' => $this->n, 'x' => $x, 'y' => $y, 'w' => $w, 'h' => $h, 'txt' => $text, 'opt' => $opt, 'numspaces' => $spaces);
5321 if ((($opt['Subtype'] == 'FileAttachment') OR ($opt['Subtype'] == 'Sound')) AND (!$this->empty_string($opt['FS'])) AND file_exists($opt['FS']) AND (!isset($this->embeddedfiles[basename($opt['FS'])]))) {
5322 ++$this->n;
5323 $this->embeddedfiles[basename($opt['FS'])] = array('n' => $this->n, 'file' => $opt['FS']);
5325 // Add widgets annotation's icons
5326 if (isset($opt['mk']['i']) AND file_exists($opt['mk']['i'])) {
5327 $this->Image($opt['mk']['i'], '', '', 10, 10, '', '', '', false, 300, '', false, false, 0, false, true);
5329 if (isset($opt['mk']['ri']) AND file_exists($opt['mk']['ri'])) {
5330 $this->Image($opt['mk']['ri'], '', '', 0, 0, '', '', '', false, 300, '', false, false, 0, false, true);
5332 if (isset($opt['mk']['ix']) AND file_exists($opt['mk']['ix'])) {
5333 $this->Image($opt['mk']['ix'], '', '', 0, 0, '', '', '', false, 300, '', false, false, 0, false, true);
5338 * Embedd the attached files.
5339 * @since 4.4.000 (2008-12-07)
5340 * @protected
5341 * @see Annotation()
5343 protected function _putEmbeddedFiles() {
5344 reset($this->embeddedfiles);
5345 foreach ($this->embeddedfiles as $filename => $filedata) {
5346 $data = file_get_contents($filedata['file']);
5347 $filter = '';
5348 if ($this->compress) {
5349 $data = gzcompress($data);
5350 $filter = ' /Filter /FlateDecode';
5352 $stream = $this->_getrawstream($data, $filedata['n']);
5353 $out = $this->_getobj($filedata['n'])."\n";
5354 $out .= '<< /Type /EmbeddedFile'.$filter.' /Length '.strlen($stream).' >>';
5355 $out .= ' stream'."\n".$stream."\n".'endstream';
5356 $out .= "\n".'endobj';
5357 $this->_out($out);
5362 * Prints a text cell at the specified position.
5363 * This method allows to place a string precisely on the page.
5364 * @param $x (float) Abscissa of the cell origin
5365 * @param $y (float) Ordinate of the cell origin
5366 * @param $txt (string) String to print
5367 * @param $fstroke (int) outline size in user units (false = disable)
5368 * @param $fclip (boolean) if true activate clipping mode (you must call StartTransform() before this function and StopTransform() to stop the clipping tranformation).
5369 * @param $ffill (boolean) if true fills the text
5370 * @param $border (mixed) Indicates if borders must be drawn around the cell. The value can be a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul> or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul> or an array of line styles for each border group - for example: array('LTRB' => array('width' => 2, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0)))
5371 * @param $ln (int) Indicates where the current position should go after the call. Possible values are:<ul><li>0: to the right (or left for RTL languages)</li><li>1: to the beginning of the next line</li><li>2: below</li></ul>Putting 1 is equivalent to putting 0 and calling Ln() just after. Default value: 0.
5372 * @param $align (string) Allows to center or align the text. Possible values are:<ul><li>L or empty string: left align (default value)</li><li>C: center</li><li>R: right align</li><li>J: justify</li></ul>
5373 * @param $fill (boolean) Indicates if the cell background must be painted (true) or transparent (false).
5374 * @param $link (mixed) URL or identifier returned by AddLink().
5375 * @param $stretch (int) font stretch mode: <ul><li>0 = disabled</li><li>1 = horizontal scaling only if text is larger than cell width</li><li>2 = forced horizontal scaling to fit cell width</li><li>3 = character spacing only if text is larger than cell width</li><li>4 = forced character spacing to fit cell width</li></ul> General font stretching and scaling values will be preserved when possible.
5376 * @param $ignore_min_height (boolean) if true ignore automatic minimum height value.
5377 * @param $calign (string) cell vertical alignment relative to the specified Y value. Possible values are:<ul><li>T : cell top</li><li>A : font top</li><li>L : font baseline</li><li>D : font bottom</li><li>B : cell bottom</li></ul>
5378 * @param $valign (string) text vertical alignment inside the cell. Possible values are:<ul><li>T : top</li><li>C : center</li><li>B : bottom</li></ul>
5379 * @param $rtloff (boolean) if true uses the page top-left corner as origin of axis for $x and $y initial position.
5380 * @public
5381 * @since 1.0
5382 * @see Cell(), Write(), MultiCell(), WriteHTML(), WriteHTMLCell()
5384 public function Text($x, $y, $txt, $fstroke=false, $fclip=false, $ffill=true, $border=0, $ln=0, $align='', $fill=false, $link='', $stretch=0, $ignore_min_height=false, $calign='T', $valign='M', $rtloff=false) {
5385 $textrendermode = $this->textrendermode;
5386 $textstrokewidth = $this->textstrokewidth;
5387 $this->setTextRenderingMode($fstroke, $ffill, $fclip);
5388 $this->SetXY($x, $y, $rtloff);
5389 $this->Cell(0, 0, $txt, $border, $ln, $align, $fill, $link, $stretch, $ignore_min_height, $calign, $valign);
5390 // restore previous rendering mode
5391 $this->textrendermode = $textrendermode;
5392 $this->textstrokewidth = $textstrokewidth;
5396 * Whenever a page break condition is met, the method is called, and the break is issued or not depending on the returned value.
5397 * The default implementation returns a value according to the mode selected by SetAutoPageBreak().<br />
5398 * This method is called automatically and should not be called directly by the application.
5399 * @return boolean
5400 * @public
5401 * @since 1.4
5402 * @see SetAutoPageBreak()
5404 public function AcceptPageBreak() {
5405 if ($this->num_columns > 1) {
5406 // multi column mode
5407 if ($this->current_column < ($this->num_columns - 1)) {
5408 // go to next column
5409 $this->selectColumn($this->current_column + 1);
5410 } else {
5411 // add a new page
5412 $this->AddPage();
5413 // set first column
5414 $this->selectColumn(0);
5416 // avoid page breaking from checkPageBreak()
5417 return false;
5419 return $this->AutoPageBreak;
5423 * Add page if needed.
5424 * @param $h (float) Cell height. Default value: 0.
5425 * @param $y (mixed) starting y position, leave empty for current position.
5426 * @param $addpage (boolean) if true add a page, otherwise only return the true/false state
5427 * @return boolean true in case of page break, false otherwise.
5428 * @since 3.2.000 (2008-07-01)
5429 * @protected
5431 protected function checkPageBreak($h=0, $y='', $addpage=true) {
5432 if ($this->empty_string($y)) {
5433 $y = $this->y;
5435 $current_page = $this->page;
5436 if ((($y + $h) > $this->PageBreakTrigger) AND ($this->inPageBody()) AND ($this->AcceptPageBreak())) {
5437 if ($addpage) {
5438 //Automatic page break
5439 $x = $this->x;
5440 $this->AddPage($this->CurOrientation);
5441 $this->y = $this->tMargin;
5442 $oldpage = $this->page - 1;
5443 if ($this->rtl) {
5444 if ($this->pagedim[$this->page]['orm'] != $this->pagedim[$oldpage]['orm']) {
5445 $this->x = $x - ($this->pagedim[$this->page]['orm'] - $this->pagedim[$oldpage]['orm']);
5446 } else {
5447 $this->x = $x;
5449 } else {
5450 if ($this->pagedim[$this->page]['olm'] != $this->pagedim[$oldpage]['olm']) {
5451 $this->x = $x + ($this->pagedim[$this->page]['olm'] - $this->pagedim[$oldpage]['olm']);
5452 } else {
5453 $this->x = $x;
5457 return true;
5459 if ($current_page != $this->page) {
5460 // account for columns mode
5461 return true;
5463 return false;
5467 * Removes SHY characters from text.
5468 * Unicode Data:<ul>
5469 * <li>Name : SOFT HYPHEN, commonly abbreviated as SHY</li>
5470 * <li>HTML Entity (decimal): "&amp;#173;"</li>
5471 * <li>HTML Entity (hex): "&amp;#xad;"</li>
5472 * <li>HTML Entity (named): "&amp;shy;"</li>
5473 * <li>How to type in Microsoft Windows: [Alt +00AD] or [Alt 0173]</li>
5474 * <li>UTF-8 (hex): 0xC2 0xAD (c2ad)</li>
5475 * <li>UTF-8 character: chr(194).chr(173)</li>
5476 * </ul>
5477 * @param $txt (string) input string
5478 * @return string without SHY characters.
5479 * @public
5480 * @since (4.5.019) 2009-02-28
5482 public function removeSHY($txt='') {
5483 $txt = preg_replace('/([\\xc2]{1}[\\xad]{1})/', '', $txt);
5484 if (!$this->isunicode) {
5485 $txt = preg_replace('/([\\xad]{1})/', '', $txt);
5487 return $txt;
5491 * 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 />
5492 * If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting.
5493 * @param $w (float) Cell width. If 0, the cell extends up to the right margin.
5494 * @param $h (float) Cell height. Default value: 0.
5495 * @param $txt (string) String to print. Default value: empty string.
5496 * @param $border (mixed) Indicates if borders must be drawn around the cell. The value can be a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul> or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul> or an array of line styles for each border group - for example: array('LTRB' => array('width' => 2, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0)))
5497 * @param $ln (int) Indicates where the current position should go after the call. Possible values are:<ul><li>0: to the right (or left for RTL languages)</li><li>1: to the beginning of the next line</li><li>2: below</li></ul> Putting 1 is equivalent to putting 0 and calling Ln() just after. Default value: 0.
5498 * @param $align (string) Allows to center or align the text. Possible values are:<ul><li>L or empty string: left align (default value)</li><li>C: center</li><li>R: right align</li><li>J: justify</li></ul>
5499 * @param $fill (boolean) Indicates if the cell background must be painted (true) or transparent (false).
5500 * @param $link (mixed) URL or identifier returned by AddLink().
5501 * @param $stretch (int) font stretch mode: <ul><li>0 = disabled</li><li>1 = horizontal scaling only if text is larger than cell width</li><li>2 = forced horizontal scaling to fit cell width</li><li>3 = character spacing only if text is larger than cell width</li><li>4 = forced character spacing to fit cell width</li></ul> General font stretching and scaling values will be preserved when possible.
5502 * @param $ignore_min_height (boolean) if true ignore automatic minimum height value.
5503 * @param $calign (string) cell vertical alignment relative to the specified Y value. Possible values are:<ul><li>T : cell top</li><li>C : center</li><li>B : cell bottom</li><li>A : font top</li><li>L : font baseline</li><li>D : font bottom</li></ul>
5504 * @param $valign (string) text vertical alignment inside the cell. Possible values are:<ul><li>T : top</li><li>C : center</li><li>B : bottom</li></ul>
5505 * @public
5506 * @since 1.0
5507 * @see SetFont(), SetDrawColor(), SetFillColor(), SetTextColor(), SetLineWidth(), AddLink(), Ln(), MultiCell(), Write(), SetAutoPageBreak()
5509 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') {
5510 $prev_cell_margin = $this->cell_margin;
5511 $prev_cell_padding = $this->cell_padding;
5512 $this->adjustCellPadding($border);
5513 if (!$ignore_min_height) {
5514 $min_cell_height = ($this->FontSize * $this->cell_height_ratio) + $this->cell_padding['T'] + $this->cell_padding['B'];
5515 if ($h < $min_cell_height) {
5516 $h = $min_cell_height;
5519 $this->checkPageBreak($h + $this->cell_margin['T'] + $this->cell_margin['B']);
5520 $this->_out($this->getCellCode($w, $h, $txt, $border, $ln, $align, $fill, $link, $stretch, true, $calign, $valign));
5521 $this->cell_padding = $prev_cell_padding;
5522 $this->cell_margin = $prev_cell_margin;
5526 * 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 />
5527 * If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting.
5528 * @param $w (float) Cell width. If 0, the cell extends up to the right margin.
5529 * @param $h (float) Cell height. Default value: 0.
5530 * @param $txt (string) String to print. Default value: empty string.
5531 * @param $border (mixed) Indicates if borders must be drawn around the cell. The value can be a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul> or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul> or an array of line styles for each border group - for example: array('LTRB' => array('width' => 2, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0)))
5532 * @param $ln (int) Indicates where the current position should go after the call. Possible values are:<ul><li>0: to the right (or left for RTL languages)</li><li>1: to the beginning of the next line</li><li>2: below</li></ul>Putting 1 is equivalent to putting 0 and calling Ln() just after. Default value: 0.
5533 * @param $align (string) Allows to center or align the text. Possible values are:<ul><li>L or empty string: left align (default value)</li><li>C: center</li><li>R: right align</li><li>J: justify</li></ul>
5534 * @param $fill (boolean) Indicates if the cell background must be painted (true) or transparent (false).
5535 * @param $link (mixed) URL or identifier returned by AddLink().
5536 * @param $stretch (int) font stretch mode: <ul><li>0 = disabled</li><li>1 = horizontal scaling only if text is larger than cell width</li><li>2 = forced horizontal scaling to fit cell width</li><li>3 = character spacing only if text is larger than cell width</li><li>4 = forced character spacing to fit cell width</li></ul> General font stretching and scaling values will be preserved when possible.
5537 * @param $ignore_min_height (boolean) if true ignore automatic minimum height value.
5538 * @param $calign (string) cell vertical alignment relative to the specified Y value. Possible values are:<ul><li>T : cell top</li><li>C : center</li><li>B : cell bottom</li><li>A : font top</li><li>L : font baseline</li><li>D : font bottom</li></ul>
5539 * @param $valign (string) text vertical alignment inside the cell. Possible values are:<ul><li>T : top</li><li>M : middle</li><li>B : bottom</li></ul>
5540 * @return string containing cell code
5541 * @protected
5542 * @since 1.0
5543 * @see Cell()
5545 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') {
5546 // replace 'NO-BREAK SPACE' (U+00A0) character with a simple space
5547 $txt = str_replace($this->unichr(160), ' ', $txt);
5548 $prev_cell_margin = $this->cell_margin;
5549 $prev_cell_padding = $this->cell_padding;
5550 $txt = $this->removeSHY($txt);
5551 $rs = ''; //string to be returned
5552 $this->adjustCellPadding($border);
5553 if (!$ignore_min_height) {
5554 $min_cell_height = ($this->FontSize * $this->cell_height_ratio) + $this->cell_padding['T'] + $this->cell_padding['B'];
5555 if ($h < $min_cell_height) {
5556 $h = $min_cell_height;
5559 $k = $this->k;
5560 // check page for no-write regions and adapt page margins if necessary
5561 list($this->x, $this->y) = $this->checkPageRegions($h, $this->x, $this->y);
5562 if ($this->rtl) {
5563 $x = $this->x - $this->cell_margin['R'];
5564 } else {
5565 $x = $this->x + $this->cell_margin['L'];
5567 $y = $this->y + $this->cell_margin['T'];
5568 $prev_font_stretching = $this->font_stretching;
5569 $prev_font_spacing = $this->font_spacing;
5570 // cell vertical alignment
5571 switch ($calign) {
5572 case 'A': {
5573 // font top
5574 switch ($valign) {
5575 case 'T': {
5576 // top
5577 $y -= $this->cell_padding['T'];
5578 break;
5580 case 'B': {
5581 // bottom
5582 $y -= ($h - $this->cell_padding['B'] - $this->FontAscent - $this->FontDescent);
5583 break;
5585 default:
5586 case 'C':
5587 case 'M': {
5588 // center
5589 $y -= (($h - $this->FontAscent - $this->FontDescent) / 2);
5590 break;
5593 break;
5595 case 'L': {
5596 // font baseline
5597 switch ($valign) {
5598 case 'T': {
5599 // top
5600 $y -= ($this->cell_padding['T'] + $this->FontAscent);
5601 break;
5603 case 'B': {
5604 // bottom
5605 $y -= ($h - $this->cell_padding['B'] - $this->FontDescent);
5606 break;
5608 default:
5609 case 'C':
5610 case 'M': {
5611 // center
5612 $y -= (($h + $this->FontAscent - $this->FontDescent) / 2);
5613 break;
5616 break;
5618 case 'D': {
5619 // font bottom
5620 switch ($valign) {
5621 case 'T': {
5622 // top
5623 $y -= ($this->cell_padding['T'] + $this->FontAscent + $this->FontDescent);
5624 break;
5626 case 'B': {
5627 // bottom
5628 $y -= ($h - $this->cell_padding['B']);
5629 break;
5631 default:
5632 case 'C':
5633 case 'M': {
5634 // center
5635 $y -= (($h + $this->FontAscent + $this->FontDescent) / 2);
5636 break;
5639 break;
5641 case 'B': {
5642 // cell bottom
5643 $y -= $h;
5644 break;
5646 case 'C':
5647 case 'M': {
5648 // cell center
5649 $y -= ($h / 2);
5650 break;
5652 default:
5653 case 'T': {
5654 // cell top
5655 break;
5658 // text vertical alignment
5659 switch ($valign) {
5660 case 'T': {
5661 // top
5662 $yt = $y + $this->cell_padding['T'];
5663 break;
5665 case 'B': {
5666 // bottom
5667 $yt = $y + $h - $this->cell_padding['B'] - $this->FontAscent - $this->FontDescent;
5668 break;
5670 default:
5671 case 'C':
5672 case 'M': {
5673 // center
5674 $yt = $y + (($h - $this->FontAscent - $this->FontDescent) / 2);
5675 break;
5678 $basefonty = $yt + $this->FontAscent;
5679 if ($this->empty_string($w) OR ($w <= 0)) {
5680 if ($this->rtl) {
5681 $w = $x - $this->lMargin;
5682 } else {
5683 $w = $this->w - $this->rMargin - $x;
5686 $s = '';
5687 // fill and borders
5688 if (is_string($border) AND (strlen($border) == 4)) {
5689 // full border
5690 $border = 1;
5692 if ($fill OR ($border == 1)) {
5693 if ($fill) {
5694 $op = ($border == 1) ? 'B' : 'f';
5695 } else {
5696 $op = 'S';
5698 if ($this->rtl) {
5699 $xk = (($x - $w) * $k);
5700 } else {
5701 $xk = ($x * $k);
5703 $s .= sprintf('%.2F %.2F %.2F %.2F re %s ', $xk, (($this->h - $y) * $k), ($w * $k), (-$h * $k), $op);
5705 // draw borders
5706 $s .= $this->getCellBorder($x, $y, $w, $h, $border);
5707 if ($txt != '') {
5708 $txt2 = $txt;
5709 if ($this->isunicode) {
5710 if (($this->CurrentFont['type'] == 'core') OR ($this->CurrentFont['type'] == 'TrueType') OR ($this->CurrentFont['type'] == 'Type1')) {
5711 $txt2 = $this->UTF8ToLatin1($txt2);
5712 } else {
5713 $unicode = $this->UTF8StringToArray($txt); // array of UTF-8 unicode values
5714 $unicode = $this->utf8Bidi($unicode, '', $this->tmprtl);
5715 if (defined('K_THAI_TOPCHARS') AND (K_THAI_TOPCHARS == true)) {
5716 // ---- Fix for bug #2977340 "Incorrect Thai characters position arrangement" ----
5717 // NOTE: this doesn't work with HTML justification
5718 // Symbols that could overlap on the font top (only works in LTR)
5719 $topchar = array(3611, 3613, 3615, 3650, 3651, 3652); // chars that extends on top
5720 $topsym = array(3633, 3636, 3637, 3638, 3639, 3655, 3656, 3657, 3658, 3659, 3660, 3661, 3662); // symbols with top position
5721 $numchars = count($unicode); // number of chars
5722 $unik = 0;
5723 $uniblock = array();
5724 $uniblock[$unik] = array();
5725 $uniblock[$unik][] = $unicode[0];
5726 // resolve overlapping conflicts by splitting the string in several parts
5727 for ($i = 1; $i < $numchars; ++$i) {
5728 // check if symbols overlaps at top
5729 if (in_array($unicode[$i], $topsym) AND (in_array($unicode[($i - 1)], $topsym) OR in_array($unicode[($i - 1)], $topchar))) {
5730 // move symbols to another array
5731 ++$unik;
5732 $uniblock[$unik] = array();
5733 $uniblock[$unik][] = $unicode[$i];
5734 ++$unik;
5735 $uniblock[$unik] = array();
5736 $unicode[$i] = 0x200b; // Unicode Character 'ZERO WIDTH SPACE' (DEC:8203, U+200B)
5737 } else {
5738 $uniblock[$unik][] = $unicode[$i];
5741 // ---- END OF Fix for bug #2977340
5743 $txt2 = $this->arrUTF8ToUTF16BE($unicode, false);
5746 $txt2 = $this->_escape($txt2);
5747 // get current text width (considering general font stretching and spacing)
5748 $txwidth = $this->GetStringWidth($txt);
5749 $width = $txwidth;
5750 // check for stretch mode
5751 if ($stretch > 0) {
5752 // calculate ratio between cell width and text width
5753 if ($width <= 0) {
5754 $ratio = 1;
5755 } else {
5756 $ratio = (($w - $this->cell_padding['L'] - $this->cell_padding['R']) / $width);
5758 // check if stretching is required
5759 if (($ratio < 1) OR (($ratio > 1) AND (($stretch % 2) == 0))) {
5760 // the text will be stretched to fit cell width
5761 if ($stretch > 2) {
5762 // set new character spacing
5763 $this->font_spacing += ($w - $this->cell_padding['L'] - $this->cell_padding['R'] - $width) / (max(($this->GetNumChars($txt) - 1), 1) * ($this->font_stretching / 100));
5764 } else {
5765 // set new horizontal stretching
5766 $this->font_stretching *= $ratio;
5768 // recalculate text width (the text fills the entire cell)
5769 $width = $w - $this->cell_padding['L'] - $this->cell_padding['R'];
5770 // reset alignment
5771 $align = '';
5774 if ($this->font_stretching != 100) {
5775 // apply font stretching
5776 $rs .= sprintf('BT %.2F Tz ET ', $this->font_stretching);
5778 if ($this->font_spacing != 0) {
5779 // increase/decrease font spacing
5780 $rs .= sprintf('BT %.2F Tc ET ', ($this->font_spacing * $this->k));
5782 if ($this->ColorFlag AND ($this->textrendermode < 4)) {
5783 $s .= 'q '.$this->TextColor.' ';
5785 // rendering mode
5786 $s .= sprintf('BT %d Tr %.2F w ET ', $this->textrendermode, $this->textstrokewidth);
5787 // count number of spaces
5788 $ns = substr_count($txt, chr(32));
5789 // Justification
5790 $spacewidth = 0;
5791 if (($align == 'J') AND ($ns > 0)) {
5792 if ($this->isUnicodeFont()) {
5793 // get string width without spaces
5794 $width = $this->GetStringWidth(str_replace(' ', '', $txt));
5795 // calculate average space width
5796 $spacewidth = -1000 * ($w - $width - $this->cell_padding['L'] - $this->cell_padding['R']) / ($ns?$ns:1) / $this->FontSize;
5797 if ($this->font_stretching != 100) {
5798 // word spacing is affected by stretching
5799 $spacewidth /= ($this->font_stretching / 100);
5801 // set word position to be used with TJ operator
5802 $txt2 = str_replace(chr(0).chr(32), ') '.sprintf('%.3F', $spacewidth).' (', $txt2);
5803 $unicode_justification = true;
5804 } else {
5805 // get string width
5806 $width = $txwidth;
5807 // new space width
5808 $spacewidth = (($w - $width - $this->cell_padding['L'] - $this->cell_padding['R']) / ($ns?$ns:1)) * $this->k;
5809 if ($this->font_stretching != 100) {
5810 // word spacing (Tw) is affected by stretching
5811 $spacewidth /= ($this->font_stretching / 100);
5813 // set word spacing
5814 $rs .= sprintf('BT %.3F Tw ET ', $spacewidth);
5816 $width = $w - $this->cell_padding['L'] - $this->cell_padding['R'];
5818 // replace carriage return characters
5819 $txt2 = str_replace("\r", ' ', $txt2);
5820 switch ($align) {
5821 case 'C': {
5822 $dx = ($w - $width) / 2;
5823 break;
5825 case 'R': {
5826 if ($this->rtl) {
5827 $dx = $this->cell_padding['R'];
5828 } else {
5829 $dx = $w - $width - $this->cell_padding['R'];
5831 break;
5833 case 'L': {
5834 if ($this->rtl) {
5835 $dx = $w - $width - $this->cell_padding['L'];
5836 } else {
5837 $dx = $this->cell_padding['L'];
5839 break;
5841 case 'J':
5842 default: {
5843 if ($this->rtl) {
5844 $dx = $this->cell_padding['R'];
5845 } else {
5846 $dx = $this->cell_padding['L'];
5848 break;
5851 if ($this->rtl) {
5852 $xdx = $x - $dx - $width;
5853 } else {
5854 $xdx = $x + $dx;
5856 $xdk = $xdx * $k;
5857 // print text
5858 $s .= sprintf('BT %.2F %.2F Td [(%s)] TJ ET', $xdk, (($this->h - $basefonty) * $k), $txt2);
5859 if (isset($uniblock)) {
5860 // print overlapping characters as separate string
5861 $xshift = 0; // horizontal shift
5862 $ty = (($this->h - $basefonty + (0.2 * $this->FontSize)) * $k);
5863 $spw = (($w - $txwidth - $this->cell_padding['L'] - $this->cell_padding['R']) / ($ns?$ns:1));
5864 foreach ($uniblock as $uk => $uniarr) {
5865 if (($uk % 2) == 0) {
5866 // x space to skip
5867 if ($spacewidth != 0) {
5868 // justification shift
5869 $xshift += (count(array_keys($uniarr, 32)) * $spw);
5871 $xshift += $this->GetArrStringWidth($uniarr); // + shift justification
5872 } else {
5873 // character to print
5874 $topchr = $this->arrUTF8ToUTF16BE($uniarr, false);
5875 $topchr = $this->_escape($topchr);
5876 $s .= sprintf(' BT %.2F %.2F Td [(%s)] TJ ET', ($xdk + ($xshift * $k)), $ty, $topchr);
5880 if ($this->underline) {
5881 $s .= ' '.$this->_dounderlinew($xdx, $basefonty, $width);
5883 if ($this->linethrough) {
5884 $s .= ' '.$this->_dolinethroughw($xdx, $basefonty, $width);
5886 if ($this->overline) {
5887 $s .= ' '.$this->_dooverlinew($xdx, $basefonty, $width);
5889 if ($this->ColorFlag AND ($this->textrendermode < 4)) {
5890 $s .= ' Q';
5892 if ($link) {
5893 $this->Link($xdx, $yt, $width, ($this->FontAscent + $this->FontDescent), $link, $ns);
5896 // output cell
5897 if ($s) {
5898 // output cell
5899 $rs .= $s;
5900 if ($this->font_spacing != 0) {
5901 // reset font spacing mode
5902 $rs .= ' BT 0 Tc ET';
5904 if ($this->font_stretching != 100) {
5905 // reset font stretching mode
5906 $rs .= ' BT 100 Tz ET';
5909 // reset word spacing
5910 if (!$this->isUnicodeFont() AND ($align == 'J')) {
5911 $rs .= ' BT 0 Tw ET';
5913 // reset stretching and spacing
5914 $this->font_stretching = $prev_font_stretching;
5915 $this->font_spacing = $prev_font_spacing;
5916 $this->lasth = $h;
5917 if ($ln > 0) {
5918 //Go to the beginning of the next line
5919 $this->y = $y + $h + $this->cell_margin['B'];
5920 if ($ln == 1) {
5921 if ($this->rtl) {
5922 $this->x = $this->w - $this->rMargin;
5923 } else {
5924 $this->x = $this->lMargin;
5927 } else {
5928 // go left or right by case
5929 if ($this->rtl) {
5930 $this->x = $x - $w - $this->cell_margin['L'];
5931 } else {
5932 $this->x = $x + $w + $this->cell_margin['R'];
5935 $gstyles = ''.$this->linestyleWidth.' '.$this->linestyleCap.' '.$this->linestyleJoin.' '.$this->linestyleDash.' '.$this->DrawColor.' '.$this->FillColor."\n";
5936 $rs = $gstyles.$rs;
5937 $this->cell_padding = $prev_cell_padding;
5938 $this->cell_margin = $prev_cell_margin;
5939 return $rs;
5943 * Returns the code to draw the cell border
5944 * @param $x (float) X coordinate.
5945 * @param $y (float) Y coordinate.
5946 * @param $w (float) Cell width.
5947 * @param $h (float) Cell height.
5948 * @param $brd (mixed) Indicates if borders must be drawn around the cell. The value can be a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul> or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul> or an array of line styles for each border group - for example: array('LTRB' => array('width' => 2, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0)))
5949 * @return string containing cell border code
5950 * @protected
5951 * @see SetLineStyle()
5952 * @since 5.7.000 (2010-08-02)
5954 protected function getCellBorder($x, $y, $w, $h, $brd) {
5955 $s = ''; // string to be returned
5956 if (empty($brd)) {
5957 return $s;
5959 if ($brd == 1) {
5960 $brd = array('LRTB' => true);
5962 // calculate coordinates for border
5963 $k = $this->k;
5964 if ($this->rtl) {
5965 $xeL = ($x - $w) * $k;
5966 $xeR = $x * $k;
5967 } else {
5968 $xeL = $x * $k;
5969 $xeR = ($x + $w) * $k;
5971 $yeL = (($this->h - ($y + $h)) * $k);
5972 $yeT = (($this->h - $y) * $k);
5973 $xeT = $xeL;
5974 $xeB = $xeR;
5975 $yeR = $yeT;
5976 $yeB = $yeL;
5977 if (is_string($brd)) {
5978 // convert string to array
5979 $slen = strlen($brd);
5980 $newbrd = array();
5981 for ($i = 0; $i < $slen; ++$i) {
5982 $newbrd[$brd{$i}] = array('cap' => 'square', 'join' => 'miter');
5984 $brd = $newbrd;
5986 if (isset($brd['mode'])) {
5987 $mode = $brd['mode'];
5988 unset($brd['mode']);
5989 } else {
5990 $mode = 'normal';
5992 foreach ($brd as $border => $style) {
5993 if (is_array($style) AND !empty($style)) {
5994 // apply border style
5995 $prev_style = $this->linestyleWidth.' '.$this->linestyleCap.' '.$this->linestyleJoin.' '.$this->linestyleDash.' '.$this->DrawColor.' ';
5996 $s .= $this->SetLineStyle($style, true)."\n";
5998 switch ($mode) {
5999 case 'ext': {
6000 $off = (($this->LineWidth / 2) * $k);
6001 $xL = $xeL - $off;
6002 $xR = $xeR + $off;
6003 $yT = $yeT + $off;
6004 $yL = $yeL - $off;
6005 $xT = $xL;
6006 $xB = $xR;
6007 $yR = $yT;
6008 $yB = $yL;
6009 $w += $this->LineWidth;
6010 $h += $this->LineWidth;
6011 break;
6013 case 'int': {
6014 $off = ($this->LineWidth / 2) * $k;
6015 $xL = $xeL + $off;
6016 $xR = $xeR - $off;
6017 $yT = $yeT - $off;
6018 $yL = $yeL + $off;
6019 $xT = $xL;
6020 $xB = $xR;
6021 $yR = $yT;
6022 $yB = $yL;
6023 $w -= $this->LineWidth;
6024 $h -= $this->LineWidth;
6025 break;
6027 case 'normal':
6028 default: {
6029 $xL = $xeL;
6030 $xT = $xeT;
6031 $xB = $xeB;
6032 $xR = $xeR;
6033 $yL = $yeL;
6034 $yT = $yeT;
6035 $yB = $yeB;
6036 $yR = $yeR;
6037 break;
6040 // draw borders by case
6041 if (strlen($border) == 4) {
6042 $s .= sprintf('%.2F %.2F %.2F %.2F re S ', $xT, $yT, ($w * $k), (-$h * $k));
6043 } elseif (strlen($border) == 3) {
6044 if (strpos($border,'B') === false) { // LTR
6045 $s .= sprintf('%.2F %.2F m ', $xL, $yL);
6046 $s .= sprintf('%.2F %.2F l ', $xT, $yT);
6047 $s .= sprintf('%.2F %.2F l ', $xR, $yR);
6048 $s .= sprintf('%.2F %.2F l ', $xB, $yB);
6049 $s .= 'S ';
6050 } elseif (strpos($border,'L') === false) { // TRB
6051 $s .= sprintf('%.2F %.2F m ', $xT, $yT);
6052 $s .= sprintf('%.2F %.2F l ', $xR, $yR);
6053 $s .= sprintf('%.2F %.2F l ', $xB, $yB);
6054 $s .= sprintf('%.2F %.2F l ', $xL, $yL);
6055 $s .= 'S ';
6056 } elseif (strpos($border,'T') === false) { // RBL
6057 $s .= sprintf('%.2F %.2F m ', $xR, $yR);
6058 $s .= sprintf('%.2F %.2F l ', $xB, $yB);
6059 $s .= sprintf('%.2F %.2F l ', $xL, $yL);
6060 $s .= sprintf('%.2F %.2F l ', $xT, $yT);
6061 $s .= 'S ';
6062 } elseif (strpos($border,'R') === false) { // BLT
6063 $s .= sprintf('%.2F %.2F m ', $xB, $yB);
6064 $s .= sprintf('%.2F %.2F l ', $xL, $yL);
6065 $s .= sprintf('%.2F %.2F l ', $xT, $yT);
6066 $s .= sprintf('%.2F %.2F l ', $xR, $yR);
6067 $s .= 'S ';
6069 } elseif (strlen($border) == 2) {
6070 if ((strpos($border,'L') !== false) AND (strpos($border,'T') !== false)) { // LT
6071 $s .= sprintf('%.2F %.2F m ', $xL, $yL);
6072 $s .= sprintf('%.2F %.2F l ', $xT, $yT);
6073 $s .= sprintf('%.2F %.2F l ', $xR, $yR);
6074 $s .= 'S ';
6075 } elseif ((strpos($border,'T') !== false) AND (strpos($border,'R') !== false)) { // TR
6076 $s .= sprintf('%.2F %.2F m ', $xT, $yT);
6077 $s .= sprintf('%.2F %.2F l ', $xR, $yR);
6078 $s .= sprintf('%.2F %.2F l ', $xB, $yB);
6079 $s .= 'S ';
6080 } elseif ((strpos($border,'R') !== false) AND (strpos($border,'B') !== false)) { // RB
6081 $s .= sprintf('%.2F %.2F m ', $xR, $yR);
6082 $s .= sprintf('%.2F %.2F l ', $xB, $yB);
6083 $s .= sprintf('%.2F %.2F l ', $xL, $yL);
6084 $s .= 'S ';
6085 } elseif ((strpos($border,'B') !== false) AND (strpos($border,'L') !== false)) { // BL
6086 $s .= sprintf('%.2F %.2F m ', $xB, $yB);
6087 $s .= sprintf('%.2F %.2F l ', $xL, $yL);
6088 $s .= sprintf('%.2F %.2F l ', $xT, $yT);
6089 $s .= 'S ';
6090 } elseif ((strpos($border,'L') !== false) AND (strpos($border,'R') !== false)) { // LR
6091 $s .= sprintf('%.2F %.2F m ', $xL, $yL);
6092 $s .= sprintf('%.2F %.2F l ', $xT, $yT);
6093 $s .= 'S ';
6094 $s .= sprintf('%.2F %.2F m ', $xR, $yR);
6095 $s .= sprintf('%.2F %.2F l ', $xB, $yB);
6096 $s .= 'S ';
6097 } elseif ((strpos($border,'T') !== false) AND (strpos($border,'B') !== false)) { // TB
6098 $s .= sprintf('%.2F %.2F m ', $xT, $yT);
6099 $s .= sprintf('%.2F %.2F l ', $xR, $yR);
6100 $s .= 'S ';
6101 $s .= sprintf('%.2F %.2F m ', $xB, $yB);
6102 $s .= sprintf('%.2F %.2F l ', $xL, $yL);
6103 $s .= 'S ';
6105 } else { // strlen($border) == 1
6106 if (strpos($border,'L') !== false) { // L
6107 $s .= sprintf('%.2F %.2F m ', $xL, $yL);
6108 $s .= sprintf('%.2F %.2F l ', $xT, $yT);
6109 $s .= 'S ';
6110 } elseif (strpos($border,'T') !== false) { // T
6111 $s .= sprintf('%.2F %.2F m ', $xT, $yT);
6112 $s .= sprintf('%.2F %.2F l ', $xR, $yR);
6113 $s .= 'S ';
6114 } elseif (strpos($border,'R') !== false) { // R
6115 $s .= sprintf('%.2F %.2F m ', $xR, $yR);
6116 $s .= sprintf('%.2F %.2F l ', $xB, $yB);
6117 $s .= 'S ';
6118 } elseif (strpos($border,'B') !== false) { // B
6119 $s .= sprintf('%.2F %.2F m ', $xB, $yB);
6120 $s .= sprintf('%.2F %.2F l ', $xL, $yL);
6121 $s .= 'S ';
6124 if (is_array($style) AND !empty($style)) {
6125 // reset border style to previous value
6126 $s .= "\n".$this->linestyleWidth.' '.$this->linestyleCap.' '.$this->linestyleJoin.' '.$this->linestyleDash.' '.$this->DrawColor."\n";
6129 return $s;
6133 * This method allows printing text with line breaks.
6134 * 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 />
6135 * Text can be aligned, centered or justified. The cell block can be framed and the background painted.
6136 * @param $w (float) Width of cells. If 0, they extend up to the right margin of the page.
6137 * @param $h (float) Cell minimum height. The cell extends automatically if needed.
6138 * @param $txt (string) String to print
6139 * @param $border (mixed) Indicates if borders must be drawn around the cell. The value can be a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul> or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul> or an array of line styles for each border group - for example: array('LTRB' => array('width' => 2, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0)))
6140 * @param $align (string) Allows to center or align the text. Possible values are:<ul><li>L or empty string: left align</li><li>C: center</li><li>R: right align</li><li>J: justification (default value when $ishtml=false)</li></ul>
6141 * @param $fill (boolean) Indicates if the cell background must be painted (true) or transparent (false).
6142 * @param $ln (int) Indicates where the current position should go after the call. Possible values are:<ul><li>0: to the right</li><li>1: to the beginning of the next line [DEFAULT]</li><li>2: below</li></ul>
6143 * @param $x (float) x position in user units
6144 * @param $y (float) y position in user units
6145 * @param $reseth (boolean) if true reset the last cell height (default true).
6146 * @param $stretch (int) font stretch mode: <ul><li>0 = disabled</li><li>1 = horizontal scaling only if text is larger than cell width</li><li>2 = forced horizontal scaling to fit cell width</li><li>3 = character spacing only if text is larger than cell width</li><li>4 = forced character spacing to fit cell width</li></ul> General font stretching and scaling values will be preserved when possible.
6147 * @param $ishtml (boolean) set to true if $txt is HTML content (default = false).
6148 * @param $autopadding (boolean) if true, uses internal padding and automatically adjust it to account for line width.
6149 * @param $maxh (float) maximum height. It should be >= $h and less then remaining space to the bottom of the page, or 0 for disable this feature. This feature works only when $ishtml=false.
6150 * @param $valign (string) Vertical alignment of text (requires $maxh = $h > 0). Possible values are:<ul><li>T: TOP</li><li>M: middle</li><li>B: bottom</li></ul>. This feature works only when $ishtml=false.
6151 * @param $fitcell (boolean) if true attempt to fit all the text within the cell by reducing the font size.
6152 * @return int Return the number of cells or 1 for html mode.
6153 * @public
6154 * @since 1.3
6155 * @see SetFont(), SetDrawColor(), SetFillColor(), SetTextColor(), SetLineWidth(), Cell(), Write(), SetAutoPageBreak()
6157 public function MultiCell($w, $h, $txt, $border=0, $align='J', $fill=false, $ln=1, $x='', $y='', $reseth=true, $stretch=0, $ishtml=false, $autopadding=true, $maxh=0, $valign='T', $fitcell=false) {
6158 $prev_cell_margin = $this->cell_margin;
6159 $prev_cell_padding = $this->cell_padding;
6160 // adjust internal padding
6161 $this->adjustCellPadding($border);
6162 $mc_padding = $this->cell_padding;
6163 $mc_margin = $this->cell_margin;
6164 $this->cell_padding['T'] = 0;
6165 $this->cell_padding['B'] = 0;
6166 $this->setCellMargins(0, 0, 0, 0);
6167 if ($this->empty_string($this->lasth) OR $reseth) {
6168 // reset row height
6169 $this->resetLastH();
6171 if (!$this->empty_string($y)) {
6172 $this->SetY($y);
6173 } else {
6174 $y = $this->GetY();
6176 $resth = 0;
6177 if (($this->inPageBody()) AND (($y + $h + $mc_margin['T'] + $mc_margin['B']) > $this->PageBreakTrigger)) {
6178 // spit cell in more pages/columns
6179 $newh = $this->PageBreakTrigger - $y;
6180 $resth = $h - $newh; // cell to be printed on the next page/column
6181 $h = $newh;
6183 // get current page number
6184 $startpage = $this->page;
6185 // get current column
6186 $startcolumn = $this->current_column;
6187 if (!$this->empty_string($x)) {
6188 $this->SetX($x);
6189 } else {
6190 $x = $this->GetX();
6192 // check page for no-write regions and adapt page margins if necessary
6193 list($x, $y) = $this->checkPageRegions(0, $x, $y);
6194 // apply margins
6195 $oy = $y + $mc_margin['T'];
6196 if ($this->rtl) {
6197 $ox = $this->w - $x - $mc_margin['R'];
6198 } else {
6199 $ox = $x + $mc_margin['L'];
6201 $this->x = $ox;
6202 $this->y = $oy;
6203 // set width
6204 if ($this->empty_string($w) OR ($w <= 0)) {
6205 if ($this->rtl) {
6206 $w = $this->x - $this->lMargin - $mc_margin['L'];
6207 } else {
6208 $w = $this->w - $this->x - $this->rMargin - $mc_margin['R'];
6211 // store original margin values
6212 $lMargin = $this->lMargin;
6213 $rMargin = $this->rMargin;
6214 if ($this->rtl) {
6215 $this->rMargin = $this->w - $this->x;
6216 $this->lMargin = $this->x - $w;
6217 } else {
6218 $this->lMargin = $this->x;
6219 $this->rMargin = $this->w - $this->x - $w;
6221 if ($autopadding) {
6222 // add top padding
6223 $this->y += $mc_padding['T'];
6225 if ($ishtml) { // ******* Write HTML text
6226 $this->writeHTML($txt, true, false, $reseth, true, $align);
6227 $nl = 1;
6228 } else { // ******* Write simple text
6229 $prev_FontSizePt = $this->FontSizePt;
6230 // vertical alignment
6231 if ($maxh > 0) {
6232 // get text height
6233 $text_height = $this->getStringHeight($w, $txt, $reseth, $autopadding, $mc_padding, $border);
6234 if ($fitcell) {
6235 // try to reduce font size to fit text on cell (use a quick search algorithm)
6236 $fmin = 1;
6237 $fmax = $this->FontSizePt;
6238 $prev_text_height = $text_height;
6239 $maxit = 100; // max number of iterations
6240 while ($maxit > 0) {
6241 $fmid = (($fmax + $fmin) / 2);
6242 $this->SetFontSize($fmid, false);
6243 $this->resetLastH();
6244 $text_height = $this->getStringHeight($w, $txt, $reseth, $autopadding, $mc_padding, $border);
6245 if (($text_height == $maxh) OR (($text_height < $maxh) AND ($fmin >= ($fmax - 0.01)))) {
6246 break;
6247 } elseif ($text_height < $maxh) {
6248 $fmin = $fmid;
6249 } else {
6250 $fmax = $fmid;
6252 --$maxit;
6254 $this->SetFontSize($this->FontSizePt);
6256 if ($text_height < $maxh) {
6257 if ($valign == 'M') {
6258 // text vertically centered
6259 $this->y += (($maxh - $text_height) / 2);
6260 } elseif ($valign == 'B') {
6261 // text vertically aligned on bottom
6262 $this->y += ($maxh - $text_height);
6266 $nl = $this->Write($this->lasth, $txt, '', 0, $align, true, $stretch, false, true, $maxh, 0, $mc_margin);
6267 if ($fitcell) {
6268 // restore font size
6269 $this->SetFontSize($prev_FontSizePt);
6272 if ($autopadding) {
6273 // add bottom padding
6274 $this->y += $mc_padding['B'];
6276 // Get end-of-text Y position
6277 $currentY = $this->y;
6278 // get latest page number
6279 $endpage = $this->page;
6280 if ($resth > 0) {
6281 $skip = ($endpage - $startpage);
6282 $tmpresth = $resth;
6283 while ($tmpresth > 0) {
6284 if ($skip <= 0) {
6285 // add a page (or trig AcceptPageBreak() for multicolumn mode)
6286 $this->checkPageBreak($this->PageBreakTrigger + 1);
6288 if ($this->num_columns > 1) {
6289 $tmpresth -= ($this->h - $this->y - $this->bMargin);
6290 } else {
6291 $tmpresth -= ($this->h - $this->tMargin - $this->bMargin);
6293 --$skip;
6295 $currentY = $this->y;
6296 $endpage = $this->page;
6298 // get latest column
6299 $endcolumn = $this->current_column;
6300 if ($this->num_columns == 0) {
6301 $this->num_columns = 1;
6303 // get border modes
6304 $border_start = $this->getBorderMode($border, $position='start');
6305 $border_end = $this->getBorderMode($border, $position='end');
6306 $border_middle = $this->getBorderMode($border, $position='middle');
6307 // design borders around HTML cells.
6308 for ($page = $startpage; $page <= $endpage; ++$page) { // for each page
6309 $ccode = '';
6310 $this->setPage($page);
6311 if ($this->num_columns < 2) {
6312 // single-column mode
6313 $this->SetX($x);
6314 $this->y = $this->tMargin;
6316 // account for margin changes
6317 if ($page > $startpage) {
6318 if (($this->rtl) AND ($this->pagedim[$page]['orm'] != $this->pagedim[$startpage]['orm'])) {
6319 $this->x -= ($this->pagedim[$page]['orm'] - $this->pagedim[$startpage]['orm']);
6320 } elseif ((!$this->rtl) AND ($this->pagedim[$page]['olm'] != $this->pagedim[$startpage]['olm'])) {
6321 $this->x += ($this->pagedim[$page]['olm'] - $this->pagedim[$startpage]['olm']);
6324 if ($startpage == $endpage) {
6325 // single page
6326 for ($column = $startcolumn; $column <= $endcolumn; ++$column) { // for each column
6327 $this->selectColumn($column);
6328 if ($this->rtl) {
6329 $this->x -= $mc_margin['R'];
6330 } else {
6331 $this->x += $mc_margin['L'];
6333 if ($startcolumn == $endcolumn) { // single column
6334 $cborder = $border;
6335 $h = max($h, ($currentY - $oy));
6336 $this->y = $oy;
6337 } elseif ($column == $startcolumn) { // first column
6338 $cborder = $border_start;
6339 $this->y = $oy;
6340 $h = $this->h - $this->y - $this->bMargin;
6341 } elseif ($column == $endcolumn) { // end column
6342 $cborder = $border_end;
6343 $h = $currentY - $this->y;
6344 if ($resth > $h) {
6345 $h = $resth;
6347 } else { // middle column
6348 $cborder = $border_middle;
6349 $h = $this->h - $this->y - $this->bMargin;
6350 $resth -= $h;
6352 $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
6353 } // end for each column
6354 } elseif ($page == $startpage) { // first page
6355 for ($column = $startcolumn; $column < $this->num_columns; ++$column) { // for each column
6356 $this->selectColumn($column);
6357 if ($this->rtl) {
6358 $this->x -= $mc_margin['R'];
6359 } else {
6360 $this->x += $mc_margin['L'];
6362 if ($column == $startcolumn) { // first column
6363 $cborder = $border_start;
6364 $this->y = $oy;
6365 $h = $this->h - $this->y - $this->bMargin;
6366 } else { // middle column
6367 $cborder = $border_middle;
6368 $h = $this->h - $this->y - $this->bMargin;
6369 $resth -= $h;
6371 $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
6372 } // end for each column
6373 } elseif ($page == $endpage) { // last page
6374 for ($column = 0; $column <= $endcolumn; ++$column) { // for each column
6375 $this->selectColumn($column);
6376 if ($this->rtl) {
6377 $this->x -= $mc_margin['R'];
6378 } else {
6379 $this->x += $mc_margin['L'];
6381 if ($column == $endcolumn) {
6382 // end column
6383 $cborder = $border_end;
6384 $h = $currentY - $this->y;
6385 if ($resth > $h) {
6386 $h = $resth;
6388 } else {
6389 // middle column
6390 $cborder = $border_middle;
6391 $h = $this->h - $this->y - $this->bMargin;
6392 $resth -= $h;
6394 $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
6395 } // end for each column
6396 } else { // middle page
6397 for ($column = 0; $column < $this->num_columns; ++$column) { // for each column
6398 $this->selectColumn($column);
6399 if ($this->rtl) {
6400 $this->x -= $mc_margin['R'];
6401 } else {
6402 $this->x += $mc_margin['L'];
6404 $cborder = $border_middle;
6405 $h = $this->h - $this->y - $this->bMargin;
6406 $resth -= $h;
6407 $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
6408 } // end for each column
6410 if ($cborder OR $fill) {
6411 $offsetlen = strlen($ccode);
6412 // draw border and fill
6413 if ($this->inxobj) {
6414 // we are inside an XObject template
6415 if (end($this->xobjects[$this->xobjid]['transfmrk']) !== false) {
6416 $pagemarkkey = key($this->xobjects[$this->xobjid]['transfmrk']);
6417 $pagemark = $this->xobjects[$this->xobjid]['transfmrk'][$pagemarkkey];
6418 $this->xobjects[$this->xobjid]['transfmrk'][$pagemarkkey] += $offsetlen;
6419 } else {
6420 $pagemark = $this->xobjects[$this->xobjid]['intmrk'];
6421 $this->xobjects[$this->xobjid]['intmrk'] += $offsetlen;
6423 $pagebuff = $this->xobjects[$this->xobjid]['outdata'];
6424 $pstart = substr($pagebuff, 0, $pagemark);
6425 $pend = substr($pagebuff, $pagemark);
6426 $this->xobjects[$this->xobjid]['outdata'] = $pstart.$ccode.$pend;
6427 } else {
6428 if (end($this->transfmrk[$this->page]) !== false) {
6429 $pagemarkkey = key($this->transfmrk[$this->page]);
6430 $pagemark = $this->transfmrk[$this->page][$pagemarkkey];
6431 $this->transfmrk[$this->page][$pagemarkkey] += $offsetlen;
6432 } elseif ($this->InFooter) {
6433 $pagemark = $this->footerpos[$this->page];
6434 $this->footerpos[$this->page] += $offsetlen;
6435 } else {
6436 $pagemark = $this->intmrk[$this->page];
6437 $this->intmrk[$this->page] += $offsetlen;
6439 $pagebuff = $this->getPageBuffer($this->page);
6440 $pstart = substr($pagebuff, 0, $pagemark);
6441 $pend = substr($pagebuff, $pagemark);
6442 $this->setPageBuffer($this->page, $pstart.$ccode.$pend);
6445 } // end for each page
6446 // Get end-of-cell Y position
6447 $currentY = $this->GetY();
6448 // restore original margin values
6449 $this->SetLeftMargin($lMargin);
6450 $this->SetRightMargin($rMargin);
6451 if ($ln > 0) {
6452 //Go to the beginning of the next line
6453 $this->SetY($currentY + $mc_margin['B']);
6454 if ($ln == 2) {
6455 $this->SetX($x + $w + $mc_margin['L'] + $mc_margin['R']);
6457 } else {
6458 // go left or right by case
6459 $this->setPage($startpage);
6460 $this->y = $y;
6461 $this->SetX($x + $w + $mc_margin['L'] + $mc_margin['R']);
6463 $this->setContentMark();
6464 $this->cell_padding = $prev_cell_padding;
6465 $this->cell_margin = $prev_cell_margin;
6466 return $nl;
6470 * Get the border mode accounting for multicell position (opens bottom side of multicell crossing pages)
6471 * @param $brd (mixed) Indicates if borders must be drawn around the cell block. 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: array('LTRB' => array('width' => 2, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0)))
6472 * @param $position (string) multicell position: 'start', 'middle', 'end'
6473 * @return border mode array
6474 * @protected
6475 * @since 4.4.002 (2008-12-09)
6477 protected function getBorderMode($brd, $position='start') {
6478 if ((!$this->opencell) OR empty($brd)) {
6479 return $brd;
6481 if ($brd == 1) {
6482 $brd = 'LTRB';
6484 if (is_string($brd)) {
6485 // convert string to array
6486 $slen = strlen($brd);
6487 $newbrd = array();
6488 for ($i = 0; $i < $slen; ++$i) {
6489 $newbrd[$brd{$i}] = array('cap' => 'square', 'join' => 'miter');
6491 $brd = $newbrd;
6493 foreach ($brd as $border => $style) {
6494 switch ($position) {
6495 case 'start': {
6496 if (strpos($border, 'B') !== false) {
6497 // remove bottom line
6498 $newkey = str_replace('B', '', $border);
6499 if (strlen($newkey) > 0) {
6500 $brd[$newkey] = $style;
6502 unset($brd[$border]);
6504 break;
6506 case 'middle': {
6507 if (strpos($border, 'B') !== false) {
6508 // remove bottom line
6509 $newkey = str_replace('B', '', $border);
6510 if (strlen($newkey) > 0) {
6511 $brd[$newkey] = $style;
6513 unset($brd[$border]);
6514 $border = $newkey;
6516 if (strpos($border, 'T') !== false) {
6517 // remove bottom line
6518 $newkey = str_replace('T', '', $border);
6519 if (strlen($newkey) > 0) {
6520 $brd[$newkey] = $style;
6522 unset($brd[$border]);
6524 break;
6526 case 'end': {
6527 if (strpos($border, 'T') !== false) {
6528 // remove bottom line
6529 $newkey = str_replace('T', '', $border);
6530 if (strlen($newkey) > 0) {
6531 $brd[$newkey] = $style;
6533 unset($brd[$border]);
6535 break;
6539 return $brd;
6543 * This method return the estimated number of lines for print a simple text string using Multicell() method.
6544 * @param $txt (string) String for calculating his height
6545 * @param $w (float) Width of cells. If 0, they extend up to the right margin of the page.
6546 * @param $reseth (boolean) if true reset the last cell height (default false).
6547 * @param $autopadding (boolean) if true, uses internal padding and automatically adjust it to account for line width (default true).
6548 * @param $cellpadding (float) Internal cell padding, if empty uses default cell padding.
6549 * @param $border (mixed) Indicates if borders must be drawn around the cell. The value can be a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul> or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul> or an array of line styles for each border group - for example: array('LTRB' => array('width' => 2, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0)))
6550 * @return float Return the minimal height needed for multicell method for printing the $txt param.
6551 * @author Alexander Escalona Fernández, Nicola Asuni
6552 * @public
6553 * @since 4.5.011
6555 public function getNumLines($txt, $w=0, $reseth=false, $autopadding=true, $cellpadding='', $border=0) {
6556 if ($txt === '') {
6557 // empty string
6558 return 1;
6560 // adjust internal padding
6561 $prev_cell_padding = $this->cell_padding;
6562 $prev_lasth = $this->lasth;
6563 if (is_array($cellpadding)) {
6564 $this->cell_padding = $cellpadding;
6566 $this->adjustCellPadding($border);
6567 if ($this->empty_string($w) OR ($w <= 0)) {
6568 if ($this->rtl) {
6569 $w = $this->x - $this->lMargin;
6570 } else {
6571 $w = $this->w - $this->rMargin - $this->x;
6574 $wmax = $w - $this->cell_padding['L'] - $this->cell_padding['R'];
6575 if ($reseth) {
6576 // reset row height
6577 $this->resetLastH();
6579 $lines = 1;
6580 $sum = 0;
6581 $chars = $this->utf8Bidi($this->UTF8StringToArray($txt), $txt, $this->tmprtl);
6582 $charsWidth = $this->GetArrStringWidth($chars, '', '', 0, true);
6583 $length = count($chars);
6584 $lastSeparator = -1;
6585 for ($i = 0; $i < $length; ++$i) {
6586 $charWidth = $charsWidth[$i];
6587 if (preg_match($this->re_spaces, $this->unichr($chars[$i]))) {
6588 $lastSeparator = $i;
6590 if ((($sum + $charWidth) > $wmax) OR ($chars[$i] == 10)) {
6591 ++$lines;
6592 if ($lastSeparator != -1) {
6593 $i = $lastSeparator;
6594 $lastSeparator = -1;
6595 $sum = 0;
6596 } else {
6597 $sum = $charWidth;
6599 } else {
6600 $sum += $charWidth;
6603 if ($chars[($length - 1)] == 10) {
6604 --$lines;
6606 $this->cell_padding = $prev_cell_padding;
6607 $this->lasth = $prev_lasth;
6608 return $lines;
6612 * This method return the estimated needed height for print a simple text string in Multicell() method.
6613 * Generally, if you want to know the exact height for a block of content you can use the following alternative technique:
6614 * @pre
6615 * // store current object
6616 * $pdf->startTransaction();
6617 * // store starting values
6618 * $start_y = $pdf->GetY();
6619 * $start_page = $pdf->getPage();
6620 * // call your printing functions with your parameters
6621 * // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
6622 * $pdf->MultiCell($w=0, $h=0, $txt, $border=1, $align='L', $fill=false, $ln=1, $x='', $y='', $reseth=true, $stretch=0, $ishtml=false, $autopadding=true, $maxh=0);
6623 * // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
6624 * // get the new Y
6625 * $end_y = $pdf->GetY();
6626 * $end_page = $pdf->getPage();
6627 * // calculate height
6628 * $height = 0;
6629 * if ($end_page == $start_page) {
6630 * $height = $end_y - $start_y;
6631 * } else {
6632 * for ($page=$start_page; $page <= $end_page; ++$page) {
6633 * $this->setPage($page);
6634 * if ($page == $start_page) {
6635 * // first page
6636 * $height = $this->h - $start_y - $this->bMargin;
6637 * } elseif ($page == $end_page) {
6638 * // last page
6639 * $height = $end_y - $this->tMargin;
6640 * } else {
6641 * $height = $this->h - $this->tMargin - $this->bMargin;
6645 * // restore previous object
6646 * $pdf = $pdf->rollbackTransaction();
6648 * @param $w (float) Width of cells. If 0, they extend up to the right margin of the page.
6649 * @param $txt (string) String for calculating his height
6650 * @param $reseth (boolean) if true reset the last cell height (default false).
6651 * @param $autopadding (boolean) if true, uses internal padding and automatically adjust it to account for line width (default true).
6652 * @param $cellpadding (float) Internal cell padding, if empty uses default cell padding.
6653 * @param $border (mixed) Indicates if borders must be drawn around the cell. The value can be a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul> or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul> or an array of line styles for each border group - for example: array('LTRB' => array('width' => 2, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0)))
6654 * @return float Return the minimal height needed for multicell method for printing the $txt param.
6655 * @author Nicola Asuni, Alexander Escalona Fernández
6656 * @public
6658 public function getStringHeight($w, $txt, $reseth=false, $autopadding=true, $cellpadding='', $border=0) {
6659 // adjust internal padding
6660 $prev_cell_padding = $this->cell_padding;
6661 $prev_lasth = $this->lasth;
6662 if (is_array($cellpadding)) {
6663 $this->cell_padding = $cellpadding;
6665 $this->adjustCellPadding($border);
6666 $lines = $this->getNumLines($txt, $w, $reseth, $autopadding, $cellpadding, $border);
6667 $height = $lines * ($this->FontSize * $this->cell_height_ratio);
6668 if ($autopadding) {
6669 // add top and bottom padding
6670 $height += ($this->cell_padding['T'] + $this->cell_padding['B']);
6672 $this->cell_padding = $prev_cell_padding;
6673 $this->lasth = $prev_lasth;
6674 return $height;
6678 * This method prints text from the current position.<br />
6679 * @param $h (float) Line height
6680 * @param $txt (string) String to print
6681 * @param $link (mixed) URL or identifier returned by AddLink()
6682 * @param $fill (boolean) Indicates if the cell background must be painted (true) or transparent (false).
6683 * @param $align (string) Allows to center or align the text. Possible values are:<ul><li>L or empty string: left align (default value)</li><li>C: center</li><li>R: right align</li><li>J: justify</li></ul>
6684 * @param $ln (boolean) if true set cursor at the bottom of the line, otherwise set cursor at the top of the line.
6685 * @param $stretch (int) font stretch mode: <ul><li>0 = disabled</li><li>1 = horizontal scaling only if text is larger than cell width</li><li>2 = forced horizontal scaling to fit cell width</li><li>3 = character spacing only if text is larger than cell width</li><li>4 = forced character spacing to fit cell width</li></ul> General font stretching and scaling values will be preserved when possible.
6686 * @param $firstline (boolean) if true prints only the first line and return the remaining string.
6687 * @param $firstblock (boolean) if true the string is the starting of a line.
6688 * @param $maxh (float) maximum height. The remaining unprinted text will be returned. It should be >= $h and less then remaining space to the bottom of the page, or 0 for disable this feature.
6689 * @param $wadj (float) first line width will be reduced by this amount (used in HTML mode).
6690 * @param $margin (array) margin array of the parent container
6691 * @return mixed Return the number of cells or the remaining string if $firstline = true.
6692 * @public
6693 * @since 1.5
6695 public function Write($h, $txt, $link='', $fill=false, $align='', $ln=false, $stretch=0, $firstline=false, $firstblock=false, $maxh=0, $wadj=0, $margin='') {
6696 // check page for no-write regions and adapt page margins if necessary
6697 list($this->x, $this->y) = $this->checkPageRegions($h, $this->x, $this->y);
6698 if (strlen($txt) == 0) {
6699 // fix empty text
6700 $txt = ' ';
6702 if ($margin === '') {
6703 // set default margins
6704 $margin = $this->cell_margin;
6706 // remove carriage returns
6707 $s = str_replace("\r", '', $txt);
6708 // check if string contains arabic text
6709 if (preg_match($this->unicode->uni_RE_PATTERN_ARABIC, $s)) {
6710 $arabic = true;
6711 } else {
6712 $arabic = false;
6714 // check if string contains RTL text
6715 if ($arabic OR ($this->tmprtl == 'R') OR preg_match($this->unicode->uni_RE_PATTERN_RTL, $s)) {
6716 $rtlmode = true;
6717 } else {
6718 $rtlmode = false;
6720 // get a char width
6721 $chrwidth = $this->GetCharWidth(46); // dot character
6722 // get array of unicode values
6723 $chars = $this->UTF8StringToArray($s);
6724 // get array of chars
6725 $uchars = $this->UTF8ArrayToUniArray($chars);
6726 // get the number of characters
6727 $nb = count($chars);
6728 // replacement for SHY character (minus symbol)
6729 $shy_replacement = 45;
6730 $shy_replacement_char = $this->unichr($shy_replacement);
6731 // widht for SHY replacement
6732 $shy_replacement_width = $this->GetCharWidth($shy_replacement);
6733 // max Y
6734 $maxy = $this->y + $maxh - $h - $this->cell_padding['T'] - $this->cell_padding['B'];
6735 // page width
6736 $pw = $w = $this->w - $this->lMargin - $this->rMargin;
6737 // calculate remaining line width ($w)
6738 if ($this->rtl) {
6739 $w = $this->x - $this->lMargin;
6740 } else {
6741 $w = $this->w - $this->rMargin - $this->x;
6743 // max column width
6744 $wmax = $w - $wadj;
6745 if (!$firstline) {
6746 $wmax -= ($this->cell_padding['L'] + $this->cell_padding['R']);
6748 if ((!$firstline) AND (($chrwidth > $wmax) OR ($this->GetCharWidth($chars[0]) > $wmax))) {
6749 // a single character do not fit on column
6750 return '';
6752 // minimum row height
6753 $row_height = max($h, $this->FontSize * $this->cell_height_ratio);
6754 $start_page = $this->page;
6755 $i = 0; // character position
6756 $j = 0; // current starting position
6757 $sep = -1; // position of the last blank space
6758 $shy = false; // true if the last blank is a soft hypen (SHY)
6759 $l = 0; // current string length
6760 $nl = 0; //number of lines
6761 $linebreak = false;
6762 $pc = 0; // previous character
6763 // for each character
6764 while ($i < $nb) {
6765 if (($maxh > 0) AND ($this->y >= $maxy) ) {
6766 break;
6768 //Get the current character
6769 $c = $chars[$i];
6770 if ($c == 10) { // 10 = "\n" = new line
6771 //Explicit line break
6772 if ($align == 'J') {
6773 if ($this->rtl) {
6774 $talign = 'R';
6775 } else {
6776 $talign = 'L';
6778 } else {
6779 $talign = $align;
6781 $tmpstr = $this->UniArrSubString($uchars, $j, $i);
6782 if ($firstline) {
6783 $startx = $this->x;
6784 $tmparr = array_slice($chars, $j, ($i - $j));
6785 if ($rtlmode) {
6786 $tmparr = $this->utf8Bidi($tmparr, $tmpstr, $this->tmprtl);
6788 $linew = $this->GetArrStringWidth($tmparr);
6789 unset($tmparr);
6790 if ($this->rtl) {
6791 $this->endlinex = $startx - $linew;
6792 } else {
6793 $this->endlinex = $startx + $linew;
6795 $w = $linew;
6796 $tmpcellpadding = $this->cell_padding;
6797 if ($maxh == 0) {
6798 $this->SetCellPadding(0);
6801 if ($firstblock AND $this->isRTLTextDir()) {
6802 $tmpstr = $this->stringRightTrim($tmpstr);
6804 // Skip newlines at the begining of a page or column
6805 if (!empty($tmpstr) OR ($this->y < ($this->PageBreakTrigger - $row_height))) {
6806 $this->Cell($w, $h, $tmpstr, 0, 1, $talign, $fill, $link, $stretch);
6808 unset($tmpstr);
6809 if ($firstline) {
6810 $this->cell_padding = $tmpcellpadding;
6811 return ($this->UniArrSubString($uchars, $i));
6813 ++$nl;
6814 $j = $i + 1;
6815 $l = 0;
6816 $sep = -1;
6817 $shy = false;
6818 // account for margin changes
6819 if ((($this->y + $this->lasth) > $this->PageBreakTrigger) AND ($this->inPageBody())) {
6820 $this->AcceptPageBreak();
6821 if ($this->rtl) {
6822 $this->x -= $margin['R'];
6823 } else {
6824 $this->x += $margin['L'];
6826 $this->lMargin += $margin['L'];
6827 $this->rMargin += $margin['R'];
6829 $w = $this->getRemainingWidth();
6830 $wmax = $w - $this->cell_padding['L'] - $this->cell_padding['R'];
6831 } else {
6832 // 160 is the non-breaking space.
6833 // 173 is SHY (Soft Hypen).
6834 // \p{Z} or \p{Separator}: any kind of Unicode whitespace or invisible separator.
6835 // \p{Lo} or \p{Other_Letter}: a Unicode letter or ideograph that does not have lowercase and uppercase variants.
6836 // \p{Lo} is needed because Chinese characters are packed next to each other without spaces in between.
6837 if (($c != 160) AND (($c == 173) OR preg_match($this->re_spaces, $this->unichr($c)))) {
6838 // update last blank space position
6839 $sep = $i;
6840 // check if is a SHY
6841 if ($c == 173) {
6842 $shy = true;
6843 if ($pc == 45) {
6844 $tmp_shy_replacement_width = 0;
6845 $tmp_shy_replacement_char = '';
6846 } else {
6847 $tmp_shy_replacement_width = $shy_replacement_width;
6848 $tmp_shy_replacement_char = $shy_replacement_char;
6850 } else {
6851 $shy = false;
6854 // update string length
6855 if ($this->isUnicodeFont() AND ($arabic)) {
6856 // with bidirectional algorithm some chars may be changed affecting the line length
6857 // *** very slow ***
6858 $l = $this->GetArrStringWidth($this->utf8Bidi(array_slice($chars, $j, ($i - $j)), '', $this->tmprtl));
6859 } else {
6860 $l += $this->GetCharWidth($c);
6862 if (($l > $wmax) OR (($c == 173) AND (($l + $tmp_shy_replacement_width) > $wmax)) ) {
6863 // we have reached the end of column
6864 if ($sep == -1) {
6865 // check if the line was already started
6866 if (($this->rtl AND ($this->x <= ($this->w - $this->rMargin - $chrwidth)))
6867 OR ((!$this->rtl) AND ($this->x >= ($this->lMargin + $chrwidth)))) {
6868 // print a void cell and go to next line
6869 $this->Cell($w, $h, '', 0, 1);
6870 $linebreak = true;
6871 if ($firstline) {
6872 return ($this->UniArrSubString($uchars, $j));
6874 } else {
6875 // truncate the word because do not fit on column
6876 $tmpstr = $this->UniArrSubString($uchars, $j, $i);
6877 if ($firstline) {
6878 $startx = $this->x;
6879 $tmparr = array_slice($chars, $j, ($i - $j));
6880 if ($rtlmode) {
6881 $tmparr = $this->utf8Bidi($tmparr, $tmpstr, $this->tmprtl);
6883 $linew = $this->GetArrStringWidth($tmparr);
6884 unset($tmparr);
6885 if ($this->rtl) {
6886 $this->endlinex = $startx - $linew;
6887 } else {
6888 $this->endlinex = $startx + $linew;
6890 $w = $linew;
6891 $tmpcellpadding = $this->cell_padding;
6892 if ($maxh == 0) {
6893 $this->SetCellPadding(0);
6896 if ($firstblock AND $this->isRTLTextDir()) {
6897 $tmpstr = $this->stringRightTrim($tmpstr);
6899 $this->Cell($w, $h, $tmpstr, 0, 1, $align, $fill, $link, $stretch);
6900 unset($tmpstr);
6901 if ($firstline) {
6902 $this->cell_padding = $tmpcellpadding;
6903 return ($this->UniArrSubString($uchars, $i));
6905 $j = $i;
6906 --$i;
6908 } else {
6909 // word wrapping
6910 if ($this->rtl AND (!$firstblock) AND ($sep < $i)) {
6911 $endspace = 1;
6912 } else {
6913 $endspace = 0;
6915 // check the length of the next string
6916 $strrest = $this->UniArrSubString($uchars, ($sep + $endspace));
6917 $nextstr = preg_split('/'.$this->re_space['p'].'/'.$this->re_space['m'], $this->stringTrim($strrest));
6918 if (isset($nextstr[0]) AND ($this->GetStringWidth($nextstr[0]) > $pw)) {
6919 // truncate the word because do not fit on a full page width
6920 $tmpstr = $this->UniArrSubString($uchars, $j, $i);
6921 if ($firstline) {
6922 $startx = $this->x;
6923 $tmparr = array_slice($chars, $j, ($i - $j));
6924 if ($rtlmode) {
6925 $tmparr = $this->utf8Bidi($tmparr, $tmpstr, $this->tmprtl);
6927 $linew = $this->GetArrStringWidth($tmparr);
6928 unset($tmparr);
6929 if ($this->rtl) {
6930 $this->endlinex = $startx - $linew;
6931 } else {
6932 $this->endlinex = $startx + $linew;
6934 $w = $linew;
6935 $tmpcellpadding = $this->cell_padding;
6936 if ($maxh == 0) {
6937 $this->SetCellPadding(0);
6940 if ($firstblock AND $this->isRTLTextDir()) {
6941 $tmpstr = $this->stringRightTrim($tmpstr);
6943 $this->Cell($w, $h, $tmpstr, 0, 1, $align, $fill, $link, $stretch);
6944 unset($tmpstr);
6945 if ($firstline) {
6946 $this->cell_padding = $tmpcellpadding;
6947 return ($this->UniArrSubString($uchars, $i));
6949 $j = $i;
6950 --$i;
6951 } else {
6952 // word wrapping
6953 if ($shy) {
6954 // add hypen (minus symbol) at the end of the line
6955 $shy_width = $tmp_shy_replacement_width;
6956 if ($this->rtl) {
6957 $shy_char_left = $tmp_shy_replacement_char;
6958 $shy_char_right = '';
6959 } else {
6960 $shy_char_left = '';
6961 $shy_char_right = $tmp_shy_replacement_char;
6963 } else {
6964 $shy_width = 0;
6965 $shy_char_left = '';
6966 $shy_char_right = '';
6968 $tmpstr = $this->UniArrSubString($uchars, $j, ($sep + $endspace));
6969 if ($firstline) {
6970 $startx = $this->x;
6971 $tmparr = array_slice($chars, $j, (($sep + $endspace) - $j));
6972 if ($rtlmode) {
6973 $tmparr = $this->utf8Bidi($tmparr, $tmpstr, $this->tmprtl);
6975 $linew = $this->GetArrStringWidth($tmparr);
6976 unset($tmparr);
6977 if ($this->rtl) {
6978 $this->endlinex = $startx - $linew - $shy_width;
6979 } else {
6980 $this->endlinex = $startx + $linew + $shy_width;
6982 $w = $linew;
6983 $tmpcellpadding = $this->cell_padding;
6984 if ($maxh == 0) {
6985 $this->SetCellPadding(0);
6988 // print the line
6989 if ($firstblock AND $this->isRTLTextDir()) {
6990 $tmpstr = $this->stringRightTrim($tmpstr);
6992 $this->Cell($w, $h, $shy_char_left.$tmpstr.$shy_char_right, 0, 1, $align, $fill, $link, $stretch);
6993 unset($tmpstr);
6994 if ($firstline) {
6995 // return the remaining text
6996 $this->cell_padding = $tmpcellpadding;
6997 return ($this->UniArrSubString($uchars, ($sep + $endspace)));
6999 $i = $sep;
7000 $sep = -1;
7001 $shy = false;
7002 $j = ($i+1);
7005 // account for margin changes
7006 if ((($this->y + $this->lasth) > $this->PageBreakTrigger) AND ($this->inPageBody())) {
7007 $this->AcceptPageBreak();
7008 if ($this->rtl) {
7009 $this->x -= $margin['R'];
7010 } else {
7011 $this->x += $margin['L'];
7013 $this->lMargin += $margin['L'];
7014 $this->rMargin += $margin['R'];
7016 $w = $this->getRemainingWidth();
7017 $wmax = $w - $this->cell_padding['L'] - $this->cell_padding['R'];
7018 if ($linebreak) {
7019 $linebreak = false;
7020 } else {
7021 ++$nl;
7022 $l = 0;
7026 // save last character
7027 $pc = $c;
7028 ++$i;
7029 } // end while i < nb
7030 // print last substring (if any)
7031 if ($l > 0) {
7032 switch ($align) {
7033 case 'J':
7034 case 'C': {
7035 $w = $w;
7036 break;
7038 case 'L': {
7039 if ($this->rtl) {
7040 $w = $w;
7041 } else {
7042 $w = $l;
7044 break;
7046 case 'R': {
7047 if ($this->rtl) {
7048 $w = $l;
7049 } else {
7050 $w = $w;
7052 break;
7054 default: {
7055 $w = $l;
7056 break;
7059 $tmpstr = $this->UniArrSubString($uchars, $j, $nb);
7060 if ($firstline) {
7061 $startx = $this->x;
7062 $tmparr = array_slice($chars, $j, ($nb - $j));
7063 if ($rtlmode) {
7064 $tmparr = $this->utf8Bidi($tmparr, $tmpstr, $this->tmprtl);
7066 $linew = $this->GetArrStringWidth($tmparr);
7067 unset($tmparr);
7068 if ($this->rtl) {
7069 $this->endlinex = $startx - $linew;
7070 } else {
7071 $this->endlinex = $startx + $linew;
7073 $w = $linew;
7074 $tmpcellpadding = $this->cell_padding;
7075 if ($maxh == 0) {
7076 $this->SetCellPadding(0);
7079 if ($firstblock AND $this->isRTLTextDir()) {
7080 $tmpstr = $this->stringRightTrim($tmpstr);
7082 $this->Cell($w, $h, $tmpstr, 0, $ln, $align, $fill, $link, $stretch);
7083 unset($tmpstr);
7084 if ($firstline) {
7085 $this->cell_padding = $tmpcellpadding;
7086 return ($this->UniArrSubString($uchars, $nb));
7088 ++$nl;
7090 if ($firstline) {
7091 return '';
7093 return $nl;
7097 * Returns the remaining width between the current position and margins.
7098 * @return int Return the remaining width
7099 * @protected
7101 protected function getRemainingWidth() {
7102 list($this->x, $this->y) = $this->checkPageRegions(0, $this->x, $this->y);
7103 if ($this->rtl) {
7104 return ($this->x - $this->lMargin);
7105 } else {
7106 return ($this->w - $this->rMargin - $this->x);
7111 * Extract a slice of the $strarr array and return it as string.
7112 * @param $strarr (string) The input array of characters.
7113 * @param $start (int) the starting element of $strarr.
7114 * @param $end (int) first element that will not be returned.
7115 * @return Return part of a string
7116 * @public
7118 public function UTF8ArrSubString($strarr, $start='', $end='') {
7119 if (strlen($start) == 0) {
7120 $start = 0;
7122 if (strlen($end) == 0) {
7123 $end = count($strarr);
7125 $string = '';
7126 for ($i=$start; $i < $end; ++$i) {
7127 $string .= $this->unichr($strarr[$i]);
7129 return $string;
7133 * Extract a slice of the $uniarr array and return it as string.
7134 * @param $uniarr (string) The input array of characters.
7135 * @param $start (int) the starting element of $strarr.
7136 * @param $end (int) first element that will not be returned.
7137 * @return Return part of a string
7138 * @public
7139 * @since 4.5.037 (2009-04-07)
7141 public function UniArrSubString($uniarr, $start='', $end='') {
7142 if (strlen($start) == 0) {
7143 $start = 0;
7145 if (strlen($end) == 0) {
7146 $end = count($uniarr);
7148 $string = '';
7149 for ($i=$start; $i < $end; ++$i) {
7150 $string .= $uniarr[$i];
7152 return $string;
7156 * Convert an array of UTF8 values to array of unicode characters
7157 * @param $ta (string) The input array of UTF8 values.
7158 * @return Return array of unicode characters
7159 * @public
7160 * @since 4.5.037 (2009-04-07)
7162 public function UTF8ArrayToUniArray($ta) {
7163 return array_map(array($this, 'unichr'), $ta);
7167 * Returns the unicode caracter specified by UTF-8 value
7168 * @param $c (int) UTF-8 value
7169 * @return Returns the specified character.
7170 * @author Miguel Perez, Nicola Asuni
7171 * @public
7172 * @since 2.3.000 (2008-03-05)
7174 public function unichr($c) {
7175 if (!$this->isunicode) {
7176 return chr($c);
7177 } elseif ($c <= 0x7F) {
7178 // one byte
7179 return chr($c);
7180 } elseif ($c <= 0x7FF) {
7181 // two bytes
7182 return chr(0xC0 | $c >> 6).chr(0x80 | $c & 0x3F);
7183 } elseif ($c <= 0xFFFF) {
7184 // three bytes
7185 return chr(0xE0 | $c >> 12).chr(0x80 | $c >> 6 & 0x3F).chr(0x80 | $c & 0x3F);
7186 } elseif ($c <= 0x10FFFF) {
7187 // four bytes
7188 return chr(0xF0 | $c >> 18).chr(0x80 | $c >> 12 & 0x3F).chr(0x80 | $c >> 6 & 0x3F).chr(0x80 | $c & 0x3F);
7189 } else {
7190 return '';
7195 * Return the image type given the file name or array returned by getimagesize() function.
7196 * @param $imgfile (string) image file name
7197 * @param $iminfo (array) array of image information returned by getimagesize() function.
7198 * @return string image type
7199 * @since 4.8.017 (2009-11-27)
7201 public function getImageFileType($imgfile, $iminfo=array()) {
7202 $type = '';
7203 if (isset($iminfo['mime']) AND !empty($iminfo['mime'])) {
7204 $mime = explode('/', $iminfo['mime']);
7205 if ((count($mime) > 1) AND ($mime[0] == 'image') AND (!empty($mime[1]))) {
7206 $type = strtolower(trim($mime[1]));
7209 if (empty($type)) {
7210 $fileinfo = pathinfo($imgfile);
7211 if (isset($fileinfo['extension']) AND (!$this->empty_string($fileinfo['extension']))) {
7212 $type = strtolower(trim($fileinfo['extension']));
7215 if ($type == 'jpg') {
7216 $type = 'jpeg';
7218 return $type;
7222 * Set the block dimensions accounting for page breaks and page/column fitting
7223 * @param $w (float) width
7224 * @param $h (float) height
7225 * @param $x (float) X coordinate
7226 * @param $y (float) Y coodiante
7227 * @param $fitonpage (boolean) if true the block is resized to not exceed page dimensions.
7228 * @return array($w, $h, $x, $y)
7229 * @protected
7230 * @since 5.5.009 (2010-07-05)
7232 protected function fitBlock($w, $h, $x, $y, $fitonpage=false) {
7233 if ($w <= 0) {
7234 // set maximum width
7235 $w = ($this->w - $this->lMargin - $this->rMargin);
7237 if ($h <= 0) {
7238 // set maximum height
7239 $h = ($this->PageBreakTrigger - $this->tMargin);
7241 // resize the block to be vertically contained on a single page or single column
7242 if ($fitonpage OR $this->AutoPageBreak) {
7243 $ratio_wh = ($w / $h);
7244 if ($h > ($this->PageBreakTrigger - $this->tMargin)) {
7245 $h = $this->PageBreakTrigger - $this->tMargin;
7246 $w = ($h * $ratio_wh);
7248 // resize the block to be horizontally contained on a single page or single column
7249 if ($fitonpage) {
7250 $maxw = ($this->w - $this->lMargin - $this->rMargin);
7251 if ($w > $maxw) {
7252 $w = $maxw;
7253 $h = ($w / $ratio_wh);
7257 // Check whether we need a new page or new column first as this does not fit
7258 $prev_x = $this->x;
7259 $prev_y = $this->y;
7260 if ($this->checkPageBreak($h, $y) OR ($this->y < $prev_y)) {
7261 $y = $this->y;
7262 if ($this->rtl) {
7263 $x += ($prev_x - $this->x);
7264 } else {
7265 $x += ($this->x - $prev_x);
7267 $this->newline = true;
7269 // resize the block to be contained on the remaining available page or column space
7270 if ($fitonpage) {
7271 $ratio_wh = ($w / $h);
7272 if (($y + $h) > $this->PageBreakTrigger) {
7273 $h = $this->PageBreakTrigger - $y;
7274 $w = ($h * $ratio_wh);
7276 if ((!$this->rtl) AND (($x + $w) > ($this->w - $this->rMargin))) {
7277 $w = $this->w - $this->rMargin - $x;
7278 $h = ($w / $ratio_wh);
7279 } elseif (($this->rtl) AND (($x - $w) < ($this->lMargin))) {
7280 $w = $x - $this->lMargin;
7281 $h = ($w / $ratio_wh);
7284 return array($w, $h, $x, $y);
7288 * Puts an image in the page.
7289 * The upper-left corner must be given.
7290 * The dimensions can be specified in different ways:<ul>
7291 * <li>explicit width and height (expressed in user unit)</li>
7292 * <li>one explicit dimension, the other being calculated automatically in order to keep the original proportions</li>
7293 * <li>no explicit dimension, in which case the image is put at 72 dpi</li></ul>
7294 * 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;
7295 * The format can be specified explicitly or inferred from the file extension.<br />
7296 * It is possible to put a link on the image.<br />
7297 * Remark: if an image is used several times, only one copy will be embedded in the file.<br />
7298 * @param $file (string) Name of the file containing the image or a '@' character followed by the image data string. To link an image without embedding it on the document, set an asterisk character before the URL (i.e.: '*http://www.example.com/image.jpg').
7299 * @param $x (float) Abscissa of the upper-left corner (LTR) or upper-right corner (RTL).
7300 * @param $y (float) Ordinate of the upper-left corner (LTR) or upper-right corner (RTL).
7301 * @param $w (float) Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
7302 * @param $h (float) Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
7303 * @param $type (string) Image format. Possible values are (case insensitive): JPEG and PNG (whitout GD library) and all images supported by GD: GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM;. If not specified, the type is inferred from the file extension.
7304 * @param $link (mixed) URL or identifier returned by AddLink().
7305 * @param $align (string) Indicates the alignment of the pointer next to image insertion relative to image height. The value can be:<ul><li>T: top-right for LTR or top-left for RTL</li><li>M: middle-right for LTR or middle-left for RTL</li><li>B: bottom-right for LTR or bottom-left for RTL</li><li>N: next line</li></ul>
7306 * @param $resize (mixed) If true resize (reduce) the image to fit $w and $h (requires GD or ImageMagick library); if false do not resize; if 2 force resize in all cases (upscaling and downscaling).
7307 * @param $dpi (int) dot-per-inch resolution used on resize
7308 * @param $palign (string) Allows to center or align the image on the current line. Possible values are:<ul><li>L : left align</li><li>C : center</li><li>R : right align</li><li>'' : empty string : left for LTR or right for RTL</li></ul>
7309 * @param $ismask (boolean) true if this image is a mask, false otherwise
7310 * @param $imgmask (mixed) image object returned by this function or false
7311 * @param $border (mixed) Indicates if borders must be drawn around the cell. The value can be a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul> or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul> or an array of line styles for each border group - for example: array('LTRB' => array('width' => 2, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0)))
7312 * @param $fitbox (mixed) If not false scale image dimensions proportionally to fit within the ($w, $h) box. $fitbox can be true or a 2 characters string indicating the image alignment inside the box. The first character indicate the horizontal alignment (L = left, C = center, R = right) the second character indicate the vertical algnment (T = top, M = middle, B = bottom).
7313 * @param $hidden (boolean) If true do not display the image.
7314 * @param $fitonpage (boolean) If true the image is resized to not exceed page dimensions.
7315 * @param $alt (boolean) If true the image will be added as alternative and not directly printed (the ID of the image will be returned).
7316 * @param $altimgs (array) Array of alternate images IDs. Each alternative image must be an array with two values: an integer representing the image ID (the value returned by the Image method) and a boolean value to indicate if the image is the default for printing.
7317 * @return image information
7318 * @public
7319 * @since 1.1
7321 public function Image($file, $x='', $y='', $w=0, $h=0, $type='', $link='', $align='', $resize=false, $dpi=300, $palign='', $ismask=false, $imgmask=false, $border=0, $fitbox=false, $hidden=false, $fitonpage=false, $alt=false, $altimgs=array()) {
7322 if ($x === '') {
7323 $x = $this->x;
7325 if ($y === '') {
7326 $y = $this->y;
7328 // check page for no-write regions and adapt page margins if necessary
7329 list($x, $y) = $this->checkPageRegions($h, $x, $y);
7330 $cached_file = false; // true when the file is cached
7331 $exurl = ''; // external streams
7332 // check if we are passing an image as file or string
7333 if ($file{0} === '@') {
7334 // image from string
7335 $imgdata = substr($file, 1);
7336 $file = K_PATH_CACHE.'img_'.md5($imgdata);
7337 $fp = fopen($file, 'w');
7338 fwrite($fp, $imgdata);
7339 fclose($fp);
7340 unset($imgdata);
7341 $cached_file = true;
7342 $imsize = @getimagesize($file);
7343 if ($imsize === FALSE) {
7344 unlink($file);
7345 $cached_file = false;
7347 } else { // image file
7348 if ($file{0} === '*') {
7349 // image as external stream
7350 $file = substr($file, 1);
7351 $exurl = $file;
7353 // check if is local file
7354 if (!@file_exists($file)) {
7355 // encode spaces on filename (file is probably an URL)
7356 $file = str_replace(' ', '%20', $file);
7358 if (@file_exists($file)) {
7359 // get image dimensions
7360 $imsize = @getimagesize($file);
7361 } else {
7362 $imsize = false;
7364 if ($imsize === FALSE) {
7365 if (function_exists('curl_init')) {
7366 // try to get remote file data using cURL
7367 $cs = curl_init(); // curl session
7368 curl_setopt($cs, CURLOPT_URL, $file);
7369 curl_setopt($cs, CURLOPT_BINARYTRANSFER, true);
7370 curl_setopt($cs, CURLOPT_FAILONERROR, true);
7371 curl_setopt($cs, CURLOPT_RETURNTRANSFER, true);
7372 curl_setopt($cs, CURLOPT_FOLLOWLOCATION, true);
7373 curl_setopt($cs, CURLOPT_CONNECTTIMEOUT, 5);
7374 curl_setopt($cs, CURLOPT_TIMEOUT, 30);
7375 $imgdata = curl_exec($cs);
7376 curl_close($cs);
7377 if ($imgdata !== FALSE) {
7378 // copy image to cache
7379 $file = K_PATH_CACHE.'img_'.md5($imgdata);
7380 $fp = fopen($file, 'w');
7381 fwrite($fp, $imgdata);
7382 fclose($fp);
7383 unset($imgdata);
7384 $cached_file = true;
7385 $imsize = @getimagesize($file);
7386 if ($imsize === FALSE) {
7387 unlink($file);
7388 $cached_file = false;
7391 } elseif (($w > 0) AND ($h > 0)) {
7392 // get measures from specified data
7393 $pw = $this->getHTMLUnitToUnits($w, 0, $this->pdfunit, true) * $this->imgscale * $this->k;
7394 $ph = $this->getHTMLUnitToUnits($h, 0, $this->pdfunit, true) * $this->imgscale * $this->k;
7395 $imsize = array($pw, $ph);
7399 if ($imsize === FALSE) {
7400 if (substr($file, 0, -34) == K_PATH_CACHE.'msk') { // mask file
7401 // get measures from specified data
7402 $pw = $this->getHTMLUnitToUnits($w, 0, $this->pdfunit, true) * $this->imgscale * $this->k;
7403 $ph = $this->getHTMLUnitToUnits($h, 0, $this->pdfunit, true) * $this->imgscale * $this->k;
7404 $imsize = array($pw, $ph);
7405 } else {
7406 $this->Error('[Image] Unable to get image: '.$file);
7409 // get original image width and height in pixels
7410 list($pixw, $pixh) = $imsize;
7411 // calculate image width and height on document
7412 if (($w <= 0) AND ($h <= 0)) {
7413 // convert image size to document unit
7414 $w = $this->pixelsToUnits($pixw);
7415 $h = $this->pixelsToUnits($pixh);
7416 } elseif ($w <= 0) {
7417 $w = $h * $pixw / $pixh;
7418 } elseif ($h <= 0) {
7419 $h = $w * $pixh / $pixw;
7420 } elseif (($fitbox !== false) AND ($w > 0) AND ($h > 0)) {
7421 if (strlen($fitbox) !== 2) {
7422 // set default alignment
7423 $fitbox = '--';
7425 // scale image dimensions proportionally to fit within the ($w, $h) box
7426 if ((($w * $pixh) / ($h * $pixw)) < 1) {
7427 // store current height
7428 $oldh = $h;
7429 // calculate new height
7430 $h = $w * $pixh / $pixw;
7431 // height difference
7432 $hdiff = ($oldh - $h);
7433 // vertical alignment
7434 switch (strtoupper($fitbox{1})) {
7435 case 'T': {
7436 break;
7438 case 'M': {
7439 $y += ($hdiff / 2);
7440 break;
7442 case 'B': {
7443 $y += $hdiff;
7444 break;
7447 } else {
7448 // store current width
7449 $oldw = $w;
7450 // calculate new width
7451 $w = $h * $pixw / $pixh;
7452 // width difference
7453 $wdiff = ($oldw - $w);
7454 // horizontal alignment
7455 switch (strtoupper($fitbox{0})) {
7456 case 'L': {
7457 if ($this->rtl) {
7458 $x -= $wdiff;
7460 break;
7462 case 'C': {
7463 if ($this->rtl) {
7464 $x -= ($wdiff / 2);
7465 } else {
7466 $x += ($wdiff / 2);
7468 break;
7470 case 'R': {
7471 if (!$this->rtl) {
7472 $x += $wdiff;
7474 break;
7479 // fit the image on available space
7480 list($w, $h, $x, $y) = $this->fitBlock($w, $h, $x, $y, $fitonpage);
7481 // calculate new minimum dimensions in pixels
7482 $neww = round($w * $this->k * $dpi / $this->dpi);
7483 $newh = round($h * $this->k * $dpi / $this->dpi);
7484 // check if resize is necessary (resize is used only to reduce the image)
7485 $newsize = ($neww * $newh);
7486 $pixsize = ($pixw * $pixh);
7487 if (intval($resize) == 2) {
7488 $resize = true;
7489 } elseif ($newsize >= $pixsize) {
7490 $resize = false;
7492 // check if image has been already added on document
7493 $newimage = true;
7494 if (in_array($file, $this->imagekeys)) {
7495 $newimage = false;
7496 // get existing image data
7497 $info = $this->getImageBuffer($file);
7498 if (substr($file, 0, -34) != K_PATH_CACHE.'msk') {
7499 // check if the newer image is larger
7500 $oldsize = ($info['w'] * $info['h']);
7501 if ((($oldsize < $newsize) AND ($resize)) OR (($oldsize < $pixsize) AND (!$resize))) {
7502 $newimage = true;
7505 } elseif (substr($file, 0, -34) != K_PATH_CACHE.'msk') {
7506 // check for cached images with alpha channel
7507 $filehash = md5($file);
7508 $tempfile_plain = K_PATH_CACHE.'mskp_'.$filehash;
7509 $tempfile_alpha = K_PATH_CACHE.'mska_'.$filehash;
7510 if (in_array($tempfile_plain, $this->imagekeys)) {
7511 // get existing image data
7512 $info = $this->getImageBuffer($tempfile_plain);
7513 // check if the newer image is larger
7514 $oldsize = ($info['w'] * $info['h']);
7515 if ((($oldsize < $newsize) AND ($resize)) OR (($oldsize < $pixsize) AND (!$resize))) {
7516 $newimage = true;
7517 } else {
7518 $newimage = false;
7519 // embed mask image
7520 $imgmask = $this->Image($tempfile_alpha, $x, $y, $w, $h, 'PNG', '', '', $resize, $dpi, '', true, false);
7521 // embed image, masked with previously embedded mask
7522 return $this->Image($tempfile_plain, $x, $y, $w, $h, $type, $link, $align, $resize, $dpi, $palign, false, $imgmask);
7526 if ($newimage) {
7527 //First use of image, get info
7528 $type = strtolower($type);
7529 if ($type == '') {
7530 $type = $this->getImageFileType($file, $imsize);
7531 } elseif ($type == 'jpg') {
7532 $type = 'jpeg';
7534 $mqr = $this->get_mqr();
7535 $this->set_mqr(false);
7536 // Specific image handlers
7537 $mtd = '_parse'.$type;
7538 // GD image handler function
7539 $gdfunction = 'imagecreatefrom'.$type;
7540 $info = false;
7541 if ((method_exists($this, $mtd)) AND (!($resize AND (function_exists($gdfunction) OR extension_loaded('imagick'))))) {
7542 // TCPDF image functions
7543 $info = $this->$mtd($file);
7544 if ($info == 'pngalpha') {
7545 return $this->ImagePngAlpha($file, $x, $y, $pixw, $pixh, $w, $h, 'PNG', $link, $align, $resize, $dpi, $palign, $filehash);
7548 if (!$info) {
7549 if (function_exists($gdfunction)) {
7550 // GD library
7551 $img = $gdfunction($file);
7552 if ($resize) {
7553 $imgr = imagecreatetruecolor($neww, $newh);
7554 if (($type == 'gif') OR ($type == 'png')) {
7555 $imgr = $this->_setGDImageTransparency($imgr, $img);
7557 imagecopyresampled($imgr, $img, 0, 0, 0, 0, $neww, $newh, $pixw, $pixh);
7558 if (($type == 'gif') OR ($type == 'png')) {
7559 $info = $this->_toPNG($imgr);
7560 } else {
7561 $info = $this->_toJPEG($imgr);
7563 } else {
7564 if (($type == 'gif') OR ($type == 'png')) {
7565 $info = $this->_toPNG($img);
7566 } else {
7567 $info = $this->_toJPEG($img);
7570 } elseif (extension_loaded('imagick')) {
7571 // ImageMagick library
7572 $img = new Imagick();
7573 if ($type == 'SVG') {
7574 // get SVG file content
7575 $svgimg = file_get_contents($file);
7576 // get width and height
7577 $regs = array();
7578 if (preg_match('/<svg([^\>]*)>/si', $svgimg, $regs)) {
7579 $svgtag = $regs[1];
7580 $tmp = array();
7581 if (preg_match('/[\s]+width[\s]*=[\s]*"([^"]*)"/si', $svgtag, $tmp)) {
7582 $ow = $this->getHTMLUnitToUnits($tmp[1], 1, $this->svgunit, false);
7583 $owu = sprintf('%.3F', ($ow * $dpi / 72)).$this->pdfunit;
7584 $svgtag = preg_replace('/[\s]+width[\s]*=[\s]*"[^"]*"/si', ' width="'.$owu.'"', $svgtag, 1);
7585 } else {
7586 $ow = $w;
7588 $tmp = array();
7589 if (preg_match('/[\s]+height[\s]*=[\s]*"([^"]*)"/si', $svgtag, $tmp)) {
7590 $oh = $this->getHTMLUnitToUnits($tmp[1], 1, $this->svgunit, false);
7591 $ohu = sprintf('%.3F', ($oh * $dpi / 72)).$this->pdfunit;
7592 $svgtag = preg_replace('/[\s]+height[\s]*=[\s]*"[^"]*"/si', ' height="'.$ohu.'"', $svgtag, 1);
7593 } else {
7594 $oh = $h;
7596 $tmp = array();
7597 if (!preg_match('/[\s]+viewBox[\s]*=[\s]*"[\s]*([0-9\.]+)[\s]+([0-9\.]+)[\s]+([0-9\.]+)[\s]+([0-9\.]+)[\s]*"/si', $svgtag, $tmp)) {
7598 $vbw = ($ow * $this->imgscale * $this->k);
7599 $vbh = ($oh * $this->imgscale * $this->k);
7600 $vbox = sprintf(' viewBox="0 0 %.3F %.3F" ', $vbw, $vbh);
7601 $svgtag = $vbox.$svgtag;
7603 $svgimg = preg_replace('/<svg([^\>]*)>/si', '<svg'.$svgtag.'>', $svgimg, 1);
7605 $img->readImageBlob($svgimg);
7606 } else {
7607 $img->readImage($file);
7609 if ($resize) {
7610 $img->resizeImage($neww, $newh, 10, 1, false);
7612 $img->setCompressionQuality($this->jpeg_quality);
7613 $img->setImageFormat('jpeg');
7614 $tempname = tempnam(K_PATH_CACHE, 'jpg_');
7615 $img->writeImage($tempname);
7616 $info = $this->_parsejpeg($tempname);
7617 unlink($tempname);
7618 $img->destroy();
7619 } else {
7620 return;
7623 if ($info === false) {
7624 //If false, we cannot process image
7625 return;
7627 $this->set_mqr($mqr);
7628 if ($ismask) {
7629 // force grayscale
7630 $info['cs'] = 'DeviceGray';
7632 $info['i'] = $this->numimages;
7633 if (!in_array($file, $this->imagekeys)) {
7634 ++$info['i'];
7636 if ($imgmask !== false) {
7637 $info['masked'] = $imgmask;
7639 if (!empty($exurl)) {
7640 $info['exurl'] = $exurl;
7642 // array of alternative images
7643 $info['altimgs'] = $altimgs;
7644 // add image to document
7645 $this->setImageBuffer($file, $info);
7647 if ($cached_file) {
7648 // remove cached file
7649 unlink($file);
7651 // set alignment
7652 $this->img_rb_y = $y + $h;
7653 // set alignment
7654 if ($this->rtl) {
7655 if ($palign == 'L') {
7656 $ximg = $this->lMargin;
7657 } elseif ($palign == 'C') {
7658 $ximg = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
7659 } elseif ($palign == 'R') {
7660 $ximg = $this->w - $this->rMargin - $w;
7661 } else {
7662 $ximg = $x - $w;
7664 $this->img_rb_x = $ximg;
7665 } else {
7666 if ($palign == 'L') {
7667 $ximg = $this->lMargin;
7668 } elseif ($palign == 'C') {
7669 $ximg = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
7670 } elseif ($palign == 'R') {
7671 $ximg = $this->w - $this->rMargin - $w;
7672 } else {
7673 $ximg = $x;
7675 $this->img_rb_x = $ximg + $w;
7677 if ($ismask OR $hidden) {
7678 // image is not displayed
7679 return $info['i'];
7681 $xkimg = $ximg * $this->k;
7682 if (!$alt) {
7683 // only non-alternative immages will be set
7684 $this->_out(sprintf('q %.2F 0 0 %.2F %.2F %.2F cm /I%u Do Q', ($w * $this->k), ($h * $this->k), $xkimg, (($this->h - ($y + $h)) * $this->k), $info['i']));
7686 if (!empty($border)) {
7687 $bx = $this->x;
7688 $by = $this->y;
7689 $this->x = $ximg;
7690 if ($this->rtl) {
7691 $this->x += $w;
7693 $this->y = $y;
7694 $this->Cell($w, $h, '', $border, 0, '', 0, '', 0, true);
7695 $this->x = $bx;
7696 $this->y = $by;
7698 if ($link) {
7699 $this->Link($ximg, $y, $w, $h, $link, 0);
7701 // set pointer to align the next text/objects
7702 switch($align) {
7703 case 'T': {
7704 $this->y = $y;
7705 $this->x = $this->img_rb_x;
7706 break;
7708 case 'M': {
7709 $this->y = $y + round($h/2);
7710 $this->x = $this->img_rb_x;
7711 break;
7713 case 'B': {
7714 $this->y = $this->img_rb_y;
7715 $this->x = $this->img_rb_x;
7716 break;
7718 case 'N': {
7719 $this->SetY($this->img_rb_y);
7720 break;
7722 default:{
7723 break;
7726 $this->endlinex = $this->img_rb_x;
7727 if ($this->inxobj) {
7728 // we are inside an XObject template
7729 $this->xobjects[$this->xobjid]['images'][] = $info['i'];
7731 return $info['i'];
7735 * Sets the current active configuration setting of magic_quotes_runtime (if the set_magic_quotes_runtime function exist)
7736 * @param $mqr (boolean) FALSE for off, TRUE for on.
7737 * @since 4.6.025 (2009-08-17)
7739 public function set_mqr($mqr) {
7740 if (!defined('PHP_VERSION_ID')) {
7741 $version = PHP_VERSION;
7742 define('PHP_VERSION_ID', (($version{0} * 10000) + ($version{2} * 100) + $version{4}));
7744 if (PHP_VERSION_ID < 50300) {
7745 @set_magic_quotes_runtime($mqr);
7750 * Gets the current active configuration setting of magic_quotes_runtime (if the get_magic_quotes_runtime function exist)
7751 * @return Returns 0 if magic quotes runtime is off or get_magic_quotes_runtime doesn't exist, 1 otherwise.
7752 * @since 4.6.025 (2009-08-17)
7754 public function get_mqr() {
7755 if (!defined('PHP_VERSION_ID')) {
7756 $version = PHP_VERSION;
7757 define('PHP_VERSION_ID', (($version{0} * 10000) + ($version{2} * 100) + $version{4}));
7759 if (PHP_VERSION_ID < 50300) {
7760 return @get_magic_quotes_runtime();
7762 return 0;
7766 * Convert the loaded image to a JPEG and then return a structure for the PDF creator.
7767 * This function requires GD library and write access to the directory defined on K_PATH_CACHE constant.
7768 * @param $image (image) Image object.
7769 * return image JPEG image object.
7770 * @protected
7772 protected function _toJPEG($image) {
7773 $tempname = tempnam(K_PATH_CACHE, 'jpg_');
7774 imagejpeg($image, $tempname, $this->jpeg_quality);
7775 imagedestroy($image);
7776 $retvars = $this->_parsejpeg($tempname);
7777 // tidy up by removing temporary image
7778 unlink($tempname);
7779 return $retvars;
7783 * Convert the loaded image to a PNG and then return a structure for the PDF creator.
7784 * This function requires GD library and write access to the directory defined on K_PATH_CACHE constant.
7785 * @param $image (image) Image object.
7786 * return image PNG image object.
7787 * @protected
7788 * @since 4.9.016 (2010-04-20)
7790 protected function _toPNG($image) {
7791 // set temporary image file name
7792 $tempname = tempnam(K_PATH_CACHE, 'jpg_');
7793 // turn off interlaced mode
7794 imageinterlace($image, 0);
7795 // create temporary PNG image
7796 imagepng($image, $tempname);
7797 // remove image from memory
7798 imagedestroy($image);
7799 // get PNG image data
7800 $retvars = $this->_parsepng($tempname);
7801 // tidy up by removing temporary image
7802 unlink($tempname);
7803 return $retvars;
7807 * Set the transparency for the given GD image.
7808 * @param $new_image (image) GD image object
7809 * @param $image (image) GD image object.
7810 * return GD image object.
7811 * @protected
7812 * @since 4.9.016 (2010-04-20)
7814 protected function _setGDImageTransparency($new_image, $image) {
7815 // transparency index
7816 $tid = imagecolortransparent($image);
7817 // default transparency color
7818 $tcol = array('red' => 255, 'green' => 255, 'blue' => 255);
7819 if ($tid >= 0) {
7820 // get the colors for the transparency index
7821 $tcol = imagecolorsforindex($image, $tid);
7823 $tid = imagecolorallocate($new_image, $tcol['red'], $tcol['green'], $tcol['blue']);
7824 imagefill($new_image, 0, 0, $tid);
7825 imagecolortransparent($new_image, $tid);
7826 return $new_image;
7830 * Extract info from a JPEG file without using the GD library.
7831 * @param $file (string) image file to parse
7832 * @return array structure containing the image data
7833 * @protected
7835 protected function _parsejpeg($file) {
7836 $a = getimagesize($file);
7837 if (empty($a)) {
7838 $this->Error('Missing or incorrect image file: '.$file);
7840 if ($a[2] != 2) {
7841 $this->Error('Not a JPEG file: '.$file);
7843 // bits per pixel
7844 $bpc = isset($a['bits']) ? intval($a['bits']) : 8;
7845 // number of image channels
7846 if (!isset($a['channels'])) {
7847 $channels = 3;
7848 } else {
7849 $channels = intval($a['channels']);
7851 // default colour space
7852 switch ($channels) {
7853 case 1: {
7854 $colspace = 'DeviceGray';
7855 break;
7857 case 3: {
7858 $colspace = 'DeviceRGB';
7859 break;
7861 case 4: {
7862 $colspace = 'DeviceCMYK';
7863 break;
7865 default: {
7866 $channels = 3;
7867 $colspace = 'DeviceRGB';
7868 break;
7871 // get file content
7872 $data = file_get_contents($file);
7873 // check for embedded ICC profile
7874 $icc = array();
7875 $offset = 0;
7876 while (($pos = strpos($data, "ICC_PROFILE\0", $offset)) !== false) {
7877 // get ICC sequence length
7878 $length = ($this->_getUSHORT($data, ($pos - 2)) - 16);
7879 // marker sequence number
7880 $msn = max(1, ord($data{($pos + 12)}));
7881 // number of markers (total of APP2 used)
7882 $nom = max(1, ord($data{($pos + 13)}));
7883 // get sequence segment
7884 $icc[($msn - 1)] = substr($data, ($pos + 14), $length);
7885 // move forward to next sequence
7886 $offset = ($pos + 14 + $length);
7888 // order and compact ICC segments
7889 if (count($icc) > 0) {
7890 ksort($icc);
7891 $icc = implode('', $icc);
7892 if ((ord($icc{36}) != 0x61) OR (ord($icc{37}) != 0x63) OR (ord($icc{38}) != 0x73) OR (ord($icc{39}) != 0x70)) {
7893 // invalid ICC profile
7894 $icc = false;
7896 } else {
7897 $icc = false;
7899 return array('w' => $a[0], 'h' => $a[1], 'ch' => $channels, 'icc' => $icc, 'cs' => $colspace, 'bpc' => $bpc, 'f' => 'DCTDecode', 'data' => $data);
7903 * Extract info from a PNG file without using the GD library.
7904 * @param $file (string) image file to parse
7905 * @return array structure containing the image data
7906 * @protected
7908 protected function _parsepng($file) {
7909 $f = fopen($file, 'rb');
7910 if ($f === false) {
7911 $this->Error('Can\'t open image file: '.$file);
7913 //Check signature
7914 if (fread($f, 8) != chr(137).'PNG'.chr(13).chr(10).chr(26).chr(10)) {
7915 $this->Error('Not a PNG file: '.$file);
7917 //Read header chunk
7918 fread($f, 4);
7919 if (fread($f, 4) != 'IHDR') {
7920 $this->Error('Incorrect PNG file: '.$file);
7922 $w = $this->_freadint($f);
7923 $h = $this->_freadint($f);
7924 $bpc = ord(fread($f, 1));
7925 if ($bpc > 8) {
7926 //$this->Error('16-bit depth not supported: '.$file);
7927 fclose($f);
7928 return false;
7930 $ct = ord(fread($f, 1));
7931 if ($ct == 0) {
7932 $colspace = 'DeviceGray';
7933 } elseif ($ct == 2) {
7934 $colspace = 'DeviceRGB';
7935 } elseif ($ct == 3) {
7936 $colspace = 'Indexed';
7937 } else {
7938 // alpha channel
7939 fclose($f);
7940 return 'pngalpha';
7942 if (ord(fread($f, 1)) != 0) {
7943 //$this->Error('Unknown compression method: '.$file);
7944 fclose($f);
7945 return false;
7947 if (ord(fread($f, 1)) != 0) {
7948 //$this->Error('Unknown filter method: '.$file);
7949 fclose($f);
7950 return false;
7952 if (ord(fread($f, 1)) != 0) {
7953 //$this->Error('Interlacing not supported: '.$file);
7954 fclose($f);
7955 return false;
7957 fread($f, 4);
7958 $channels = ($ct == 2 ? 3 : 1);
7959 $parms = '/DecodeParms << /Predictor 15 /Colors '.$channels.' /BitsPerComponent '.$bpc.' /Columns '.$w.' >>';
7960 //Scan chunks looking for palette, transparency and image data
7961 $pal = '';
7962 $trns = '';
7963 $data = '';
7964 $icc = false;
7965 do {
7966 $n = $this->_freadint($f);
7967 $type = fread($f, 4);
7968 if ($type == 'PLTE') {
7969 // read palette
7970 $pal = $this->rfread($f, $n);
7971 fread($f, 4);
7972 } elseif ($type == 'tRNS') {
7973 // read transparency info
7974 $t = $this->rfread($f, $n);
7975 if ($ct == 0) {
7976 $trns = array(ord($t{1}));
7977 } elseif ($ct == 2) {
7978 $trns = array(ord($t{1}), ord($t{3}), ord($t{5}));
7979 } else {
7980 $pos = strpos($t, chr(0));
7981 if ($pos !== false) {
7982 $trns = array($pos);
7985 fread($f, 4);
7986 } elseif ($type == 'IDAT') {
7987 // read image data block
7988 $data .= $this->rfread($f, $n);
7989 fread($f, 4);
7990 } elseif ($type == 'iCCP') {
7991 // skip profile name and null separator
7992 $len = 0;
7993 while ((ord(fread($f, 1)) > 0) AND ($len < 80)) {
7994 ++$len;
7996 // get compression method
7997 if (ord(fread($f, 1)) != 0) {
7998 //$this->Error('Unknown filter method: '.$file);
7999 fclose($f);
8000 return false;
8002 // read ICC Color Profile
8003 $icc = $this->rfread($f, ($n - $len - 2));
8004 // decompress profile
8005 $icc = gzuncompress($icc);
8006 fread($f, 4);
8007 } elseif ($type == 'IEND') {
8008 break;
8009 } else {
8010 $this->rfread($f, $n + 4);
8012 } while ($n);
8013 if (($colspace == 'Indexed') AND (empty($pal))) {
8014 //$this->Error('Missing palette in '.$file);
8015 fclose($f);
8016 return false;
8018 fclose($f);
8019 return array('w' => $w, 'h' => $h, 'ch' => $channels, 'icc' => $icc, 'cs' => $colspace, 'bpc' => $bpc, 'f' => 'FlateDecode', 'parms' => $parms, 'pal' => $pal, 'trns' => $trns, 'data' => $data);
8023 * Binary-safe and URL-safe file read.
8024 * Reads up to length bytes from the file pointer referenced by handle. Reading stops as soon as one of the following conditions is met: length bytes have been read; EOF (end of file) is reached.
8025 * @param $handle (resource)
8026 * @param $length (int)
8027 * @return Returns the read string or FALSE in case of error.
8028 * @author Nicola Asuni
8029 * @protected
8030 * @since 4.5.027 (2009-03-16)
8032 protected function rfread($handle, $length) {
8033 $data = fread($handle, $length);
8034 if ($data === false) {
8035 return false;
8037 $rest = $length - strlen($data);
8038 if ($rest > 0) {
8039 $data .= $this->rfread($handle, $rest);
8041 return $data;
8045 * Extract info from a PNG image with alpha channel using the GD library.
8046 * @param $file (string) Name of the file containing the image.
8047 * @param $x (float) Abscissa of the upper-left corner.
8048 * @param $y (float) Ordinate of the upper-left corner.
8049 * @param $wpx (float) Original width of the image in pixels.
8050 * @param $hpx (float) original height of the image in pixels.
8051 * @param $w (float) Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
8052 * @param $h (float) Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
8053 * @param $type (string) Image format. Possible values are (case insensitive): JPEG and PNG (whitout GD library) and all images supported by GD: GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM;. If not specified, the type is inferred from the file extension.
8054 * @param $link (mixed) URL or identifier returned by AddLink().
8055 * @param $align (string) Indicates the alignment of the pointer next to image insertion relative to image height. The value can be:<ul><li>T: top-right for LTR or top-left for RTL</li><li>M: middle-right for LTR or middle-left for RTL</li><li>B: bottom-right for LTR or bottom-left for RTL</li><li>N: next line</li></ul>
8056 * @param $resize (boolean) If true resize (reduce) the image to fit $w and $h (requires GD library).
8057 * @param $dpi (int) dot-per-inch resolution used on resize
8058 * @param $palign (string) Allows to center or align the image on the current line. Possible values are:<ul><li>L : left align</li><li>C : center</li><li>R : right align</li><li>'' : empty string : left for LTR or right for RTL</li></ul>
8059 * @param $filehash (string) File hash used to build unique file names.
8060 * @author Nicola Asuni
8061 * @protected
8062 * @since 4.3.007 (2008-12-04)
8063 * @see Image()
8065 protected function ImagePngAlpha($file, $x, $y, $wpx, $hpx, $w, $h, $type, $link, $align, $resize, $dpi, $palign, $filehash='') {
8066 if (empty($filehash)) {
8067 $filehash = md5($file);
8069 // create temp image file (without alpha channel)
8070 $tempfile_plain = K_PATH_CACHE.'mskp_'.$filehash;
8071 // create temp alpha file
8072 $tempfile_alpha = K_PATH_CACHE.'mska_'.$filehash;
8073 if (extension_loaded('imagick')) { // ImageMagick
8074 // ImageMagick library
8075 $img = new Imagick();
8076 $img->readImage($file);
8077 // clone image object
8078 $imga = $img->clone();
8079 // extract alpha channel
8080 $img->separateImageChannel(8); // 8 = (imagick::CHANNEL_ALPHA | imagick::CHANNEL_OPACITY | imagick::CHANNEL_MATTE);
8081 $img->negateImage(true);
8082 $img->setImageFormat('png');
8083 $img->writeImage($tempfile_alpha);
8084 // remove alpha channel
8085 $imga->separateImageChannel(39); // 39 = (imagick::CHANNEL_ALL & ~(imagick::CHANNEL_ALPHA | imagick::CHANNEL_OPACITY | imagick::CHANNEL_MATTE));
8086 $imga->setImageFormat('png');
8087 $imga->writeImage($tempfile_plain);
8088 } else { // GD library
8089 // generate images
8090 $img = imagecreatefrompng($file);
8091 $imgalpha = imagecreate($wpx, $hpx);
8092 // generate gray scale palette (0 -> 255)
8093 for ($c = 0; $c < 256; ++$c) {
8094 ImageColorAllocate($imgalpha, $c, $c, $c);
8096 // extract alpha channel
8097 for ($xpx = 0; $xpx < $wpx; ++$xpx) {
8098 for ($ypx = 0; $ypx < $hpx; ++$ypx) {
8099 $color = imagecolorat($img, $xpx, $ypx);
8100 $alpha = ($color >> 24); // shifts off the first 24 bits (where 8x3 are used for each color), and returns the remaining 7 allocated bits (commonly used for alpha)
8101 $alpha = (((127 - $alpha) / 127) * 255); // GD alpha is only 7 bit (0 -> 127)
8102 $alpha = $this->getGDgamma($alpha); // correct gamma
8103 imagesetpixel($imgalpha, $xpx, $ypx, $alpha);
8106 imagepng($imgalpha, $tempfile_alpha);
8107 imagedestroy($imgalpha);
8108 // extract image without alpha channel
8109 $imgplain = imagecreatetruecolor($wpx, $hpx);
8110 imagecopy($imgplain, $img, 0, 0, 0, 0, $wpx, $hpx);
8111 imagepng($imgplain, $tempfile_plain);
8112 imagedestroy($imgplain);
8114 // embed mask image
8115 $imgmask = $this->Image($tempfile_alpha, $x, $y, $w, $h, 'PNG', '', '', $resize, $dpi, '', true, false);
8116 // embed image, masked with previously embedded mask
8117 $this->Image($tempfile_plain, $x, $y, $w, $h, $type, $link, $align, $resize, $dpi, $palign, false, $imgmask);
8118 // remove temp files
8119 unlink($tempfile_alpha);
8120 unlink($tempfile_plain);
8124 * Correct the gamma value to be used with GD library
8125 * @param $v (float) the gamma value to be corrected
8126 * @protected
8127 * @since 4.3.007 (2008-12-04)
8129 protected function getGDgamma($v) {
8130 return (pow(($v / 255), 2.2) * 255);
8134 * Performs a line break.
8135 * The current abscissa goes back to the left margin and the ordinate increases by the amount passed in parameter.
8136 * @param $h (float) The height of the break. By default, the value equals the height of the last printed cell.
8137 * @param $cell (boolean) if true add the current left (or right o for RTL) padding to the X coordinate
8138 * @public
8139 * @since 1.0
8140 * @see Cell()
8142 public function Ln($h='', $cell=false) {
8143 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'])) {
8144 // revove vertical space from the top of the column
8145 return;
8147 if ($cell) {
8148 if ($this->rtl) {
8149 $cellpadding = $this->cell_padding['R'];
8150 } else {
8151 $cellpadding = $this->cell_padding['L'];
8153 } else {
8154 $cellpadding = 0;
8156 if ($this->rtl) {
8157 $this->x = $this->w - $this->rMargin - $cellpadding;
8158 } else {
8159 $this->x = $this->lMargin + $cellpadding;
8161 if (is_string($h)) {
8162 $this->y += $this->lasth;
8163 } else {
8164 $this->y += $h;
8166 $this->newline = true;
8170 * Returns the relative X value of current position.
8171 * The value is relative to the left border for LTR languages and to the right border for RTL languages.
8172 * @return float
8173 * @public
8174 * @since 1.2
8175 * @see SetX(), GetY(), SetY()
8177 public function GetX() {
8178 //Get x position
8179 if ($this->rtl) {
8180 return ($this->w - $this->x);
8181 } else {
8182 return $this->x;
8187 * Returns the absolute X value of current position.
8188 * @return float
8189 * @public
8190 * @since 1.2
8191 * @see SetX(), GetY(), SetY()
8193 public function GetAbsX() {
8194 return $this->x;
8198 * Returns the ordinate of the current position.
8199 * @return float
8200 * @public
8201 * @since 1.0
8202 * @see SetY(), GetX(), SetX()
8204 public function GetY() {
8205 return $this->y;
8209 * Defines the abscissa of the current position.
8210 * If the passed value is negative, it is relative to the right of the page (or left if language is RTL).
8211 * @param $x (float) The value of the abscissa.
8212 * @param $rtloff (boolean) if true always uses the page top-left corner as origin of axis.
8213 * @public
8214 * @since 1.2
8215 * @see GetX(), GetY(), SetY(), SetXY()
8217 public function SetX($x, $rtloff=false) {
8218 if (!$rtloff AND $this->rtl) {
8219 if ($x >= 0) {
8220 $this->x = $this->w - $x;
8221 } else {
8222 $this->x = abs($x);
8224 } else {
8225 if ($x >= 0) {
8226 $this->x = $x;
8227 } else {
8228 $this->x = $this->w + $x;
8231 if ($this->x < 0) {
8232 $this->x = 0;
8234 if ($this->x > $this->w) {
8235 $this->x = $this->w;
8240 * Moves the current abscissa back to the left margin and sets the ordinate.
8241 * If the passed value is negative, it is relative to the bottom of the page.
8242 * @param $y (float) The value of the ordinate.
8243 * @param $resetx (bool) if true (default) reset the X position.
8244 * @param $rtloff (boolean) if true always uses the page top-left corner as origin of axis.
8245 * @public
8246 * @since 1.0
8247 * @see GetX(), GetY(), SetY(), SetXY()
8249 public function SetY($y, $resetx=true, $rtloff=false) {
8250 if ($resetx) {
8251 //reset x
8252 if (!$rtloff AND $this->rtl) {
8253 $this->x = $this->w - $this->rMargin;
8254 } else {
8255 $this->x = $this->lMargin;
8258 if ($y >= 0) {
8259 $this->y = $y;
8260 } else {
8261 $this->y = $this->h + $y;
8263 if ($this->y < 0) {
8264 $this->y = 0;
8266 if ($this->y > $this->h) {
8267 $this->y = $this->h;
8272 * Defines the abscissa and ordinate of the current position.
8273 * If the passed values are negative, they are relative respectively to the right and bottom of the page.
8274 * @param $x (float) The value of the abscissa.
8275 * @param $y (float) The value of the ordinate.
8276 * @param $rtloff (boolean) if true always uses the page top-left corner as origin of axis.
8277 * @public
8278 * @since 1.2
8279 * @see SetX(), SetY()
8281 public function SetXY($x, $y, $rtloff=false) {
8282 $this->SetY($y, false, $rtloff);
8283 $this->SetX($x, $rtloff);
8287 * Ouput input data and compress it if possible.
8288 * @param $data (string) Data to output.
8289 * @param $length (int) Data length in bytes.
8290 * @protected
8291 * @since 5.9.086
8293 protected function sendOutputData($data, $length) {
8294 if (!isset($_SERVER['HTTP_ACCEPT_ENCODING']) OR empty($_SERVER['HTTP_ACCEPT_ENCODING'])) {
8295 // the content length may vary if the server is using compression
8296 header('Content-Length: '.$length);
8298 echo $data;
8302 * Send the document to a given destination: string, local file or browser.
8303 * In the last case, the plug-in may be used (if present) or a download ("Save as" dialog box) may be forced.<br />
8304 * The method first calls Close() if necessary to terminate the document.
8305 * @param $name (string) The name of the file when saved. Note that special characters are removed and blanks characters are replaced with the underscore character.
8306 * @param $dest (string) Destination where to send the document. It can take one of the following values:<ul><li>I: send the file inline to the browser (default). The plug-in is used if available. The name given by name is used when one selects the "Save as" option on the link generating the PDF.</li><li>D: send to the browser and force a file download with the name given by name.</li><li>F: save to a local server file with the name given by name.</li><li>S: return the document as a string (name is ignored).</li><li>FI: equivalent to F + I option</li><li>FD: equivalent to F + D option</li><li>E: return the document as base64 mime multi-part email attachment (RFC 2045)</li></ul>
8307 * @public
8308 * @since 1.0
8309 * @see Close()
8311 public function Output($name='doc.pdf', $dest='I') {
8312 //Output PDF to some destination
8313 //Finish document if necessary
8314 if ($this->state < 3) {
8315 $this->Close();
8317 //Normalize parameters
8318 if (is_bool($dest)) {
8319 $dest = $dest ? 'D' : 'F';
8321 $dest = strtoupper($dest);
8322 if ($dest{0} != 'F') {
8323 $name = preg_replace('/[\s]+/', '_', $name);
8324 $name = preg_replace('/[^a-zA-Z0-9_\.-]/', '', $name);
8326 if ($this->sign) {
8327 // *** apply digital signature to the document ***
8328 // get the document content
8329 $pdfdoc = $this->getBuffer();
8330 // remove last newline
8331 $pdfdoc = substr($pdfdoc, 0, -1);
8332 // Remove the original buffer
8333 if (isset($this->diskcache) AND $this->diskcache) {
8334 // remove buffer file from cache
8335 unlink($this->buffer);
8337 unset($this->buffer);
8338 // remove filler space
8339 $byterange_string_len = strlen($this->byterange_string);
8340 // define the ByteRange
8341 $byte_range = array();
8342 $byte_range[0] = 0;
8343 $byte_range[1] = strpos($pdfdoc, $this->byterange_string) + $byterange_string_len + 10;
8344 $byte_range[2] = $byte_range[1] + $this->signature_max_length + 2;
8345 $byte_range[3] = strlen($pdfdoc) - $byte_range[2];
8346 $pdfdoc = substr($pdfdoc, 0, $byte_range[1]).substr($pdfdoc, $byte_range[2]);
8347 // replace the ByteRange
8348 $byterange = sprintf('/ByteRange[0 %u %u %u]', $byte_range[1], $byte_range[2], $byte_range[3]);
8349 $byterange .= str_repeat(' ', ($byterange_string_len - strlen($byterange)));
8350 $pdfdoc = str_replace($this->byterange_string, $byterange, $pdfdoc);
8351 // write the document to a temporary folder
8352 $tempdoc = tempnam(K_PATH_CACHE, 'tmppdf_');
8353 $f = fopen($tempdoc, 'wb');
8354 if (!$f) {
8355 $this->Error('Unable to create temporary file: '.$tempdoc);
8357 $pdfdoc_length = strlen($pdfdoc);
8358 fwrite($f, $pdfdoc, $pdfdoc_length);
8359 fclose($f);
8360 // get digital signature via openssl library
8361 $tempsign = tempnam(K_PATH_CACHE, 'tmpsig_');
8362 if (empty($this->signature_data['extracerts'])) {
8363 openssl_pkcs7_sign($tempdoc, $tempsign, $this->signature_data['signcert'], array($this->signature_data['privkey'], $this->signature_data['password']), array(), PKCS7_BINARY | PKCS7_DETACHED);
8364 } else {
8365 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']);
8367 unlink($tempdoc);
8368 // read signature
8369 $signature = file_get_contents($tempsign);
8370 unlink($tempsign);
8371 // extract signature
8372 $signature = substr($signature, $pdfdoc_length);
8373 $signature = substr($signature, (strpos($signature, "%%EOF\n\n------") + 13));
8374 $tmparr = explode("\n\n", $signature);
8375 $signature = $tmparr[1];
8376 unset($tmparr);
8377 // decode signature
8378 $signature = base64_decode(trim($signature));
8379 // convert signature to hex
8380 $signature = current(unpack('H*', $signature));
8381 $signature = str_pad($signature, $this->signature_max_length, '0');
8382 // disable disk caching
8383 $this->diskcache = false;
8384 // Add signature to the document
8385 $this->buffer = substr($pdfdoc, 0, $byte_range[1]).'<'.$signature.'>'.substr($pdfdoc, $byte_range[1]);
8386 $this->bufferlen = strlen($this->buffer);
8388 switch($dest) {
8389 case 'I': {
8390 // Send PDF to the standard output
8391 if (ob_get_contents()) {
8392 $this->Error('Some data has already been output, can\'t send PDF file');
8394 if (php_sapi_name() != 'cli') {
8395 // send output to a browser
8396 header('Content-Type: application/pdf');
8397 if (headers_sent()) {
8398 $this->Error('Some data has already been output to browser, can\'t send PDF file');
8400 header('Cache-Control: public, must-revalidate, max-age=0'); // HTTP/1.1
8401 header('Pragma: public');
8402 header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
8403 header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
8404 header('Content-Disposition: inline; filename="'.basename($name).'";');
8405 $this->sendOutputData($this->getBuffer(), $this->bufferlen);
8406 } else {
8407 echo $this->getBuffer();
8409 break;
8411 case 'D': {
8412 // download PDF as file
8413 if (ob_get_contents()) {
8414 $this->Error('Some data has already been output, can\'t send PDF file');
8416 header('Content-Description: File Transfer');
8417 if (headers_sent()) {
8418 $this->Error('Some data has already been output to browser, can\'t send PDF file');
8420 header('Cache-Control: public, must-revalidate, max-age=0'); // HTTP/1.1
8421 header('Pragma: public');
8422 header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
8423 header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
8424 // force download dialog
8425 if (strpos(php_sapi_name(), 'cgi') === false) {
8426 header('Content-Type: application/force-download');
8427 header('Content-Type: application/octet-stream', false);
8428 header('Content-Type: application/download', false);
8429 header('Content-Type: application/pdf', false);
8430 } else {
8431 header('Content-Type: application/pdf');
8433 // use the Content-Disposition header to supply a recommended filename
8434 header('Content-Disposition: attachment; filename="'.basename($name).'";');
8435 header('Content-Transfer-Encoding: binary');
8436 $this->sendOutputData($this->getBuffer(), $this->bufferlen);
8437 break;
8439 case 'F':
8440 case 'FI':
8441 case 'FD': {
8442 // save PDF to a local file
8443 if ($this->diskcache) {
8444 copy($this->buffer, $name);
8445 } else {
8446 $f = fopen($name, 'wb');
8447 if (!$f) {
8448 $this->Error('Unable to create output file: '.$name);
8450 fwrite($f, $this->getBuffer(), $this->bufferlen);
8451 fclose($f);
8453 if ($dest == 'FI') {
8454 // send headers to browser
8455 header('Content-Type: application/pdf');
8456 header('Cache-Control: public, must-revalidate, max-age=0'); // HTTP/1.1
8457 header('Pragma: public');
8458 header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
8459 header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
8460 header('Content-Disposition: inline; filename="'.basename($name).'";');
8461 $this->sendOutputData(file_get_contents($name), filesize($name));
8462 } elseif ($dest == 'FD') {
8463 // send headers to browser
8464 if (ob_get_contents()) {
8465 $this->Error('Some data has already been output, can\'t send PDF file');
8467 header('Content-Description: File Transfer');
8468 if (headers_sent()) {
8469 $this->Error('Some data has already been output to browser, can\'t send PDF file');
8471 header('Cache-Control: public, must-revalidate, max-age=0'); // HTTP/1.1
8472 header('Pragma: public');
8473 header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
8474 header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
8475 // force download dialog
8476 if (strpos(php_sapi_name(), 'cgi') === false) {
8477 header('Content-Type: application/force-download');
8478 header('Content-Type: application/octet-stream', false);
8479 header('Content-Type: application/download', false);
8480 header('Content-Type: application/pdf', false);
8481 } else {
8482 header('Content-Type: application/pdf');
8484 // use the Content-Disposition header to supply a recommended filename
8485 header('Content-Disposition: attachment; filename="'.basename($name).'";');
8486 header('Content-Transfer-Encoding: binary');
8487 $this->sendOutputData(file_get_contents($name), filesize($name));
8489 break;
8491 case 'E': {
8492 // return PDF as base64 mime multi-part email attachment (RFC 2045)
8493 $retval = 'Content-Type: application/pdf;'."\r\n";
8494 $retval .= ' name="'.$name.'"'."\r\n";
8495 $retval .= 'Content-Transfer-Encoding: base64'."\r\n";
8496 $retval .= 'Content-Disposition: attachment;'."\r\n";
8497 $retval .= ' filename="'.$name.'"'."\r\n\r\n";
8498 $retval .= chunk_split(base64_encode($this->getBuffer()), 76, "\r\n");
8499 return $retval;
8501 case 'S': {
8502 // returns PDF as a string
8503 return $this->getBuffer();
8505 default: {
8506 $this->Error('Incorrect output destination: '.$dest);
8509 return '';
8513 * Unset all class variables except the following critical variables: internal_encoding, state, bufferlen, buffer and diskcache.
8514 * @param $destroyall (boolean) if true destroys all class variables, otherwise preserves critical variables.
8515 * @param $preserve_objcopy (boolean) if true preserves the objcopy variable
8516 * @public
8517 * @since 4.5.016 (2009-02-24)
8519 public function _destroy($destroyall=false, $preserve_objcopy=false) {
8520 if ($destroyall AND isset($this->diskcache) AND $this->diskcache AND (!$preserve_objcopy) AND (!$this->empty_string($this->buffer))) {
8521 // remove buffer file from cache
8522 unlink($this->buffer);
8524 foreach (array_keys(get_object_vars($this)) as $val) {
8525 if ($destroyall OR (
8526 ($val != 'internal_encoding')
8527 AND ($val != 'state')
8528 AND ($val != 'bufferlen')
8529 AND ($val != 'buffer')
8530 AND ($val != 'diskcache')
8531 AND ($val != 'sign')
8532 AND ($val != 'signature_data')
8533 AND ($val != 'signature_max_length')
8534 AND ($val != 'byterange_string')
8535 )) {
8536 if ((!$preserve_objcopy OR ($val != 'objcopy')) AND isset($this->$val)) {
8537 unset($this->$val);
8544 * Check for locale-related bug
8545 * @protected
8547 protected function _dochecks() {
8548 //Check for locale-related bug
8549 if (1.1 == 1) {
8550 $this->Error('Don\'t alter the locale before including class file');
8552 //Check for decimal separator
8553 if (sprintf('%.1F', 1.0) != '1.0') {
8554 setlocale(LC_NUMERIC, 'C');
8559 * Return fonts path
8560 * @return string
8561 * @protected
8563 protected function _getfontpath() {
8564 if (!defined('K_PATH_FONTS') AND is_dir(dirname(__FILE__).'/fonts')) {
8565 define('K_PATH_FONTS', dirname(__FILE__).'/fonts/');
8567 return defined('K_PATH_FONTS') ? K_PATH_FONTS : '';
8571 * Return an array containing variations for the basic page number alias.
8572 * @param $a (string) Base alias.
8573 * @return array of page number aliases
8574 * @protected
8576 protected function getInternalPageNumberAliases($a= '') {
8577 $alias = array();
8578 // build array of Unicode + ASCII variants (the order is important)
8579 $alias = array('u' => array(), 'a' => array());
8580 $u = '{'.$a.'}';
8581 $alias['u'][] = $this->_escape($u);
8582 if ($this->isunicode) {
8583 $alias['u'][] = $this->_escape($this->UTF8ToLatin1($u));
8584 $alias['u'][] = $this->_escape($this->utf8StrRev($u, false, $this->tmprtl));
8585 $alias['a'][] = $this->_escape($this->UTF8ToLatin1($a));
8586 $alias['a'][] = $this->_escape($this->utf8StrRev($a, false, $this->tmprtl));
8588 $alias['a'][] = $this->_escape($a);
8589 return $alias;
8593 * Return an array containing all internal page aliases.
8594 * @return array of page number aliases
8595 * @protected
8597 protected function getAllInternalPageNumberAliases() {
8598 $basic_alias = array($this->alias_tot_pages, $this->alias_num_page, $this->alias_group_tot_pages, $this->alias_group_num_page, $this->alias_right_shift);
8599 $pnalias = array();
8600 foreach($basic_alias as $k => $a) {
8601 $pnalias[$k] = $this->getInternalPageNumberAliases($a);
8603 return $pnalias;
8607 * Replace page number aliases with number.
8608 * @param $page (string) Page content.
8609 * @param $replace (array) Array of replacements (array keys are replacement strings, values are alias arrays).
8610 * @param $diff (int) If passed, this will be set to the total char number difference between alias and replacements.
8611 * @return replaced page content and updated $diff parameter as array.
8612 * @protected
8614 protected function replacePageNumAliases($page, $replace, $diff=0) {
8615 foreach ($replace as $rep) {
8616 foreach ($rep[3] as $a) {
8617 if (strpos($page, $a) !== false) {
8618 $page = str_replace($a, $rep[0], $page);
8619 $diff += ($rep[2] - $rep[1]);
8623 return array($page, $diff);
8627 * Replace right shift page number aliases with spaces to correct right alignment.
8628 * This works perfectly only when using monospaced fonts.
8629 * @param $page (string) Page content.
8630 * @param $aliases (array) Array of page aliases.
8631 * @param $diff (int) initial difference to add.
8632 * @return replaced page content.
8633 * @protected
8635 protected function replaceRightShiftPageNumAliases($page, $aliases, $diff) {
8636 foreach ($aliases as $type => $alias) {
8637 foreach ($alias as $a) {
8638 // find position of compensation factor
8639 $startnum = (strpos($a, ':') + 1);
8640 $a = substr($a, 0, $startnum);
8641 if (($pos = strpos($page, $a)) !== false) {
8642 // end of alias
8643 $endnum = strpos($page, '}', $pos);
8644 // string to be replaced
8645 $aa = substr($page, $pos, ($endnum - $pos + 1));
8646 // get compensation factor
8647 $ratio = substr($page, ($pos + $startnum), ($endnum - $pos - $startnum));
8648 $ratio = preg_replace('/[^0-9\.]/', '', $ratio);
8649 $ratio = floatval($ratio);
8650 if ($type == 'u') {
8651 $chrdiff = floor(($diff + 12) * $ratio);
8652 $shift = str_repeat(' ', $chrdiff);
8653 $shift = $this->UTF8ToUTF16BE($shift, false);
8654 } else {
8655 $chrdiff = floor(($diff + 11) * $ratio);
8656 $shift = str_repeat(' ', $chrdiff);
8658 $page = str_replace($aa, $shift, $page);
8662 return $page;
8666 * Output pages (and replace page number aliases).
8667 * @protected
8669 protected function _putpages() {
8670 $filter = ($this->compress) ? '/Filter /FlateDecode ' : '';
8671 // get internal aliases for page numbers
8672 $pnalias = $this->getAllInternalPageNumberAliases();
8673 $num_pages = $this->numpages;
8674 $ptpa = $this->formatPageNumber(($this->starting_page_number + $num_pages - 1));
8675 $ptpu = $this->UTF8ToUTF16BE($ptpa, false);
8676 $ptp_num_chars = $this->GetNumChars($ptpa);
8677 $pagegroupnum = 0;
8678 $groupnum = 0;
8679 $ptgu = 1;
8680 $ptga = 1;
8681 for ($n = 1; $n <= $num_pages; ++$n) {
8682 // get current page
8683 $temppage = $this->getPageBuffer($n);
8684 $pagelen = strlen($temppage);
8685 // set replacements for total pages number
8686 $pnpa = $this->formatPageNumber(($this->starting_page_number + $n - 1));
8687 $pnpu = $this->UTF8ToUTF16BE($pnpa, false);
8688 $pnp_num_chars = $this->GetNumChars($pnpa);
8689 $pdiff = 0; // difference used for right shift alignment of page numbers
8690 $gdiff = 0; // difference used for right shift alignment of page group numbers
8691 if (!empty($this->pagegroups)) {
8692 if (isset($this->newpagegroup[$n])) {
8693 $pagegroupnum = 0;
8694 ++$groupnum;
8695 $ptga = $this->formatPageNumber($this->pagegroups[$groupnum]);
8696 $ptgu = $this->UTF8ToUTF16BE($ptga, false);
8697 $ptg_num_chars = $this->GetNumChars($ptga);
8699 ++$pagegroupnum;
8700 $pnga = $this->formatPageNumber($pagegroupnum);
8701 $pngu = $this->UTF8ToUTF16BE($pnga, false);
8702 $png_num_chars = $this->GetNumChars($pnga);
8703 // replace page numbers
8704 $replace = array();
8705 $replace[] = array($ptgu, $ptg_num_chars, 9, $pnalias[2]['u']);
8706 $replace[] = array($ptga, $ptg_num_chars, 7, $pnalias[2]['a']);
8707 $replace[] = array($pngu, $png_num_chars, 9, $pnalias[3]['u']);
8708 $replace[] = array($pnga, $png_num_chars, 7, $pnalias[3]['a']);
8709 list($temppage, $gdiff) = $this->replacePageNumAliases($temppage, $replace, $gdiff);
8711 // replace page numbers
8712 $replace = array();
8713 $replace[] = array($ptpu, $ptp_num_chars, 9, $pnalias[0]['u']);
8714 $replace[] = array($ptpa, $ptp_num_chars, 7, $pnalias[0]['a']);
8715 $replace[] = array($pnpu, $pnp_num_chars, 9, $pnalias[1]['u']);
8716 $replace[] = array($pnpa, $pnp_num_chars, 7, $pnalias[1]['a']);
8717 list($temppage, $pdiff) = $this->replacePageNumAliases($temppage, $replace, $pdiff);
8718 // replace right shift alias
8719 $temppage = $this->replaceRightShiftPageNumAliases($temppage, $pnalias[4], max($pdiff, $gdiff));
8720 // replace EPS marker
8721 $temppage = str_replace($this->epsmarker, '', $temppage);
8722 //Page
8723 $this->page_obj_id[$n] = $this->_newobj();
8724 $out = '<<';
8725 $out .= ' /Type /Page';
8726 $out .= ' /Parent 1 0 R';
8727 $out .= ' /LastModified '.$this->_datestring();
8728 $out .= ' /Resources 2 0 R';
8729 $boxes = array('MediaBox', 'CropBox', 'BleedBox', 'TrimBox', 'ArtBox');
8730 foreach ($boxes as $box) {
8731 $out .= ' /'.$box;
8732 $out .= sprintf(' [%.2F %.2F %.2F %.2F]', $this->pagedim[$n][$box]['llx'], $this->pagedim[$n][$box]['lly'], $this->pagedim[$n][$box]['urx'], $this->pagedim[$n][$box]['ury']);
8734 if (isset($this->pagedim[$n]['BoxColorInfo']) AND !empty($this->pagedim[$n]['BoxColorInfo'])) {
8735 $out .= ' /BoxColorInfo <<';
8736 foreach ($boxes as $box) {
8737 if (isset($this->pagedim[$n]['BoxColorInfo'][$box])) {
8738 $out .= ' /'.$box.' <<';
8739 if (isset($this->pagedim[$n]['BoxColorInfo'][$box]['C'])) {
8740 $color = $this->pagedim[$n]['BoxColorInfo'][$box]['C'];
8741 $out .= ' /C [';
8742 $out .= sprintf(' %.3F %.3F %.3F', $color[0]/255, $color[1]/255, $color[2]/255);
8743 $out .= ' ]';
8745 if (isset($this->pagedim[$n]['BoxColorInfo'][$box]['W'])) {
8746 $out .= ' /W '.($this->pagedim[$n]['BoxColorInfo'][$box]['W'] * $this->k);
8748 if (isset($this->pagedim[$n]['BoxColorInfo'][$box]['S'])) {
8749 $out .= ' /S /'.$this->pagedim[$n]['BoxColorInfo'][$box]['S'];
8751 if (isset($this->pagedim[$n]['BoxColorInfo'][$box]['D'])) {
8752 $dashes = $this->pagedim[$n]['BoxColorInfo'][$box]['D'];
8753 $out .= ' /D [';
8754 foreach ($dashes as $dash) {
8755 $out .= sprintf(' %.3F', ($dash * $this->k));
8757 $out .= ' ]';
8759 $out .= ' >>';
8762 $out .= ' >>';
8764 $out .= ' /Contents '.($this->n + 1).' 0 R';
8765 $out .= ' /Rotate '.$this->pagedim[$n]['Rotate'];
8766 $out .= ' /Group << /Type /Group /S /Transparency /CS /DeviceRGB >>';
8767 if (isset($this->pagedim[$n]['trans']) AND !empty($this->pagedim[$n]['trans'])) {
8768 // page transitions
8769 if (isset($this->pagedim[$n]['trans']['Dur'])) {
8770 $out .= ' /Dur '.$this->pagedim[$n]['trans']['Dur'];
8772 $out .= ' /Trans <<';
8773 $out .= ' /Type /Trans';
8774 if (isset($this->pagedim[$n]['trans']['S'])) {
8775 $out .= ' /S /'.$this->pagedim[$n]['trans']['S'];
8777 if (isset($this->pagedim[$n]['trans']['D'])) {
8778 $out .= ' /D '.$this->pagedim[$n]['trans']['D'];
8780 if (isset($this->pagedim[$n]['trans']['Dm'])) {
8781 $out .= ' /Dm /'.$this->pagedim[$n]['trans']['Dm'];
8783 if (isset($this->pagedim[$n]['trans']['M'])) {
8784 $out .= ' /M /'.$this->pagedim[$n]['trans']['M'];
8786 if (isset($this->pagedim[$n]['trans']['Di'])) {
8787 $out .= ' /Di '.$this->pagedim[$n]['trans']['Di'];
8789 if (isset($this->pagedim[$n]['trans']['SS'])) {
8790 $out .= ' /SS '.$this->pagedim[$n]['trans']['SS'];
8792 if (isset($this->pagedim[$n]['trans']['B'])) {
8793 $out .= ' /B '.$this->pagedim[$n]['trans']['B'];
8795 $out .= ' >>';
8797 $out .= $this->_getannotsrefs($n);
8798 $out .= ' /PZ '.$this->pagedim[$n]['PZ'];
8799 $out .= ' >>';
8800 $out .= "\n".'endobj';
8801 $this->_out($out);
8802 //Page content
8803 $p = ($this->compress) ? gzcompress($temppage) : $temppage;
8804 $this->_newobj();
8805 $p = $this->_getrawstream($p);
8806 $this->_out('<<'.$filter.'/Length '.strlen($p).'>> stream'."\n".$p."\n".'endstream'."\n".'endobj');
8807 if ($this->diskcache) {
8808 // remove temporary files
8809 unlink($this->pages[$n]);
8812 //Pages root
8813 $out = $this->_getobj(1)."\n";
8814 $out .= '<< /Type /Pages /Kids [';
8815 foreach($this->page_obj_id as $page_obj) {
8816 $out .= ' '.$page_obj.' 0 R';
8818 $out .= ' ] /Count '.$num_pages.' >>';
8819 $out .= "\n".'endobj';
8820 $this->_out($out);
8824 * Output references to page annotations
8825 * @param $n (int) page number
8826 * @protected
8827 * @author Nicola Asuni
8828 * @since 4.7.000 (2008-08-29)
8829 * @deprecated
8831 protected function _putannotsrefs($n) {
8832 $this->_out($this->_getannotsrefs($n));
8836 * Get references to page annotations.
8837 * @param $n (int) page number
8838 * @return string
8839 * @protected
8840 * @author Nicola Asuni
8841 * @since 5.0.010 (2010-05-17)
8843 protected function _getannotsrefs($n) {
8844 if (!(isset($this->PageAnnots[$n]) OR ($this->sign AND isset($this->signature_data['cert_type'])))) {
8845 return '';
8847 $out = ' /Annots [';
8848 if (isset($this->PageAnnots[$n])) {
8849 foreach ($this->PageAnnots[$n] as $key => $val) {
8850 if (!in_array($val['n'], $this->radio_groups)) {
8851 $out .= ' '.$val['n'].' 0 R';
8854 // add radiobutton groups
8855 if (isset($this->radiobutton_groups[$n])) {
8856 foreach ($this->radiobutton_groups[$n] as $key => $data) {
8857 if (isset($data['n'])) {
8858 $out .= ' '.$data['n'].' 0 R';
8863 if ($this->sign AND ($n == $this->signature_appearance['page']) AND isset($this->signature_data['cert_type'])) {
8864 // set reference for signature object
8865 $out .= ' '.$this->sig_obj_id.' 0 R';
8867 if (!empty($this->empty_signature_appearance)) {
8868 foreach ($this->empty_signature_appearance as $esa) {
8869 if ($esa['page'] == $n) {
8870 // set reference for empty signature objects
8871 $out .= ' '.$esa['objid'].' 0 R';
8875 $out .= ' ]';
8876 return $out;
8880 * Output annotations objects for all pages.
8881 * !!! THIS METHOD IS NOT YET COMPLETED !!!
8882 * See section 12.5 of PDF 32000_2008 reference.
8883 * @protected
8884 * @author Nicola Asuni
8885 * @since 4.0.018 (2008-08-06)
8887 protected function _putannotsobjs() {
8888 // reset object counter
8889 for ($n=1; $n <= $this->numpages; ++$n) {
8890 if (isset($this->PageAnnots[$n])) {
8891 // set page annotations
8892 foreach ($this->PageAnnots[$n] as $key => $pl) {
8893 $annot_obj_id = $this->PageAnnots[$n][$key]['n'];
8894 // create annotation object for grouping radiobuttons
8895 if (isset($this->radiobutton_groups[$n][$pl['txt']]) AND is_array($this->radiobutton_groups[$n][$pl['txt']])) {
8896 $radio_button_obj_id = $this->radiobutton_groups[$n][$pl['txt']]['n'];
8897 $annots = '<<';
8898 $annots .= ' /Type /Annot';
8899 $annots .= ' /Subtype /Widget';
8900 $annots .= ' /Rect [0 0 0 0]';
8901 $annots .= ' /T '.$this->_datastring($pl['txt'], $radio_button_obj_id);
8902 $annots .= ' /FT /Btn';
8903 $annots .= ' /Ff 49152';
8904 $annots .= ' /Kids [';
8905 foreach ($this->radiobutton_groups[$n][$pl['txt']] as $key => $data) {
8906 if ($key !== 'n') {
8907 $annots .= ' '.$data['kid'].' 0 R';
8908 if ($data['def'] !== 'Off') {
8909 $defval = $data['def'];
8913 $annots .= ' ]';
8914 if (isset($defval)) {
8915 $annots .= ' /V /'.$defval;
8917 $annots .= ' >>';
8918 $this->_out($this->_getobj($radio_button_obj_id)."\n".$annots."\n".'endobj');
8919 $this->form_obj_id[] = $radio_button_obj_id;
8920 // store object id to be used on Parent entry of Kids
8921 $this->radiobutton_groups[$n][$pl['txt']] = $radio_button_obj_id;
8923 $formfield = false;
8924 $pl['opt'] = array_change_key_case($pl['opt'], CASE_LOWER);
8925 $a = $pl['x'] * $this->k;
8926 $b = $this->pagedim[$n]['h'] - (($pl['y'] + $pl['h']) * $this->k);
8927 $c = $pl['w'] * $this->k;
8928 $d = $pl['h'] * $this->k;
8929 $rect = sprintf('%.2F %.2F %.2F %.2F', $a, $b, $a+$c, $b+$d);
8930 // create new annotation object
8931 $annots = '<</Type /Annot';
8932 $annots .= ' /Subtype /'.$pl['opt']['subtype'];
8933 $annots .= ' /Rect ['.$rect.']';
8934 $ft = array('Btn', 'Tx', 'Ch', 'Sig');
8935 if (isset($pl['opt']['ft']) AND in_array($pl['opt']['ft'], $ft)) {
8936 $annots .= ' /FT /'.$pl['opt']['ft'];
8937 $formfield = true;
8939 $annots .= ' /Contents '.$this->_textstring($pl['txt'], $annot_obj_id);
8940 $annots .= ' /P '.$this->page_obj_id[$n].' 0 R';
8941 $annots .= ' /NM '.$this->_datastring(sprintf('%04u-%04u', $n, $key), $annot_obj_id);
8942 $annots .= ' /M '.$this->_datestring($annot_obj_id);
8943 if (isset($pl['opt']['f'])) {
8944 $val = 0;
8945 if (is_array($pl['opt']['f'])) {
8946 foreach ($pl['opt']['f'] as $f) {
8947 switch (strtolower($f)) {
8948 case 'invisible': {
8949 $val += 1 << 0;
8950 break;
8952 case 'hidden': {
8953 $val += 1 << 1;
8954 break;
8956 case 'print': {
8957 $val += 1 << 2;
8958 break;
8960 case 'nozoom': {
8961 $val += 1 << 3;
8962 break;
8964 case 'norotate': {
8965 $val += 1 << 4;
8966 break;
8968 case 'noview': {
8969 $val += 1 << 5;
8970 break;
8972 case 'readonly': {
8973 $val += 1 << 6;
8974 break;
8976 case 'locked': {
8977 $val += 1 << 8;
8978 break;
8980 case 'togglenoview': {
8981 $val += 1 << 9;
8982 break;
8984 case 'lockedcontents': {
8985 $val += 1 << 10;
8986 break;
8988 default: {
8989 break;
8993 } else {
8994 $val = intval($pl['opt']['f']);
8996 $annots .= ' /F '.intval($val);
8998 if (isset($pl['opt']['as']) AND is_string($pl['opt']['as'])) {
8999 $annots .= ' /AS /'.$pl['opt']['as'];
9001 if (isset($pl['opt']['ap'])) {
9002 // appearance stream
9003 $annots .= ' /AP <<';
9004 if (is_array($pl['opt']['ap'])) {
9005 foreach ($pl['opt']['ap'] as $apmode => $apdef) {
9006 // $apmode can be: n = normal; r = rollover; d = down;
9007 $annots .= ' /'.strtoupper($apmode);
9008 if (is_array($apdef)) {
9009 $annots .= ' <<';
9010 foreach ($apdef as $apstate => $stream) {
9011 // reference to XObject that define the appearance for this mode-state
9012 $apsobjid = $this->_putAPXObject($c, $d, $stream);
9013 $annots .= ' /'.$apstate.' '.$apsobjid.' 0 R';
9015 $annots .= ' >>';
9016 } else {
9017 // reference to XObject that define the appearance for this mode
9018 $apsobjid = $this->_putAPXObject($c, $d, $apdef);
9019 $annots .= ' '.$apsobjid.' 0 R';
9022 } else {
9023 $annots .= $pl['opt']['ap'];
9025 $annots .= ' >>';
9027 if (isset($pl['opt']['bs']) AND (is_array($pl['opt']['bs']))) {
9028 $annots .= ' /BS <<';
9029 $annots .= ' /Type /Border';
9030 if (isset($pl['opt']['bs']['w'])) {
9031 $annots .= ' /W '.intval($pl['opt']['bs']['w']);
9033 $bstyles = array('S', 'D', 'B', 'I', 'U');
9034 if (isset($pl['opt']['bs']['s']) AND in_array($pl['opt']['bs']['s'], $bstyles)) {
9035 $annots .= ' /S /'.$pl['opt']['bs']['s'];
9037 if (isset($pl['opt']['bs']['d']) AND (is_array($pl['opt']['bs']['d']))) {
9038 $annots .= ' /D [';
9039 foreach ($pl['opt']['bs']['d'] as $cord) {
9040 $annots .= ' '.intval($cord);
9042 $annots .= ']';
9044 $annots .= ' >>';
9045 } else {
9046 $annots .= ' /Border [';
9047 if (isset($pl['opt']['border']) AND (count($pl['opt']['border']) >= 3)) {
9048 $annots .= intval($pl['opt']['border'][0]).' ';
9049 $annots .= intval($pl['opt']['border'][1]).' ';
9050 $annots .= intval($pl['opt']['border'][2]);
9051 if (isset($pl['opt']['border'][3]) AND is_array($pl['opt']['border'][3])) {
9052 $annots .= ' [';
9053 foreach ($pl['opt']['border'][3] as $dash) {
9054 $annots .= intval($dash).' ';
9056 $annots .= ']';
9058 } else {
9059 $annots .= '0 0 0';
9061 $annots .= ']';
9063 if (isset($pl['opt']['be']) AND (is_array($pl['opt']['be']))) {
9064 $annots .= ' /BE <<';
9065 $bstyles = array('S', 'C');
9066 if (isset($pl['opt']['be']['s']) AND in_array($pl['opt']['be']['s'], $markups)) {
9067 $annots .= ' /S /'.$pl['opt']['bs']['s'];
9068 } else {
9069 $annots .= ' /S /S';
9071 if (isset($pl['opt']['be']['i']) AND ($pl['opt']['be']['i'] >= 0) AND ($pl['opt']['be']['i'] <= 2)) {
9072 $annots .= ' /I '.sprintf(' %.4F', $pl['opt']['be']['i']);
9074 $annots .= '>>';
9076 if (isset($pl['opt']['c']) AND (is_array($pl['opt']['c'])) AND !empty($pl['opt']['c'])) {
9077 $annots .= ' /C [';
9078 foreach ($pl['opt']['c'] as $col) {
9079 $col = intval($col);
9080 $color = $col <= 0 ? 0 : ($col >= 255 ? 1 : $col / 255);
9081 $annots .= sprintf(' %.4F', $color);
9083 $annots .= ']';
9085 //$annots .= ' /StructParent ';
9086 //$annots .= ' /OC ';
9087 $markups = array('text', 'freetext', 'line', 'square', 'circle', 'polygon', 'polyline', 'highlight', 'underline', 'squiggly', 'strikeout', 'stamp', 'caret', 'ink', 'fileattachment', 'sound');
9088 if (in_array(strtolower($pl['opt']['subtype']), $markups)) {
9089 // this is a markup type
9090 if (isset($pl['opt']['t']) AND is_string($pl['opt']['t'])) {
9091 $annots .= ' /T '.$this->_textstring($pl['opt']['t'], $annot_obj_id);
9093 //$annots .= ' /Popup ';
9094 if (isset($pl['opt']['ca'])) {
9095 $annots .= ' /CA '.sprintf('%.4F', floatval($pl['opt']['ca']));
9097 if (isset($pl['opt']['rc'])) {
9098 $annots .= ' /RC '.$this->_textstring($pl['opt']['rc'], $annot_obj_id);
9100 $annots .= ' /CreationDate '.$this->_datestring($annot_obj_id);
9101 //$annots .= ' /IRT ';
9102 if (isset($pl['opt']['subj'])) {
9103 $annots .= ' /Subj '.$this->_textstring($pl['opt']['subj'], $annot_obj_id);
9105 //$annots .= ' /RT ';
9106 //$annots .= ' /IT ';
9107 //$annots .= ' /ExData ';
9109 $lineendings = array('Square', 'Circle', 'Diamond', 'OpenArrow', 'ClosedArrow', 'None', 'Butt', 'ROpenArrow', 'RClosedArrow', 'Slash');
9110 // Annotation types
9111 switch (strtolower($pl['opt']['subtype'])) {
9112 case 'text': {
9113 if (isset($pl['opt']['open'])) {
9114 $annots .= ' /Open '. (strtolower($pl['opt']['open']) == 'true' ? 'true' : 'false');
9116 $iconsapp = array('Comment', 'Help', 'Insert', 'Key', 'NewParagraph', 'Note', 'Paragraph');
9117 if (isset($pl['opt']['name']) AND in_array($pl['opt']['name'], $iconsapp)) {
9118 $annots .= ' /Name /'.$pl['opt']['name'];
9119 } else {
9120 $annots .= ' /Name /Note';
9122 $statemodels = array('Marked', 'Review');
9123 if (isset($pl['opt']['statemodel']) AND in_array($pl['opt']['statemodel'], $statemodels)) {
9124 $annots .= ' /StateModel /'.$pl['opt']['statemodel'];
9125 } else {
9126 $pl['opt']['statemodel'] = 'Marked';
9127 $annots .= ' /StateModel /'.$pl['opt']['statemodel'];
9129 if ($pl['opt']['statemodel'] == 'Marked') {
9130 $states = array('Accepted', 'Unmarked');
9131 } else {
9132 $states = array('Accepted', 'Rejected', 'Cancelled', 'Completed', 'None');
9134 if (isset($pl['opt']['state']) AND in_array($pl['opt']['state'], $states)) {
9135 $annots .= ' /State /'.$pl['opt']['state'];
9136 } else {
9137 if ($pl['opt']['statemodel'] == 'Marked') {
9138 $annots .= ' /State /Unmarked';
9139 } else {
9140 $annots .= ' /State /None';
9143 break;
9145 case 'link': {
9146 if (is_string($pl['txt'])) {
9147 // external URI link
9148 $annots .= ' /A <</S /URI /URI '.$this->_datastring($this->unhtmlentities($pl['txt']), $annot_obj_id).'>>';
9149 } else {
9150 // internal link
9151 $l = $this->links[$pl['txt']];
9152 $annots .= sprintf(' /Dest [%u 0 R /XYZ 0 %.2F null]', $this->page_obj_id[($l[0])], ($this->pagedim[$l[0]]['h'] - ($l[1] * $this->k)));
9154 $hmodes = array('N', 'I', 'O', 'P');
9155 if (isset($pl['opt']['h']) AND in_array($pl['opt']['h'], $hmodes)) {
9156 $annots .= ' /H /'.$pl['opt']['h'];
9157 } else {
9158 $annots .= ' /H /I';
9160 //$annots .= ' /PA ';
9161 //$annots .= ' /Quadpoints ';
9162 break;
9164 case 'freetext': {
9165 if (isset($pl['opt']['da']) AND !empty($pl['opt']['da'])) {
9166 $annots .= ' /DA ('.$pl['opt']['da'].')';
9168 if (isset($pl['opt']['q']) AND ($pl['opt']['q'] >= 0) AND ($pl['opt']['q'] <= 2)) {
9169 $annots .= ' /Q '.intval($pl['opt']['q']);
9171 if (isset($pl['opt']['rc'])) {
9172 $annots .= ' /RC '.$this->_textstring($pl['opt']['rc'], $annot_obj_id);
9174 if (isset($pl['opt']['ds'])) {
9175 $annots .= ' /DS '.$this->_textstring($pl['opt']['ds'], $annot_obj_id);
9177 if (isset($pl['opt']['cl']) AND is_array($pl['opt']['cl'])) {
9178 $annots .= ' /CL [';
9179 foreach ($pl['opt']['cl'] as $cl) {
9180 $annots .= sprintf('%.4F ', $cl * $this->k);
9182 $annots .= ']';
9184 $tfit = array('FreeText', 'FreeTextCallout', 'FreeTextTypeWriter');
9185 if (isset($pl['opt']['it']) AND in_array($pl['opt']['it'], $tfit)) {
9186 $annots .= ' /IT /'.$pl['opt']['it'];
9188 if (isset($pl['opt']['rd']) AND is_array($pl['opt']['rd'])) {
9189 $l = $pl['opt']['rd'][0] * $this->k;
9190 $r = $pl['opt']['rd'][1] * $this->k;
9191 $t = $pl['opt']['rd'][2] * $this->k;
9192 $b = $pl['opt']['rd'][3] * $this->k;
9193 $annots .= ' /RD ['.sprintf('%.2F %.2F %.2F %.2F', $l, $r, $t, $b).']';
9195 if (isset($pl['opt']['le']) AND in_array($pl['opt']['le'], $lineendings)) {
9196 $annots .= ' /LE /'.$pl['opt']['le'];
9198 break;
9200 case 'line': {
9201 break;
9203 case 'square': {
9204 break;
9206 case 'circle': {
9207 break;
9209 case 'polygon': {
9210 break;
9212 case 'polyline': {
9213 break;
9215 case 'highlight': {
9216 break;
9218 case 'underline': {
9219 break;
9221 case 'squiggly': {
9222 break;
9224 case 'strikeout': {
9225 break;
9227 case 'stamp': {
9228 break;
9230 case 'caret': {
9231 break;
9233 case 'ink': {
9234 break;
9236 case 'popup': {
9237 break;
9239 case 'fileattachment': {
9240 if (!isset($pl['opt']['fs'])) {
9241 break;
9243 $filename = basename($pl['opt']['fs']);
9244 if (isset($this->embeddedfiles[$filename]['n'])) {
9245 $annots .= ' /FS <</Type /Filespec /F '.$this->_datastring($filename, $annot_obj_id).' /EF <</F '.$this->embeddedfiles[$filename]['n'].' 0 R>> >>';
9246 $iconsapp = array('Graph', 'Paperclip', 'PushPin', 'Tag');
9247 if (isset($pl['opt']['name']) AND in_array($pl['opt']['name'], $iconsapp)) {
9248 $annots .= ' /Name /'.$pl['opt']['name'];
9249 } else {
9250 $annots .= ' /Name /PushPin';
9253 break;
9255 case 'sound': {
9256 if (!isset($pl['opt']['fs'])) {
9257 break;
9259 $filename = basename($pl['opt']['fs']);
9260 if (isset($this->embeddedfiles[$filename]['n'])) {
9261 // ... TO BE COMPLETED ...
9262 // /R /C /B /E /CO /CP
9263 $annots .= ' /Sound <</Type /Filespec /F '.$this->_datastring($filename, $annot_obj_id).' /EF <</F '.$this->embeddedfiles[$filename]['n'].' 0 R>> >>';
9264 $iconsapp = array('Speaker', 'Mic');
9265 if (isset($pl['opt']['name']) AND in_array($pl['opt']['name'], $iconsapp)) {
9266 $annots .= ' /Name /'.$pl['opt']['name'];
9267 } else {
9268 $annots .= ' /Name /Speaker';
9271 break;
9273 case 'movie': {
9274 break;
9276 case 'widget': {
9277 $hmode = array('N', 'I', 'O', 'P', 'T');
9278 if (isset($pl['opt']['h']) AND in_array($pl['opt']['h'], $hmode)) {
9279 $annots .= ' /H /'.$pl['opt']['h'];
9281 if (isset($pl['opt']['mk']) AND (is_array($pl['opt']['mk'])) AND !empty($pl['opt']['mk'])) {
9282 $annots .= ' /MK <<';
9283 if (isset($pl['opt']['mk']['r'])) {
9284 $annots .= ' /R '.$pl['opt']['mk']['r'];
9286 if (isset($pl['opt']['mk']['bc']) AND (is_array($pl['opt']['mk']['bc']))) {
9287 $annots .= ' /BC [';
9288 foreach($pl['opt']['mk']['bc'] AS $col) {
9289 $col = intval($col);
9290 $color = $col <= 0 ? 0 : ($col >= 255 ? 1 : $col / 255);
9291 $annots .= sprintf(' %.2F', $color);
9293 $annots .= ']';
9295 if (isset($pl['opt']['mk']['bg']) AND (is_array($pl['opt']['mk']['bg']))) {
9296 $annots .= ' /BG [';
9297 foreach($pl['opt']['mk']['bg'] AS $col) {
9298 $col = intval($col);
9299 $color = $col <= 0 ? 0 : ($col >= 255 ? 1 : $col / 255);
9300 $annots .= sprintf(' %.2F', $color);
9302 $annots .= ']';
9304 if (isset($pl['opt']['mk']['ca'])) {
9305 $annots .= ' /CA '.$pl['opt']['mk']['ca'];
9307 if (isset($pl['opt']['mk']['rc'])) {
9308 $annots .= ' /RC '.$pl['opt']['mk']['rc'];
9310 if (isset($pl['opt']['mk']['ac'])) {
9311 $annots .= ' /AC '.$pl['opt']['mk']['ac'];
9313 if (isset($pl['opt']['mk']['i'])) {
9314 $info = $this->getImageBuffer($pl['opt']['mk']['i']);
9315 if ($info !== false) {
9316 $annots .= ' /I '.$info['n'].' 0 R';
9319 if (isset($pl['opt']['mk']['ri'])) {
9320 $info = $this->getImageBuffer($pl['opt']['mk']['ri']);
9321 if ($info !== false) {
9322 $annots .= ' /RI '.$info['n'].' 0 R';
9325 if (isset($pl['opt']['mk']['ix'])) {
9326 $info = $this->getImageBuffer($pl['opt']['mk']['ix']);
9327 if ($info !== false) {
9328 $annots .= ' /IX '.$info['n'].' 0 R';
9331 if (isset($pl['opt']['mk']['if']) AND (is_array($pl['opt']['mk']['if'])) AND !empty($pl['opt']['mk']['if'])) {
9332 $annots .= ' /IF <<';
9333 $if_sw = array('A', 'B', 'S', 'N');
9334 if (isset($pl['opt']['mk']['if']['sw']) AND in_array($pl['opt']['mk']['if']['sw'], $if_sw)) {
9335 $annots .= ' /SW /'.$pl['opt']['mk']['if']['sw'];
9337 $if_s = array('A', 'P');
9338 if (isset($pl['opt']['mk']['if']['s']) AND in_array($pl['opt']['mk']['if']['s'], $if_s)) {
9339 $annots .= ' /S /'.$pl['opt']['mk']['if']['s'];
9341 if (isset($pl['opt']['mk']['if']['a']) AND (is_array($pl['opt']['mk']['if']['a'])) AND !empty($pl['opt']['mk']['if']['a'])) {
9342 $annots .= sprintf(' /A [%.2F %.2F]', $pl['opt']['mk']['if']['a'][0], $pl['opt']['mk']['if']['a'][1]);
9344 if (isset($pl['opt']['mk']['if']['fb']) AND ($pl['opt']['mk']['if']['fb'])) {
9345 $annots .= ' /FB true';
9347 $annots .= '>>';
9349 if (isset($pl['opt']['mk']['tp']) AND ($pl['opt']['mk']['tp'] >= 0) AND ($pl['opt']['mk']['tp'] <= 6)) {
9350 $annots .= ' /TP '.intval($pl['opt']['mk']['tp']);
9351 } else {
9352 $annots .= ' /TP 0';
9354 $annots .= '>>';
9355 } // end MK
9356 // --- Entries for field dictionaries ---
9357 if (isset($this->radiobutton_groups[$n][$pl['txt']])) {
9358 // set parent
9359 $annots .= ' /Parent '.$this->radiobutton_groups[$n][$pl['txt']].' 0 R';
9361 if (isset($pl['opt']['t']) AND is_string($pl['opt']['t'])) {
9362 $annots .= ' /T '.$this->_datastring($pl['opt']['t'], $annot_obj_id);
9364 if (isset($pl['opt']['tu']) AND is_string($pl['opt']['tu'])) {
9365 $annots .= ' /TU '.$this->_datastring($pl['opt']['tu'], $annot_obj_id);
9367 if (isset($pl['opt']['tm']) AND is_string($pl['opt']['tm'])) {
9368 $annots .= ' /TM '.$this->_datastring($pl['opt']['tm'], $annot_obj_id);
9370 if (isset($pl['opt']['ff'])) {
9371 if (is_array($pl['opt']['ff'])) {
9372 // array of bit settings
9373 $flag = 0;
9374 foreach($pl['opt']['ff'] as $val) {
9375 $flag += 1 << ($val - 1);
9377 } else {
9378 $flag = intval($pl['opt']['ff']);
9380 $annots .= ' /Ff '.$flag;
9382 if (isset($pl['opt']['maxlen'])) {
9383 $annots .= ' /MaxLen '.intval($pl['opt']['maxlen']);
9385 if (isset($pl['opt']['v'])) {
9386 $annots .= ' /V';
9387 if (is_array($pl['opt']['v'])) {
9388 foreach ($pl['opt']['v'] AS $optval) {
9389 if (is_float($optval)) {
9390 $optval = sprintf('%.2F', $optval);
9392 $annots .= ' '.$optval;
9394 } else {
9395 $annots .= ' '.$this->_textstring($pl['opt']['v'], $annot_obj_id);
9398 if (isset($pl['opt']['dv'])) {
9399 $annots .= ' /DV';
9400 if (is_array($pl['opt']['dv'])) {
9401 foreach ($pl['opt']['dv'] AS $optval) {
9402 if (is_float($optval)) {
9403 $optval = sprintf('%.2F', $optval);
9405 $annots .= ' '.$optval;
9407 } else {
9408 $annots .= ' '.$this->_textstring($pl['opt']['dv'], $annot_obj_id);
9411 if (isset($pl['opt']['rv'])) {
9412 $annots .= ' /RV';
9413 if (is_array($pl['opt']['rv'])) {
9414 foreach ($pl['opt']['rv'] AS $optval) {
9415 if (is_float($optval)) {
9416 $optval = sprintf('%.2F', $optval);
9418 $annots .= ' '.$optval;
9420 } else {
9421 $annots .= ' '.$this->_textstring($pl['opt']['rv'], $annot_obj_id);
9424 if (isset($pl['opt']['a']) AND !empty($pl['opt']['a'])) {
9425 $annots .= ' /A << '.$pl['opt']['a'].' >>';
9427 if (isset($pl['opt']['aa']) AND !empty($pl['opt']['aa'])) {
9428 $annots .= ' /AA << '.$pl['opt']['aa'].' >>';
9430 if (isset($pl['opt']['da']) AND !empty($pl['opt']['da'])) {
9431 $annots .= ' /DA ('.$pl['opt']['da'].')';
9433 if (isset($pl['opt']['q']) AND ($pl['opt']['q'] >= 0) AND ($pl['opt']['q'] <= 2)) {
9434 $annots .= ' /Q '.intval($pl['opt']['q']);
9436 if (isset($pl['opt']['opt']) AND (is_array($pl['opt']['opt'])) AND !empty($pl['opt']['opt'])) {
9437 $annots .= ' /Opt [';
9438 foreach($pl['opt']['opt'] AS $copt) {
9439 if (is_array($copt)) {
9440 $annots .= ' ['.$this->_textstring($copt[0], $annot_obj_id).' '.$this->_textstring($copt[1], $annot_obj_id).']';
9441 } else {
9442 $annots .= ' '.$this->_textstring($copt, $annot_obj_id);
9445 $annots .= ']';
9447 if (isset($pl['opt']['ti'])) {
9448 $annots .= ' /TI '.intval($pl['opt']['ti']);
9450 if (isset($pl['opt']['i']) AND (is_array($pl['opt']['i'])) AND !empty($pl['opt']['i'])) {
9451 $annots .= ' /I [';
9452 foreach($pl['opt']['i'] AS $copt) {
9453 $annots .= intval($copt).' ';
9455 $annots .= ']';
9457 break;
9459 case 'screen': {
9460 break;
9462 case 'printermark': {
9463 break;
9465 case 'trapnet': {
9466 break;
9468 case 'watermark': {
9469 break;
9471 case '3d': {
9472 break;
9474 default: {
9475 break;
9478 $annots .= '>>';
9479 // create new annotation object
9480 $this->_out($this->_getobj($annot_obj_id)."\n".$annots."\n".'endobj');
9481 if ($formfield AND !isset($this->radiobutton_groups[$n][$pl['txt']])) {
9482 // store reference of form object
9483 $this->form_obj_id[] = $annot_obj_id;
9487 } // end for each page
9491 * Put appearance streams XObject used to define annotation's appearance states
9492 * @param $w (int) annotation width
9493 * @param $h (int) annotation height
9494 * @param $stream (string) appearance stream
9495 * @return int object ID
9496 * @protected
9497 * @since 4.8.001 (2009-09-09)
9499 protected function _putAPXObject($w=0, $h=0, $stream='') {
9500 $stream = trim($stream);
9501 $out = $this->_getobj()."\n";
9502 $this->xobjects['AX'.$this->n] = array('n' => $this->n);
9503 $out .= '<<';
9504 $out .= ' /Type /XObject';
9505 $out .= ' /Subtype /Form';
9506 $out .= ' /FormType 1';
9507 if ($this->compress) {
9508 $stream = gzcompress($stream);
9509 $out .= ' /Filter /FlateDecode';
9511 $rect = sprintf('%.2F %.2F', $w, $h);
9512 $out .= ' /BBox [0 0 '.$rect.']';
9513 $out .= ' /Matrix [1 0 0 1 0 0]';
9514 $out .= ' /Resources <<';
9515 $out .= ' /ProcSet [/PDF /Text]';
9516 $out .= ' /Font <<';
9517 foreach ($this->annotation_fonts as $fontkey => $fontid) {
9518 $out .= ' /F'.$fontid.' '.$this->font_obj_ids[$fontkey].' 0 R';
9520 $out .= ' >>';
9521 $out .= ' >>';
9522 $stream = $this->_getrawstream($stream);
9523 $out .= ' /Length '.strlen($stream);
9524 $out .= ' >>';
9525 $out .= ' stream'."\n".$stream."\n".'endstream';
9526 $out .= "\n".'endobj';
9527 $this->_out($out);
9528 return $this->n;
9532 * Get ULONG from string (Big Endian 32-bit unsigned integer).
9533 * @param $str (string) string from where to extract value
9534 * @param $offset (int) point from where to read the data
9535 * @return int 32 bit value
9536 * @author Nicola Asuni
9537 * @protected
9538 * @since 5.2.000 (2010-06-02)
9540 protected function _getULONG($str, $offset) {
9541 $v = unpack('Ni', substr($str, $offset, 4));
9542 return $v['i'];
9546 * Get USHORT from string (Big Endian 16-bit unsigned integer).
9547 * @param $str (string) string from where to extract value
9548 * @param $offset (int) point from where to read the data
9549 * @return int 16 bit value
9550 * @author Nicola Asuni
9551 * @protected
9552 * @since 5.2.000 (2010-06-02)
9554 protected function _getUSHORT($str, $offset) {
9555 $v = unpack('ni', substr($str, $offset, 2));
9556 return $v['i'];
9560 * Get SHORT from string (Big Endian 16-bit signed integer).
9561 * @param $str (string) string from where to extract value
9562 * @param $offset (int) point from where to read the data
9563 * @return int 16 bit value
9564 * @author Nicola Asuni
9565 * @protected
9566 * @since 5.2.000 (2010-06-02)
9568 protected function _getSHORT($str, $offset) {
9569 $v = unpack('si', substr($str, $offset, 2));
9570 return $v['i'];
9574 * Get BYTE from string (8-bit unsigned integer).
9575 * @param $str (string) string from where to extract value
9576 * @param $offset (int) point from where to read the data
9577 * @return int 8 bit value
9578 * @author Nicola Asuni
9579 * @protected
9580 * @since 5.2.000 (2010-06-02)
9582 protected function _getBYTE($str, $offset) {
9583 $v = unpack('Ci', substr($str, $offset, 1));
9584 return $v['i'];
9588 * Returns a subset of the TrueType font data without the unused glyphs.
9589 * @param $font (string) TrueType font data.
9590 * @param $subsetchars (array) Array of used characters (the glyphs to keep).
9591 * @return string a subset of TrueType font data without the unused glyphs
9592 * @author Nicola Asuni
9593 * @protected
9594 * @since 5.2.000 (2010-06-02)
9596 protected function _getTrueTypeFontSubset($font, $subsetchars) {
9597 ksort($subsetchars);
9598 $offset = 0; // offset position of the font data
9599 if ($this->_getULONG($font, $offset) != 0x10000) {
9600 // sfnt version must be 0x00010000 for TrueType version 1.0.
9601 return $font;
9603 $offset += 4;
9604 // get number of tables
9605 $numTables = $this->_getUSHORT($font, $offset);
9606 $offset += 2;
9607 // skip searchRange, entrySelector and rangeShift
9608 $offset += 6;
9609 // tables array
9610 $table = array();
9611 // for each table
9612 for ($i = 0; $i < $numTables; ++$i) {
9613 // get table info
9614 $tag = substr($font, $offset, 4);
9615 $offset += 4;
9616 $table[$tag] = array();
9617 $table[$tag]['checkSum'] = $this->_getULONG($font, $offset);
9618 $offset += 4;
9619 $table[$tag]['offset'] = $this->_getULONG($font, $offset);
9620 $offset += 4;
9621 $table[$tag]['length'] = $this->_getULONG($font, $offset);
9622 $offset += 4;
9624 // check magicNumber
9625 $offset = $table['head']['offset'] + 12;
9626 if ($this->_getULONG($font, $offset) != 0x5F0F3CF5) {
9627 // magicNumber must be 0x5F0F3CF5
9628 return $font;
9630 $offset += 4;
9631 // get offset mode (indexToLocFormat : 0 = short, 1 = long)
9632 $offset = $table['head']['offset'] + 50;
9633 $short_offset = ($this->_getSHORT($font, $offset) == 0);
9634 $offset += 2;
9635 // get the offsets to the locations of the glyphs in the font, relative to the beginning of the glyphData table
9636 $indexToLoc = array();
9637 $offset = $table['loca']['offset'];
9638 if ($short_offset) {
9639 // short version
9640 $tot_num_glyphs = ($table['loca']['length'] / 2); // numGlyphs + 1
9641 for ($i = 0; $i < $tot_num_glyphs; ++$i) {
9642 $indexToLoc[$i] = $this->_getUSHORT($font, $offset) * 2;
9643 $offset += 2;
9645 } else {
9646 // long version
9647 $tot_num_glyphs = ($table['loca']['length'] / 4); // numGlyphs + 1
9648 for ($i = 0; $i < $tot_num_glyphs; ++$i) {
9649 $indexToLoc[$i] = $this->_getULONG($font, $offset);
9650 $offset += 4;
9653 // get glyphs indexes of chars from cmap table
9654 $subsetglyphs = array(); // glyph IDs on key
9655 $subsetglyphs[0] = true; // character codes that do not correspond to any glyph in the font should be mapped to glyph index 0
9656 $offset = $table['cmap']['offset'] + 2;
9657 $numEncodingTables = $this->_getUSHORT($font, $offset);
9658 $offset += 2;
9659 $encodingTables = array();
9660 for ($i = 0; $i < $numEncodingTables; ++$i) {
9661 $encodingTables[$i]['platformID'] = $this->_getUSHORT($font, $offset);
9662 $offset += 2;
9663 $encodingTables[$i]['encodingID'] = $this->_getUSHORT($font, $offset);
9664 $offset += 2;
9665 $encodingTables[$i]['offset'] = $this->_getULONG($font, $offset);
9666 $offset += 4;
9668 foreach ($encodingTables as $enctable) {
9669 if (($enctable['platformID'] == 3) AND ($enctable['encodingID'] == 0)) {
9670 $modesymbol = true;
9671 } else {
9672 $modesymbol = false;
9674 $offset = $table['cmap']['offset'] + $enctable['offset'];
9675 $format = $this->_getUSHORT($font, $offset);
9676 $offset += 2;
9677 switch ($format) {
9678 case 0: { // Format 0: Byte encoding table
9679 $offset += 4; // skip length and version/language
9680 for ($c = 0; $c < 256; ++$c) {
9681 if (isset($subsetchars[$c])) {
9682 $g = $this->_getBYTE($font, $offset);
9683 $subsetglyphs[$g] = true;
9685 ++$offset;
9687 break;
9689 case 2: { // Format 2: High-byte mapping through table
9690 $offset += 4; // skip length and version/language
9691 $numSubHeaders = 0;
9692 for ($i = 0; $i < 256; ++$i) {
9693 // Array that maps high bytes to subHeaders: value is subHeader index * 8.
9694 $subHeaderKeys[$i] = ($this->_getUSHORT($font, $offset) / 8);
9695 $offset += 2;
9696 if ($numSubHeaders < $subHeaderKeys[$i]) {
9697 $numSubHeaders = $subHeaderKeys[$i];
9700 // the number of subHeaders is equal to the max of subHeaderKeys + 1
9701 ++$numSubHeaders;
9702 // read subHeader structures
9703 $subHeaders = array();
9704 for ($k = 0; $k < $numSubHeaders; ++$k) {
9705 $subHeaders[$k]['firstCode'] = $this->_getUSHORT($font, $offset);
9706 $offset += 2;
9707 $subHeaders[$k]['entryCount'] = $this->_getUSHORT($font, $offset);
9708 $offset += 2;
9709 $subHeaders[$k]['idDelta'] = $this->_getSHORT($font, $offset);
9710 $offset += 2;
9711 $subHeaders[$k]['idRangeOffset'] = $this->_getUSHORT($font, $offset);
9712 $offset += 2;
9713 $subHeaders[$k]['idRangeOffset'] -= (2 + (($numSubHeaders - $k - 1) * 8));
9714 $subHeaders[$k]['idRangeOffset'] /= 2;
9715 $numGlyphIndexArray += $subHeaders[$k]['entryCount'];
9717 for ($k = 0; $k < $numGlyphIndexArray; ++$k) {
9718 $glyphIndexArray[$k] = $this->_getUSHORT($font, $offset);
9719 $offset += 2;
9721 for ($i = 0; $i < 256; ++$i) {
9722 $k = $subHeaderKeys[$i];
9723 if ($k == 0) {
9724 // one byte code
9725 $c = $i;
9726 if (isset($subsetchars[$c])) {
9727 $g = $glyphIndexArray[0];
9728 $subsetglyphs[$g] = true;
9730 } else {
9731 // two bytes code
9732 $start_byte = $subHeaders[$k]['firstCode'];
9733 $end_byte = $start_byte + $subHeaders[$k]['entryCount'];
9734 for ($j = $start_byte; $j < $end_byte; ++$j) {
9735 // combine high and low bytes
9736 $c = (($i << 8) + $j);
9737 if (isset($subsetchars[$c])) {
9738 $idRangeOffset = ($subHeaders[$k]['idRangeOffset'] + $j - $subHeaders[$k]['firstCode']);
9739 $g = $glyphIndexArray[$idRangeOffset];
9740 $g += ($idDelta[$k] - 65536);
9741 if ($g < 0) {
9742 $g = 0;
9744 $subsetglyphs[$g] = true;
9749 break;
9751 case 4: { // Format 4: Segment mapping to delta values
9752 $length = $this->_getUSHORT($font, $offset);
9753 $offset += 2;
9754 $offset += 2; // skip version/language
9755 $segCount = ($this->_getUSHORT($font, $offset) / 2);
9756 $offset += 2;
9757 $offset += 6; // skip searchRange, entrySelector, rangeShift
9758 $endCount = array(); // array of end character codes for each segment
9759 for ($k = 0; $k < $segCount; ++$k) {
9760 $endCount[$k] = $this->_getUSHORT($font, $offset);
9761 $offset += 2;
9763 $offset += 2; // skip reservedPad
9764 $startCount = array(); // array of start character codes for each segment
9765 for ($k = 0; $k < $segCount; ++$k) {
9766 $startCount[$k] = $this->_getUSHORT($font, $offset);
9767 $offset += 2;
9769 $idDelta = array(); // delta for all character codes in segment
9770 for ($k = 0; $k < $segCount; ++$k) {
9771 $idDelta[$k] = $this->_getUSHORT($font, $offset);
9772 $offset += 2;
9774 $idRangeOffset = array(); // Offsets into glyphIdArray or 0
9775 for ($k = 0; $k < $segCount; ++$k) {
9776 $idRangeOffset[$k] = $this->_getUSHORT($font, $offset);
9777 $offset += 2;
9779 $gidlen = ($length / 2) - 8 - (4 * $segCount);
9780 $glyphIdArray = array(); // glyph index array
9781 for ($k = 0; $k < $gidlen; ++$k) {
9782 $glyphIdArray[$k] = $this->_getUSHORT($font, $offset);
9783 $offset += 2;
9785 for ($k = 0; $k < $segCount; ++$k) {
9786 for ($c = $startCount[$k]; $c <= $endCount[$k]; ++$c) {
9787 if (isset($subsetchars[$c])) {
9788 if ($idRangeOffset[$k] == 0) {
9789 $g = $c;
9790 } else {
9791 $gid = (($idRangeOffset[$k] / 2) + ($c - $startCount[$k]) - ($segCount - $k));
9792 $g = $glyphIdArray[$gid];
9794 $g += ($idDelta[$k] - 65536);
9795 if ($g < 0) {
9796 $g = 0;
9798 $subsetglyphs[$g] = true;
9802 break;
9804 case 6: { // Format 6: Trimmed table mapping
9805 $offset += 4; // skip length and version/language
9806 $firstCode = $this->_getUSHORT($font, $offset);
9807 $offset += 2;
9808 $entryCount = $this->_getUSHORT($font, $offset);
9809 $offset += 2;
9810 for ($k = 0; $k < $entryCount; ++$k) {
9811 $c = ($k + $firstCode);
9812 if (isset($subsetchars[$c])) {
9813 $g = $this->_getUSHORT($font, $offset);
9814 $subsetglyphs[$g] = true;
9816 $offset += 2;
9818 break;
9820 case 8: { // Format 8: Mixed 16-bit and 32-bit coverage
9821 $offset += 10; // skip reserved, length and version/language
9822 for ($k = 0; $k < 8192; ++$k) {
9823 $is32[$k] = $this->_getBYTE($font, $offset);
9824 ++$offset;
9826 $nGroups = $this->_getULONG($font, $offset);
9827 $offset += 4;
9828 for ($i = 0; $i < $nGroups; ++$i) {
9829 $startCharCode = $this->_getULONG($font, $offset);
9830 $offset += 4;
9831 $endCharCode = $this->_getULONG($font, $offset);
9832 $offset += 4;
9833 $startGlyphID = $this->_getULONG($font, $offset);
9834 $offset += 4;
9835 for ($k = $startCharCode; $k <= $endCharCode; ++$k) {
9836 $is32idx = floor($c / 8);
9837 if ((isset($is32[$is32idx])) AND (($is32[$is32idx] & (1 << (7 - ($c % 8)))) == 0)) {
9838 $c = $k;
9839 } else {
9840 // 32 bit format
9841 // convert to decimal (http://www.unicode.org/faq//utf_bom.html#utf16-4)
9842 //LEAD_OFFSET = (0xD800 - (0x10000 >> 10)) = 55232
9843 //SURROGATE_OFFSET = (0x10000 - (0xD800 << 10) - 0xDC00) = -56613888
9844 $c = ((55232 + ($k >> 10)) << 10) + (0xDC00 + ($k & 0x3FF)) -56613888;
9846 if (isset($subsetchars[$c])) {
9847 $subsetglyphs[$startGlyphID] = true;
9849 ++$startGlyphID;
9852 break;
9854 case 10: { // Format 10: Trimmed array
9855 $offset += 10; // skip reserved, length and version/language
9856 $startCharCode = $this->_getULONG($font, $offset);
9857 $offset += 4;
9858 $numChars = $this->_getULONG($font, $offset);
9859 $offset += 4;
9860 for ($k = 0; $k < $numChars; ++$k) {
9861 $c = ($k + $startCharCode);
9862 if (isset($subsetchars[$c])) {
9863 $g = $this->_getUSHORT($font, $offset);
9864 $subsetglyphs[$g] = true;
9866 $offset += 2;
9868 break;
9870 case 12: { // Format 12: Segmented coverage
9871 $offset += 10; // skip length and version/language
9872 $nGroups = $this->_getULONG($font, $offset);
9873 $offset += 4;
9874 for ($k = 0; $k < $nGroups; ++$k) {
9875 $startCharCode = $this->_getULONG($font, $offset);
9876 $offset += 4;
9877 $endCharCode = $this->_getULONG($font, $offset);
9878 $offset += 4;
9879 $startGlyphCode = $this->_getULONG($font, $offset);
9880 $offset += 4;
9881 for ($c = $startCharCode; $c <= $endCharCode; ++$c) {
9882 if (isset($subsetchars[$c])) {
9883 $subsetglyphs[$startGlyphCode] = true;
9885 ++$startGlyphCode;
9888 break;
9890 case 13: { // Format 13: Many-to-one range mappings
9891 // to be implemented ...
9892 break;
9894 case 14: { // Format 14: Unicode Variation Sequences
9895 // to be implemented ...
9896 break;
9900 // include all parts of composite glyphs
9901 $new_sga = $subsetglyphs;
9902 while (!empty($new_sga)) {
9903 $sga = $new_sga;
9904 $new_sga = array();
9905 foreach ($sga as $key => $val) {
9906 if (isset($indexToLoc[$key])) {
9907 $offset = ($table['glyf']['offset'] + $indexToLoc[$key]);
9908 $numberOfContours = $this->_getSHORT($font, $offset);
9909 $offset += 2;
9910 if ($numberOfContours < 0) { // composite glyph
9911 $offset += 8; // skip xMin, yMin, xMax, yMax
9912 do {
9913 $flags = $this->_getUSHORT($font, $offset);
9914 $offset += 2;
9915 $glyphIndex = $this->_getUSHORT($font, $offset);
9916 $offset += 2;
9917 if (!isset($subsetglyphs[$glyphIndex])) {
9918 // add missing glyphs
9919 $new_sga[$glyphIndex] = true;
9921 // skip some bytes by case
9922 if ($flags & 1) {
9923 $offset += 4;
9924 } else {
9925 $offset += 2;
9927 if ($flags & 8) {
9928 $offset += 2;
9929 } elseif ($flags & 64) {
9930 $offset += 4;
9931 } elseif ($flags & 128) {
9932 $offset += 8;
9934 } while ($flags & 32);
9938 $subsetglyphs += $new_sga;
9940 // sort glyphs by key (and remove duplicates)
9941 ksort($subsetglyphs);
9942 // build new glyf and loca tables
9943 $glyf = '';
9944 $loca = '';
9945 $offset = 0;
9946 $glyf_offset = $table['glyf']['offset'];
9947 for ($i = 0; $i < $tot_num_glyphs; ++$i) {
9948 if (isset($subsetglyphs[$i])) {
9949 $length = ($indexToLoc[($i + 1)] - $indexToLoc[$i]);
9950 $glyf .= substr($font, ($glyf_offset + $indexToLoc[$i]), $length);
9951 } else {
9952 $length = 0;
9954 if ($short_offset) {
9955 $loca .= pack('n', ($offset / 2));
9956 } else {
9957 $loca .= pack('N', $offset);
9959 $offset += $length;
9961 // array of table names to preserve (loca and glyf tables will be added later)
9962 // the cmap table is not needed and shall not be present, since the mapping from character codes to glyph descriptions is provided separately
9963 $table_names = array ('head', 'hhea', 'hmtx', 'maxp', 'cvt ', 'fpgm', 'prep'); // minimum required table names
9964 // get the tables to preserve
9965 $offset = 12;
9966 foreach ($table as $tag => $val) {
9967 if (in_array($tag, $table_names)) {
9968 $table[$tag]['data'] = substr($font, $table[$tag]['offset'], $table[$tag]['length']);
9969 if ($tag == 'head') {
9970 // set the checkSumAdjustment to 0
9971 $table[$tag]['data'] = substr($table[$tag]['data'], 0, 8)."\x0\x0\x0\x0".substr($table[$tag]['data'], 12);
9973 $pad = 4 - ($table[$tag]['length'] % 4);
9974 if ($pad != 4) {
9975 // the length of a table must be a multiple of four bytes
9976 $table[$tag]['length'] += $pad;
9977 $table[$tag]['data'] .= str_repeat("\x0", $pad);
9979 $table[$tag]['offset'] = $offset;
9980 $offset += $table[$tag]['length'];
9981 // check sum is not changed (so keep the following line commented)
9982 //$table[$tag]['checkSum'] = $this->_getTTFtableChecksum($table[$tag]['data'], $table[$tag]['length']);
9983 } else {
9984 unset($table[$tag]);
9987 // add loca
9988 $table['loca']['data'] = $loca;
9989 $table['loca']['length'] = strlen($loca);
9990 $pad = 4 - ($table['loca']['length'] % 4);
9991 if ($pad != 4) {
9992 // the length of a table must be a multiple of four bytes
9993 $table['loca']['length'] += $pad;
9994 $table['loca']['data'] .= str_repeat("\x0", $pad);
9996 $table['loca']['offset'] = $offset;
9997 $table['loca']['checkSum'] = $this->_getTTFtableChecksum($table['loca']['data'], $table['loca']['length']);
9998 $offset += $table['loca']['length'];
9999 // add glyf
10000 $table['glyf']['data'] = $glyf;
10001 $table['glyf']['length'] = strlen($glyf);
10002 $pad = 4 - ($table['glyf']['length'] % 4);
10003 if ($pad != 4) {
10004 // the length of a table must be a multiple of four bytes
10005 $table['glyf']['length'] += $pad;
10006 $table['glyf']['data'] .= str_repeat("\x0", $pad);
10008 $table['glyf']['offset'] = $offset;
10009 $table['glyf']['checkSum'] = $this->_getTTFtableChecksum($table['glyf']['data'], $table['glyf']['length']);
10010 // rebuild font
10011 $font = '';
10012 $font .= pack('N', 0x10000); // sfnt version
10013 $numTables = count($table);
10014 $font .= pack('n', $numTables); // numTables
10015 $entrySelector = floor(log($numTables, 2));
10016 $searchRange = pow(2, $entrySelector) * 16;
10017 $rangeShift = ($numTables * 16) - $searchRange;
10018 $font .= pack('n', $searchRange); // searchRange
10019 $font .= pack('n', $entrySelector); // entrySelector
10020 $font .= pack('n', $rangeShift); // rangeShift
10021 $offset = ($numTables * 16);
10022 foreach ($table as $tag => $data) {
10023 $font .= $tag; // tag
10024 $font .= pack('N', $data['checkSum']); // checkSum
10025 $font .= pack('N', ($data['offset'] + $offset)); // offset
10026 $font .= pack('N', $data['length']); // length
10028 foreach ($table as $data) {
10029 $font .= $data['data'];
10031 // set checkSumAdjustment on head table
10032 $checkSumAdjustment = 0xB1B0AFBA - $this->_getTTFtableChecksum($font, strlen($font));
10033 $font = substr($font, 0, $table['head']['offset'] + 8).pack('N', $checkSumAdjustment).substr($font, $table['head']['offset'] + 12);
10034 return $font;
10038 * Returs the checksum of a TTF table.
10039 * @param $table (string) table to check
10040 * @param $length (int) length of table in bytes
10041 * @return int checksum
10042 * @author Nicola Asuni
10043 * @protected
10044 * @since 5.2.000 (2010-06-02)
10046 protected function _getTTFtableChecksum($table, $length) {
10047 $sum = 0;
10048 $tlen = ($length / 4);
10049 $offset = 0;
10050 for ($i = 0; $i < $tlen; ++$i) {
10051 $v = unpack('Ni', substr($table, $offset, 4));
10052 $sum += $v['i'];
10053 $offset += 4;
10055 $sum = unpack('Ni', pack('N', $sum));
10056 return $sum['i'];
10060 * Outputs font widths
10061 * @param $font (array) font data
10062 * @param $cidoffset (int) offset for CID values
10063 * @return PDF command string for font widths
10064 * @author Nicola Asuni
10065 * @protected
10066 * @since 4.4.000 (2008-12-07)
10068 protected function _putfontwidths($font, $cidoffset=0) {
10069 ksort($font['cw']);
10070 $rangeid = 0;
10071 $range = array();
10072 $prevcid = -2;
10073 $prevwidth = -1;
10074 $interval = false;
10075 // for each character
10076 foreach ($font['cw'] as $cid => $width) {
10077 $cid -= $cidoffset;
10078 if ($font['subset'] AND ($cid > 255) AND (!isset($font['subsetchars'][$cid]))) {
10079 // ignore the unused characters (font subsetting)
10080 continue;
10082 if ($width != $font['dw']) {
10083 if ($cid == ($prevcid + 1)) {
10084 // consecutive CID
10085 if ($width == $prevwidth) {
10086 if ($width == $range[$rangeid][0]) {
10087 $range[$rangeid][] = $width;
10088 } else {
10089 array_pop($range[$rangeid]);
10090 // new range
10091 $rangeid = $prevcid;
10092 $range[$rangeid] = array();
10093 $range[$rangeid][] = $prevwidth;
10094 $range[$rangeid][] = $width;
10096 $interval = true;
10097 $range[$rangeid]['interval'] = true;
10098 } else {
10099 if ($interval) {
10100 // new range
10101 $rangeid = $cid;
10102 $range[$rangeid] = array();
10103 $range[$rangeid][] = $width;
10104 } else {
10105 $range[$rangeid][] = $width;
10107 $interval = false;
10109 } else {
10110 // new range
10111 $rangeid = $cid;
10112 $range[$rangeid] = array();
10113 $range[$rangeid][] = $width;
10114 $interval = false;
10116 $prevcid = $cid;
10117 $prevwidth = $width;
10120 // optimize ranges
10121 $prevk = -1;
10122 $nextk = -1;
10123 $prevint = false;
10124 foreach ($range as $k => $ws) {
10125 $cws = count($ws);
10126 if (($k == $nextk) AND (!$prevint) AND ((!isset($ws['interval'])) OR ($cws < 4))) {
10127 if (isset($range[$k]['interval'])) {
10128 unset($range[$k]['interval']);
10130 $range[$prevk] = array_merge($range[$prevk], $range[$k]);
10131 unset($range[$k]);
10132 } else {
10133 $prevk = $k;
10135 $nextk = $k + $cws;
10136 if (isset($ws['interval'])) {
10137 if ($cws > 3) {
10138 $prevint = true;
10139 } else {
10140 $prevint = false;
10142 unset($range[$k]['interval']);
10143 --$nextk;
10144 } else {
10145 $prevint = false;
10148 // output data
10149 $w = '';
10150 foreach ($range as $k => $ws) {
10151 if (count(array_count_values($ws)) == 1) {
10152 // interval mode is more compact
10153 $w .= ' '.$k.' '.($k + count($ws) - 1).' '.$ws[0];
10154 } else {
10155 // range mode
10156 $w .= ' '.$k.' [ '.implode(' ', $ws).' ]';
10159 return '/W ['.$w.' ]';
10163 * Output fonts.
10164 * @author Nicola Asuni
10165 * @protected
10167 protected function _putfonts() {
10168 $nf = $this->n;
10169 foreach ($this->diffs as $diff) {
10170 //Encodings
10171 $this->_newobj();
10172 $this->_out('<< /Type /Encoding /BaseEncoding /WinAnsiEncoding /Differences ['.$diff.'] >>'."\n".'endobj');
10174 $mqr = $this->get_mqr();
10175 $this->set_mqr(false);
10176 foreach ($this->FontFiles as $file => $info) {
10177 // search and get font file to embedd
10178 $fontdir = $info['fontdir'];
10179 $file = strtolower($file);
10180 $fontfile = '';
10181 // search files on various directories
10182 if (($fontdir !== false) AND file_exists($fontdir.$file)) {
10183 $fontfile = $fontdir.$file;
10184 } elseif (file_exists($this->_getfontpath().$file)) {
10185 $fontfile = $this->_getfontpath().$file;
10186 } elseif (file_exists($file)) {
10187 $fontfile = $file;
10189 if (!$this->empty_string($fontfile)) {
10190 $font = file_get_contents($fontfile);
10191 $compressed = (substr($file, -2) == '.z');
10192 if ((!$compressed) AND (isset($info['length2']))) {
10193 $header = (ord($font{0}) == 128);
10194 if ($header) {
10195 // strip first binary header
10196 $font = substr($font, 6);
10198 if ($header AND (ord($font{$info['length1']}) == 128)) {
10199 // strip second binary header
10200 $font = substr($font, 0, $info['length1']).substr($font, ($info['length1'] + 6));
10202 } elseif ($info['subset'] AND ((!$compressed) OR ($compressed AND function_exists('gzcompress')))) {
10203 if ($compressed) {
10204 // uncompress font
10205 $font = gzuncompress($font);
10207 // merge subset characters
10208 $subsetchars = array(); // used chars
10209 foreach ($info['fontkeys'] as $fontkey) {
10210 $fontinfo = $this->getFontBuffer($fontkey);
10211 $subsetchars += $fontinfo['subsetchars'];
10213 // rebuild a font subset
10214 $font = $this->_getTrueTypeFontSubset($font, $subsetchars);
10215 // calculate new font length
10216 $info['length1'] = strlen($font);
10217 if ($compressed) {
10218 // recompress font
10219 $font = gzcompress($font);
10222 $this->_newobj();
10223 $this->FontFiles[$file]['n'] = $this->n;
10224 $stream = $this->_getrawstream($font);
10225 $out = '<< /Length '.strlen($stream);
10226 if ($compressed) {
10227 $out .= ' /Filter /FlateDecode';
10229 $out .= ' /Length1 '.$info['length1'];
10230 if (isset($info['length2'])) {
10231 $out .= ' /Length2 '.$info['length2'].' /Length3 0';
10233 $out .= ' >>';
10234 $out .= ' stream'."\n".$stream."\n".'endstream';
10235 $out .= "\n".'endobj';
10236 $this->_out($out);
10239 $this->set_mqr($mqr);
10240 foreach ($this->fontkeys as $k) {
10241 //Font objects
10242 $font = $this->getFontBuffer($k);
10243 $type = $font['type'];
10244 $name = $font['name'];
10245 if ($type == 'core') {
10246 // standard core font
10247 $out = $this->_getobj($this->font_obj_ids[$k])."\n";
10248 $out .= '<</Type /Font';
10249 $out .= ' /Subtype /Type1';
10250 $out .= ' /BaseFont /'.$name;
10251 $out .= ' /Name /F'.$font['i'];
10252 if ((strtolower($name) != 'symbol') AND (strtolower($name) != 'zapfdingbats')) {
10253 $out .= ' /Encoding /WinAnsiEncoding';
10255 if ($k == 'helvetica') {
10256 // add default font for annotations
10257 $this->annotation_fonts[$k] = $font['i'];
10259 $out .= ' >>';
10260 $out .= "\n".'endobj';
10261 $this->_out($out);
10262 } elseif (($type == 'Type1') OR ($type == 'TrueType')) {
10263 // additional Type1 or TrueType font
10264 $out = $this->_getobj($this->font_obj_ids[$k])."\n";
10265 $out .= '<</Type /Font';
10266 $out .= ' /Subtype /'.$type;
10267 $out .= ' /BaseFont /'.$name;
10268 $out .= ' /Name /F'.$font['i'];
10269 $out .= ' /FirstChar 32 /LastChar 255';
10270 $out .= ' /Widths '.($this->n + 1).' 0 R';
10271 $out .= ' /FontDescriptor '.($this->n + 2).' 0 R';
10272 if ($font['enc']) {
10273 if (isset($font['diff'])) {
10274 $out .= ' /Encoding '.($nf + $font['diff']).' 0 R';
10275 } else {
10276 $out .= ' /Encoding /WinAnsiEncoding';
10279 $out .= ' >>';
10280 $out .= "\n".'endobj';
10281 $this->_out($out);
10282 // Widths
10283 $this->_newobj();
10284 $s = '[';
10285 for ($i = 32; $i < 256; ++$i) {
10286 $s .= $font['cw'][$i].' ';
10288 $s .= ']';
10289 $s .= "\n".'endobj';
10290 $this->_out($s);
10291 //Descriptor
10292 $this->_newobj();
10293 $s = '<</Type /FontDescriptor /FontName /'.$name;
10294 foreach ($font['desc'] as $fdk => $fdv) {
10295 if (is_float($fdv)) {
10296 $fdv = sprintf('%.3F', $fdv);
10298 $s .= ' /'.$fdk.' '.$fdv.'';
10300 if (!$this->empty_string($font['file'])) {
10301 $s .= ' /FontFile'.($type == 'Type1' ? '' : '2').' '.$this->FontFiles[$font['file']]['n'].' 0 R';
10303 $s .= '>>';
10304 $s .= "\n".'endobj';
10305 $this->_out($s);
10306 } else {
10307 // additional types
10308 $mtd = '_put'.strtolower($type);
10309 if (!method_exists($this, $mtd)) {
10310 $this->Error('Unsupported font type: '.$type);
10312 $this->$mtd($font);
10318 * Adds unicode fonts.<br>
10319 * Based on PDF Reference 1.3 (section 5)
10320 * @param $font (array) font data
10321 * @protected
10322 * @author Nicola Asuni
10323 * @since 1.52.0.TC005 (2005-01-05)
10325 protected function _puttruetypeunicode($font) {
10326 $fontname = '';
10327 if ($font['subset']) {
10328 // change name for font subsetting
10329 $subtag = sprintf('%06u', $font['i']);
10330 $subtag = strtr($subtag, '0123456789', 'ABCDEFGHIJ');
10331 $fontname .= $subtag.'+';
10333 $fontname .= $font['name'];
10334 // Type0 Font
10335 // A composite font composed of other fonts, organized hierarchically
10336 $out = $this->_getobj($this->font_obj_ids[$font['fontkey']])."\n";
10337 $out .= '<< /Type /Font';
10338 $out .= ' /Subtype /Type0';
10339 $out .= ' /BaseFont /'.$fontname;
10340 $out .= ' /Name /F'.$font['i'];
10341 $out .= ' /Encoding /'.$font['enc'];
10342 $out .= ' /ToUnicode '.($this->n + 1).' 0 R';
10343 $out .= ' /DescendantFonts ['.($this->n + 2).' 0 R]';
10344 $out .= ' >>';
10345 $out .= "\n".'endobj';
10346 $this->_out($out);
10347 // ToUnicode map for Identity-H
10348 $stream = "/CIDInit /ProcSet findresource begin\n";
10349 $stream .= "12 dict begin\n";
10350 $stream .= "begincmap\n";
10351 $stream .= "/CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def\n";
10352 $stream .= "/CMapName /Adobe-Identity-UCS def\n";
10353 $stream .= "/CMapType 2 def\n";
10354 $stream .= "/WMode 0 def\n";
10355 $stream .= "1 begincodespacerange\n";
10356 $stream .= "<0000> <FFFF>\n";
10357 $stream .= "endcodespacerange\n";
10358 $stream .= "100 beginbfrange\n";
10359 $stream .= "<0000> <00ff> <0000>\n";
10360 $stream .= "<0100> <01ff> <0100>\n";
10361 $stream .= "<0200> <02ff> <0200>\n";
10362 $stream .= "<0300> <03ff> <0300>\n";
10363 $stream .= "<0400> <04ff> <0400>\n";
10364 $stream .= "<0500> <05ff> <0500>\n";
10365 $stream .= "<0600> <06ff> <0600>\n";
10366 $stream .= "<0700> <07ff> <0700>\n";
10367 $stream .= "<0800> <08ff> <0800>\n";
10368 $stream .= "<0900> <09ff> <0900>\n";
10369 $stream .= "<0a00> <0aff> <0a00>\n";
10370 $stream .= "<0b00> <0bff> <0b00>\n";
10371 $stream .= "<0c00> <0cff> <0c00>\n";
10372 $stream .= "<0d00> <0dff> <0d00>\n";
10373 $stream .= "<0e00> <0eff> <0e00>\n";
10374 $stream .= "<0f00> <0fff> <0f00>\n";
10375 $stream .= "<1000> <10ff> <1000>\n";
10376 $stream .= "<1100> <11ff> <1100>\n";
10377 $stream .= "<1200> <12ff> <1200>\n";
10378 $stream .= "<1300> <13ff> <1300>\n";
10379 $stream .= "<1400> <14ff> <1400>\n";
10380 $stream .= "<1500> <15ff> <1500>\n";
10381 $stream .= "<1600> <16ff> <1600>\n";
10382 $stream .= "<1700> <17ff> <1700>\n";
10383 $stream .= "<1800> <18ff> <1800>\n";
10384 $stream .= "<1900> <19ff> <1900>\n";
10385 $stream .= "<1a00> <1aff> <1a00>\n";
10386 $stream .= "<1b00> <1bff> <1b00>\n";
10387 $stream .= "<1c00> <1cff> <1c00>\n";
10388 $stream .= "<1d00> <1dff> <1d00>\n";
10389 $stream .= "<1e00> <1eff> <1e00>\n";
10390 $stream .= "<1f00> <1fff> <1f00>\n";
10391 $stream .= "<2000> <20ff> <2000>\n";
10392 $stream .= "<2100> <21ff> <2100>\n";
10393 $stream .= "<2200> <22ff> <2200>\n";
10394 $stream .= "<2300> <23ff> <2300>\n";
10395 $stream .= "<2400> <24ff> <2400>\n";
10396 $stream .= "<2500> <25ff> <2500>\n";
10397 $stream .= "<2600> <26ff> <2600>\n";
10398 $stream .= "<2700> <27ff> <2700>\n";
10399 $stream .= "<2800> <28ff> <2800>\n";
10400 $stream .= "<2900> <29ff> <2900>\n";
10401 $stream .= "<2a00> <2aff> <2a00>\n";
10402 $stream .= "<2b00> <2bff> <2b00>\n";
10403 $stream .= "<2c00> <2cff> <2c00>\n";
10404 $stream .= "<2d00> <2dff> <2d00>\n";
10405 $stream .= "<2e00> <2eff> <2e00>\n";
10406 $stream .= "<2f00> <2fff> <2f00>\n";
10407 $stream .= "<3000> <30ff> <3000>\n";
10408 $stream .= "<3100> <31ff> <3100>\n";
10409 $stream .= "<3200> <32ff> <3200>\n";
10410 $stream .= "<3300> <33ff> <3300>\n";
10411 $stream .= "<3400> <34ff> <3400>\n";
10412 $stream .= "<3500> <35ff> <3500>\n";
10413 $stream .= "<3600> <36ff> <3600>\n";
10414 $stream .= "<3700> <37ff> <3700>\n";
10415 $stream .= "<3800> <38ff> <3800>\n";
10416 $stream .= "<3900> <39ff> <3900>\n";
10417 $stream .= "<3a00> <3aff> <3a00>\n";
10418 $stream .= "<3b00> <3bff> <3b00>\n";
10419 $stream .= "<3c00> <3cff> <3c00>\n";
10420 $stream .= "<3d00> <3dff> <3d00>\n";
10421 $stream .= "<3e00> <3eff> <3e00>\n";
10422 $stream .= "<3f00> <3fff> <3f00>\n";
10423 $stream .= "<4000> <40ff> <4000>\n";
10424 $stream .= "<4100> <41ff> <4100>\n";
10425 $stream .= "<4200> <42ff> <4200>\n";
10426 $stream .= "<4300> <43ff> <4300>\n";
10427 $stream .= "<4400> <44ff> <4400>\n";
10428 $stream .= "<4500> <45ff> <4500>\n";
10429 $stream .= "<4600> <46ff> <4600>\n";
10430 $stream .= "<4700> <47ff> <4700>\n";
10431 $stream .= "<4800> <48ff> <4800>\n";
10432 $stream .= "<4900> <49ff> <4900>\n";
10433 $stream .= "<4a00> <4aff> <4a00>\n";
10434 $stream .= "<4b00> <4bff> <4b00>\n";
10435 $stream .= "<4c00> <4cff> <4c00>\n";
10436 $stream .= "<4d00> <4dff> <4d00>\n";
10437 $stream .= "<4e00> <4eff> <4e00>\n";
10438 $stream .= "<4f00> <4fff> <4f00>\n";
10439 $stream .= "<5000> <50ff> <5000>\n";
10440 $stream .= "<5100> <51ff> <5100>\n";
10441 $stream .= "<5200> <52ff> <5200>\n";
10442 $stream .= "<5300> <53ff> <5300>\n";
10443 $stream .= "<5400> <54ff> <5400>\n";
10444 $stream .= "<5500> <55ff> <5500>\n";
10445 $stream .= "<5600> <56ff> <5600>\n";
10446 $stream .= "<5700> <57ff> <5700>\n";
10447 $stream .= "<5800> <58ff> <5800>\n";
10448 $stream .= "<5900> <59ff> <5900>\n";
10449 $stream .= "<5a00> <5aff> <5a00>\n";
10450 $stream .= "<5b00> <5bff> <5b00>\n";
10451 $stream .= "<5c00> <5cff> <5c00>\n";
10452 $stream .= "<5d00> <5dff> <5d00>\n";
10453 $stream .= "<5e00> <5eff> <5e00>\n";
10454 $stream .= "<5f00> <5fff> <5f00>\n";
10455 $stream .= "<6000> <60ff> <6000>\n";
10456 $stream .= "<6100> <61ff> <6100>\n";
10457 $stream .= "<6200> <62ff> <6200>\n";
10458 $stream .= "<6300> <63ff> <6300>\n";
10459 $stream .= "endbfrange\n";
10460 $stream .= "100 beginbfrange\n";
10461 $stream .= "<6400> <64ff> <6400>\n";
10462 $stream .= "<6500> <65ff> <6500>\n";
10463 $stream .= "<6600> <66ff> <6600>\n";
10464 $stream .= "<6700> <67ff> <6700>\n";
10465 $stream .= "<6800> <68ff> <6800>\n";
10466 $stream .= "<6900> <69ff> <6900>\n";
10467 $stream .= "<6a00> <6aff> <6a00>\n";
10468 $stream .= "<6b00> <6bff> <6b00>\n";
10469 $stream .= "<6c00> <6cff> <6c00>\n";
10470 $stream .= "<6d00> <6dff> <6d00>\n";
10471 $stream .= "<6e00> <6eff> <6e00>\n";
10472 $stream .= "<6f00> <6fff> <6f00>\n";
10473 $stream .= "<7000> <70ff> <7000>\n";
10474 $stream .= "<7100> <71ff> <7100>\n";
10475 $stream .= "<7200> <72ff> <7200>\n";
10476 $stream .= "<7300> <73ff> <7300>\n";
10477 $stream .= "<7400> <74ff> <7400>\n";
10478 $stream .= "<7500> <75ff> <7500>\n";
10479 $stream .= "<7600> <76ff> <7600>\n";
10480 $stream .= "<7700> <77ff> <7700>\n";
10481 $stream .= "<7800> <78ff> <7800>\n";
10482 $stream .= "<7900> <79ff> <7900>\n";
10483 $stream .= "<7a00> <7aff> <7a00>\n";
10484 $stream .= "<7b00> <7bff> <7b00>\n";
10485 $stream .= "<7c00> <7cff> <7c00>\n";
10486 $stream .= "<7d00> <7dff> <7d00>\n";
10487 $stream .= "<7e00> <7eff> <7e00>\n";
10488 $stream .= "<7f00> <7fff> <7f00>\n";
10489 $stream .= "<8000> <80ff> <8000>\n";
10490 $stream .= "<8100> <81ff> <8100>\n";
10491 $stream .= "<8200> <82ff> <8200>\n";
10492 $stream .= "<8300> <83ff> <8300>\n";
10493 $stream .= "<8400> <84ff> <8400>\n";
10494 $stream .= "<8500> <85ff> <8500>\n";
10495 $stream .= "<8600> <86ff> <8600>\n";
10496 $stream .= "<8700> <87ff> <8700>\n";
10497 $stream .= "<8800> <88ff> <8800>\n";
10498 $stream .= "<8900> <89ff> <8900>\n";
10499 $stream .= "<8a00> <8aff> <8a00>\n";
10500 $stream .= "<8b00> <8bff> <8b00>\n";
10501 $stream .= "<8c00> <8cff> <8c00>\n";
10502 $stream .= "<8d00> <8dff> <8d00>\n";
10503 $stream .= "<8e00> <8eff> <8e00>\n";
10504 $stream .= "<8f00> <8fff> <8f00>\n";
10505 $stream .= "<9000> <90ff> <9000>\n";
10506 $stream .= "<9100> <91ff> <9100>\n";
10507 $stream .= "<9200> <92ff> <9200>\n";
10508 $stream .= "<9300> <93ff> <9300>\n";
10509 $stream .= "<9400> <94ff> <9400>\n";
10510 $stream .= "<9500> <95ff> <9500>\n";
10511 $stream .= "<9600> <96ff> <9600>\n";
10512 $stream .= "<9700> <97ff> <9700>\n";
10513 $stream .= "<9800> <98ff> <9800>\n";
10514 $stream .= "<9900> <99ff> <9900>\n";
10515 $stream .= "<9a00> <9aff> <9a00>\n";
10516 $stream .= "<9b00> <9bff> <9b00>\n";
10517 $stream .= "<9c00> <9cff> <9c00>\n";
10518 $stream .= "<9d00> <9dff> <9d00>\n";
10519 $stream .= "<9e00> <9eff> <9e00>\n";
10520 $stream .= "<9f00> <9fff> <9f00>\n";
10521 $stream .= "<a000> <a0ff> <a000>\n";
10522 $stream .= "<a100> <a1ff> <a100>\n";
10523 $stream .= "<a200> <a2ff> <a200>\n";
10524 $stream .= "<a300> <a3ff> <a300>\n";
10525 $stream .= "<a400> <a4ff> <a400>\n";
10526 $stream .= "<a500> <a5ff> <a500>\n";
10527 $stream .= "<a600> <a6ff> <a600>\n";
10528 $stream .= "<a700> <a7ff> <a700>\n";
10529 $stream .= "<a800> <a8ff> <a800>\n";
10530 $stream .= "<a900> <a9ff> <a900>\n";
10531 $stream .= "<aa00> <aaff> <aa00>\n";
10532 $stream .= "<ab00> <abff> <ab00>\n";
10533 $stream .= "<ac00> <acff> <ac00>\n";
10534 $stream .= "<ad00> <adff> <ad00>\n";
10535 $stream .= "<ae00> <aeff> <ae00>\n";
10536 $stream .= "<af00> <afff> <af00>\n";
10537 $stream .= "<b000> <b0ff> <b000>\n";
10538 $stream .= "<b100> <b1ff> <b100>\n";
10539 $stream .= "<b200> <b2ff> <b200>\n";
10540 $stream .= "<b300> <b3ff> <b300>\n";
10541 $stream .= "<b400> <b4ff> <b400>\n";
10542 $stream .= "<b500> <b5ff> <b500>\n";
10543 $stream .= "<b600> <b6ff> <b600>\n";
10544 $stream .= "<b700> <b7ff> <b700>\n";
10545 $stream .= "<b800> <b8ff> <b800>\n";
10546 $stream .= "<b900> <b9ff> <b900>\n";
10547 $stream .= "<ba00> <baff> <ba00>\n";
10548 $stream .= "<bb00> <bbff> <bb00>\n";
10549 $stream .= "<bc00> <bcff> <bc00>\n";
10550 $stream .= "<bd00> <bdff> <bd00>\n";
10551 $stream .= "<be00> <beff> <be00>\n";
10552 $stream .= "<bf00> <bfff> <bf00>\n";
10553 $stream .= "<c000> <c0ff> <c000>\n";
10554 $stream .= "<c100> <c1ff> <c100>\n";
10555 $stream .= "<c200> <c2ff> <c200>\n";
10556 $stream .= "<c300> <c3ff> <c300>\n";
10557 $stream .= "<c400> <c4ff> <c400>\n";
10558 $stream .= "<c500> <c5ff> <c500>\n";
10559 $stream .= "<c600> <c6ff> <c600>\n";
10560 $stream .= "<c700> <c7ff> <c700>\n";
10561 $stream .= "endbfrange\n";
10562 $stream .= "56 beginbfrange\n";
10563 $stream .= "<c800> <c8ff> <c800>\n";
10564 $stream .= "<c900> <c9ff> <c900>\n";
10565 $stream .= "<ca00> <caff> <ca00>\n";
10566 $stream .= "<cb00> <cbff> <cb00>\n";
10567 $stream .= "<cc00> <ccff> <cc00>\n";
10568 $stream .= "<cd00> <cdff> <cd00>\n";
10569 $stream .= "<ce00> <ceff> <ce00>\n";
10570 $stream .= "<cf00> <cfff> <cf00>\n";
10571 $stream .= "<d000> <d0ff> <d000>\n";
10572 $stream .= "<d100> <d1ff> <d100>\n";
10573 $stream .= "<d200> <d2ff> <d200>\n";
10574 $stream .= "<d300> <d3ff> <d300>\n";
10575 $stream .= "<d400> <d4ff> <d400>\n";
10576 $stream .= "<d500> <d5ff> <d500>\n";
10577 $stream .= "<d600> <d6ff> <d600>\n";
10578 $stream .= "<d700> <d7ff> <d700>\n";
10579 $stream .= "<d800> <d8ff> <d800>\n";
10580 $stream .= "<d900> <d9ff> <d900>\n";
10581 $stream .= "<da00> <daff> <da00>\n";
10582 $stream .= "<db00> <dbff> <db00>\n";
10583 $stream .= "<dc00> <dcff> <dc00>\n";
10584 $stream .= "<dd00> <ddff> <dd00>\n";
10585 $stream .= "<de00> <deff> <de00>\n";
10586 $stream .= "<df00> <dfff> <df00>\n";
10587 $stream .= "<e000> <e0ff> <e000>\n";
10588 $stream .= "<e100> <e1ff> <e100>\n";
10589 $stream .= "<e200> <e2ff> <e200>\n";
10590 $stream .= "<e300> <e3ff> <e300>\n";
10591 $stream .= "<e400> <e4ff> <e400>\n";
10592 $stream .= "<e500> <e5ff> <e500>\n";
10593 $stream .= "<e600> <e6ff> <e600>\n";
10594 $stream .= "<e700> <e7ff> <e700>\n";
10595 $stream .= "<e800> <e8ff> <e800>\n";
10596 $stream .= "<e900> <e9ff> <e900>\n";
10597 $stream .= "<ea00> <eaff> <ea00>\n";
10598 $stream .= "<eb00> <ebff> <eb00>\n";
10599 $stream .= "<ec00> <ecff> <ec00>\n";
10600 $stream .= "<ed00> <edff> <ed00>\n";
10601 $stream .= "<ee00> <eeff> <ee00>\n";
10602 $stream .= "<ef00> <efff> <ef00>\n";
10603 $stream .= "<f000> <f0ff> <f000>\n";
10604 $stream .= "<f100> <f1ff> <f100>\n";
10605 $stream .= "<f200> <f2ff> <f200>\n";
10606 $stream .= "<f300> <f3ff> <f300>\n";
10607 $stream .= "<f400> <f4ff> <f400>\n";
10608 $stream .= "<f500> <f5ff> <f500>\n";
10609 $stream .= "<f600> <f6ff> <f600>\n";
10610 $stream .= "<f700> <f7ff> <f700>\n";
10611 $stream .= "<f800> <f8ff> <f800>\n";
10612 $stream .= "<f900> <f9ff> <f900>\n";
10613 $stream .= "<fa00> <faff> <fa00>\n";
10614 $stream .= "<fb00> <fbff> <fb00>\n";
10615 $stream .= "<fc00> <fcff> <fc00>\n";
10616 $stream .= "<fd00> <fdff> <fd00>\n";
10617 $stream .= "<fe00> <feff> <fe00>\n";
10618 $stream .= "<ff00> <ffff> <ff00>\n";
10619 $stream .= "endbfrange\n";
10620 $stream .= "endcmap\n";
10621 $stream .= "CMapName currentdict /CMap defineresource pop\n";
10622 $stream .= "end\n";
10623 $stream .= "end";
10624 // ToUnicode Object
10625 $this->_newobj();
10626 $stream = ($this->compress) ? gzcompress($stream) : $stream;
10627 $filter = ($this->compress) ? '/Filter /FlateDecode ' : '';
10628 $stream = $this->_getrawstream($stream);
10629 $this->_out('<<'.$filter.'/Length '.strlen($stream).'>> stream'."\n".$stream."\n".'endstream'."\n".'endobj');
10630 // CIDFontType2
10631 // A CIDFont whose glyph descriptions are based on TrueType font technology
10632 $oid = $this->_newobj();
10633 $out = '<< /Type /Font';
10634 $out .= ' /Subtype /CIDFontType2';
10635 $out .= ' /BaseFont /'.$fontname;
10636 // A dictionary containing entries that define the character collection of the CIDFont.
10637 $cidinfo = '/Registry '.$this->_datastring($font['cidinfo']['Registry'], $oid);
10638 $cidinfo .= ' /Ordering '.$this->_datastring($font['cidinfo']['Ordering'], $oid);
10639 $cidinfo .= ' /Supplement '.$font['cidinfo']['Supplement'];
10640 $out .= ' /CIDSystemInfo << '.$cidinfo.' >>';
10641 $out .= ' /FontDescriptor '.($this->n + 1).' 0 R';
10642 $out .= ' /DW '.$font['dw']; // default width
10643 $out .= "\n".$this->_putfontwidths($font, 0);
10644 if (isset($font['ctg']) AND (!$this->empty_string($font['ctg']))) {
10645 $out .= "\n".'/CIDToGIDMap '.($this->n + 2).' 0 R';
10647 $out .= ' >>';
10648 $out .= "\n".'endobj';
10649 $this->_out($out);
10650 // Font descriptor
10651 // A font descriptor describing the CIDFont default metrics other than its glyph widths
10652 $this->_newobj();
10653 $out = '<< /Type /FontDescriptor';
10654 $out .= ' /FontName /'.$fontname;
10655 foreach ($font['desc'] as $key => $value) {
10656 if (is_float($value)) {
10657 $value = sprintf('%.3F', $value);
10659 $out .= ' /'.$key.' '.$value;
10661 $fontdir = false;
10662 if (!$this->empty_string($font['file'])) {
10663 // A stream containing a TrueType font
10664 $out .= ' /FontFile2 '.$this->FontFiles[$font['file']]['n'].' 0 R';
10665 $fontdir = $this->FontFiles[$font['file']]['fontdir'];
10667 $out .= ' >>';
10668 $out .= "\n".'endobj';
10669 $this->_out($out);
10670 if (isset($font['ctg']) AND (!$this->empty_string($font['ctg']))) {
10671 $this->_newobj();
10672 // Embed CIDToGIDMap
10673 // A specification of the mapping from CIDs to glyph indices
10674 // search and get CTG font file to embedd
10675 $ctgfile = strtolower($font['ctg']);
10676 // search and get ctg font file to embedd
10677 $fontfile = '';
10678 // search files on various directories
10679 if (($fontdir !== false) AND file_exists($fontdir.$ctgfile)) {
10680 $fontfile = $fontdir.$ctgfile;
10681 } elseif (file_exists($this->_getfontpath().$ctgfile)) {
10682 $fontfile = $this->_getfontpath().$ctgfile;
10683 } elseif (file_exists($ctgfile)) {
10684 $fontfile = $ctgfile;
10686 if ($this->empty_string($fontfile)) {
10687 $this->Error('Font file not found: '.$ctgfile);
10689 $stream = $this->_getrawstream(file_get_contents($fontfile));
10690 $out = '<< /Length '.strlen($stream).'';
10691 if (substr($fontfile, -2) == '.z') { // check file extension
10692 // Decompresses data encoded using the public-domain
10693 // zlib/deflate compression method, reproducing the
10694 // original text or binary data
10695 $out .= ' /Filter /FlateDecode';
10697 $out .= ' >>';
10698 $out .= ' stream'."\n".$stream."\n".'endstream';
10699 $out .= "\n".'endobj';
10700 $this->_out($out);
10705 * Output CID-0 fonts.
10706 * A Type 0 CIDFont contains glyph descriptions based on the Adobe Type 1 font format
10707 * @param $font (array) font data
10708 * @protected
10709 * @author Andrew Whitehead, Nicola Asuni, Yukihiro Nakadaira
10710 * @since 3.2.000 (2008-06-23)
10712 protected function _putcidfont0($font) {
10713 $cidoffset = 0;
10714 if (!isset($font['cw'][1])) {
10715 $cidoffset = 31;
10717 if (isset($font['cidinfo']['uni2cid'])) {
10718 // convert unicode to cid.
10719 $uni2cid = $font['cidinfo']['uni2cid'];
10720 $cw = array();
10721 foreach ($font['cw'] as $uni => $width) {
10722 if (isset($uni2cid[$uni])) {
10723 $cw[($uni2cid[$uni] + $cidoffset)] = $width;
10724 } elseif ($uni < 256) {
10725 $cw[$uni] = $width;
10726 } // else unknown character
10728 $font = array_merge($font, array('cw' => $cw));
10730 $name = $font['name'];
10731 $enc = $font['enc'];
10732 if ($enc) {
10733 $longname = $name.'-'.$enc;
10734 } else {
10735 $longname = $name;
10737 $out = $this->_getobj($this->font_obj_ids[$font['fontkey']])."\n";
10738 $out .= '<</Type /Font';
10739 $out .= ' /Subtype /Type0';
10740 $out .= ' /BaseFont /'.$longname;
10741 $out .= ' /Name /F'.$font['i'];
10742 if ($enc) {
10743 $out .= ' /Encoding /'.$enc;
10745 $out .= ' /DescendantFonts ['.($this->n + 1).' 0 R]';
10746 $out .= ' >>';
10747 $out .= "\n".'endobj';
10748 $this->_out($out);
10749 $oid = $this->_newobj();
10750 $out = '<</Type /Font';
10751 $out .= ' /Subtype /CIDFontType0';
10752 $out .= ' /BaseFont /'.$name;
10753 $cidinfo = '/Registry '.$this->_datastring($font['cidinfo']['Registry'], $oid);
10754 $cidinfo .= ' /Ordering '.$this->_datastring($font['cidinfo']['Ordering'], $oid);
10755 $cidinfo .= ' /Supplement '.$font['cidinfo']['Supplement'];
10756 $out .= ' /CIDSystemInfo <<'.$cidinfo.'>>';
10757 $out .= ' /FontDescriptor '.($this->n + 1).' 0 R';
10758 $out .= ' /DW '.$font['dw'];
10759 $out .= "\n".$this->_putfontwidths($font, $cidoffset);
10760 $out .= ' >>';
10761 $out .= "\n".'endobj';
10762 $this->_out($out);
10763 $this->_newobj();
10764 $s = '<</Type /FontDescriptor /FontName /'.$name;
10765 foreach ($font['desc'] as $k => $v) {
10766 if ($k != 'Style') {
10767 if (is_float($v)) {
10768 $v = sprintf('%.3F', $v);
10770 $s .= ' /'.$k.' '.$v.'';
10773 $s .= '>>';
10774 $s .= "\n".'endobj';
10775 $this->_out($s);
10779 * Output images.
10780 * @protected
10782 protected function _putimages() {
10783 $filter = ($this->compress) ? '/Filter /FlateDecode ' : '';
10784 foreach ($this->imagekeys as $file) {
10785 $info = $this->getImageBuffer($file);
10786 // set object for alternate images array
10787 if (!empty($info['altimgs'])) {
10788 $altoid = $this->_newobj();
10789 $out = '[';
10790 foreach ($info['altimgs'] as $altimage) {
10791 if (isset($this->xobjects['I'.$altimage[0]]['n'])) {
10792 $out .= ' << /Image '.$this->xobjects['I'.$altimage[0]]['n'].' 0 R';
10793 $out .= ' /DefaultForPrinting';
10794 if ($altimage[1] === true) {
10795 $out .= ' true';
10796 } else {
10797 $out .= ' false';
10799 $out .= ' >>';
10802 $out .= ' ]';
10803 $out .= "\n".'endobj';
10804 $this->_out($out);
10806 // set image object
10807 $oid = $this->_newobj();
10808 $this->xobjects['I'.$info['i']] = array('n' => $oid);
10809 $this->setImageSubBuffer($file, 'n', $this->n);
10810 $out = '<</Type /XObject';
10811 $out .= ' /Subtype /Image';
10812 $out .= ' /Width '.$info['w'];
10813 $out .= ' /Height '.$info['h'];
10814 if (array_key_exists('masked', $info)) {
10815 $out .= ' /SMask '.($this->n - 1).' 0 R';
10817 // set color space
10818 $icc = false;
10819 if (isset($info['icc']) AND ($info['icc'] !== false)) {
10820 // ICC Colour Space
10821 $icc = true;
10822 $out .= ' /ColorSpace [/ICCBased '.($this->n + 1).' 0 R]';
10823 } elseif ($info['cs'] == 'Indexed') {
10824 // Indexed Colour Space
10825 $out .= ' /ColorSpace [/Indexed /DeviceRGB '.((strlen($info['pal']) / 3) - 1).' '.($this->n + 1).' 0 R]';
10826 } else {
10827 // Device Colour Space
10828 $out .= ' /ColorSpace /'.$info['cs'];
10830 if ($info['cs'] == 'DeviceCMYK') {
10831 $out .= ' /Decode [1 0 1 0 1 0 1 0]';
10833 $out .= ' /BitsPerComponent '.$info['bpc'];
10834 if (isset($altoid) AND ($altoid > 0)) {
10835 // reference to alternate images dictionary
10836 $out .= ' /Alternates '.$altoid.' 0 R';
10838 if (isset($info['exurl']) AND !empty($info['exurl'])) {
10839 // external stream
10840 $out .= ' /Length 0';
10841 $out .= ' /F << /FS /URL /F '.$this->_datastring($info['exurl'], $oid).' >>';
10842 if (isset($info['f'])) {
10843 $out .= ' /FFilter /'.$info['f'];
10845 $out .= ' >>';
10846 $out .= ' stream'."\n".'endstream';
10847 } else {
10848 if (isset($info['f'])) {
10849 $out .= ' /Filter /'.$info['f'];
10851 if (isset($info['parms'])) {
10852 $out .= ' '.$info['parms'];
10854 if (isset($info['trns']) AND is_array($info['trns'])) {
10855 $trns = '';
10856 $count_info = count($info['trns']);
10857 for ($i=0; $i < $count_info; ++$i) {
10858 $trns .= $info['trns'][$i].' '.$info['trns'][$i].' ';
10860 $out .= ' /Mask ['.$trns.']';
10862 $stream = $this->_getrawstream($info['data']);
10863 $out .= ' /Length '.strlen($stream).' >>';
10864 $out .= ' stream'."\n".$stream."\n".'endstream';
10866 $out .= "\n".'endobj';
10867 $this->_out($out);
10868 if ($icc) {
10869 // ICC colour profile
10870 $this->_newobj();
10871 $icc = ($this->compress) ? gzcompress($info['icc']) : $info['icc'];
10872 $icc = $this->_getrawstream($icc);
10873 $this->_out('<</N '.$info['ch'].' /Alternate /'.$info['cs'].' '.$filter.'/Length '.strlen($icc).'>> stream'."\n".$icc."\n".'endstream'."\n".'endobj');
10874 } elseif ($info['cs'] == 'Indexed') {
10875 // colour palette
10876 $this->_newobj();
10877 $pal = ($this->compress) ? gzcompress($info['pal']) : $info['pal'];
10878 $pal = $this->_getrawstream($pal);
10879 $this->_out('<<'.$filter.'/Length '.strlen($pal).'>> stream'."\n".$pal."\n".'endstream'."\n".'endobj');
10885 * Output Form XObjects Templates.
10886 * @author Nicola Asuni
10887 * @since 5.8.017 (2010-08-24)
10888 * @protected
10889 * @see startTemplate(), endTemplate(), printTemplate()
10891 protected function _putxobjects() {
10892 foreach ($this->xobjects as $key => $data) {
10893 if (isset($data['outdata'])) {
10894 $stream = trim($data['outdata']);
10895 $out = $this->_getobj($data['n'])."\n";
10896 $out .= '<<';
10897 $out .= ' /Type /XObject';
10898 $out .= ' /Subtype /Form';
10899 $out .= ' /FormType 1';
10900 if ($this->compress) {
10901 $stream = gzcompress($stream);
10902 $out .= ' /Filter /FlateDecode';
10904 $out .= sprintf(' /BBox [%.2F %.2F %.2F %.2F]', ($data['x'] * $this->k), (-$data['y'] * $this->k), (($data['w'] + $data['x']) * $this->k), (($data['h'] - $data['y']) * $this->k));
10905 $out .= ' /Matrix [1 0 0 1 0 0]';
10906 $out .= ' /Resources <<';
10907 $out .= ' /ProcSet [/PDF /Text /ImageB /ImageC /ImageI]';
10908 // fonts
10909 if (!empty($data['fonts'])) {
10910 $out .= ' /Font <<';
10911 foreach ($data['fonts'] as $fontkey => $fontid) {
10912 $out .= ' /F'.$fontid.' '.$this->font_obj_ids[$fontkey].' 0 R';
10914 $out .= ' >>';
10916 // images or nested xobjects
10917 if (!empty($data['images']) OR !empty($data['xobjects'])) {
10918 $out .= ' /XObject <<';
10919 foreach ($data['images'] as $imgid) {
10920 $out .= ' /I'.$imgid.' '.$this->xobjects['I'.$imgid]['n'].' 0 R';
10922 foreach ($data['xobjects'] as $sub_id => $sub_objid) {
10923 $out .= ' /'.$sub_id.' '.$sub_objid['n'].' 0 R';
10925 $out .= ' >>';
10927 $out .= ' >>'; //end resources
10928 if (isset($data['group']) AND ($data['group'] !== false)) {
10929 // set transparency group
10930 $out .= ' /Group << /Type /Group /S /Transparency';
10931 if (is_array($data['group'])) {
10932 if (isset($data['group']['CS']) AND !empty($data['group']['CS'])) {
10933 $out .= ' /CS /'.$data['group']['CS'];
10935 if (isset($data['group']['I'])) {
10936 $out .= ' /I /'.($data['group']['I']===true?'true':'false');
10938 if (isset($data['group']['K'])) {
10939 $out .= ' /K /'.($data['group']['K']===true?'true':'false');
10942 $out .= ' >>';
10944 $stream = $this->_getrawstream($stream, $data['n']);
10945 $out .= ' /Length '.strlen($stream);
10946 $out .= ' >>';
10947 $out .= ' stream'."\n".$stream."\n".'endstream';
10948 $out .= "\n".'endobj';
10949 $this->_out($out);
10955 * Output Spot Colors Resources.
10956 * @protected
10957 * @since 4.0.024 (2008-09-12)
10959 protected function _putspotcolors() {
10960 foreach ($this->spot_colors as $name => $color) {
10961 $this->_newobj();
10962 $this->spot_colors[$name]['n'] = $this->n;
10963 $out = '[/Separation /'.str_replace(' ', '#20', $name);
10964 $out .= ' /DeviceCMYK <<';
10965 $out .= ' /Range [0 1 0 1 0 1 0 1] /C0 [0 0 0 0]';
10966 $out .= ' '.sprintf('/C1 [%.4F %.4F %.4F %.4F] ', ($color['c'] / 100), ($color['m'] / 100), ($color['y'] / 100), ($color['k'] / 100));
10967 $out .= ' /FunctionType 2 /Domain [0 1] /N 1>>]';
10968 $out .= "\n".'endobj';
10969 $this->_out($out);
10974 * Return XObjects Dictionary.
10975 * @return string XObjects dictionary
10976 * @protected
10977 * @since 5.8.014 (2010-08-23)
10979 protected function _getxobjectdict() {
10980 $out = '';
10981 foreach ($this->xobjects as $id => $objid) {
10982 $out .= ' /'.$id.' '.$objid['n'].' 0 R';
10984 return $out;
10988 * Output Resources Dictionary.
10989 * @protected
10991 protected function _putresourcedict() {
10992 $out = $this->_getobj(2)."\n";
10993 $out .= '<< /ProcSet [/PDF /Text /ImageB /ImageC /ImageI]';
10994 $out .= ' /Font <<';
10995 foreach ($this->fontkeys as $fontkey) {
10996 $font = $this->getFontBuffer($fontkey);
10997 $out .= ' /F'.$font['i'].' '.$font['n'].' 0 R';
10999 $out .= ' >>';
11000 $out .= ' /XObject <<';
11001 $out .= $this->_getxobjectdict();
11002 $out .= ' >>';
11003 // layers
11004 if (!empty($this->pdflayers)) {
11005 $out .= ' /Properties <<';
11006 foreach ($this->pdflayers as $layer) {
11007 $out .= ' /'.$layer['layer'].' '.$layer['objid'].' 0 R';
11009 $out .= ' >>';
11011 // transparency
11012 $out .= ' /ExtGState <<';
11013 foreach ($this->extgstates as $k => $extgstate) {
11014 if (isset($extgstate['name'])) {
11015 $out .= ' /'.$extgstate['name'];
11016 } else {
11017 $out .= ' /GS'.$k;
11019 $out .= ' '.$extgstate['n'].' 0 R';
11021 $out .= ' >>';
11022 // gradient patterns
11023 if (isset($this->gradients) AND (count($this->gradients) > 0)) {
11024 $out .= ' /Pattern <<';
11025 foreach ($this->gradients as $id => $grad) {
11026 $out .= ' /p'.$id.' '.$grad['pattern'].' 0 R';
11028 $out .= ' >>';
11030 // gradient shadings
11031 if (isset($this->gradients) AND (count($this->gradients) > 0)) {
11032 $out .= ' /Shading <<';
11033 foreach ($this->gradients as $id => $grad) {
11034 $out .= ' /Sh'.$id.' '.$grad['id'].' 0 R';
11036 $out .= ' >>';
11038 // spot colors
11039 if (isset($this->spot_colors) AND (count($this->spot_colors) > 0)) {
11040 $out .= ' /ColorSpace <<';
11041 foreach ($this->spot_colors as $color) {
11042 $out .= ' /CS'.$color['i'].' '.$color['n'].' 0 R';
11044 $out .= ' >>';
11046 $out .= ' >>';
11047 $out .= "\n".'endobj';
11048 $this->_out($out);
11052 * Output Resources.
11053 * @protected
11055 protected function _putresources() {
11056 $this->_putextgstates();
11057 $this->_putocg();
11058 $this->_putfonts();
11059 $this->_putimages();
11060 $this->_putxobjects();
11061 $this->_putspotcolors();
11062 $this->_putshaders();
11063 $this->_putresourcedict();
11064 $this->_putdests();
11065 $this->_putbookmarks();
11066 $this->_putEmbeddedFiles();
11067 $this->_putannotsobjs();
11068 $this->_putjavascript();
11069 $this->_putencryption();
11073 * Adds some Metadata information (Document Information Dictionary)
11074 * (see Chapter 14.3.3 Document Information Dictionary of PDF32000_2008.pdf Reference)
11075 * @return int object id
11076 * @protected
11078 protected function _putinfo() {
11079 $oid = $this->_newobj();
11080 $out = '<<';
11081 // store current isunicode value
11082 $prev_isunicode = $this->isunicode;
11083 if ($this->docinfounicode) {
11084 $this->isunicode = true;
11086 if (!$this->empty_string($this->title)) {
11087 // The document's title.
11088 $out .= ' /Title '.$this->_textstring($this->title, $oid);
11090 if (!$this->empty_string($this->author)) {
11091 // The name of the person who created the document.
11092 $out .= ' /Author '.$this->_textstring($this->author, $oid);
11094 if (!$this->empty_string($this->subject)) {
11095 // The subject of the document.
11096 $out .= ' /Subject '.$this->_textstring($this->subject, $oid);
11098 if (!$this->empty_string($this->keywords)) {
11099 // Keywords associated with the document.
11100 $out .= ' /Keywords '.$this->_textstring($this->keywords.' TCPDF', $oid);
11102 if (!$this->empty_string($this->creator)) {
11103 // 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.
11104 $out .= ' /Creator '.$this->_textstring($this->creator, $oid);
11106 // restore previous isunicode value
11107 $this->isunicode = $prev_isunicode;
11108 // default producer
11109 $out .= ' /Producer '.$this->_textstring("\x54\x43\x50\x44\x46\x20".$this->tcpdf_version."\x20\x28\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x74\x63\x70\x64\x66\x2e\x6f\x72\x67\x29", $oid);
11110 // The date and time the document was created, in human-readable form
11111 $out .= ' /CreationDate '.$this->_datestring();
11112 // The date and time the document was most recently modified, in human-readable form
11113 $out .= ' /ModDate '.$this->_datestring();
11114 // A name object indicating whether the document has been modified to include trapping information
11115 $out .= ' /Trapped /False';
11116 $out .= ' >>';
11117 $out .= "\n".'endobj';
11118 $this->_out($out);
11119 return $oid;
11123 * Output Catalog.
11124 * @return int object id
11125 * @protected
11127 protected function _putcatalog() {
11128 $oid = $this->_newobj();
11129 $out = '<< /Type /Catalog';
11130 $out .= ' /Version /'.$this->PDFVersion;
11131 //$out .= ' /Extensions <<>>';
11132 $out .= ' /Pages 1 0 R';
11133 //$out .= ' /PageLabels ' //...;
11134 $out .= ' /Names <<';
11135 if ((!empty($this->javascript)) OR (!empty($this->js_objects))) {
11136 $out .= ' /JavaScript '.($this->n_js).' 0 R';
11138 $out .= ' >>';
11139 if (!empty($this->dests)) {
11140 $out .= ' /Dests '.$this->n_dests.' 0 R';
11142 $out .= $this->_putviewerpreferences();
11143 if (isset($this->LayoutMode) AND (!$this->empty_string($this->LayoutMode))) {
11144 $out .= ' /PageLayout /'.$this->LayoutMode;
11146 if (isset($this->PageMode) AND (!$this->empty_string($this->PageMode))) {
11147 $out .= ' /PageMode /'.$this->PageMode;
11149 if (count($this->outlines) > 0) {
11150 $out .= ' /Outlines '.$this->OutlineRoot.' 0 R';
11151 $out .= ' /PageMode /UseOutlines';
11153 //$out .= ' /Threads []';
11154 if ($this->ZoomMode == 'fullpage') {
11155 $out .= ' /OpenAction ['.$this->page_obj_id[1].' 0 R /Fit]';
11156 } elseif ($this->ZoomMode == 'fullwidth') {
11157 $out .= ' /OpenAction ['.$this->page_obj_id[1].' 0 R /FitH null]';
11158 } elseif ($this->ZoomMode == 'real') {
11159 $out .= ' /OpenAction ['.$this->page_obj_id[1].' 0 R /XYZ null null 1]';
11160 } elseif (!is_string($this->ZoomMode)) {
11161 $out .= sprintf(' /OpenAction ['.$this->page_obj_id[1].' 0 R /XYZ null null %.2F]', ($this->ZoomMode / 100));
11163 //$out .= ' /AA <<>>';
11164 //$out .= ' /URI <<>>';
11165 //$out .= ' /Metadata X Y R';
11166 //$out .= ' /StructTreeRoot <<>>';
11167 //$out .= ' /MarkInfo <<>>';
11168 if (isset($this->l['a_meta_language'])) {
11169 $out .= ' /Lang '.$this->_textstring($this->l['a_meta_language'], $oid);
11171 //$out .= ' /SpiderInfo <<>>';
11172 //$out .= ' /OutputIntents []';
11173 //$out .= ' /PieceInfo <<>>';
11174 if (!empty($this->pdflayers)) {
11175 $lyrobjs = '';
11176 $lyrobjs_print = '';
11177 $lyrobjs_view = '';
11178 foreach ($this->pdflayers as $layer) {
11179 $lyrobjs .= ' '.$layer['objid'].' 0 R';
11180 if ($layer['print']) {
11181 $lyrobjs_print .= ' '.$layer['objid'].' 0 R';
11183 if ($layer['view']) {
11184 $lyrobjs_view .= ' '.$layer['objid'].' 0 R';
11187 $out .= ' /OCProperties << /OCGs ['.$lyrobjs.']';
11188 $out .= ' /D << /ON ['.$lyrobjs_print.']';
11189 $out .= ' /OFF ['.$lyrobjs_view.']';
11190 $out .= ' /AS [';
11191 $out .= '<< /Event /Print /OCGs ['.$lyrobjs.'] /Category [/Print] >> << /Event /View /OCGs ['.$lyrobjs.'] /Category [/View] >>';
11192 $out .= ' ]';
11193 $out .= ' >> >>';
11195 // AcroForm
11196 if (!empty($this->form_obj_id) OR ($this->sign AND isset($this->signature_data['cert_type']))) {
11197 $out .= ' /AcroForm <<';
11198 $objrefs = '';
11199 if ($this->sign AND isset($this->signature_data['cert_type'])) {
11200 // set reference for signature object
11201 $objrefs .= $this->sig_obj_id.' 0 R';
11203 if (!empty($this->empty_signature_appearance)) {
11204 foreach ($this->empty_signature_appearance as $esa) {
11205 // set reference for empty signature objects
11206 $objrefs .= ' '.$esa['objid'].' 0 R';
11209 if (!empty($this->form_obj_id)) {
11210 foreach($this->form_obj_id as $objid) {
11211 $objrefs .= ' '.$objid.' 0 R';
11214 $out .= ' /Fields ['.$objrefs.']';
11215 if (!empty($this->form_obj_id) AND !$this->sign) {
11216 // It's better to turn off this value and set the appearance stream for each annotation (/AP) to avoid conflicts with signature fields.
11217 $out .= ' /NeedAppearances true';
11219 if ($this->sign AND isset($this->signature_data['cert_type'])) {
11220 if ($this->signature_data['cert_type'] > 0) {
11221 $out .= ' /SigFlags 3';
11222 } else {
11223 $out .= ' /SigFlags 1';
11226 //$out .= ' /CO ';
11227 if (isset($this->annotation_fonts) AND !empty($this->annotation_fonts)) {
11228 $out .= ' /DR <<';
11229 $out .= ' /Font <<';
11230 foreach ($this->annotation_fonts as $fontkey => $fontid) {
11231 $out .= ' /F'.$fontid.' '.$this->font_obj_ids[$fontkey].' 0 R';
11233 $out .= ' >> >>';
11235 $font = $this->getFontBuffer('helvetica');
11236 $out .= ' /DA (/F'.$font['i'].' 0 Tf 0 g)';
11237 $out .= ' /Q '.(($this->rtl)?'2':'0');
11238 //$out .= ' /XFA ';
11239 $out .= ' >>';
11240 // signatures
11241 if ($this->sign AND isset($this->signature_data['cert_type'])) {
11242 if ($this->signature_data['cert_type'] > 0) {
11243 $out .= ' /Perms << /DocMDP '.($this->sig_obj_id + 1).' 0 R >>';
11244 } else {
11245 $out .= ' /Perms << /UR3 '.($this->sig_obj_id + 1).' 0 R >>';
11249 //$out .= ' /Legal <<>>';
11250 //$out .= ' /Requirements []';
11251 //$out .= ' /Collection <<>>';
11252 //$out .= ' /NeedsRendering true';
11253 $out .= ' >>';
11254 $out .= "\n".'endobj';
11255 $this->_out($out);
11256 return $oid;
11260 * Output viewer preferences.
11261 * @return string for viewer preferences
11262 * @author Nicola asuni
11263 * @since 3.1.000 (2008-06-09)
11264 * @protected
11266 protected function _putviewerpreferences() {
11267 $out = ' /ViewerPreferences <<';
11268 if ($this->rtl) {
11269 $out .= ' /Direction /R2L';
11270 } else {
11271 $out .= ' /Direction /L2R';
11273 if (isset($this->viewer_preferences['HideToolbar']) AND ($this->viewer_preferences['HideToolbar'])) {
11274 $out .= ' /HideToolbar true';
11276 if (isset($this->viewer_preferences['HideMenubar']) AND ($this->viewer_preferences['HideMenubar'])) {
11277 $out .= ' /HideMenubar true';
11279 if (isset($this->viewer_preferences['HideWindowUI']) AND ($this->viewer_preferences['HideWindowUI'])) {
11280 $out .= ' /HideWindowUI true';
11282 if (isset($this->viewer_preferences['FitWindow']) AND ($this->viewer_preferences['FitWindow'])) {
11283 $out .= ' /FitWindow true';
11285 if (isset($this->viewer_preferences['CenterWindow']) AND ($this->viewer_preferences['CenterWindow'])) {
11286 $out .= ' /CenterWindow true';
11288 if (isset($this->viewer_preferences['DisplayDocTitle']) AND ($this->viewer_preferences['DisplayDocTitle'])) {
11289 $out .= ' /DisplayDocTitle true';
11291 if (isset($this->viewer_preferences['NonFullScreenPageMode'])) {
11292 $out .= ' /NonFullScreenPageMode /'.$this->viewer_preferences['NonFullScreenPageMode'];
11294 if (isset($this->viewer_preferences['ViewArea'])) {
11295 $out .= ' /ViewArea /'.$this->viewer_preferences['ViewArea'];
11297 if (isset($this->viewer_preferences['ViewClip'])) {
11298 $out .= ' /ViewClip /'.$this->viewer_preferences['ViewClip'];
11300 if (isset($this->viewer_preferences['PrintArea'])) {
11301 $out .= ' /PrintArea /'.$this->viewer_preferences['PrintArea'];
11303 if (isset($this->viewer_preferences['PrintClip'])) {
11304 $out .= ' /PrintClip /'.$this->viewer_preferences['PrintClip'];
11306 if (isset($this->viewer_preferences['PrintScaling'])) {
11307 $out .= ' /PrintScaling /'.$this->viewer_preferences['PrintScaling'];
11309 if (isset($this->viewer_preferences['Duplex']) AND (!$this->empty_string($this->viewer_preferences['Duplex']))) {
11310 $out .= ' /Duplex /'.$this->viewer_preferences['Duplex'];
11312 if (isset($this->viewer_preferences['PickTrayByPDFSize'])) {
11313 if ($this->viewer_preferences['PickTrayByPDFSize']) {
11314 $out .= ' /PickTrayByPDFSize true';
11315 } else {
11316 $out .= ' /PickTrayByPDFSize false';
11319 if (isset($this->viewer_preferences['PrintPageRange'])) {
11320 $PrintPageRangeNum = '';
11321 foreach ($this->viewer_preferences['PrintPageRange'] as $k => $v) {
11322 $PrintPageRangeNum .= ' '.($v - 1).'';
11324 $out .= ' /PrintPageRange ['.substr($PrintPageRangeNum,1).']';
11326 if (isset($this->viewer_preferences['NumCopies'])) {
11327 $out .= ' /NumCopies '.intval($this->viewer_preferences['NumCopies']);
11329 $out .= ' >>';
11330 return $out;
11334 * Output PDF header.
11335 * @protected
11337 protected function _putheader() {
11338 $this->_out('%PDF-'.$this->PDFVersion);
11342 * Output end of document (EOF).
11343 * @protected
11345 protected function _enddoc() {
11346 $this->state = 1;
11347 $this->_putheader();
11348 $this->_putpages();
11349 $this->_putresources();
11350 // empty signature fields
11351 if (!empty($this->empty_signature_appearance)) {
11352 foreach ($this->empty_signature_appearance as $key => $esa) {
11353 // widget annotation for empty signature
11354 $out = $this->_getobj($esa['objid'])."\n";
11355 $out .= '<< /Type /Annot';
11356 $out .= ' /Subtype /Widget';
11357 $out .= ' /Rect ['.$esa['rect'].']';
11358 $out .= ' /P '.$this->page_obj_id[($esa['page'])].' 0 R'; // link to signature appearance page
11359 $out .= ' /F 4';
11360 $out .= ' /FT /Sig';
11361 $signame = sprintf('Signature_%03d', ($key + 1));
11362 $out .= ' /T '.$this->_textstring($signame, $esa['objid']);
11363 $out .= ' /Ff 0';
11364 $out .= ' >>';
11365 $out .= "\n".'endobj';
11366 $this->_out($out);
11369 // Signature
11370 if ($this->sign AND isset($this->signature_data['cert_type'])) {
11371 // widget annotation for signature
11372 $out = $this->_getobj($this->sig_obj_id)."\n";
11373 $out .= '<< /Type /Annot';
11374 $out .= ' /Subtype /Widget';
11375 $out .= ' /Rect ['.$this->signature_appearance['rect'].']';
11376 $out .= ' /P '.$this->page_obj_id[($this->signature_appearance['page'])].' 0 R'; // link to signature appearance page
11377 $out .= ' /F 4';
11378 $out .= ' /FT /Sig';
11379 $out .= ' /T '.$this->_textstring('Signature_000', $this->sig_obj_id);
11380 $out .= ' /Ff 0';
11381 $out .= ' /V '.($this->sig_obj_id + 1).' 0 R';
11382 $out .= ' >>';
11383 $out .= "\n".'endobj';
11384 $this->_out($out);
11385 // signature
11386 $this->_putsignature();
11388 // Info
11389 $objid_info = $this->_putinfo();
11390 // Catalog
11391 $objid_catalog = $this->_putcatalog();
11392 // Cross-ref
11393 $o = $this->bufferlen;
11394 // XREF section
11395 $this->_out('xref');
11396 $this->_out('0 '.($this->n + 1));
11397 $this->_out('0000000000 65535 f ');
11398 for ($i=1; $i <= $this->n; ++$i) {
11399 if (!isset($this->offsets[$i]) AND ($i > 1)) {
11400 $this->offsets[$i] = $this->offsets[($i - 1)];
11402 $this->_out(sprintf('%010d 00000 n ', $this->offsets[$i]));
11404 // TRAILER
11405 $out = 'trailer <<';
11406 $out .= ' /Size '.($this->n + 1);
11407 $out .= ' /Root '.$objid_catalog.' 0 R';
11408 $out .= ' /Info '.$objid_info.' 0 R';
11409 if ($this->encrypted) {
11410 $out .= ' /Encrypt '.$this->encryptdata['objid'].' 0 R';
11412 $out .= ' /ID [ <'.$this->file_id.'> <'.$this->file_id.'> ]';
11413 $out .= ' >>';
11414 $this->_out($out);
11415 $this->_out('startxref');
11416 $this->_out($o);
11417 $this->_out('%%EOF');
11418 $this->state = 3; // end-of-doc
11419 if ($this->diskcache) {
11420 // remove temporary files used for images
11421 foreach ($this->imagekeys as $key) {
11422 // remove temporary files
11423 unlink($this->images[$key]);
11425 foreach ($this->fontkeys as $key) {
11426 // remove temporary files
11427 unlink($this->fonts[$key]);
11433 * Initialize a new page.
11434 * @param $orientation (string) page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
11435 * @param $format (mixed) The format used for pages. It can be either: one of the string values specified at getPageSizeFromFormat() or an array of parameters specified at setPageFormat().
11436 * @protected
11437 * @see getPageSizeFromFormat(), setPageFormat()
11439 protected function _beginpage($orientation='', $format='') {
11440 ++$this->page;
11441 $this->setPageBuffer($this->page, '');
11442 // initialize array for graphics tranformation positions inside a page buffer
11443 $this->transfmrk[$this->page] = array();
11444 $this->state = 2;
11445 if ($this->empty_string($orientation)) {
11446 if (isset($this->CurOrientation)) {
11447 $orientation = $this->CurOrientation;
11448 } elseif ($this->fwPt > $this->fhPt) {
11449 // landscape
11450 $orientation = 'L';
11451 } else {
11452 // portrait
11453 $orientation = 'P';
11456 if ($this->empty_string($format)) {
11457 $this->pagedim[$this->page] = $this->pagedim[($this->page - 1)];
11458 $this->setPageOrientation($orientation);
11459 } else {
11460 $this->setPageFormat($format, $orientation);
11462 if ($this->rtl) {
11463 $this->x = $this->w - $this->rMargin;
11464 } else {
11465 $this->x = $this->lMargin;
11467 $this->y = $this->tMargin;
11468 if (isset($this->newpagegroup[$this->page])) {
11469 // start a new group
11470 $this->currpagegroup = $this->newpagegroup[$this->page];
11471 $this->pagegroups[$this->currpagegroup] = 1;
11472 } elseif (isset($this->currpagegroup) AND ($this->currpagegroup > 0)) {
11473 ++$this->pagegroups[$this->currpagegroup];
11478 * Mark end of page.
11479 * @protected
11481 protected function _endpage() {
11482 $this->setVisibility('all');
11483 $this->state = 1;
11487 * Begin a new object and return the object number.
11488 * @return int object number
11489 * @protected
11491 protected function _newobj() {
11492 $this->_out($this->_getobj());
11493 return $this->n;
11497 * Return the starting object string for the selected object ID.
11498 * @param $objid (int) Object ID (leave empty to get a new ID).
11499 * @return string the starting object string
11500 * @protected
11501 * @since 5.8.009 (2010-08-20)
11503 protected function _getobj($objid='') {
11504 if ($objid === '') {
11505 ++$this->n;
11506 $objid = $this->n;
11508 $this->offsets[$objid] = $this->bufferlen;
11509 return $objid.' 0 obj';
11513 * Underline text.
11514 * @param $x (int) X coordinate
11515 * @param $y (int) Y coordinate
11516 * @param $txt (string) text to underline
11517 * @protected
11519 protected function _dounderline($x, $y, $txt) {
11520 $w = $this->GetStringWidth($txt);
11521 return $this->_dounderlinew($x, $y, $w);
11525 * Underline for rectangular text area.
11526 * @param $x (int) X coordinate
11527 * @param $y (int) Y coordinate
11528 * @param $w (int) width to underline
11529 * @protected
11530 * @since 4.8.008 (2009-09-29)
11532 protected function _dounderlinew($x, $y, $w) {
11533 $linew = - $this->CurrentFont['ut'] / 1000 * $this->FontSizePt;
11534 return sprintf('%.2F %.2F %.2F %.2F re f', $x * $this->k, ((($this->h - $y) * $this->k) + $linew), $w * $this->k, $linew);
11538 * Line through text.
11539 * @param $x (int) X coordinate
11540 * @param $y (int) Y coordinate
11541 * @param $txt (string) text to linethrough
11542 * @protected
11544 protected function _dolinethrough($x, $y, $txt) {
11545 $w = $this->GetStringWidth($txt);
11546 return $this->_dolinethroughw($x, $y, $w);
11550 * Line through for rectangular text area.
11551 * @param $x (int) X coordinate
11552 * @param $y (int) Y coordinate
11553 * @param $w (int) line length (width)
11554 * @protected
11555 * @since 4.9.008 (2009-09-29)
11557 protected function _dolinethroughw($x, $y, $w) {
11558 $linew = - $this->CurrentFont['ut'] / 1000 * $this->FontSizePt;
11559 return sprintf('%.2F %.2F %.2F %.2F re f', $x * $this->k, ((($this->h - $y) * $this->k) + $linew + ($this->FontSizePt / 3)), $w * $this->k, $linew);
11563 * Overline text.
11564 * @param $x (int) X coordinate
11565 * @param $y (int) Y coordinate
11566 * @param $txt (string) text to overline
11567 * @protected
11568 * @since 4.9.015 (2010-04-19)
11570 protected function _dooverline($x, $y, $txt) {
11571 $w = $this->GetStringWidth($txt);
11572 return $this->_dooverlinew($x, $y, $w);
11576 * Overline for rectangular text area.
11577 * @param $x (int) X coordinate
11578 * @param $y (int) Y coordinate
11579 * @param $w (int) width to overline
11580 * @protected
11581 * @since 4.9.015 (2010-04-19)
11583 protected function _dooverlinew($x, $y, $w) {
11584 $linew = - $this->CurrentFont['ut'] / 1000 * $this->FontSizePt;
11585 return sprintf('%.2F %.2F %.2F %.2F re f', $x * $this->k, (($this->h - $y + $this->FontAscent) * $this->k) - $linew, $w * $this->k, $linew);
11590 * Read a 4-byte (32 bit) integer from file.
11591 * @param $f (string) file name.
11592 * @return 4-byte integer
11593 * @protected
11595 protected function _freadint($f) {
11596 $a = unpack('Ni', fread($f, 4));
11597 return $a['i'];
11601 * Add "\" before "\", "(" and ")"
11602 * @param $s (string) string to escape.
11603 * @return string escaped string.
11604 * @protected
11606 protected function _escape($s) {
11607 // the chr(13) substitution fixes the Bugs item #1421290.
11608 return strtr($s, array(')' => '\\)', '(' => '\\(', '\\' => '\\\\', chr(13) => '\r'));
11612 * Format a data string for meta information
11613 * @param $s (string) data string to escape.
11614 * @param $n (int) object ID
11615 * @return string escaped string.
11616 * @protected
11618 protected function _datastring($s, $n=0) {
11619 if ($n == 0) {
11620 $n = $this->n;
11622 $s = $this->_encrypt_data($n, $s);
11623 return '('. $this->_escape($s).')';
11627 * Returns a formatted date for meta information
11628 * @param $n (int) object ID
11629 * @return string escaped date string.
11630 * @protected
11631 * @since 4.6.028 (2009-08-25)
11633 protected function _datestring($n=0) {
11634 $current_time = substr_replace(date('YmdHisO'), '\'', (0 - 2), 0).'\'';
11635 return $this->_datastring('D:'.$current_time, $n);
11639 * Format a text string for meta information
11640 * @param $s (string) string to escape.
11641 * @param $n (int) object ID
11642 * @return string escaped string.
11643 * @protected
11645 protected function _textstring($s, $n=0) {
11646 if ($this->isunicode) {
11647 //Convert string to UTF-16BE
11648 $s = $this->UTF8ToUTF16BE($s, true);
11650 return $this->_datastring($s, $n);
11654 * THIS METHOD IS DEPRECATED
11655 * Format a text string
11656 * @param $s (string) string to escape.
11657 * @return string escaped string.
11658 * @protected
11659 * @deprecated
11661 protected function _escapetext($s) {
11662 if ($this->isunicode) {
11663 if (($this->CurrentFont['type'] == 'core') OR ($this->CurrentFont['type'] == 'TrueType') OR ($this->CurrentFont['type'] == 'Type1')) {
11664 $s = $this->UTF8ToLatin1($s);
11665 } else {
11666 //Convert string to UTF-16BE and reverse RTL language
11667 $s = $this->utf8StrRev($s, false, $this->tmprtl);
11670 return $this->_escape($s);
11674 * get raw output stream.
11675 * @param $s (string) string to output.
11676 * @param $n (int) object reference for encryption mode
11677 * @protected
11678 * @author Nicola Asuni
11679 * @since 5.5.000 (2010-06-22)
11681 protected function _getrawstream($s, $n=0) {
11682 if ($n <= 0) {
11683 // default to current object
11684 $n = $this->n;
11686 return $this->_encrypt_data($n, $s);
11690 * Format output stream (DEPRECATED).
11691 * @param $s (string) string to output.
11692 * @param $n (int) object reference for encryption mode
11693 * @protected
11694 * @deprecated
11696 protected function _getstream($s, $n=0) {
11697 return 'stream'."\n".$this->_getrawstream($s, $n)."\n".'endstream';
11701 * Output a stream (DEPRECATED).
11702 * @param $s (string) string to output.
11703 * @param $n (int) object reference for encryption mode
11704 * @protected
11705 * @deprecated
11707 protected function _putstream($s, $n=0) {
11708 $this->_out($this->_getstream($s, $n));
11712 * Output a string to the document.
11713 * @param $s (string) string to output.
11714 * @protected
11716 protected function _out($s) {
11717 if ($this->state == 2) {
11718 if ($this->inxobj) {
11719 // we are inside an XObject template
11720 $this->xobjects[$this->xobjid]['outdata'] .= $s."\n";
11721 } elseif ((!$this->InFooter) AND isset($this->footerlen[$this->page]) AND ($this->footerlen[$this->page] > 0)) {
11722 // puts data before page footer
11723 $pagebuff = $this->getPageBuffer($this->page);
11724 $page = substr($pagebuff, 0, -$this->footerlen[$this->page]);
11725 $footer = substr($pagebuff, -$this->footerlen[$this->page]);
11726 $this->setPageBuffer($this->page, $page.$s."\n".$footer);
11727 // update footer position
11728 $this->footerpos[$this->page] += strlen($s."\n");
11729 } else {
11730 $this->setPageBuffer($this->page, $s."\n", true);
11732 } else {
11733 $this->setBuffer($s."\n");
11738 * Converts UTF-8 strings to codepoints array.<br>
11739 * Invalid byte sequences will be replaced with 0xFFFD (replacement character)<br>
11740 * Based on: http://www.faqs.org/rfcs/rfc3629.html
11741 * <pre>
11742 * Char. number range | UTF-8 octet sequence
11743 * (hexadecimal) | (binary)
11744 * --------------------+-----------------------------------------------
11745 * 0000 0000-0000 007F | 0xxxxxxx
11746 * 0000 0080-0000 07FF | 110xxxxx 10xxxxxx
11747 * 0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx
11748 * 0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
11749 * ---------------------------------------------------------------------
11751 * ABFN notation:
11752 * ---------------------------------------------------------------------
11753 * UTF8-octets = *( UTF8-char )
11754 * UTF8-char = UTF8-1 / UTF8-2 / UTF8-3 / UTF8-4
11755 * UTF8-1 = %x00-7F
11756 * UTF8-2 = %xC2-DF UTF8-tail
11758 * UTF8-3 = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) /
11759 * %xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail )
11760 * UTF8-4 = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) /
11761 * %xF4 %x80-8F 2( UTF8-tail )
11762 * UTF8-tail = %x80-BF
11763 * ---------------------------------------------------------------------
11764 * </pre>
11765 * @param $str (string) string to process.
11766 * @return array containing codepoints (UTF-8 characters values)
11767 * @protected
11768 * @author Nicola Asuni
11769 * @since 1.53.0.TC005 (2005-01-05)
11771 protected function UTF8StringToArray($str) {
11772 // build a unique string key
11773 $strkey = md5($str);
11774 if (isset($this->cache_UTF8StringToArray[$strkey])) {
11775 // return cached value
11776 $chrarray = $this->cache_UTF8StringToArray[$strkey]['s'];
11777 if (!isset($this->cache_UTF8StringToArray[$strkey]['f'][$this->CurrentFont['fontkey']])) {
11778 if ($this->isunicode) {
11779 foreach ($chrarray as $chr) {
11780 // store this char for font subsetting
11781 $this->CurrentFont['subsetchars'][$chr] = true;
11783 // update font subsetchars
11784 $this->setFontSubBuffer($this->CurrentFont['fontkey'], 'subsetchars', $this->CurrentFont['subsetchars']);
11786 $this->cache_UTF8StringToArray[$strkey]['f'][$this->CurrentFont['fontkey']] = true;
11788 return $chrarray;
11790 // check cache size
11791 if ($this->cache_size_UTF8StringToArray >= $this->cache_maxsize_UTF8StringToArray) {
11792 // remove first element
11793 array_shift($this->cache_UTF8StringToArray);
11795 // new cache array for selected string
11796 $this->cache_UTF8StringToArray[$strkey] = array('s' => array(), 'f' => array());
11797 ++$this->cache_size_UTF8StringToArray;
11798 if (!$this->isunicode) {
11799 // split string into array of equivalent codes
11800 $strarr = array();
11801 $strlen = strlen($str);
11802 for ($i=0; $i < $strlen; ++$i) {
11803 $strarr[] = ord($str{$i});
11805 // insert new value on cache
11806 $this->cache_UTF8StringToArray[$strkey]['s'] = $strarr;
11807 $this->cache_UTF8StringToArray[$strkey]['f'][$this->CurrentFont['fontkey']] = true;
11808 return $strarr;
11810 $unichar = -1; // last unicode char
11811 $unicode = array(); // array containing unicode values
11812 $bytes = array(); // array containing single character byte sequences
11813 $numbytes = 1; // number of octetc needed to represent the UTF-8 character
11814 $str .= ''; // force $str to be a string
11815 $length = strlen($str);
11816 for ($i = 0; $i < $length; ++$i) {
11817 $char = ord($str{$i}); // get one string character at time
11818 if (count($bytes) == 0) { // get starting octect
11819 if ($char <= 0x7F) {
11820 $unichar = $char; // use the character "as is" because is ASCII
11821 $numbytes = 1;
11822 } elseif (($char >> 0x05) == 0x06) { // 2 bytes character (0x06 = 110 BIN)
11823 $bytes[] = ($char - 0xC0) << 0x06;
11824 $numbytes = 2;
11825 } elseif (($char >> 0x04) == 0x0E) { // 3 bytes character (0x0E = 1110 BIN)
11826 $bytes[] = ($char - 0xE0) << 0x0C;
11827 $numbytes = 3;
11828 } elseif (($char >> 0x03) == 0x1E) { // 4 bytes character (0x1E = 11110 BIN)
11829 $bytes[] = ($char - 0xF0) << 0x12;
11830 $numbytes = 4;
11831 } else {
11832 // use replacement character for other invalid sequences
11833 $unichar = 0xFFFD;
11834 $bytes = array();
11835 $numbytes = 1;
11837 } elseif (($char >> 0x06) == 0x02) { // bytes 2, 3 and 4 must start with 0x02 = 10 BIN
11838 $bytes[] = $char - 0x80;
11839 if (count($bytes) == $numbytes) {
11840 // compose UTF-8 bytes to a single unicode value
11841 $char = $bytes[0];
11842 for ($j = 1; $j < $numbytes; ++$j) {
11843 $char += ($bytes[$j] << (($numbytes - $j - 1) * 0x06));
11845 if ((($char >= 0xD800) AND ($char <= 0xDFFF)) OR ($char >= 0x10FFFF)) {
11846 /* The definition of UTF-8 prohibits encoding character numbers between
11847 U+D800 and U+DFFF, which are reserved for use with the UTF-16
11848 encoding form (as surrogate pairs) and do not directly represent
11849 characters. */
11850 $unichar = 0xFFFD; // use replacement character
11851 } else {
11852 $unichar = $char; // add char to array
11854 // reset data for next char
11855 $bytes = array();
11856 $numbytes = 1;
11858 } else {
11859 // use replacement character for other invalid sequences
11860 $unichar = 0xFFFD;
11861 $bytes = array();
11862 $numbytes = 1;
11864 if ($unichar >= 0) {
11865 // insert unicode value into array
11866 $unicode[] = $unichar;
11867 // store this char for font subsetting
11868 $this->CurrentFont['subsetchars'][$unichar] = true;
11869 $unichar = -1;
11872 // update font subsetchars
11873 $this->setFontSubBuffer($this->CurrentFont['fontkey'], 'subsetchars', $this->CurrentFont['subsetchars']);
11874 // insert new value on cache
11875 $this->cache_UTF8StringToArray[$strkey]['s'] = $unicode;
11876 $this->cache_UTF8StringToArray[$strkey]['f'][$this->CurrentFont['fontkey']] = true;
11877 return $unicode;
11881 * Converts UTF-8 strings to UTF16-BE.<br>
11882 * @param $str (string) string to process.
11883 * @param $setbom (boolean) if true set the Byte Order Mark (BOM = 0xFEFF)
11884 * @return string
11885 * @author Nicola Asuni
11886 * @since 1.53.0.TC005 (2005-01-05)
11887 * @see UTF8StringToArray(), arrUTF8ToUTF16BE()
11888 * @protected
11890 protected function UTF8ToUTF16BE($str, $setbom=false) {
11891 if (!$this->isunicode) {
11892 return $str; // string is not in unicode
11894 $unicode = $this->UTF8StringToArray($str); // array containing UTF-8 unicode values
11895 return $this->arrUTF8ToUTF16BE($unicode, $setbom);
11899 * Converts UTF-8 strings to Latin1 when using the standard 14 core fonts.<br>
11900 * @param $str (string) string to process.
11901 * @return string
11902 * @author Andrew Whitehead, Nicola Asuni
11903 * @protected
11904 * @since 3.2.000 (2008-06-23)
11906 protected function UTF8ToLatin1($str) {
11907 if (!$this->isunicode) {
11908 return $str; // string is not in unicode
11910 $outstr = ''; // string to be returned
11911 $unicode = $this->UTF8StringToArray($str); // array containing UTF-8 unicode values
11912 foreach ($unicode as $char) {
11913 if ($char < 256) {
11914 $outstr .= chr($char);
11915 } elseif (array_key_exists($char, $this->unicode->uni_utf8tolatin)) {
11916 // map from UTF-8
11917 $outstr .= chr($this->unicode->uni_utf8tolatin[$char]);
11918 } elseif ($char == 0xFFFD) {
11919 // skip
11920 } else {
11921 $outstr .= '?';
11924 return $outstr;
11928 * Converts UTF-8 characters array to array of Latin1 characters<br>
11929 * @param $unicode (array) array containing UTF-8 unicode values
11930 * @return array
11931 * @author Nicola Asuni
11932 * @protected
11933 * @since 4.8.023 (2010-01-15)
11935 protected function UTF8ArrToLatin1($unicode) {
11936 if ((!$this->isunicode) OR $this->isUnicodeFont()) {
11937 return $unicode;
11939 $outarr = array(); // array to be returned
11940 foreach ($unicode as $char) {
11941 if ($char < 256) {
11942 $outarr[] = $char;
11943 } elseif (array_key_exists($char, $this->unicode->uni_utf8tolatin)) {
11944 // map from UTF-8
11945 $outarr[] = $this->unicode->uni_utf8tolatin[$char];
11946 } elseif ($char == 0xFFFD) {
11947 // skip
11948 } else {
11949 $outarr[] = 63; // '?' character
11952 return $outarr;
11956 * Converts array of UTF-8 characters to UTF16-BE string.<br>
11957 * Based on: http://www.faqs.org/rfcs/rfc2781.html
11958 * <pre>
11959 * Encoding UTF-16:
11961 * Encoding of a single character from an ISO 10646 character value to
11962 * UTF-16 proceeds as follows. Let U be the character number, no greater
11963 * than 0x10FFFF.
11965 * 1) If U < 0x10000, encode U as a 16-bit unsigned integer and
11966 * terminate.
11968 * 2) Let U' = U - 0x10000. Because U is less than or equal to 0x10FFFF,
11969 * U' must be less than or equal to 0xFFFFF. That is, U' can be
11970 * represented in 20 bits.
11972 * 3) Initialize two 16-bit unsigned integers, W1 and W2, to 0xD800 and
11973 * 0xDC00, respectively. These integers each have 10 bits free to
11974 * encode the character value, for a total of 20 bits.
11976 * 4) Assign the 10 high-order bits of the 20-bit U' to the 10 low-order
11977 * bits of W1 and the 10 low-order bits of U' to the 10 low-order
11978 * bits of W2. Terminate.
11980 * Graphically, steps 2 through 4 look like:
11981 * U' = yyyyyyyyyyxxxxxxxxxx
11982 * W1 = 110110yyyyyyyyyy
11983 * W2 = 110111xxxxxxxxxx
11984 * </pre>
11985 * @param $unicode (array) array containing UTF-8 unicode values
11986 * @param $setbom (boolean) if true set the Byte Order Mark (BOM = 0xFEFF)
11987 * @return string
11988 * @protected
11989 * @author Nicola Asuni
11990 * @since 2.1.000 (2008-01-08)
11991 * @see UTF8ToUTF16BE()
11993 protected function arrUTF8ToUTF16BE($unicode, $setbom=false) {
11994 $outstr = ''; // string to be returned
11995 if ($setbom) {
11996 $outstr .= "\xFE\xFF"; // Byte Order Mark (BOM)
11998 foreach ($unicode as $char) {
11999 if ($char == 0x200b) {
12000 // skip Unicode Character 'ZERO WIDTH SPACE' (DEC:8203, U+200B)
12001 } elseif ($char == 0xFFFD) {
12002 $outstr .= "\xFF\xFD"; // replacement character
12003 } elseif ($char < 0x10000) {
12004 $outstr .= chr($char >> 0x08);
12005 $outstr .= chr($char & 0xFF);
12006 } else {
12007 $char -= 0x10000;
12008 $w1 = 0xD800 | ($char >> 0x0a);
12009 $w2 = 0xDC00 | ($char & 0x3FF);
12010 $outstr .= chr($w1 >> 0x08);
12011 $outstr .= chr($w1 & 0xFF);
12012 $outstr .= chr($w2 >> 0x08);
12013 $outstr .= chr($w2 & 0xFF);
12016 return $outstr;
12018 // ====================================================
12021 * Set header font.
12022 * @param $font (array) font
12023 * @public
12024 * @since 1.1
12026 public function setHeaderFont($font) {
12027 $this->header_font = $font;
12031 * Get header font.
12032 * @return array()
12033 * @public
12034 * @since 4.0.012 (2008-07-24)
12036 public function getHeaderFont() {
12037 return $this->header_font;
12041 * Set footer font.
12042 * @param $font (array) font
12043 * @public
12044 * @since 1.1
12046 public function setFooterFont($font) {
12047 $this->footer_font = $font;
12051 * Get Footer font.
12052 * @return array()
12053 * @public
12054 * @since 4.0.012 (2008-07-24)
12056 public function getFooterFont() {
12057 return $this->footer_font;
12061 * Set language array.
12062 * @param $language (array)
12063 * @public
12064 * @since 1.1
12066 public function setLanguageArray($language) {
12067 $this->l = $language;
12068 if (isset($this->l['a_meta_dir'])) {
12069 $this->rtl = $this->l['a_meta_dir']=='rtl' ? true : false;
12070 } else {
12071 $this->rtl = false;
12076 * Returns the PDF data.
12077 * @public
12079 public function getPDFData() {
12080 if ($this->state < 3) {
12081 $this->Close();
12083 return $this->buffer;
12087 * Output anchor link.
12088 * @param $url (string) link URL or internal link (i.e.: &lt;a href="#23,4.5"&gt;link to page 23 at 4.5 Y position&lt;/a&gt;)
12089 * @param $name (string) link name
12090 * @param $fill (boolean) Indicates if the cell background must be painted (true) or transparent (false).
12091 * @param $firstline (boolean) if true prints only the first line and return the remaining string.
12092 * @param $color (array) array of RGB text color
12093 * @param $style (string) font style (U, D, B, I)
12094 * @param $firstblock (boolean) if true the string is the starting of a line.
12095 * @return the number of cells used or the remaining text if $firstline = true;
12096 * @public
12098 public function addHtmlLink($url, $name, $fill=false, $firstline=false, $color='', $style=-1, $firstblock=false) {
12099 if (!$this->empty_string($url) AND ($url{0} == '#')) {
12100 // convert url to internal link
12101 $lnkdata = explode(',', $url);
12102 if (isset($lnkdata[0])) {
12103 $page = intval(substr($lnkdata[0], 1));
12104 if (empty($page) OR ($page <= 0)) {
12105 $page = $this->page;
12107 if (isset($lnkdata[1]) AND (strlen($lnkdata[1]) > 0)) {
12108 $lnky = floatval($lnkdata[1]);
12109 } else {
12110 $lnky = 0;
12112 $url = $this->AddLink();
12113 $this->SetLink($url, $lnky, $page);
12116 // store current settings
12117 $prevcolor = $this->fgcolor;
12118 $prevstyle = $this->FontStyle;
12119 if (empty($color)) {
12120 $this->SetTextColorArray($this->htmlLinkColorArray);
12121 } else {
12122 $this->SetTextColorArray($color);
12124 if ($style == -1) {
12125 $this->SetFont('', $this->FontStyle.$this->htmlLinkFontStyle);
12126 } else {
12127 $this->SetFont('', $this->FontStyle.$style);
12129 $ret = $this->Write($this->lasth, $name, $url, $fill, '', false, 0, $firstline, $firstblock, 0);
12130 // restore settings
12131 $this->SetFont('', $prevstyle);
12132 $this->SetTextColorArray($prevcolor);
12133 return $ret;
12137 * Returns an array (RGB or CMYK) from an html color name or a six-digit (i.e. #3FE5AA) or three-digit (i.e. #7FF) hexadecimal color representation.
12138 * @param $hcolor (string) html color
12139 * @return array RGB or CMYK color, or false in case of error.
12140 * @public
12142 public function convertHTMLColorToDec($hcolor='#FFFFFF') {
12143 $returncolor = false;
12144 $color = preg_replace('/[\s]*/', '', $hcolor); // remove extra spaces
12145 $color = strtolower($color);
12146 if (($dotpos = strpos($color, '.')) !== false) {
12147 // remove class parent (i.e.: color.red)
12148 $color = substr($color, ($dotpos + 1));
12150 if (strlen($color) == 0) {
12151 return false;
12153 // RGB ARRAY
12154 if (substr($color, 0, 3) == 'rgb') {
12155 $codes = substr($color, 4);
12156 $codes = str_replace(')', '', $codes);
12157 $returncolor = explode(',', $codes);
12158 foreach ($returncolor as $key => $val) {
12159 if (strpos($val, '%') > 0) {
12160 // percentage
12161 $returncolor[$key] = (255 * intval($val) / 100);
12162 } else {
12163 $returncolor[$key] = intval($val);
12165 // normalize value
12166 $returncolor[$key] = max(0, min(255, $returncolor[$key]));
12168 return $returncolor;
12170 // CMYK ARRAY
12171 if (substr($color, 0, 4) == 'cmyk') {
12172 $codes = substr($color, 5);
12173 $codes = str_replace(')', '', $codes);
12174 $returncolor = explode(',', $codes);
12175 foreach ($returncolor as $key => $val) {
12176 if (strpos($val, '%') !== false) {
12177 // percentage
12178 $returncolor[$key] = (100 * intval($val) / 100);
12179 } else {
12180 $returncolor[$key] = intval($val);
12182 // normalize value
12183 $returncolor[$key] = max(0, min(100, $returncolor[$key]));
12185 return $returncolor;
12187 // COLOR NAME
12188 if (substr($color, 0, 1) != '#') {
12189 // decode color name
12190 if (isset($this->webcolor[$color])) {
12191 // web color
12192 $color_code = $this->webcolor[$color];
12193 } elseif (isset($this->spot_colors[$hcolor])) {
12194 // custom defined spot color
12195 return array($this->spot_colors[$hcolor]['c'], $this->spot_colors[$hcolor]['m'], $this->spot_colors[$hcolor]['y'], $this->spot_colors[$hcolor]['k'], $hcolor);
12196 } elseif (isset($this->spotcolor[$color])) {
12197 // spot color from configuration file
12198 return $this->spotcolor[$color];
12199 } else {
12200 return false;
12202 } else {
12203 $color_code = substr($color, 1);
12205 // RGB VALUE
12206 switch (strlen($color_code)) {
12207 case 3: {
12208 // three-digit hexadecimal representation
12209 $r = substr($color_code, 0, 1);
12210 $g = substr($color_code, 1, 1);
12211 $b = substr($color_code, 2, 1);
12212 $returncolor = array();
12213 $returncolor['R'] = max(0, min(255, hexdec($r.$r)));
12214 $returncolor['G'] = max(0, min(255, hexdec($g.$g)));
12215 $returncolor['B'] = max(0, min(255, hexdec($b.$b)));
12216 break;
12218 case 6: {
12219 // six-digit hexadecimal representation
12220 $returncolor = array();
12221 $returncolor['R'] = max(0, min(255, hexdec(substr($color_code, 0, 2))));
12222 $returncolor['G'] = max(0, min(255, hexdec(substr($color_code, 2, 2))));
12223 $returncolor['B'] = max(0, min(255, hexdec(substr($color_code, 4, 2))));
12224 break;
12227 return $returncolor;
12231 * Converts pixels to User's Units.
12232 * @param $px (int) pixels
12233 * @return float value in user's unit
12234 * @public
12235 * @see setImageScale(), getImageScale()
12237 public function pixelsToUnits($px) {
12238 return ($px / ($this->imgscale * $this->k));
12242 * Reverse function for htmlentities.
12243 * Convert entities in UTF-8.
12244 * @param $text_to_convert (string) Text to convert.
12245 * @return string converted text string
12246 * @public
12248 public function unhtmlentities($text_to_convert) {
12249 return @html_entity_decode($text_to_convert, ENT_QUOTES, $this->encoding);
12252 // ENCRYPTION METHODS ----------------------------------
12255 * Returns a string containing random data to be used as a seed for encryption methods.
12256 * @param $seed (string) starting seed value
12257 * @return string containing random data
12258 * @author Nicola Asuni
12259 * @since 5.9.006 (2010-10-19)
12260 * @protected
12262 protected function getRandomSeed($seed='') {
12263 $seed .= microtime();
12264 if (function_exists('openssl_random_pseudo_bytes') AND (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN')) {
12265 // this is not used on windows systems because it is very slow for a know bug
12266 $seed .= openssl_random_pseudo_bytes(512);
12267 } else {
12268 for ($i = 0; $i < 23; ++$i) {
12269 $seed .= uniqid('', true);
12272 $seed .= uniqid('', true);
12273 $seed .= rand();
12274 $seed .= getmypid();
12275 $seed .= __FILE__;
12276 $seed .= $this->bufferlen;
12277 if (isset($_SERVER['REMOTE_ADDR'])) {
12278 $seed .= $_SERVER['REMOTE_ADDR'];
12280 if (isset($_SERVER['HTTP_USER_AGENT'])) {
12281 $seed .= $_SERVER['HTTP_USER_AGENT'];
12283 if (isset($_SERVER['HTTP_ACCEPT'])) {
12284 $seed .= $_SERVER['HTTP_ACCEPT'];
12286 if (isset($_SERVER['HTTP_ACCEPT_ENCODING'])) {
12287 $seed .= $_SERVER['HTTP_ACCEPT_ENCODING'];
12289 if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
12290 $seed .= $_SERVER['HTTP_ACCEPT_LANGUAGE'];
12292 if (isset($_SERVER['HTTP_ACCEPT_CHARSET'])) {
12293 $seed .= $_SERVER['HTTP_ACCEPT_CHARSET'];
12295 $seed .= rand();
12296 $seed .= uniqid('', true);
12297 $seed .= microtime();
12298 return $seed;
12302 * Compute encryption key depending on object number where the encrypted data is stored.
12303 * This is used for all strings and streams without crypt filter specifier.
12304 * @param $n (int) object number
12305 * @return int object key
12306 * @protected
12307 * @author Nicola Asuni
12308 * @since 2.0.000 (2008-01-02)
12310 protected function _objectkey($n) {
12311 $objkey = $this->encryptdata['key'].pack('VXxx', $n);
12312 if ($this->encryptdata['mode'] == 2) { // AES-128
12313 // AES padding
12314 $objkey .= "\x73\x41\x6C\x54"; // sAlT
12316 $objkey = substr($this->_md5_16($objkey), 0, (($this->encryptdata['Length'] / 8) + 5));
12317 $objkey = substr($objkey, 0, 16);
12318 return $objkey;
12322 * Encrypt the input string.
12323 * @param $n (int) object number
12324 * @param $s (string) data string to encrypt
12325 * @return encrypted string
12326 * @protected
12327 * @author Nicola Asuni
12328 * @since 5.0.005 (2010-05-11)
12330 protected function _encrypt_data($n, $s) {
12331 if (!$this->encrypted) {
12332 return $s;
12334 switch ($this->encryptdata['mode']) {
12335 case 0: // RC4-40
12336 case 1: { // RC4-128
12337 $s = $this->_RC4($this->_objectkey($n), $s);
12338 break;
12340 case 2: { // AES-128
12341 $s = $this->_AES($this->_objectkey($n), $s);
12342 break;
12344 case 3: { // AES-256
12345 $s = $this->_AES($this->encryptdata['key'], $s);
12346 break;
12349 return $s;
12353 * Put encryption on PDF document.
12354 * @protected
12355 * @author Nicola Asuni
12356 * @since 2.0.000 (2008-01-02)
12358 protected function _putencryption() {
12359 if (!$this->encrypted) {
12360 return;
12362 $this->encryptdata['objid'] = $this->_newobj();
12363 $out = '<<';
12364 if (!isset($this->encryptdata['Filter']) OR empty($this->encryptdata['Filter'])) {
12365 $this->encryptdata['Filter'] = 'Standard';
12367 $out .= ' /Filter /'.$this->encryptdata['Filter'];
12368 if (isset($this->encryptdata['SubFilter']) AND !empty($this->encryptdata['SubFilter'])) {
12369 $out .= ' /SubFilter /'.$this->encryptdata['SubFilter'];
12371 if (!isset($this->encryptdata['V']) OR empty($this->encryptdata['V'])) {
12372 $this->encryptdata['V'] = 1;
12374 // V is a code specifying the algorithm to be used in encrypting and decrypting the document
12375 $out .= ' /V '.$this->encryptdata['V'];
12376 if (isset($this->encryptdata['Length']) AND !empty($this->encryptdata['Length'])) {
12377 // The length of the encryption key, in bits. The value shall be a multiple of 8, in the range 40 to 256
12378 $out .= ' /Length '.$this->encryptdata['Length'];
12379 } else {
12380 $out .= ' /Length 40';
12382 if ($this->encryptdata['V'] >= 4) {
12383 if (!isset($this->encryptdata['StmF']) OR empty($this->encryptdata['StmF'])) {
12384 $this->encryptdata['StmF'] = 'Identity';
12386 if (!isset($this->encryptdata['StrF']) OR empty($this->encryptdata['StrF'])) {
12387 // The name of the crypt filter that shall be used when decrypting all strings in the document.
12388 $this->encryptdata['StrF'] = 'Identity';
12390 // A dictionary whose keys shall be crypt filter names and whose values shall be the corresponding crypt filter dictionaries.
12391 if (isset($this->encryptdata['CF']) AND !empty($this->encryptdata['CF'])) {
12392 $out .= ' /CF <<';
12393 $out .= ' /'.$this->encryptdata['StmF'].' <<';
12394 $out .= ' /Type /CryptFilter';
12395 if (isset($this->encryptdata['CF']['CFM']) AND !empty($this->encryptdata['CF']['CFM'])) {
12396 // The method used
12397 $out .= ' /CFM /'.$this->encryptdata['CF']['CFM'];
12398 if ($this->encryptdata['pubkey']) {
12399 $out .= ' /Recipients [';
12400 foreach ($this->encryptdata['Recipients'] as $rec) {
12401 $out .= ' <'.$rec.'>';
12403 $out .= ' ]';
12404 if (isset($this->encryptdata['CF']['EncryptMetadata']) AND (!$this->encryptdata['CF']['EncryptMetadata'])) {
12405 $out .= ' /EncryptMetadata false';
12406 } else {
12407 $out .= ' /EncryptMetadata true';
12410 } else {
12411 $out .= ' /CFM /None';
12413 if (isset($this->encryptdata['CF']['AuthEvent']) AND !empty($this->encryptdata['CF']['AuthEvent'])) {
12414 // The event to be used to trigger the authorization that is required to access encryption keys used by this filter.
12415 $out .= ' /AuthEvent /'.$this->encryptdata['CF']['AuthEvent'];
12416 } else {
12417 $out .= ' /AuthEvent /DocOpen';
12419 if (isset($this->encryptdata['CF']['Length']) AND !empty($this->encryptdata['CF']['Length'])) {
12420 // The bit length of the encryption key.
12421 $out .= ' /Length '.$this->encryptdata['CF']['Length'];
12423 $out .= ' >> >>';
12425 // The name of the crypt filter that shall be used by default when decrypting streams.
12426 $out .= ' /StmF /'.$this->encryptdata['StmF'];
12427 // The name of the crypt filter that shall be used when decrypting all strings in the document.
12428 $out .= ' /StrF /'.$this->encryptdata['StrF'];
12429 if (isset($this->encryptdata['EFF']) AND !empty($this->encryptdata['EFF'])) {
12430 // The name of the crypt filter that shall be used when encrypting embedded file streams that do not have their own crypt filter specifier.
12431 $out .= ' /EFF /'.$this->encryptdata[''];
12434 // Additional encryption dictionary entries for the standard security handler
12435 if ($this->encryptdata['pubkey']) {
12436 if (($this->encryptdata['V'] < 4) AND isset($this->encryptdata['Recipients']) AND !empty($this->encryptdata['Recipients'])) {
12437 $out .= ' /Recipients [';
12438 foreach ($this->encryptdata['Recipients'] as $rec) {
12439 $out .= ' <'.$rec.'>';
12441 $out .= ' ]';
12443 } else {
12444 $out .= ' /R';
12445 if ($this->encryptdata['V'] == 5) { // AES-256
12446 $out .= ' 5';
12447 $out .= ' /OE ('.$this->_escape($this->encryptdata['OE']).')';
12448 $out .= ' /UE ('.$this->_escape($this->encryptdata['UE']).')';
12449 $out .= ' /Perms ('.$this->_escape($this->encryptdata['perms']).')';
12450 } elseif ($this->encryptdata['V'] == 4) { // AES-128
12451 $out .= ' 4';
12452 } elseif ($this->encryptdata['V'] < 2) { // RC-40
12453 $out .= ' 2';
12454 } else { // RC-128
12455 $out .= ' 3';
12457 $out .= ' /O ('.$this->_escape($this->encryptdata['O']).')';
12458 $out .= ' /U ('.$this->_escape($this->encryptdata['U']).')';
12459 $out .= ' /P '.$this->encryptdata['P'];
12460 if (isset($this->encryptdata['EncryptMetadata']) AND (!$this->encryptdata['EncryptMetadata'])) {
12461 $out .= ' /EncryptMetadata false';
12462 } else {
12463 $out .= ' /EncryptMetadata true';
12466 $out .= ' >>';
12467 $out .= "\n".'endobj';
12468 $this->_out($out);
12472 * Returns the input text encrypted using RC4 algorithm and the specified key.
12473 * RC4 is the standard encryption algorithm used in PDF format
12474 * @param $key (string) encryption key
12475 * @param $text (String) input text to be encrypted
12476 * @return String encrypted text
12477 * @protected
12478 * @since 2.0.000 (2008-01-02)
12479 * @author Klemen Vodopivec, Nicola Asuni
12481 protected function _RC4($key, $text) {
12482 if (function_exists('mcrypt_decrypt') AND ($out = @mcrypt_decrypt(MCRYPT_ARCFOUR, $key, $text, MCRYPT_MODE_STREAM, ''))) {
12483 // try to use mcrypt function if exist
12484 return $out;
12486 if ($this->last_enc_key != $key) {
12487 $k = str_repeat($key, ((256 / strlen($key)) + 1));
12488 $rc4 = range(0, 255);
12489 $j = 0;
12490 for ($i = 0; $i < 256; ++$i) {
12491 $t = $rc4[$i];
12492 $j = ($j + $t + ord($k{$i})) % 256;
12493 $rc4[$i] = $rc4[$j];
12494 $rc4[$j] = $t;
12496 $this->last_enc_key = $key;
12497 $this->last_enc_key_c = $rc4;
12498 } else {
12499 $rc4 = $this->last_enc_key_c;
12501 $len = strlen($text);
12502 $a = 0;
12503 $b = 0;
12504 $out = '';
12505 for ($i = 0; $i < $len; ++$i) {
12506 $a = ($a + 1) % 256;
12507 $t = $rc4[$a];
12508 $b = ($b + $t) % 256;
12509 $rc4[$a] = $rc4[$b];
12510 $rc4[$b] = $t;
12511 $k = $rc4[($rc4[$a] + $rc4[$b]) % 256];
12512 $out .= chr(ord($text{$i}) ^ $k);
12514 return $out;
12518 * Returns the input text exrypted using AES algorithm and the specified key.
12519 * This method requires mcrypt.
12520 * @param $key (string) encryption key
12521 * @param $text (String) input text to be encrypted
12522 * @return String encrypted text
12523 * @protected
12524 * @author Nicola Asuni
12525 * @since 5.0.005 (2010-05-11)
12527 protected function _AES($key, $text) {
12528 // padding (RFC 2898, PKCS #5: Password-Based Cryptography Specification Version 2.0)
12529 $padding = 16 - (strlen($text) % 16);
12530 $text .= str_repeat(chr($padding), $padding);
12531 $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC), MCRYPT_RAND);
12532 $text = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $text, MCRYPT_MODE_CBC, $iv);
12533 $text = $iv.$text;
12534 return $text;
12538 * Encrypts a string using MD5 and returns it's value as a binary string.
12539 * @param $str (string) input string
12540 * @return String MD5 encrypted binary string
12541 * @protected
12542 * @since 2.0.000 (2008-01-02)
12543 * @author Klemen Vodopivec
12545 protected function _md5_16($str) {
12546 return pack('H*', md5($str));
12550 * Compute U value (used for encryption)
12551 * @return string U value
12552 * @protected
12553 * @since 2.0.000 (2008-01-02)
12554 * @author Nicola Asuni
12556 protected function _Uvalue() {
12557 if ($this->encryptdata['mode'] == 0) { // RC4-40
12558 return $this->_RC4($this->encryptdata['key'], $this->enc_padding);
12559 } elseif ($this->encryptdata['mode'] < 3) { // RC4-128, AES-128
12560 $tmp = $this->_md5_16($this->enc_padding.$this->encryptdata['fileid']);
12561 $enc = $this->_RC4($this->encryptdata['key'], $tmp);
12562 $len = strlen($tmp);
12563 for ($i = 1; $i <= 19; ++$i) {
12564 $ek = '';
12565 for ($j = 0; $j < $len; ++$j) {
12566 $ek .= chr(ord($this->encryptdata['key']{$j}) ^ $i);
12568 $enc = $this->_RC4($ek, $enc);
12570 $enc .= str_repeat("\x00", 16);
12571 return substr($enc, 0, 32);
12572 } elseif ($this->encryptdata['mode'] == 3) { // AES-256
12573 $seed = $this->_md5_16($this->getRandomSeed());
12574 // User Validation Salt
12575 $this->encryptdata['UVS'] = substr($seed, 0, 8);
12576 // User Key Salt
12577 $this->encryptdata['UKS'] = substr($seed, 8, 16);
12578 return hash('sha256', $this->encryptdata['user_password'].$this->encryptdata['UVS'], true).$this->encryptdata['UVS'].$this->encryptdata['UKS'];
12583 * Compute UE value (used for encryption)
12584 * @return string UE value
12585 * @protected
12586 * @since 5.9.006 (2010-10-19)
12587 * @author Nicola Asuni
12589 protected function _UEvalue() {
12590 $hashkey = hash('sha256', $this->encryptdata['user_password'].$this->encryptdata['UKS'], true);
12591 $iv = str_repeat("\x00", mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC));
12592 return mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $hashkey, $this->encryptdata['key'], MCRYPT_MODE_CBC, $iv);
12596 * Compute O value (used for encryption)
12597 * @return string O value
12598 * @protected
12599 * @since 2.0.000 (2008-01-02)
12600 * @author Nicola Asuni
12602 protected function _Ovalue() {
12603 if ($this->encryptdata['mode'] < 3) { // RC4-40, RC4-128, AES-128
12604 $tmp = $this->_md5_16($this->encryptdata['owner_password']);
12605 if ($this->encryptdata['mode'] > 0) {
12606 for ($i = 0; $i < 50; ++$i) {
12607 $tmp = $this->_md5_16($tmp);
12610 $owner_key = substr($tmp, 0, ($this->encryptdata['Length'] / 8));
12611 $enc = $this->_RC4($owner_key, $this->encryptdata['user_password']);
12612 if ($this->encryptdata['mode'] > 0) {
12613 $len = strlen($owner_key);
12614 for ($i = 1; $i <= 19; ++$i) {
12615 $ek = '';
12616 for ($j = 0; $j < $len; ++$j) {
12617 $ek .= chr(ord($owner_key{$j}) ^ $i);
12619 $enc = $this->_RC4($ek, $enc);
12622 return $enc;
12623 } elseif ($this->encryptdata['mode'] == 3) { // AES-256
12624 $seed = $this->_md5_16($this->getRandomSeed());
12625 // Owner Validation Salt
12626 $this->encryptdata['OVS'] = substr($seed, 0, 8);
12627 // Owner Key Salt
12628 $this->encryptdata['OKS'] = substr($seed, 8, 16);
12629 return hash('sha256', $this->encryptdata['owner_password'].$this->encryptdata['OVS'].$this->encryptdata['U'], true).$this->encryptdata['OVS'].$this->encryptdata['OKS'];
12634 * Compute OE value (used for encryption)
12635 * @return string OE value
12636 * @protected
12637 * @since 5.9.006 (2010-10-19)
12638 * @author Nicola Asuni
12640 protected function _OEvalue() {
12641 $hashkey = hash('sha256', $this->encryptdata['owner_password'].$this->encryptdata['OKS'].$this->encryptdata['U'], true);
12642 $iv = str_repeat("\x00", mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC));
12643 return mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $hashkey, $this->encryptdata['key'], MCRYPT_MODE_CBC, $iv);
12647 * Convert password for AES-256 encryption mode
12648 * @param $password (string) password
12649 * @return string password
12650 * @protected
12651 * @since 5.9.006 (2010-10-19)
12652 * @author Nicola Asuni
12654 protected function _fixAES256Password($password) {
12655 $psw = ''; // password to be returned
12656 $psw_array = $this->utf8Bidi($this->UTF8StringToArray($password), $password, $this->rtl);
12657 foreach ($psw_array as $c) {
12658 $psw .= $this->unichr($c);
12660 return substr($psw, 0, 127);
12664 * Compute encryption key
12665 * @protected
12666 * @since 2.0.000 (2008-01-02)
12667 * @author Nicola Asuni
12669 protected function _generateencryptionkey() {
12670 $keybytelen = ($this->encryptdata['Length'] / 8);
12671 if (!$this->encryptdata['pubkey']) { // standard mode
12672 if ($this->encryptdata['mode'] == 3) { // AES-256
12673 // generate 256 bit random key
12674 $this->encryptdata['key'] = substr(hash('sha256', $this->getRandomSeed(), true), 0, $keybytelen);
12675 // truncate passwords
12676 $this->encryptdata['user_password'] = $this->_fixAES256Password($this->encryptdata['user_password']);
12677 $this->encryptdata['owner_password'] = $this->_fixAES256Password($this->encryptdata['owner_password']);
12678 // Compute U value
12679 $this->encryptdata['U'] = $this->_Uvalue();
12680 // Compute UE value
12681 $this->encryptdata['UE'] = $this->_UEvalue();
12682 // Compute O value
12683 $this->encryptdata['O'] = $this->_Ovalue();
12684 // Compute OE value
12685 $this->encryptdata['OE'] = $this->_OEvalue();
12686 // Compute P value
12687 $this->encryptdata['P'] = $this->encryptdata['protection'];
12688 // Computing the encryption dictionary's Perms (permissions) value
12689 $perms = $this->getEncPermissionsString($this->encryptdata['protection']); // bytes 0-3
12690 $perms .= chr(255).chr(255).chr(255).chr(255); // bytes 4-7
12691 if (isset($this->encryptdata['CF']['EncryptMetadata']) AND (!$this->encryptdata['CF']['EncryptMetadata'])) { // byte 8
12692 $perms .= 'F';
12693 } else {
12694 $perms .= 'T';
12696 $perms .= 'adb'; // bytes 9-11
12697 $perms .= 'nick'; // bytes 12-15
12698 $iv = str_repeat("\x00", mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB));
12699 $this->encryptdata['perms'] = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $this->encryptdata['key'], $perms, MCRYPT_MODE_ECB, $iv);
12700 } else { // RC4-40, RC4-128, AES-128
12701 // Pad passwords
12702 $this->encryptdata['user_password'] = substr($this->encryptdata['user_password'].$this->enc_padding, 0, 32);
12703 $this->encryptdata['owner_password'] = substr($this->encryptdata['owner_password'].$this->enc_padding, 0, 32);
12704 // Compute O value
12705 $this->encryptdata['O'] = $this->_Ovalue();
12706 // get default permissions (reverse byte order)
12707 $permissions = $this->getEncPermissionsString($this->encryptdata['protection']);
12708 // Compute encryption key
12709 $tmp = $this->_md5_16($this->encryptdata['user_password'].$this->encryptdata['O'].$permissions.$this->encryptdata['fileid']);
12710 if ($this->encryptdata['mode'] > 0) {
12711 for ($i = 0; $i < 50; ++$i) {
12712 $tmp = $this->_md5_16(substr($tmp, 0, $keybytelen));
12715 $this->encryptdata['key'] = substr($tmp, 0, $keybytelen);
12716 // Compute U value
12717 $this->encryptdata['U'] = $this->_Uvalue();
12718 // Compute P value
12719 $this->encryptdata['P'] = $this->encryptdata['protection'];
12721 } else { // Public-Key mode
12722 // random 20-byte seed
12723 $seed = sha1($this->getRandomSeed(), true);
12724 $recipient_bytes = '';
12725 foreach ($this->encryptdata['pubkeys'] as $pubkey) {
12726 // for each public certificate
12727 if (isset($pubkey['p'])) {
12728 $pkprotection = $this->getUserPermissionCode($pubkey['p'], $this->encryptdata['mode']);
12729 } else {
12730 $pkprotection = $this->encryptdata['protection'];
12732 // get default permissions (reverse byte order)
12733 $pkpermissions = $this->getEncPermissionsString($pkprotection);
12734 // envelope data
12735 $envelope = $seed.$pkpermissions;
12736 // write the envelope data to a temporary file
12737 $tempkeyfile = tempnam(K_PATH_CACHE, 'tmpkey_');
12738 $f = fopen($tempkeyfile, 'wb');
12739 if (!$f) {
12740 $this->Error('Unable to create temporary key file: '.$tempkeyfile);
12742 $envelope_length = strlen($envelope);
12743 fwrite($f, $envelope, $envelope_length);
12744 fclose($f);
12745 $tempencfile = tempnam(K_PATH_CACHE, 'tmpenc_');
12746 if (!openssl_pkcs7_encrypt($tempkeyfile, $tempencfile, $pubkey['c'], array(), PKCS7_DETACHED | PKCS7_BINARY)) {
12747 $this->Error('Unable to encrypt the file: '.$tempkeyfile);
12749 unlink($tempkeyfile);
12750 // read encryption signature
12751 $signature = file_get_contents($tempencfile, false, null, $envelope_length);
12752 unlink($tempencfile);
12753 // extract signature
12754 $signature = substr($signature, strpos($signature, 'Content-Disposition'));
12755 $tmparr = explode("\n\n", $signature);
12756 $signature = trim($tmparr[1]);
12757 unset($tmparr);
12758 // decode signature
12759 $signature = base64_decode($signature);
12760 // convert signature to hex
12761 $hexsignature = current(unpack('H*', $signature));
12762 // store signature on recipients array
12763 $this->encryptdata['Recipients'][] = $hexsignature;
12764 // The bytes of each item in the Recipients array of PKCS#7 objects in the order in which they appear in the array
12765 $recipient_bytes .= $signature;
12767 // calculate encryption key
12768 if ($this->encryptdata['mode'] == 3) { // AES-256
12769 $this->encryptdata['key'] = substr(hash('sha256', $seed.$recipient_bytes, true), 0, $keybytelen);
12770 } else { // RC4-40, RC4-128, AES-128
12771 $this->encryptdata['key'] = substr(sha1($seed.$recipient_bytes, true), 0, $keybytelen);
12777 * Return the premission code used on encryption (P value).
12778 * @param $permissions (Array) the set of permissions (specify the ones you want to block).
12779 * @param $mode (int) encryption strength: 0 = RC4 40 bit; 1 = RC4 128 bit; 2 = AES 128 bit; 3 = AES 256 bit.
12780 * @protected
12781 * @since 5.0.005 (2010-05-12)
12782 * @author Nicola Asuni
12784 protected function getUserPermissionCode($permissions, $mode=0) {
12785 $options = array(
12786 'owner' => 2, // bit 2 -- inverted logic: cleared by default
12787 'print' => 4, // bit 3
12788 'modify' => 8, // bit 4
12789 'copy' => 16, // bit 5
12790 'annot-forms' => 32, // bit 6
12791 'fill-forms' => 256, // bit 9
12792 'extract' => 512, // bit 10
12793 'assemble' => 1024,// bit 11
12794 'print-high' => 2048 // bit 12
12796 $protection = 2147422012; // 32 bit: (01111111 11111111 00001111 00111100)
12797 foreach ($permissions as $permission) {
12798 if (!isset($options[$permission])) {
12799 $this->Error('Incorrect permission: '.$permission);
12801 if (($mode > 0) OR ($options[$permission] <= 32)) {
12802 // set only valid permissions
12803 if ($options[$permission] == 2) {
12804 // the logic for bit 2 is inverted (cleared by default)
12805 $protection += $options[$permission];
12806 } else {
12807 $protection -= $options[$permission];
12811 return $protection;
12815 * Set document protection
12816 * Remark: the protection against modification is for people who have the full Acrobat product.
12817 * 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.
12818 * 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.
12819 * @param $permissions (Array) the set of permissions (specify the ones you want to block):<ul><li>print : Print the document;</li><li>modify : Modify the contents of the document by operations other than those controlled by 'fill-forms', 'extract' and 'assemble';</li><li>copy : Copy or otherwise extract text and graphics from the document;</li><li>annot-forms : Add or modify text annotations, fill in interactive form fields, and, if 'modify' is also set, create or modify interactive form fields (including signature fields);</li><li>fill-forms : Fill in existing interactive form fields (including signature fields), even if 'annot-forms' is not specified;</li><li>extract : Extract text and graphics (in support of accessibility to users with disabilities or for other purposes);</li><li>assemble : Assemble the document (insert, rotate, or delete pages and create bookmarks or thumbnail images), even if 'modify' is not set;</li><li>print-high : Print the document to a representation from which a faithful digital copy of the PDF content could be generated. When this is not set, printing is limited to a low-level representation of the appearance, possibly of degraded quality.</li><li>owner : (inverted logic - only for public-key) when set permits change of encryption and enables all other permissions.</li></ul>
12820 * @param $user_pass (String) user password. Empty by default.
12821 * @param $owner_pass (String) owner password. If not specified, a random value is used.
12822 * @param $mode (int) encryption strength: 0 = RC4 40 bit; 1 = RC4 128 bit; 2 = AES 128 bit; 3 = AES 256 bit.
12823 * @param $pubkeys (String) array of recipients containing public-key certificates ('c') and permissions ('p'). For example: array(array('c' => 'file://../tcpdf.crt', 'p' => array('print')))
12824 * @public
12825 * @since 2.0.000 (2008-01-02)
12826 * @author Nicola Asuni
12828 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) {
12829 $this->encryptdata['protection'] = $this->getUserPermissionCode($permissions, $mode);
12830 if (($pubkeys !== null) AND (is_array($pubkeys))) {
12831 // public-key mode
12832 $this->encryptdata['pubkeys'] = $pubkeys;
12833 if ($mode == 0) {
12834 // public-Key Security requires at least 128 bit
12835 $mode = 1;
12837 if (!function_exists('openssl_pkcs7_encrypt')) {
12838 $this->Error('Public-Key Security requires openssl library.');
12840 // Set Public-Key filter (availabe are: Entrust.PPKEF, Adobe.PPKLite, Adobe.PubSec)
12841 $this->encryptdata['pubkey'] = true;
12842 $this->encryptdata['Filter'] = 'Adobe.PubSec';
12843 $this->encryptdata['StmF'] = 'DefaultCryptFilter';
12844 $this->encryptdata['StrF'] = 'DefaultCryptFilter';
12845 } else {
12846 // standard mode (password mode)
12847 $this->encryptdata['pubkey'] = false;
12848 $this->encryptdata['Filter'] = 'Standard';
12849 $this->encryptdata['StmF'] = 'StdCF';
12850 $this->encryptdata['StrF'] = 'StdCF';
12852 if ($mode > 1) { // AES
12853 if (!extension_loaded('mcrypt')) {
12854 $this->Error('AES encryption requires mcrypt library (http://www.php.net/manual/en/mcrypt.requirements.php).');
12856 if (mcrypt_get_cipher_name(MCRYPT_RIJNDAEL_128) === false) {
12857 $this->Error('AES encryption requires MCRYPT_RIJNDAEL_128 cypher.');
12859 if (($mode == 3) AND !function_exists('hash')) {
12860 // the Hash extension requires no external libraries and is enabled by default as of PHP 5.1.2.
12861 $this->Error('AES 256 encryption requires HASH Message Digest Framework (http://www.php.net/manual/en/book.hash.php).');
12864 if ($owner_pass === null) {
12865 $owner_pass = md5($this->getRandomSeed());
12867 $this->encryptdata['user_password'] = $user_pass;
12868 $this->encryptdata['owner_password'] = $owner_pass;
12869 $this->encryptdata['mode'] = $mode;
12870 switch ($mode) {
12871 case 0: { // RC4 40 bit
12872 $this->encryptdata['V'] = 1;
12873 $this->encryptdata['Length'] = 40;
12874 $this->encryptdata['CF']['CFM'] = 'V2';
12875 break;
12877 case 1: { // RC4 128 bit
12878 $this->encryptdata['V'] = 2;
12879 $this->encryptdata['Length'] = 128;
12880 $this->encryptdata['CF']['CFM'] = 'V2';
12881 if ($this->encryptdata['pubkey']) {
12882 $this->encryptdata['SubFilter'] = 'adbe.pkcs7.s4';
12883 $this->encryptdata['Recipients'] = array();
12885 break;
12887 case 2: { // AES 128 bit
12888 $this->encryptdata['V'] = 4;
12889 $this->encryptdata['Length'] = 128;
12890 $this->encryptdata['CF']['CFM'] = 'AESV2';
12891 $this->encryptdata['CF']['Length'] = 128;
12892 if ($this->encryptdata['pubkey']) {
12893 $this->encryptdata['SubFilter'] = 'adbe.pkcs7.s5';
12894 $this->encryptdata['Recipients'] = array();
12896 break;
12898 case 3: { // AES 256 bit
12899 $this->encryptdata['V'] = 5;
12900 $this->encryptdata['Length'] = 256;
12901 $this->encryptdata['CF']['CFM'] = 'AESV3';
12902 $this->encryptdata['CF']['Length'] = 256;
12903 if ($this->encryptdata['pubkey']) {
12904 $this->encryptdata['SubFilter'] = 'adbe.pkcs7.s5';
12905 $this->encryptdata['Recipients'] = array();
12907 break;
12910 $this->encrypted = true;
12911 $this->encryptdata['fileid'] = $this->convertHexStringToString($this->file_id);
12912 $this->_generateencryptionkey();
12916 * Convert hexadecimal string to string
12917 * @param $bs (string) byte-string to convert
12918 * @return String
12919 * @protected
12920 * @since 5.0.005 (2010-05-12)
12921 * @author Nicola Asuni
12923 protected function convertHexStringToString($bs) {
12924 $string = ''; // string to be returned
12925 $bslength = strlen($bs);
12926 if (($bslength % 2) != 0) {
12927 // padding
12928 $bs .= '0';
12929 ++$bslength;
12931 for ($i = 0; $i < $bslength; $i += 2) {
12932 $string .= chr(hexdec($bs{$i}.$bs{($i + 1)}));
12934 return $string;
12938 * Convert string to hexadecimal string (byte string)
12939 * @param $s (string) string to convert
12940 * @return byte string
12941 * @protected
12942 * @since 5.0.010 (2010-05-17)
12943 * @author Nicola Asuni
12945 protected function convertStringToHexString($s) {
12946 $bs = '';
12947 $chars = preg_split('//', $s, -1, PREG_SPLIT_NO_EMPTY);
12948 foreach ($chars as $c) {
12949 $bs .= sprintf('%02s', dechex(ord($c)));
12951 return $bs;
12955 * Convert encryption P value to a string of bytes, low-order byte first.
12956 * @param $protection (string) 32bit encryption permission value (P value)
12957 * @return String
12958 * @protected
12959 * @since 5.0.005 (2010-05-12)
12960 * @author Nicola Asuni
12962 protected function getEncPermissionsString($protection) {
12963 $binprot = sprintf('%032b', $protection);
12964 $str = chr(bindec(substr($binprot, 24, 8)));
12965 $str .= chr(bindec(substr($binprot, 16, 8)));
12966 $str .= chr(bindec(substr($binprot, 8, 8)));
12967 $str .= chr(bindec(substr($binprot, 0, 8)));
12968 return $str;
12971 // END OF ENCRYPTION FUNCTIONS -------------------------
12973 // START TRANSFORMATIONS SECTION -----------------------
12976 * Starts a 2D tranformation saving current graphic state.
12977 * This function must be called before scaling, mirroring, translation, rotation and skewing.
12978 * Use StartTransform() before, and StopTransform() after the transformations to restore the normal behavior.
12979 * @public
12980 * @since 2.1.000 (2008-01-07)
12981 * @see StartTransform(), StopTransform()
12983 public function StartTransform() {
12984 $this->_out('q');
12985 if ($this->inxobj) {
12986 // we are inside an XObject template
12987 $this->xobjects[$this->xobjid]['transfmrk'][] = strlen($this->xobjects[$this->xobjid]['outdata']);
12988 } else {
12989 $this->transfmrk[$this->page][] = $this->pagelen[$this->page];
12991 ++$this->transfmatrix_key;
12992 $this->transfmatrix[$this->transfmatrix_key] = array();
12996 * Stops a 2D tranformation restoring previous graphic state.
12997 * This function must be called after scaling, mirroring, translation, rotation and skewing.
12998 * Use StartTransform() before, and StopTransform() after the transformations to restore the normal behavior.
12999 * @public
13000 * @since 2.1.000 (2008-01-07)
13001 * @see StartTransform(), StopTransform()
13003 public function StopTransform() {
13004 $this->_out('Q');
13005 if (isset($this->transfmatrix[$this->transfmatrix_key])) {
13006 array_pop($this->transfmatrix[$this->transfmatrix_key]);
13007 --$this->transfmatrix_key;
13009 if ($this->inxobj) {
13010 // we are inside an XObject template
13011 array_pop($this->xobjects[$this->xobjid]['transfmrk']);
13012 } else {
13013 array_pop($this->transfmrk[$this->page]);
13017 * Horizontal Scaling.
13018 * @param $s_x (float) scaling factor for width as percent. 0 is not allowed.
13019 * @param $x (int) abscissa of the scaling center. Default is current x position
13020 * @param $y (int) ordinate of the scaling center. Default is current y position
13021 * @public
13022 * @since 2.1.000 (2008-01-07)
13023 * @see StartTransform(), StopTransform()
13025 public function ScaleX($s_x, $x='', $y='') {
13026 $this->Scale($s_x, 100, $x, $y);
13030 * Vertical Scaling.
13031 * @param $s_y (float) scaling factor for height as percent. 0 is not allowed.
13032 * @param $x (int) abscissa of the scaling center. Default is current x position
13033 * @param $y (int) ordinate of the scaling center. Default is current y position
13034 * @public
13035 * @since 2.1.000 (2008-01-07)
13036 * @see StartTransform(), StopTransform()
13038 public function ScaleY($s_y, $x='', $y='') {
13039 $this->Scale(100, $s_y, $x, $y);
13043 * Vertical and horizontal proportional Scaling.
13044 * @param $s (float) scaling factor for width and height as percent. 0 is not allowed.
13045 * @param $x (int) abscissa of the scaling center. Default is current x position
13046 * @param $y (int) ordinate of the scaling center. Default is current y position
13047 * @public
13048 * @since 2.1.000 (2008-01-07)
13049 * @see StartTransform(), StopTransform()
13051 public function ScaleXY($s, $x='', $y='') {
13052 $this->Scale($s, $s, $x, $y);
13056 * Vertical and horizontal non-proportional Scaling.
13057 * @param $s_x (float) scaling factor for width as percent. 0 is not allowed.
13058 * @param $s_y (float) scaling factor for height as percent. 0 is not allowed.
13059 * @param $x (int) abscissa of the scaling center. Default is current x position
13060 * @param $y (int) ordinate of the scaling center. Default is current y position
13061 * @public
13062 * @since 2.1.000 (2008-01-07)
13063 * @see StartTransform(), StopTransform()
13065 public function Scale($s_x, $s_y, $x='', $y='') {
13066 if ($x === '') {
13067 $x = $this->x;
13069 if ($y === '') {
13070 $y = $this->y;
13072 if (($s_x == 0) OR ($s_y == 0)) {
13073 $this->Error('Please do not use values equal to zero for scaling');
13075 $y = ($this->h - $y) * $this->k;
13076 $x *= $this->k;
13077 //calculate elements of transformation matrix
13078 $s_x /= 100;
13079 $s_y /= 100;
13080 $tm = array();
13081 $tm[0] = $s_x;
13082 $tm[1] = 0;
13083 $tm[2] = 0;
13084 $tm[3] = $s_y;
13085 $tm[4] = $x * (1 - $s_x);
13086 $tm[5] = $y * (1 - $s_y);
13087 //scale the coordinate system
13088 $this->Transform($tm);
13092 * Horizontal Mirroring.
13093 * @param $x (int) abscissa of the point. Default is current x position
13094 * @public
13095 * @since 2.1.000 (2008-01-07)
13096 * @see StartTransform(), StopTransform()
13098 public function MirrorH($x='') {
13099 $this->Scale(-100, 100, $x);
13103 * Verical Mirroring.
13104 * @param $y (int) ordinate of the point. Default is current y position
13105 * @public
13106 * @since 2.1.000 (2008-01-07)
13107 * @see StartTransform(), StopTransform()
13109 public function MirrorV($y='') {
13110 $this->Scale(100, -100, '', $y);
13114 * Point reflection mirroring.
13115 * @param $x (int) abscissa of the point. Default is current x position
13116 * @param $y (int) ordinate of the point. Default is current y position
13117 * @public
13118 * @since 2.1.000 (2008-01-07)
13119 * @see StartTransform(), StopTransform()
13121 public function MirrorP($x='',$y='') {
13122 $this->Scale(-100, -100, $x, $y);
13126 * Reflection against a straight line through point (x, y) with the gradient angle (angle).
13127 * @param $angle (float) gradient angle of the straight line. Default is 0 (horizontal line).
13128 * @param $x (int) abscissa of the point. Default is current x position
13129 * @param $y (int) ordinate of the point. Default is current y position
13130 * @public
13131 * @since 2.1.000 (2008-01-07)
13132 * @see StartTransform(), StopTransform()
13134 public function MirrorL($angle=0, $x='',$y='') {
13135 $this->Scale(-100, 100, $x, $y);
13136 $this->Rotate(-2*($angle-90), $x, $y);
13140 * Translate graphic object horizontally.
13141 * @param $t_x (int) movement to the right (or left for RTL)
13142 * @public
13143 * @since 2.1.000 (2008-01-07)
13144 * @see StartTransform(), StopTransform()
13146 public function TranslateX($t_x) {
13147 $this->Translate($t_x, 0);
13151 * Translate graphic object vertically.
13152 * @param $t_y (int) movement to the bottom
13153 * @public
13154 * @since 2.1.000 (2008-01-07)
13155 * @see StartTransform(), StopTransform()
13157 public function TranslateY($t_y) {
13158 $this->Translate(0, $t_y);
13162 * Translate graphic object horizontally and vertically.
13163 * @param $t_x (int) movement to the right
13164 * @param $t_y (int) movement to the bottom
13165 * @public
13166 * @since 2.1.000 (2008-01-07)
13167 * @see StartTransform(), StopTransform()
13169 public function Translate($t_x, $t_y) {
13170 //calculate elements of transformation matrix
13171 $tm = array();
13172 $tm[0] = 1;
13173 $tm[1] = 0;
13174 $tm[2] = 0;
13175 $tm[3] = 1;
13176 $tm[4] = $t_x * $this->k;
13177 $tm[5] = -$t_y * $this->k;
13178 //translate the coordinate system
13179 $this->Transform($tm);
13183 * Rotate object.
13184 * @param $angle (float) angle in degrees for counter-clockwise rotation
13185 * @param $x (int) abscissa of the rotation center. Default is current x position
13186 * @param $y (int) ordinate of the rotation center. Default is current y position
13187 * @public
13188 * @since 2.1.000 (2008-01-07)
13189 * @see StartTransform(), StopTransform()
13191 public function Rotate($angle, $x='', $y='') {
13192 if ($x === '') {
13193 $x = $this->x;
13195 if ($y === '') {
13196 $y = $this->y;
13198 $y = ($this->h - $y) * $this->k;
13199 $x *= $this->k;
13200 //calculate elements of transformation matrix
13201 $tm = array();
13202 $tm[0] = cos(deg2rad($angle));
13203 $tm[1] = sin(deg2rad($angle));
13204 $tm[2] = -$tm[1];
13205 $tm[3] = $tm[0];
13206 $tm[4] = $x + ($tm[1] * $y) - ($tm[0] * $x);
13207 $tm[5] = $y - ($tm[0] * $y) - ($tm[1] * $x);
13208 //rotate the coordinate system around ($x,$y)
13209 $this->Transform($tm);
13213 * Skew horizontally.
13214 * @param $angle_x (float) angle in degrees between -90 (skew to the left) and 90 (skew to the right)
13215 * @param $x (int) abscissa of the skewing center. default is current x position
13216 * @param $y (int) ordinate of the skewing center. default is current y position
13217 * @public
13218 * @since 2.1.000 (2008-01-07)
13219 * @see StartTransform(), StopTransform()
13221 public function SkewX($angle_x, $x='', $y='') {
13222 $this->Skew($angle_x, 0, $x, $y);
13226 * Skew vertically.
13227 * @param $angle_y (float) angle in degrees between -90 (skew to the bottom) and 90 (skew to the top)
13228 * @param $x (int) abscissa of the skewing center. default is current x position
13229 * @param $y (int) ordinate of the skewing center. default is current y position
13230 * @public
13231 * @since 2.1.000 (2008-01-07)
13232 * @see StartTransform(), StopTransform()
13234 public function SkewY($angle_y, $x='', $y='') {
13235 $this->Skew(0, $angle_y, $x, $y);
13239 * Skew.
13240 * @param $angle_x (float) angle in degrees between -90 (skew to the left) and 90 (skew to the right)
13241 * @param $angle_y (float) angle in degrees between -90 (skew to the bottom) and 90 (skew to the top)
13242 * @param $x (int) abscissa of the skewing center. default is current x position
13243 * @param $y (int) ordinate of the skewing center. default is current y position
13244 * @public
13245 * @since 2.1.000 (2008-01-07)
13246 * @see StartTransform(), StopTransform()
13248 public function Skew($angle_x, $angle_y, $x='', $y='') {
13249 if ($x === '') {
13250 $x = $this->x;
13252 if ($y === '') {
13253 $y = $this->y;
13255 if (($angle_x <= -90) OR ($angle_x >= 90) OR ($angle_y <= -90) OR ($angle_y >= 90)) {
13256 $this->Error('Please use values between -90 and +90 degrees for Skewing.');
13258 $x *= $this->k;
13259 $y = ($this->h - $y) * $this->k;
13260 //calculate elements of transformation matrix
13261 $tm = array();
13262 $tm[0] = 1;
13263 $tm[1] = tan(deg2rad($angle_y));
13264 $tm[2] = tan(deg2rad($angle_x));
13265 $tm[3] = 1;
13266 $tm[4] = -$tm[2] * $y;
13267 $tm[5] = -$tm[1] * $x;
13268 //skew the coordinate system
13269 $this->Transform($tm);
13273 * Apply graphic transformations.
13274 * @param $tm (array) transformation matrix
13275 * @protected
13276 * @since 2.1.000 (2008-01-07)
13277 * @see StartTransform(), StopTransform()
13279 protected function Transform($tm) {
13280 $this->_out(sprintf('%.3F %.3F %.3F %.3F %.3F %.3F cm', $tm[0], $tm[1], $tm[2], $tm[3], $tm[4], $tm[5]));
13281 // add tranformation matrix
13282 $this->transfmatrix[$this->transfmatrix_key][] = array('a' => $tm[0], 'b' => $tm[1], 'c' => $tm[2], 'd' => $tm[3], 'e' => $tm[4], 'f' => $tm[5]);
13283 // update transformation mark
13284 if ($this->inxobj) {
13285 // we are inside an XObject template
13286 if (end($this->xobjects[$this->xobjid]['transfmrk']) !== false) {
13287 $key = key($this->xobjects[$this->xobjid]['transfmrk']);
13288 $this->xobjects[$this->xobjid]['transfmrk'][$key] = strlen($this->xobjects[$this->xobjid]['outdata']);
13290 } elseif (end($this->transfmrk[$this->page]) !== false) {
13291 $key = key($this->transfmrk[$this->page]);
13292 $this->transfmrk[$this->page][$key] = $this->pagelen[$this->page];
13296 // END TRANSFORMATIONS SECTION -------------------------
13298 // START GRAPHIC FUNCTIONS SECTION ---------------------
13299 // The following section is based on the code provided by David Hernandez Sanz
13302 * 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.
13303 * @param $width (float) The width.
13304 * @public
13305 * @since 1.0
13306 * @see Line(), Rect(), Cell(), MultiCell()
13308 public function SetLineWidth($width) {
13309 //Set line width
13310 $this->LineWidth = $width;
13311 $this->linestyleWidth = sprintf('%.2F w', ($width * $this->k));
13312 if ($this->page > 0) {
13313 $this->_out($this->linestyleWidth);
13318 * Returns the current the line width.
13319 * @return int Line width
13320 * @public
13321 * @since 2.1.000 (2008-01-07)
13322 * @see Line(), SetLineWidth()
13324 public function GetLineWidth() {
13325 return $this->LineWidth;
13329 * Set line style.
13330 * @param $style (array) Line style. Array with keys among the following:
13331 * <ul>
13332 * <li>width (float): Width of the line in user units.</li>
13333 * <li>cap (string): Type of cap to put on the line. Possible values are:
13334 * butt, round, square. The difference between "square" and "butt" is that
13335 * "square" projects a flat end past the end of the line.</li>
13336 * <li>join (string): Type of join. Possible values are: miter, round,
13337 * bevel.</li>
13338 * <li>dash (mixed): Dash pattern. Is 0 (without dash) or string with
13339 * series of length values, which are the lengths of the on and off dashes.
13340 * For example: "2" represents 2 on, 2 off, 2 on, 2 off, ...; "2,1" is 2 on,
13341 * 1 off, 2 on, 1 off, ...</li>
13342 * <li>phase (integer): Modifier on the dash pattern which is used to shift
13343 * the point at which the pattern starts.</li>
13344 * <li>color (array): Draw color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K).</li>
13345 * </ul>
13346 * @param $ret (boolean) if true do not send the command.
13347 * @return string the PDF command
13348 * @public
13349 * @since 2.1.000 (2008-01-08)
13351 public function SetLineStyle($style, $ret=false) {
13352 $s = ''; // string to be returned
13353 if (!is_array($style)) {
13354 return;
13356 if (isset($style['width'])) {
13357 $this->LineWidth = $style['width'];
13358 $this->linestyleWidth = sprintf('%.2F w', ($style['width'] * $this->k));
13359 $s .= $this->linestyleWidth.' ';
13361 if (isset($style['cap'])) {
13362 $ca = array('butt' => 0, 'round'=> 1, 'square' => 2);
13363 if (isset($ca[$style['cap']])) {
13364 $this->linestyleCap = $ca[$style['cap']].' J';
13365 $s .= $this->linestyleCap.' ';
13368 if (isset($style['join'])) {
13369 $ja = array('miter' => 0, 'round' => 1, 'bevel' => 2);
13370 if (isset($ja[$style['join']])) {
13371 $this->linestyleJoin = $ja[$style['join']].' j';
13372 $s .= $this->linestyleJoin.' ';
13375 if (isset($style['dash'])) {
13376 $dash_string = '';
13377 if ($style['dash']) {
13378 if (preg_match('/^.+,/', $style['dash']) > 0) {
13379 $tab = explode(',', $style['dash']);
13380 } else {
13381 $tab = array($style['dash']);
13383 $dash_string = '';
13384 foreach ($tab as $i => $v) {
13385 if ($i) {
13386 $dash_string .= ' ';
13388 $dash_string .= sprintf('%.2F', $v);
13391 if (!isset($style['phase']) OR !$style['dash']) {
13392 $style['phase'] = 0;
13394 $this->linestyleDash = sprintf('[%s] %.2F d', $dash_string, $style['phase']);
13395 $s .= $this->linestyleDash.' ';
13397 if (isset($style['color'])) {
13398 $s .= $this->SetDrawColorArray($style['color'], true).' ';
13400 if (!$ret) {
13401 $this->_out($s);
13403 return $s;
13407 * Begin a new subpath by moving the current point to coordinates (x, y), omitting any connecting line segment.
13408 * @param $x (float) Abscissa of point.
13409 * @param $y (float) Ordinate of point.
13410 * @protected
13411 * @since 2.1.000 (2008-01-08)
13413 protected function _outPoint($x, $y) {
13414 $this->_out(sprintf('%.2F %.2F m', $x * $this->k, ($this->h - $y) * $this->k));
13418 * Append a straight line segment from the current point to the point (x, y).
13419 * The new current point shall be (x, y).
13420 * @param $x (float) Abscissa of end point.
13421 * @param $y (float) Ordinate of end point.
13422 * @protected
13423 * @since 2.1.000 (2008-01-08)
13425 protected function _outLine($x, $y) {
13426 $this->_out(sprintf('%.2F %.2F l', $x * $this->k, ($this->h - $y) * $this->k));
13430 * Append a rectangle to the current path as a complete subpath, with lower-left corner (x, y) and dimensions widthand height in user space.
13431 * @param $x (float) Abscissa of upper-left corner.
13432 * @param $y (float) Ordinate of upper-left corner.
13433 * @param $w (float) Width.
13434 * @param $h (float) Height.
13435 * @param $op (string) options
13436 * @protected
13437 * @since 2.1.000 (2008-01-08)
13439 protected function _outRect($x, $y, $w, $h, $op) {
13440 $this->_out(sprintf('%.2F %.2F %.2F %.2F re %s', $x * $this->k, ($this->h - $y) * $this->k, $w * $this->k, -$h * $this->k, $op));
13444 * Append a cubic Bézier 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 Bézier control points.
13445 * The new current point shall be (x3, y3).
13446 * @param $x1 (float) Abscissa of control point 1.
13447 * @param $y1 (float) Ordinate of control point 1.
13448 * @param $x2 (float) Abscissa of control point 2.
13449 * @param $y2 (float) Ordinate of control point 2.
13450 * @param $x3 (float) Abscissa of end point.
13451 * @param $y3 (float) Ordinate of end point.
13452 * @protected
13453 * @since 2.1.000 (2008-01-08)
13455 protected function _outCurve($x1, $y1, $x2, $y2, $x3, $y3) {
13456 $this->_out(sprintf('%.2F %.2F %.2F %.2F %.2F %.2F c', $x1 * $this->k, ($this->h - $y1) * $this->k, $x2 * $this->k, ($this->h - $y2) * $this->k, $x3 * $this->k, ($this->h - $y3) * $this->k));
13460 * Append a cubic Bézier 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 Bézier control points.
13461 * The new current point shall be (x3, y3).
13462 * @param $x2 (float) Abscissa of control point 2.
13463 * @param $y2 (float) Ordinate of control point 2.
13464 * @param $x3 (float) Abscissa of end point.
13465 * @param $y3 (float) Ordinate of end point.
13466 * @protected
13467 * @since 4.9.019 (2010-04-26)
13469 protected function _outCurveV($x2, $y2, $x3, $y3) {
13470 $this->_out(sprintf('%.2F %.2F %.2F %.2F v', $x2 * $this->k, ($this->h - $y2) * $this->k, $x3 * $this->k, ($this->h - $y3) * $this->k));
13474 * Append a cubic Bézier 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 Bézier control points.
13475 * The new current point shall be (x3, y3).
13476 * @param $x1 (float) Abscissa of control point 1.
13477 * @param $y1 (float) Ordinate of control point 1.
13478 * @param $x3 (float) Abscissa of end point.
13479 * @param $y3 (float) Ordinate of end point.
13480 * @protected
13481 * @since 2.1.000 (2008-01-08)
13483 protected function _outCurveY($x1, $y1, $x3, $y3) {
13484 $this->_out(sprintf('%.2F %.2F %.2F %.2F y', $x1 * $this->k, ($this->h - $y1) * $this->k, $x3 * $this->k, ($this->h - $y3) * $this->k));
13488 * Draws a line between two points.
13489 * @param $x1 (float) Abscissa of first point.
13490 * @param $y1 (float) Ordinate of first point.
13491 * @param $x2 (float) Abscissa of second point.
13492 * @param $y2 (float) Ordinate of second point.
13493 * @param $style (array) Line style. Array like for SetLineStyle(). Default value: default line style (empty array).
13494 * @public
13495 * @since 1.0
13496 * @see SetLineWidth(), SetDrawColor(), SetLineStyle()
13498 public function Line($x1, $y1, $x2, $y2, $style=array()) {
13499 if (is_array($style)) {
13500 $this->SetLineStyle($style);
13502 $this->_outPoint($x1, $y1);
13503 $this->_outLine($x2, $y2);
13504 $this->_out('S');
13508 * Draws a rectangle.
13509 * @param $x (float) Abscissa of upper-left corner.
13510 * @param $y (float) Ordinate of upper-left corner.
13511 * @param $w (float) Width.
13512 * @param $h (float) Height.
13513 * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
13514 * @param $border_style (array) Border style of rectangle. Array with keys among the following:
13515 * <ul>
13516 * <li>all: Line style of all borders. Array like for SetLineStyle().</li>
13517 * <li>L, T, R, B or combinations: Line style of left, top, right or bottom border. Array like for SetLineStyle().</li>
13518 * </ul>
13519 * If a key is not present or is null, not draws the border. Default value: default line style (empty array).
13520 * @param $border_style (array) Border style of rectangle. Array like for SetLineStyle(). Default value: default line style (empty array).
13521 * @param $fill_color (array) Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K). Default value: default color (empty array).
13522 * @public
13523 * @since 1.0
13524 * @see SetLineStyle()
13526 public function Rect($x, $y, $w, $h, $style='', $border_style=array(), $fill_color=array()) {
13527 if (!(false === strpos($style, 'F')) AND !empty($fill_color)) {
13528 $this->SetFillColorArray($fill_color);
13530 $op = $this->getPathPaintOperator($style);
13531 if ((!$border_style) OR (isset($border_style['all']))) {
13532 if (isset($border_style['all']) AND $border_style['all']) {
13533 $this->SetLineStyle($border_style['all']);
13534 $border_style = array();
13537 $this->_outRect($x, $y, $w, $h, $op);
13538 if ($border_style) {
13539 $border_style2 = array();
13540 foreach ($border_style as $line => $value) {
13541 $length = strlen($line);
13542 for ($i = 0; $i < $length; ++$i) {
13543 $border_style2[$line[$i]] = $value;
13546 $border_style = $border_style2;
13547 if (isset($border_style['L']) AND $border_style['L']) {
13548 $this->Line($x, $y, $x, $y + $h, $border_style['L']);
13550 if (isset($border_style['T']) AND $border_style['T']) {
13551 $this->Line($x, $y, $x + $w, $y, $border_style['T']);
13553 if (isset($border_style['R']) AND $border_style['R']) {
13554 $this->Line($x + $w, $y, $x + $w, $y + $h, $border_style['R']);
13556 if (isset($border_style['B']) AND $border_style['B']) {
13557 $this->Line($x, $y + $h, $x + $w, $y + $h, $border_style['B']);
13563 * Draws a Bezier curve.
13564 * The Bezier curve is a tangent to the line between the control points at
13565 * either end of the curve.
13566 * @param $x0 (float) Abscissa of start point.
13567 * @param $y0 (float) Ordinate of start point.
13568 * @param $x1 (float) Abscissa of control point 1.
13569 * @param $y1 (float) Ordinate of control point 1.
13570 * @param $x2 (float) Abscissa of control point 2.
13571 * @param $y2 (float) Ordinate of control point 2.
13572 * @param $x3 (float) Abscissa of end point.
13573 * @param $y3 (float) Ordinate of end point.
13574 * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
13575 * @param $line_style (array) Line style of curve. Array like for SetLineStyle(). Default value: default line style (empty array).
13576 * @param $fill_color (array) Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K). Default value: default color (empty array).
13577 * @public
13578 * @see SetLineStyle()
13579 * @since 2.1.000 (2008-01-08)
13581 public function Curve($x0, $y0, $x1, $y1, $x2, $y2, $x3, $y3, $style='', $line_style=array(), $fill_color=array()) {
13582 if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
13583 $this->SetFillColorArray($fill_color);
13585 $op = $this->getPathPaintOperator($style);
13586 if ($line_style) {
13587 $this->SetLineStyle($line_style);
13589 $this->_outPoint($x0, $y0);
13590 $this->_outCurve($x1, $y1, $x2, $y2, $x3, $y3);
13591 $this->_out($op);
13595 * Draws a poly-Bezier curve.
13596 * Each Bezier curve segment is a tangent to the line between the control points at
13597 * either end of the curve.
13598 * @param $x0 (float) Abscissa of start point.
13599 * @param $y0 (float) Ordinate of start point.
13600 * @param $segments (float) An array of bezier descriptions. Format: array(x1, y1, x2, y2, x3, y3).
13601 * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
13602 * @param $line_style (array) Line style of curve. Array like for SetLineStyle(). Default value: default line style (empty array).
13603 * @param $fill_color (array) Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K). Default value: default color (empty array).
13604 * @public
13605 * @see SetLineStyle()
13606 * @since 3.0008 (2008-05-12)
13608 public function Polycurve($x0, $y0, $segments, $style='', $line_style=array(), $fill_color=array()) {
13609 if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
13610 $this->SetFillColorArray($fill_color);
13612 $op = $this->getPathPaintOperator($style);
13613 if ($op == 'f') {
13614 $line_style = array();
13616 if ($line_style) {
13617 $this->SetLineStyle($line_style);
13619 $this->_outPoint($x0, $y0);
13620 foreach ($segments as $segment) {
13621 list($x1, $y1, $x2, $y2, $x3, $y3) = $segment;
13622 $this->_outCurve($x1, $y1, $x2, $y2, $x3, $y3);
13624 $this->_out($op);
13628 * Draws an ellipse.
13629 * An ellipse is formed from n Bezier curves.
13630 * @param $x0 (float) Abscissa of center point.
13631 * @param $y0 (float) Ordinate of center point.
13632 * @param $rx (float) Horizontal radius.
13633 * @param $ry (float) Vertical radius (if ry = 0 then is a circle, see Circle()). Default value: 0.
13634 * @param $angle: (float) Angle oriented (anti-clockwise). Default value: 0.
13635 * @param $astart: (float) Angle start of draw line. Default value: 0.
13636 * @param $afinish: (float) Angle finish of draw line. Default value: 360.
13637 * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
13638 * @param $line_style (array) Line style of ellipse. Array like for SetLineStyle(). Default value: default line style (empty array).
13639 * @param $fill_color (array) Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K). Default value: default color (empty array).
13640 * @param $nc (integer) Number of curves used to draw a 90 degrees portion of ellipse.
13641 * @author Nicola Asuni
13642 * @public
13643 * @since 2.1.000 (2008-01-08)
13645 public function Ellipse($x0, $y0, $rx, $ry='', $angle=0, $astart=0, $afinish=360, $style='', $line_style=array(), $fill_color=array(), $nc=2) {
13646 if ($this->empty_string($ry) OR ($ry == 0)) {
13647 $ry = $rx;
13649 if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
13650 $this->SetFillColorArray($fill_color);
13652 $op = $this->getPathPaintOperator($style);
13653 if ($op == 'f') {
13654 $line_style = array();
13656 if ($line_style) {
13657 $this->SetLineStyle($line_style);
13659 $this->_outellipticalarc($x0, $y0, $rx, $ry, $angle, $astart, $afinish, false, $nc, true, true, false);
13660 $this->_out($op);
13664 * Append an elliptical arc to the current path.
13665 * An ellipse is formed from n Bezier curves.
13666 * @param $xc (float) Abscissa of center point.
13667 * @param $yc (float) Ordinate of center point.
13668 * @param $rx (float) Horizontal radius.
13669 * @param $ry (float) Vertical radius (if ry = 0 then is a circle, see Circle()). Default value: 0.
13670 * @param $xang: (float) Angle between the X-axis and the major axis of the ellipse. Default value: 0.
13671 * @param $angs: (float) Angle start of draw line. Default value: 0.
13672 * @param $angf: (float) Angle finish of draw line. Default value: 360.
13673 * @param $pie (boolean) if true do not mark the border point (used to draw pie sectors).
13674 * @param $nc (integer) Number of curves used to draw a 90 degrees portion of ellipse.
13675 * @param $startpoint (boolean) if true output a starting point.
13676 * @param $ccw (boolean) if true draws in counter-clockwise.
13677 * @param $svg (boolean) if true the angles are in svg mode (already calculated).
13678 * @return array bounding box coordinates (x min, y min, x max, y max)
13679 * @author Nicola Asuni
13680 * @protected
13681 * @since 4.9.019 (2010-04-26)
13683 protected function _outellipticalarc($xc, $yc, $rx, $ry, $xang=0, $angs=0, $angf=360, $pie=false, $nc=2, $startpoint=true, $ccw=true, $svg=false) {
13684 $k = $this->k;
13685 if ($nc < 2) {
13686 $nc = 2;
13688 $xmin = 2147483647;
13689 $ymin = 2147483647;
13690 $xmax = 0;
13691 $ymax = 0;
13692 if ($pie) {
13693 // center of the arc
13694 $this->_outPoint($xc, $yc);
13696 $xang = deg2rad((float) $xang);
13697 $angs = deg2rad((float) $angs);
13698 $angf = deg2rad((float) $angf);
13699 if ($svg) {
13700 $as = $angs;
13701 $af = $angf;
13702 } else {
13703 $as = atan2((sin($angs) / $ry), (cos($angs) / $rx));
13704 $af = atan2((sin($angf) / $ry), (cos($angf) / $rx));
13706 if ($as < 0) {
13707 $as += (2 * M_PI);
13709 if ($af < 0) {
13710 $af += (2 * M_PI);
13712 if ($ccw AND ($as > $af)) {
13713 // reverse rotation
13714 $as -= (2 * M_PI);
13715 } elseif (!$ccw AND ($as < $af)) {
13716 // reverse rotation
13717 $af -= (2 * M_PI);
13719 $total_angle = ($af - $as);
13720 if ($nc < 2) {
13721 $nc = 2;
13723 // total arcs to draw
13724 $nc *= (2 * abs($total_angle) / M_PI);
13725 $nc = round($nc) + 1;
13726 // angle of each arc
13727 $arcang = ($total_angle / $nc);
13728 // center point in PDF coordinates
13729 $x0 = $xc;
13730 $y0 = ($this->h - $yc);
13731 // starting angle
13732 $ang = $as;
13733 $alpha = sin($arcang) * ((sqrt(4 + (3 * pow(tan(($arcang) / 2), 2))) - 1) / 3);
13734 $cos_xang = cos($xang);
13735 $sin_xang = sin($xang);
13736 $cos_ang = cos($ang);
13737 $sin_ang = sin($ang);
13738 // first arc point
13739 $px1 = $x0 + ($rx * $cos_xang * $cos_ang) - ($ry * $sin_xang * $sin_ang);
13740 $py1 = $y0 + ($rx * $sin_xang * $cos_ang) + ($ry * $cos_xang * $sin_ang);
13741 // first Bezier control point
13742 $qx1 = ($alpha * ((-$rx * $cos_xang * $sin_ang) - ($ry * $sin_xang * $cos_ang)));
13743 $qy1 = ($alpha * ((-$rx * $sin_xang * $sin_ang) + ($ry * $cos_xang * $cos_ang)));
13744 if ($pie) {
13745 // line from center to arc starting point
13746 $this->_outLine($px1, $this->h - $py1);
13747 } elseif ($startpoint) {
13748 // arc starting point
13749 $this->_outPoint($px1, $this->h - $py1);
13751 // draw arcs
13752 for ($i = 1; $i <= $nc; ++$i) {
13753 // starting angle
13754 $ang = $as + ($i * $arcang);
13755 if ($i == $nc) {
13756 $ang = $af;
13758 $cos_ang = cos($ang);
13759 $sin_ang = sin($ang);
13760 // second arc point
13761 $px2 = $x0 + ($rx * $cos_xang * $cos_ang) - ($ry * $sin_xang * $sin_ang);
13762 $py2 = $y0 + ($rx * $sin_xang * $cos_ang) + ($ry * $cos_xang * $sin_ang);
13763 // second Bezier control point
13764 $qx2 = ($alpha * ((-$rx * $cos_xang * $sin_ang) - ($ry * $sin_xang * $cos_ang)));
13765 $qy2 = ($alpha * ((-$rx * $sin_xang * $sin_ang) + ($ry * $cos_xang * $cos_ang)));
13766 // draw arc
13767 $cx1 = ($px1 + $qx1);
13768 $cy1 = ($this->h - ($py1 + $qy1));
13769 $cx2 = ($px2 - $qx2);
13770 $cy2 = ($this->h - ($py2 - $qy2));
13771 $cx3 = $px2;
13772 $cy3 = ($this->h - $py2);
13773 $this->_outCurve($cx1, $cy1, $cx2, $cy2, $cx3, $cy3);
13774 // get bounding box coordinates
13775 $xmin = min($xmin, $cx1, $cx2, $cx3);
13776 $ymin = min($ymin, $cy1, $cy2, $cy3);
13777 $xmax = max($xmax, $cx1, $cx2, $cx3);
13778 $ymax = max($ymax, $cy1, $cy2, $cy3);
13779 // move to next point
13780 $px1 = $px2;
13781 $py1 = $py2;
13782 $qx1 = $qx2;
13783 $qy1 = $qy2;
13785 if ($pie) {
13786 $this->_outLine($xc, $yc);
13787 // get bounding box coordinates
13788 $xmin = min($xmin, $xc);
13789 $ymin = min($ymin, $yc);
13790 $xmax = max($xmax, $xc);
13791 $ymax = max($ymax, $yc);
13793 return array($xmin, $ymin, $xmax, $ymax);
13797 * Draws a circle.
13798 * A circle is formed from n Bezier curves.
13799 * @param $x0 (float) Abscissa of center point.
13800 * @param $y0 (float) Ordinate of center point.
13801 * @param $r (float) Radius.
13802 * @param $angstr: (float) Angle start of draw line. Default value: 0.
13803 * @param $angend: (float) Angle finish of draw line. Default value: 360.
13804 * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
13805 * @param $line_style (array) Line style of circle. Array like for SetLineStyle(). Default value: default line style (empty array).
13806 * @param $fill_color (array) Fill color. Format: array(red, green, blue). Default value: default color (empty array).
13807 * @param $nc (integer) Number of curves used to draw a 90 degrees portion of circle.
13808 * @public
13809 * @since 2.1.000 (2008-01-08)
13811 public function Circle($x0, $y0, $r, $angstr=0, $angend=360, $style='', $line_style=array(), $fill_color=array(), $nc=2) {
13812 $this->Ellipse($x0, $y0, $r, $r, 0, $angstr, $angend, $style, $line_style, $fill_color, $nc);
13816 * Draws a polygonal line
13817 * @param $p (array) Points 0 to ($np - 1). Array with values (x0, y0, x1, y1,..., x(np-1), y(np - 1))
13818 * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
13819 * @param $line_style (array) Line style of polygon. Array with keys among the following:
13820 * <ul>
13821 * <li>all: Line style of all lines. Array like for SetLineStyle().</li>
13822 * <li>0 to ($np - 1): Line style of each line. Array like for SetLineStyle().</li>
13823 * </ul>
13824 * If a key is not present or is null, not draws the line. Default value is default line style (empty array).
13825 * @param $fill_color (array) Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K). Default value: default color (empty array).
13826 * @since 4.8.003 (2009-09-15)
13827 * @public
13829 public function PolyLine($p, $style='', $line_style=array(), $fill_color=array()) {
13830 $this->Polygon($p, $style, $line_style, $fill_color, false);
13834 * Draws a polygon.
13835 * @param $p (array) Points 0 to ($np - 1). Array with values (x0, y0, x1, y1,..., x(np-1), y(np - 1))
13836 * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
13837 * @param $line_style (array) Line style of polygon. Array with keys among the following:
13838 * <ul>
13839 * <li>all: Line style of all lines. Array like for SetLineStyle().</li>
13840 * <li>0 to ($np - 1): Line style of each line. Array like for SetLineStyle().</li>
13841 * </ul>
13842 * If a key is not present or is null, not draws the line. Default value is default line style (empty array).
13843 * @param $fill_color (array) Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K). Default value: default color (empty array).
13844 * @param $closed (boolean) if true the polygon is closes, otherwise will remain open
13845 * @public
13846 * @since 2.1.000 (2008-01-08)
13848 public function Polygon($p, $style='', $line_style=array(), $fill_color=array(), $closed=true) {
13849 $nc = count($p); // number of coordinates
13850 $np = $nc / 2; // number of points
13851 if ($closed) {
13852 // close polygon by adding the first 2 points at the end (one line)
13853 for ($i = 0; $i < 4; ++$i) {
13854 $p[$nc + $i] = $p[$i];
13856 // copy style for the last added line
13857 if (isset($line_style[0])) {
13858 $line_style[$np] = $line_style[0];
13860 $nc += 4;
13862 if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
13863 $this->SetFillColorArray($fill_color);
13865 $op = $this->getPathPaintOperator($style);
13866 if ($op == 'f') {
13867 $line_style = array();
13869 $draw = true;
13870 if ($line_style) {
13871 if (isset($line_style['all'])) {
13872 $this->SetLineStyle($line_style['all']);
13873 } else {
13874 $draw = false;
13875 if ($op == 'B') {
13876 // draw fill
13877 $op = 'f';
13878 $this->_outPoint($p[0], $p[1]);
13879 for ($i = 2; $i < $nc; $i = $i + 2) {
13880 $this->_outLine($p[$i], $p[$i + 1]);
13882 $this->_out($op);
13884 // draw outline
13885 $this->_outPoint($p[0], $p[1]);
13886 for ($i = 2; $i < $nc; $i = $i + 2) {
13887 $line_num = ($i / 2) - 1;
13888 if (isset($line_style[$line_num])) {
13889 if ($line_style[$line_num] != 0) {
13890 if (is_array($line_style[$line_num])) {
13891 $this->_out('S');
13892 $this->SetLineStyle($line_style[$line_num]);
13893 $this->_outPoint($p[$i - 2], $p[$i - 1]);
13894 $this->_outLine($p[$i], $p[$i + 1]);
13895 $this->_out('S');
13896 $this->_outPoint($p[$i], $p[$i + 1]);
13897 } else {
13898 $this->_outLine($p[$i], $p[$i + 1]);
13901 } else {
13902 $this->_outLine($p[$i], $p[$i + 1]);
13905 $this->_out($op);
13908 if ($draw) {
13909 $this->_outPoint($p[0], $p[1]);
13910 for ($i = 2; $i < $nc; $i = $i + 2) {
13911 $this->_outLine($p[$i], $p[$i + 1]);
13913 $this->_out($op);
13918 * Draws a regular polygon.
13919 * @param $x0 (float) Abscissa of center point.
13920 * @param $y0 (float) Ordinate of center point.
13921 * @param $r: (float) Radius of inscribed circle.
13922 * @param $ns (integer) Number of sides.
13923 * @param $angle (float) Angle oriented (anti-clockwise). Default value: 0.
13924 * @param $draw_circle (boolean) Draw inscribed circle or not. Default value: false.
13925 * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
13926 * @param $line_style (array) Line style of polygon sides. Array with keys among the following:
13927 * <ul>
13928 * <li>all: Line style of all sides. Array like for SetLineStyle().</li>
13929 * <li>0 to ($ns - 1): Line style of each side. Array like for SetLineStyle().</li>
13930 * </ul>
13931 * If a key is not present or is null, not draws the side. Default value is default line style (empty array).
13932 * @param $fill_color (array) Fill color. Format: array(red, green, blue). Default value: default color (empty array).
13933 * @param $circle_style (string) Style of rendering of inscribed circle (if draws). Possible values are:
13934 * <ul>
13935 * <li>D or empty string: Draw (default).</li>
13936 * <li>F: Fill.</li>
13937 * <li>DF or FD: Draw and fill.</li>
13938 * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
13939 * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
13940 * </ul>
13941 * @param $circle_outLine_style (array) Line style of inscribed circle (if draws). Array like for SetLineStyle(). Default value: default line style (empty array).
13942 * @param $circle_fill_color (array) Fill color of inscribed circle (if draws). Format: array(red, green, blue). Default value: default color (empty array).
13943 * @public
13944 * @since 2.1.000 (2008-01-08)
13946 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()) {
13947 if (3 > $ns) {
13948 $ns = 3;
13950 if ($draw_circle) {
13951 $this->Circle($x0, $y0, $r, 0, 360, $circle_style, $circle_outLine_style, $circle_fill_color);
13953 $p = array();
13954 for ($i = 0; $i < $ns; ++$i) {
13955 $a = $angle + ($i * 360 / $ns);
13956 $a_rad = deg2rad((float) $a);
13957 $p[] = $x0 + ($r * sin($a_rad));
13958 $p[] = $y0 + ($r * cos($a_rad));
13960 $this->Polygon($p, $style, $line_style, $fill_color);
13964 * Draws a star polygon
13965 * @param $x0 (float) Abscissa of center point.
13966 * @param $y0 (float) Ordinate of center point.
13967 * @param $r (float) Radius of inscribed circle.
13968 * @param $nv (integer) Number of vertices.
13969 * @param $ng (integer) Number of gap (if ($ng % $nv = 1) then is a regular polygon).
13970 * @param $angle: (float) Angle oriented (anti-clockwise). Default value: 0.
13971 * @param $draw_circle: (boolean) Draw inscribed circle or not. Default value is false.
13972 * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
13973 * @param $line_style (array) Line style of polygon sides. Array with keys among the following:
13974 * <ul>
13975 * <li>all: Line style of all sides. Array like for
13976 * SetLineStyle().</li>
13977 * <li>0 to (n - 1): Line style of each side. Array like for SetLineStyle().</li>
13978 * </ul>
13979 * If a key is not present or is null, not draws the side. Default value is default line style (empty array).
13980 * @param $fill_color (array) Fill color. Format: array(red, green, blue). Default value: default color (empty array).
13981 * @param $circle_style (string) Style of rendering of inscribed circle (if draws). Possible values are:
13982 * <ul>
13983 * <li>D or empty string: Draw (default).</li>
13984 * <li>F: Fill.</li>
13985 * <li>DF or FD: Draw and fill.</li>
13986 * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
13987 * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
13988 * </ul>
13989 * @param $circle_outLine_style (array) Line style of inscribed circle (if draws). Array like for SetLineStyle(). Default value: default line style (empty array).
13990 * @param $circle_fill_color (array) Fill color of inscribed circle (if draws). Format: array(red, green, blue). Default value: default color (empty array).
13991 * @public
13992 * @since 2.1.000 (2008-01-08)
13994 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()) {
13995 if ($nv < 2) {
13996 $nv = 2;
13998 if ($draw_circle) {
13999 $this->Circle($x0, $y0, $r, 0, 360, $circle_style, $circle_outLine_style, $circle_fill_color);
14001 $p2 = array();
14002 $visited = array();
14003 for ($i = 0; $i < $nv; ++$i) {
14004 $a = $angle + ($i * 360 / $nv);
14005 $a_rad = deg2rad((float) $a);
14006 $p2[] = $x0 + ($r * sin($a_rad));
14007 $p2[] = $y0 + ($r * cos($a_rad));
14008 $visited[] = false;
14010 $p = array();
14011 $i = 0;
14012 do {
14013 $p[] = $p2[$i * 2];
14014 $p[] = $p2[($i * 2) + 1];
14015 $visited[$i] = true;
14016 $i += $ng;
14017 $i %= $nv;
14018 } while (!$visited[$i]);
14019 $this->Polygon($p, $style, $line_style, $fill_color);
14023 * Draws a rounded rectangle.
14024 * @param $x (float) Abscissa of upper-left corner.
14025 * @param $y (float) Ordinate of upper-left corner.
14026 * @param $w (float) Width.
14027 * @param $h (float) Height.
14028 * @param $r (float) the radius of the circle used to round off the corners of the rectangle.
14029 * @param $round_corner (string) Draws rounded corner or not. String with a 0 (not rounded i-corner) or 1 (rounded i-corner) in i-position. Positions are, in order and begin to 0: top left, top right, bottom right and bottom left. Default value: all rounded corner ("1111").
14030 * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
14031 * @param $border_style (array) Border style of rectangle. Array like for SetLineStyle(). Default value: default line style (empty array).
14032 * @param $fill_color (array) Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K). Default value: default color (empty array).
14033 * @public
14034 * @since 2.1.000 (2008-01-08)
14036 public function RoundedRect($x, $y, $w, $h, $r, $round_corner='1111', $style='', $border_style=array(), $fill_color=array()) {
14037 $this->RoundedRectXY($x, $y, $w, $h, $r, $r, $round_corner, $style, $border_style, $fill_color);
14041 * Draws a rounded rectangle.
14042 * @param $x (float) Abscissa of upper-left corner.
14043 * @param $y (float) Ordinate of upper-left corner.
14044 * @param $w (float) Width.
14045 * @param $h (float) Height.
14046 * @param $rx (float) the x-axis radius of the ellipse used to round off the corners of the rectangle.
14047 * @param $ry (float) the y-axis radius of the ellipse used to round off the corners of the rectangle.
14048 * @param $round_corner (string) Draws rounded corner or not. String with a 0 (not rounded i-corner) or 1 (rounded i-corner) in i-position. Positions are, in order and begin to 0: top left, top right, bottom right and bottom left. Default value: all rounded corner ("1111").
14049 * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
14050 * @param $border_style (array) Border style of rectangle. Array like for SetLineStyle(). Default value: default line style (empty array).
14051 * @param $fill_color (array) Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K). Default value: default color (empty array).
14052 * @public
14053 * @since 4.9.019 (2010-04-22)
14055 public function RoundedRectXY($x, $y, $w, $h, $rx, $ry, $round_corner='1111', $style='', $border_style=array(), $fill_color=array()) {
14056 if (($round_corner == '0000') OR (($rx == $ry) AND ($rx == 0))) {
14057 // Not rounded
14058 $this->Rect($x, $y, $w, $h, $style, $border_style, $fill_color);
14059 return;
14061 // Rounded
14062 if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
14063 $this->SetFillColorArray($fill_color);
14065 $op = $this->getPathPaintOperator($style);
14066 if ($op == 'f') {
14067 $border_style = array();
14069 if ($border_style) {
14070 $this->SetLineStyle($border_style);
14072 $MyArc = 4 / 3 * (sqrt(2) - 1);
14073 $this->_outPoint($x + $rx, $y);
14074 $xc = $x + $w - $rx;
14075 $yc = $y + $ry;
14076 $this->_outLine($xc, $y);
14077 if ($round_corner[0]) {
14078 $this->_outCurve($xc + ($rx * $MyArc), $yc - $ry, $xc + $rx, $yc - ($ry * $MyArc), $xc + $rx, $yc);
14079 } else {
14080 $this->_outLine($x + $w, $y);
14082 $xc = $x + $w - $rx;
14083 $yc = $y + $h - $ry;
14084 $this->_outLine($x + $w, $yc);
14085 if ($round_corner[1]) {
14086 $this->_outCurve($xc + $rx, $yc + ($ry * $MyArc), $xc + ($rx * $MyArc), $yc + $ry, $xc, $yc + $ry);
14087 } else {
14088 $this->_outLine($x + $w, $y + $h);
14090 $xc = $x + $rx;
14091 $yc = $y + $h - $ry;
14092 $this->_outLine($xc, $y + $h);
14093 if ($round_corner[2]) {
14094 $this->_outCurve($xc - ($rx * $MyArc), $yc + $ry, $xc - $rx, $yc + ($ry * $MyArc), $xc - $rx, $yc);
14095 } else {
14096 $this->_outLine($x, $y + $h);
14098 $xc = $x + $rx;
14099 $yc = $y + $ry;
14100 $this->_outLine($x, $yc);
14101 if ($round_corner[3]) {
14102 $this->_outCurve($xc - $rx, $yc - ($ry * $MyArc), $xc - ($rx * $MyArc), $yc - $ry, $xc, $yc - $ry);
14103 } else {
14104 $this->_outLine($x, $y);
14105 $this->_outLine($x + $rx, $y);
14107 $this->_out($op);
14111 * Draws a grahic arrow.
14112 * @param $x0 (float) Abscissa of first point.
14113 * @param $y0 (float) Ordinate of first point.
14114 * @param $x1 (float) Abscissa of second point.
14115 * @param $y1 (float) Ordinate of second point.
14116 * @param $head_style (int) (0 = draw only arrowhead arms, 1 = draw closed arrowhead, but no fill, 2 = closed and filled arrowhead, 3 = filled arrowhead)
14117 * @param $arm_size (float) length of arrowhead arms
14118 * @param $arm_angle (int) angle between an arm and the shaft
14119 * @author Piotr Galecki, Nicola Asuni, Andy Meier
14120 * @since 4.6.018 (2009-07-10)
14122 public function Arrow($x0, $y0, $x1, $y1, $head_style=0, $arm_size=5, $arm_angle=15) {
14123 // getting arrow direction angle
14124 // 0 deg angle is when both arms go along X axis. angle grows clockwise.
14125 $dir_angle = atan2(($y0 - $y1), ($x0 - $x1));
14126 if ($dir_angle < 0) {
14127 $dir_angle += (2 * M_PI);
14129 $arm_angle = deg2rad($arm_angle);
14130 $sx1 = $x1;
14131 $sy1 = $y1;
14132 if ($head_style > 0) {
14133 // calculate the stopping point for the arrow shaft
14134 $sx1 = $x1 + (($arm_size - $this->LineWidth) * cos($dir_angle));
14135 $sy1 = $y1 + (($arm_size - $this->LineWidth) * sin($dir_angle));
14137 // main arrow line / shaft
14138 $this->Line($x0, $y0, $sx1, $sy1);
14139 // left arrowhead arm tip
14140 $x2L = $x1 + ($arm_size * cos($dir_angle + $arm_angle));
14141 $y2L = $y1 + ($arm_size * sin($dir_angle + $arm_angle));
14142 // right arrowhead arm tip
14143 $x2R = $x1 + ($arm_size * cos($dir_angle - $arm_angle));
14144 $y2R = $y1 + ($arm_size * sin($dir_angle - $arm_angle));
14145 $mode = 'D';
14146 $style = array();
14147 switch ($head_style) {
14148 case 0: {
14149 // draw only arrowhead arms
14150 $mode = 'D';
14151 $style = array(1, 1, 0);
14152 break;
14154 case 1: {
14155 // draw closed arrowhead, but no fill
14156 $mode = 'D';
14157 break;
14159 case 2: {
14160 // closed and filled arrowhead
14161 $mode = 'DF';
14162 break;
14164 case 3: {
14165 // filled arrowhead
14166 $mode = 'F';
14167 break;
14170 $this->Polygon(array($x2L, $y2L, $x1, $y1, $x2R, $y2R), $mode, $style, array());
14173 // END GRAPHIC FUNCTIONS SECTION -----------------------
14175 // BIDIRECTIONAL TEXT SECTION --------------------------
14178 * Reverse the RLT substrings using the Bidirectional Algorithm (http://unicode.org/reports/tr9/).
14179 * @param $str (string) string to manipulate.
14180 * @param $setbom (bool) if true set the Byte Order Mark (BOM = 0xFEFF)
14181 * @param $forcertl (bool) if true forces RTL text direction
14182 * @return string
14183 * @protected
14184 * @author Nicola Asuni
14185 * @since 2.1.000 (2008-01-08)
14187 protected function utf8StrRev($str, $setbom=false, $forcertl=false) {
14188 return $this->utf8StrArrRev($this->UTF8StringToArray($str), $str, $setbom, $forcertl);
14192 * Reverse the RLT substrings array using the Bidirectional Algorithm (http://unicode.org/reports/tr9/).
14193 * @param $arr (array) array of unicode values.
14194 * @param $str (string) string to manipulate (or empty value).
14195 * @param $setbom (bool) if true set the Byte Order Mark (BOM = 0xFEFF)
14196 * @param $forcertl (bool) if true forces RTL text direction
14197 * @return string
14198 * @protected
14199 * @author Nicola Asuni
14200 * @since 4.9.000 (2010-03-27)
14202 protected function utf8StrArrRev($arr, $str='', $setbom=false, $forcertl=false) {
14203 return $this->arrUTF8ToUTF16BE($this->utf8Bidi($arr, $str, $forcertl), $setbom);
14207 * Reverse the RLT substrings using the Bidirectional Algorithm (http://unicode.org/reports/tr9/).
14208 * @param $ta (array) array of characters composing the string.
14209 * @param $str (string) string to process
14210 * @param $forcertl (bool) if 'R' forces RTL, if 'L' forces LTR
14211 * @return array of unicode chars
14212 * @author Nicola Asuni
14213 * @protected
14214 * @since 2.4.000 (2008-03-06)
14216 protected function utf8Bidi($ta, $str='', $forcertl=false) {
14217 // paragraph embedding level
14218 $pel = 0;
14219 // max level
14220 $maxlevel = 0;
14221 if ($this->empty_string($str)) {
14222 // create string from array
14223 $str = $this->UTF8ArrSubString($ta);
14225 // check if string contains arabic text
14226 if (preg_match($this->unicode->uni_RE_PATTERN_ARABIC, $str)) {
14227 $arabic = true;
14228 } else {
14229 $arabic = false;
14231 // check if string contains RTL text
14232 if (!($forcertl OR $arabic OR preg_match($this->unicode->uni_RE_PATTERN_RTL, $str))) {
14233 return $ta;
14236 // get number of chars
14237 $numchars = count($ta);
14239 if ($forcertl == 'R') {
14240 $pel = 1;
14241 } elseif ($forcertl == 'L') {
14242 $pel = 0;
14243 } else {
14244 // P2. In each paragraph, find the first character of type L, AL, or R.
14245 // P3. If a character is found in P2 and it is of type AL or R, then set the paragraph embedding level to one; otherwise, set it to zero.
14246 for ($i=0; $i < $numchars; ++$i) {
14247 $type = $this->unicode->uni_type[$ta[$i]];
14248 if ($type == 'L') {
14249 $pel = 0;
14250 break;
14251 } elseif (($type == 'AL') OR ($type == 'R')) {
14252 $pel = 1;
14253 break;
14258 // Current Embedding Level
14259 $cel = $pel;
14260 // directional override status
14261 $dos = 'N';
14262 $remember = array();
14263 // start-of-level-run
14264 $sor = $pel % 2 ? 'R' : 'L';
14265 $eor = $sor;
14267 // Array of characters data
14268 $chardata = Array();
14270 // X1. Begin by setting the current embedding level to the paragraph embedding level. Set the directional override status to neutral. Process each character iteratively, applying rules X2 through X9. Only embedding levels from 0 to 61 are valid in this phase.
14271 // In the resolution of levels in rules I1 and I2, the maximum embedding level of 62 can be reached.
14272 for ($i=0; $i < $numchars; ++$i) {
14273 if ($ta[$i] == $this->unicode->uni_RLE) {
14274 // X2. With each RLE, compute the least greater odd embedding level.
14275 // a. If this new level would be valid, then this embedding code is valid. Remember (push) the current embedding level and override status. Reset the current level to this new level, and reset the override status to neutral.
14276 // b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
14277 $next_level = $cel + ($cel % 2) + 1;
14278 if ($next_level < 62) {
14279 $remember[] = array('num' => $this->unicode->uni_RLE, 'cel' => $cel, 'dos' => $dos);
14280 $cel = $next_level;
14281 $dos = 'N';
14282 $sor = $eor;
14283 $eor = $cel % 2 ? 'R' : 'L';
14285 } elseif ($ta[$i] == $this->unicode->uni_LRE) {
14286 // X3. With each LRE, compute the least greater even embedding level.
14287 // a. If this new level would be valid, then this embedding code is valid. Remember (push) the current embedding level and override status. Reset the current level to this new level, and reset the override status to neutral.
14288 // b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
14289 $next_level = $cel + 2 - ($cel % 2);
14290 if ( $next_level < 62 ) {
14291 $remember[] = array('num' => $this->unicode->uni_LRE, 'cel' => $cel, 'dos' => $dos);
14292 $cel = $next_level;
14293 $dos = 'N';
14294 $sor = $eor;
14295 $eor = $cel % 2 ? 'R' : 'L';
14297 } elseif ($ta[$i] == $this->unicode->uni_RLO) {
14298 // X4. With each RLO, compute the least greater odd embedding level.
14299 // a. If this new level would be valid, then this embedding code is valid. Remember (push) the current embedding level and override status. Reset the current level to this new level, and reset the override status to right-to-left.
14300 // b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
14301 $next_level = $cel + ($cel % 2) + 1;
14302 if ($next_level < 62) {
14303 $remember[] = array('num' => $this->unicode->uni_RLO, 'cel' => $cel, 'dos' => $dos);
14304 $cel = $next_level;
14305 $dos = 'R';
14306 $sor = $eor;
14307 $eor = $cel % 2 ? 'R' : 'L';
14309 } elseif ($ta[$i] == $this->unicode->uni_LRO) {
14310 // X5. With each LRO, compute the least greater even embedding level.
14311 // a. If this new level would be valid, then this embedding code is valid. Remember (push) the current embedding level and override status. Reset the current level to this new level, and reset the override status to left-to-right.
14312 // b. If the new level would not be valid, then this code is invalid. Do not change the current level or override status.
14313 $next_level = $cel + 2 - ($cel % 2);
14314 if ( $next_level < 62 ) {
14315 $remember[] = array('num' => $this->unicode->uni_LRO, 'cel' => $cel, 'dos' => $dos);
14316 $cel = $next_level;
14317 $dos = 'L';
14318 $sor = $eor;
14319 $eor = $cel % 2 ? 'R' : 'L';
14321 } elseif ($ta[$i] == $this->unicode->uni_PDF) {
14322 // X7. With each PDF, determine the matching embedding or override code. If there was a valid matching code, restore (pop) the last remembered (pushed) embedding level and directional override.
14323 if (count($remember)) {
14324 $last = count($remember ) - 1;
14325 if (($remember[$last]['num'] == $this->unicode->uni_RLE) OR
14326 ($remember[$last]['num'] == $this->unicode->uni_LRE) OR
14327 ($remember[$last]['num'] == $this->unicode->uni_RLO) OR
14328 ($remember[$last]['num'] == $this->unicode->uni_LRO)) {
14329 $match = array_pop($remember);
14330 $cel = $match['cel'];
14331 $dos = $match['dos'];
14332 $sor = $eor;
14333 $eor = ($cel > $match['cel'] ? $cel : $match['cel']) % 2 ? 'R' : 'L';
14336 } elseif (($ta[$i] != $this->unicode->uni_RLE) AND
14337 ($ta[$i] != $this->unicode->uni_LRE) AND
14338 ($ta[$i] != $this->unicode->uni_RLO) AND
14339 ($ta[$i] != $this->unicode->uni_LRO) AND
14340 ($ta[$i] != $this->unicode->uni_PDF)) {
14341 // X6. For all types besides RLE, LRE, RLO, LRO, and PDF:
14342 // a. Set the level of the current character to the current embedding level.
14343 // b. Whenever the directional override status is not neutral, reset the current character type to the directional override status.
14344 if ($dos != 'N') {
14345 $chardir = $dos;
14346 } else {
14347 if (isset($this->unicode->uni_type[$ta[$i]])) {
14348 $chardir = $this->unicode->uni_type[$ta[$i]];
14349 } else {
14350 $chardir = 'L';
14353 // stores string characters and other information
14354 $chardata[] = array('char' => $ta[$i], 'level' => $cel, 'type' => $chardir, 'sor' => $sor, 'eor' => $eor);
14356 } // end for each char
14358 // X8. All explicit directional embeddings and overrides are completely terminated at the end of each paragraph. Paragraph separators are not included in the embedding.
14359 // X9. Remove all RLE, LRE, RLO, LRO, PDF, and BN codes.
14360 // X10. The remaining rules are applied to each run of characters at the same level. For each run, determine the start-of-level-run (sor) and end-of-level-run (eor) type, either L or R. This depends on the higher of the two levels on either side of the boundary (at the start or end of the paragraph, the level of the 'other' run is the base embedding level). If the higher level is odd, the type is R; otherwise, it is L.
14362 // 3.3.3 Resolving Weak Types
14363 // Weak types are now resolved one level run at a time. At level run boundaries where the type of the character on the other side of the boundary is required, the type assigned to sor or eor is used.
14364 // Nonspacing marks are now resolved based on the previous characters.
14365 $numchars = count($chardata);
14367 // W1. Examine each nonspacing mark (NSM) in the level run, and change the type of the NSM to the type of the previous character. If the NSM is at the start of the level run, it will get the type of sor.
14368 $prevlevel = -1; // track level changes
14369 $levcount = 0; // counts consecutive chars at the same level
14370 for ($i=0; $i < $numchars; ++$i) {
14371 if ($chardata[$i]['type'] == 'NSM') {
14372 if ($levcount) {
14373 $chardata[$i]['type'] = $chardata[$i]['sor'];
14374 } elseif ($i > 0) {
14375 $chardata[$i]['type'] = $chardata[($i-1)]['type'];
14378 if ($chardata[$i]['level'] != $prevlevel) {
14379 $levcount = 0;
14380 } else {
14381 ++$levcount;
14383 $prevlevel = $chardata[$i]['level'];
14386 // W2. Search backward from each instance of a European number until the first strong type (R, L, AL, or sor) is found. If an AL is found, change the type of the European number to Arabic number.
14387 $prevlevel = -1;
14388 $levcount = 0;
14389 for ($i=0; $i < $numchars; ++$i) {
14390 if ($chardata[$i]['char'] == 'EN') {
14391 for ($j=$levcount; $j >= 0; $j--) {
14392 if ($chardata[$j]['type'] == 'AL') {
14393 $chardata[$i]['type'] = 'AN';
14394 } elseif (($chardata[$j]['type'] == 'L') OR ($chardata[$j]['type'] == 'R')) {
14395 break;
14399 if ($chardata[$i]['level'] != $prevlevel) {
14400 $levcount = 0;
14401 } else {
14402 ++$levcount;
14404 $prevlevel = $chardata[$i]['level'];
14407 // W3. Change all ALs to R.
14408 for ($i=0; $i < $numchars; ++$i) {
14409 if ($chardata[$i]['type'] == 'AL') {
14410 $chardata[$i]['type'] = 'R';
14414 // W4. A single European separator between two European numbers changes to a European number. A single common separator between two numbers of the same type changes to that type.
14415 $prevlevel = -1;
14416 $levcount = 0;
14417 for ($i=0; $i < $numchars; ++$i) {
14418 if (($levcount > 0) AND (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] == $prevlevel)) {
14419 if (($chardata[$i]['type'] == 'ES') AND ($chardata[($i-1)]['type'] == 'EN') AND ($chardata[($i+1)]['type'] == 'EN')) {
14420 $chardata[$i]['type'] = 'EN';
14421 } elseif (($chardata[$i]['type'] == 'CS') AND ($chardata[($i-1)]['type'] == 'EN') AND ($chardata[($i+1)]['type'] == 'EN')) {
14422 $chardata[$i]['type'] = 'EN';
14423 } elseif (($chardata[$i]['type'] == 'CS') AND ($chardata[($i-1)]['type'] == 'AN') AND ($chardata[($i+1)]['type'] == 'AN')) {
14424 $chardata[$i]['type'] = 'AN';
14427 if ($chardata[$i]['level'] != $prevlevel) {
14428 $levcount = 0;
14429 } else {
14430 ++$levcount;
14432 $prevlevel = $chardata[$i]['level'];
14435 // W5. A sequence of European terminators adjacent to European numbers changes to all European numbers.
14436 $prevlevel = -1;
14437 $levcount = 0;
14438 for ($i=0; $i < $numchars; ++$i) {
14439 if ($chardata[$i]['type'] == 'ET') {
14440 if (($levcount > 0) AND ($chardata[($i-1)]['type'] == 'EN')) {
14441 $chardata[$i]['type'] = 'EN';
14442 } else {
14443 $j = $i+1;
14444 while (($j < $numchars) AND ($chardata[$j]['level'] == $prevlevel)) {
14445 if ($chardata[$j]['type'] == 'EN') {
14446 $chardata[$i]['type'] = 'EN';
14447 break;
14448 } elseif ($chardata[$j]['type'] != 'ET') {
14449 break;
14451 ++$j;
14455 if ($chardata[$i]['level'] != $prevlevel) {
14456 $levcount = 0;
14457 } else {
14458 ++$levcount;
14460 $prevlevel = $chardata[$i]['level'];
14463 // W6. Otherwise, separators and terminators change to Other Neutral.
14464 $prevlevel = -1;
14465 $levcount = 0;
14466 for ($i=0; $i < $numchars; ++$i) {
14467 if (($chardata[$i]['type'] == 'ET') OR ($chardata[$i]['type'] == 'ES') OR ($chardata[$i]['type'] == 'CS')) {
14468 $chardata[$i]['type'] = 'ON';
14470 if ($chardata[$i]['level'] != $prevlevel) {
14471 $levcount = 0;
14472 } else {
14473 ++$levcount;
14475 $prevlevel = $chardata[$i]['level'];
14478 //W7. Search backward from each instance of a European number until the first strong type (R, L, or sor) is found. If an L is found, then change the type of the European number to L.
14479 $prevlevel = -1;
14480 $levcount = 0;
14481 for ($i=0; $i < $numchars; ++$i) {
14482 if ($chardata[$i]['char'] == 'EN') {
14483 for ($j=$levcount; $j >= 0; $j--) {
14484 if ($chardata[$j]['type'] == 'L') {
14485 $chardata[$i]['type'] = 'L';
14486 } elseif ($chardata[$j]['type'] == 'R') {
14487 break;
14491 if ($chardata[$i]['level'] != $prevlevel) {
14492 $levcount = 0;
14493 } else {
14494 ++$levcount;
14496 $prevlevel = $chardata[$i]['level'];
14499 // N1. A sequence of neutrals takes the direction of the surrounding strong text if the text on both sides has the same direction. European and Arabic numbers act as if they were R in terms of their influence on neutrals. Start-of-level-run (sor) and end-of-level-run (eor) are used at level run boundaries.
14500 $prevlevel = -1;
14501 $levcount = 0;
14502 for ($i=0; $i < $numchars; ++$i) {
14503 if (($levcount > 0) AND (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] == $prevlevel)) {
14504 if (($chardata[$i]['type'] == 'N') AND ($chardata[($i-1)]['type'] == 'L') AND ($chardata[($i+1)]['type'] == 'L')) {
14505 $chardata[$i]['type'] = 'L';
14506 } elseif (($chardata[$i]['type'] == 'N') AND
14507 (($chardata[($i-1)]['type'] == 'R') OR ($chardata[($i-1)]['type'] == 'EN') OR ($chardata[($i-1)]['type'] == 'AN')) AND
14508 (($chardata[($i+1)]['type'] == 'R') OR ($chardata[($i+1)]['type'] == 'EN') OR ($chardata[($i+1)]['type'] == 'AN'))) {
14509 $chardata[$i]['type'] = 'R';
14510 } elseif ($chardata[$i]['type'] == 'N') {
14511 // N2. Any remaining neutrals take the embedding direction
14512 $chardata[$i]['type'] = $chardata[$i]['sor'];
14514 } elseif (($levcount == 0) AND (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] == $prevlevel)) {
14515 // first char
14516 if (($chardata[$i]['type'] == 'N') AND ($chardata[$i]['sor'] == 'L') AND ($chardata[($i+1)]['type'] == 'L')) {
14517 $chardata[$i]['type'] = 'L';
14518 } elseif (($chardata[$i]['type'] == 'N') AND
14519 (($chardata[$i]['sor'] == 'R') OR ($chardata[$i]['sor'] == 'EN') OR ($chardata[$i]['sor'] == 'AN')) AND
14520 (($chardata[($i+1)]['type'] == 'R') OR ($chardata[($i+1)]['type'] == 'EN') OR ($chardata[($i+1)]['type'] == 'AN'))) {
14521 $chardata[$i]['type'] = 'R';
14522 } elseif ($chardata[$i]['type'] == 'N') {
14523 // N2. Any remaining neutrals take the embedding direction
14524 $chardata[$i]['type'] = $chardata[$i]['sor'];
14526 } elseif (($levcount > 0) AND ((($i+1) == $numchars) OR (($i+1) < $numchars) AND ($chardata[($i+1)]['level'] != $prevlevel))) {
14527 //last char
14528 if (($chardata[$i]['type'] == 'N') AND ($chardata[($i-1)]['type'] == 'L') AND ($chardata[$i]['eor'] == 'L')) {
14529 $chardata[$i]['type'] = 'L';
14530 } elseif (($chardata[$i]['type'] == 'N') AND
14531 (($chardata[($i-1)]['type'] == 'R') OR ($chardata[($i-1)]['type'] == 'EN') OR ($chardata[($i-1)]['type'] == 'AN')) AND
14532 (($chardata[$i]['eor'] == 'R') OR ($chardata[$i]['eor'] == 'EN') OR ($chardata[$i]['eor'] == 'AN'))) {
14533 $chardata[$i]['type'] = 'R';
14534 } elseif ($chardata[$i]['type'] == 'N') {
14535 // N2. Any remaining neutrals take the embedding direction
14536 $chardata[$i]['type'] = $chardata[$i]['sor'];
14538 } elseif ($chardata[$i]['type'] == 'N') {
14539 // N2. Any remaining neutrals take the embedding direction
14540 $chardata[$i]['type'] = $chardata[$i]['sor'];
14542 if ($chardata[$i]['level'] != $prevlevel) {
14543 $levcount = 0;
14544 } else {
14545 ++$levcount;
14547 $prevlevel = $chardata[$i]['level'];
14550 // I1. For all characters with an even (left-to-right) embedding direction, those of type R go up one level and those of type AN or EN go up two levels.
14551 // I2. For all characters with an odd (right-to-left) embedding direction, those of type L, EN or AN go up one level.
14552 for ($i=0; $i < $numchars; ++$i) {
14553 $odd = $chardata[$i]['level'] % 2;
14554 if ($odd) {
14555 if (($chardata[$i]['type'] == 'L') OR ($chardata[$i]['type'] == 'AN') OR ($chardata[$i]['type'] == 'EN')) {
14556 $chardata[$i]['level'] += 1;
14558 } else {
14559 if ($chardata[$i]['type'] == 'R') {
14560 $chardata[$i]['level'] += 1;
14561 } elseif (($chardata[$i]['type'] == 'AN') OR ($chardata[$i]['type'] == 'EN')) {
14562 $chardata[$i]['level'] += 2;
14565 $maxlevel = max($chardata[$i]['level'],$maxlevel);
14568 // L1. On each line, reset the embedding level of the following characters to the paragraph embedding level:
14569 // 1. Segment separators,
14570 // 2. Paragraph separators,
14571 // 3. Any sequence of whitespace characters preceding a segment separator or paragraph separator, and
14572 // 4. Any sequence of white space characters at the end of the line.
14573 for ($i=0; $i < $numchars; ++$i) {
14574 if (($chardata[$i]['type'] == 'B') OR ($chardata[$i]['type'] == 'S')) {
14575 $chardata[$i]['level'] = $pel;
14576 } elseif ($chardata[$i]['type'] == 'WS') {
14577 $j = $i+1;
14578 while ($j < $numchars) {
14579 if ((($chardata[$j]['type'] == 'B') OR ($chardata[$j]['type'] == 'S')) OR
14580 (($j == ($numchars-1)) AND ($chardata[$j]['type'] == 'WS'))) {
14581 $chardata[$i]['level'] = $pel;
14582 break;
14583 } elseif ($chardata[$j]['type'] != 'WS') {
14584 break;
14586 ++$j;
14591 // Arabic Shaping
14592 // Cursively connected scripts, such as Arabic or Syriac, require the selection of positional character shapes that depend on adjacent characters. Shaping is logically applied after the Bidirectional Algorithm is used and is limited to characters within the same directional run.
14593 if ($arabic) {
14594 $endedletter = array(1569,1570,1571,1572,1573,1575,1577,1583,1584,1585,1586,1608,1688);
14595 $alfletter = array(1570,1571,1573,1575);
14596 $chardata2 = $chardata;
14597 $laaletter = false;
14598 $charAL = array();
14599 $x = 0;
14600 for ($i=0; $i < $numchars; ++$i) {
14601 if (($this->unicode->uni_type[$chardata[$i]['char']] == 'AL') OR ($chardata[$i]['char'] == 32) OR ($chardata[$i]['char'] == 8204)) {
14602 $charAL[$x] = $chardata[$i];
14603 $charAL[$x]['i'] = $i;
14604 $chardata[$i]['x'] = $x;
14605 ++$x;
14608 $numAL = $x;
14609 for ($i=0; $i < $numchars; ++$i) {
14610 $thischar = $chardata[$i];
14611 if ($i > 0) {
14612 $prevchar = $chardata[($i-1)];
14613 } else {
14614 $prevchar = false;
14616 if (($i+1) < $numchars) {
14617 $nextchar = $chardata[($i+1)];
14618 } else {
14619 $nextchar = false;
14621 if ($this->unicode->uni_type[$thischar['char']] == 'AL') {
14622 $x = $thischar['x'];
14623 if ($x > 0) {
14624 $prevchar = $charAL[($x-1)];
14625 } else {
14626 $prevchar = false;
14628 if (($x+1) < $numAL) {
14629 $nextchar = $charAL[($x+1)];
14630 } else {
14631 $nextchar = false;
14633 // if laa letter
14634 if (($prevchar !== false) AND ($prevchar['char'] == 1604) AND (in_array($thischar['char'], $alfletter))) {
14635 $arabicarr = $this->unicode->uni_laa_array;
14636 $laaletter = true;
14637 if ($x > 1) {
14638 $prevchar = $charAL[($x-2)];
14639 } else {
14640 $prevchar = false;
14642 } else {
14643 $arabicarr = $this->unicode->uni_arabicsubst;
14644 $laaletter = false;
14646 if (($prevchar !== false) AND ($nextchar !== false) AND
14647 (($this->unicode->uni_type[$prevchar['char']] == 'AL') OR ($this->unicode->uni_type[$prevchar['char']] == 'NSM')) AND
14648 (($this->unicode->uni_type[$nextchar['char']] == 'AL') OR ($this->unicode->uni_type[$nextchar['char']] == 'NSM')) AND
14649 ($prevchar['type'] == $thischar['type']) AND
14650 ($nextchar['type'] == $thischar['type']) AND
14651 ($nextchar['char'] != 1567)) {
14652 if (in_array($prevchar['char'], $endedletter)) {
14653 if (isset($arabicarr[$thischar['char']][2])) {
14654 // initial
14655 $chardata2[$i]['char'] = $arabicarr[$thischar['char']][2];
14657 } else {
14658 if (isset($arabicarr[$thischar['char']][3])) {
14659 // medial
14660 $chardata2[$i]['char'] = $arabicarr[$thischar['char']][3];
14663 } elseif (($nextchar !== false) AND
14664 (($this->unicode->uni_type[$nextchar['char']] == 'AL') OR ($this->unicode->uni_type[$nextchar['char']] == 'NSM')) AND
14665 ($nextchar['type'] == $thischar['type']) AND
14666 ($nextchar['char'] != 1567)) {
14667 if (isset($arabicarr[$chardata[$i]['char']][2])) {
14668 // initial
14669 $chardata2[$i]['char'] = $arabicarr[$thischar['char']][2];
14671 } elseif ((($prevchar !== false) AND
14672 (($this->unicode->uni_type[$prevchar['char']] == 'AL') OR ($this->unicode->uni_type[$prevchar['char']] == 'NSM')) AND
14673 ($prevchar['type'] == $thischar['type'])) OR
14674 (($nextchar !== false) AND ($nextchar['char'] == 1567))) {
14675 // final
14676 if (($i > 1) AND ($thischar['char'] == 1607) AND
14677 ($chardata[$i-1]['char'] == 1604) AND
14678 ($chardata[$i-2]['char'] == 1604)) {
14679 //Allah Word
14680 // mark characters to delete with false
14681 $chardata2[$i-2]['char'] = false;
14682 $chardata2[$i-1]['char'] = false;
14683 $chardata2[$i]['char'] = 65010;
14684 } else {
14685 if (($prevchar !== false) AND in_array($prevchar['char'], $endedletter)) {
14686 if (isset($arabicarr[$thischar['char']][0])) {
14687 // isolated
14688 $chardata2[$i]['char'] = $arabicarr[$thischar['char']][0];
14690 } else {
14691 if (isset($arabicarr[$thischar['char']][1])) {
14692 // final
14693 $chardata2[$i]['char'] = $arabicarr[$thischar['char']][1];
14697 } elseif (isset($arabicarr[$thischar['char']][0])) {
14698 // isolated
14699 $chardata2[$i]['char'] = $arabicarr[$thischar['char']][0];
14701 // if laa letter
14702 if ($laaletter) {
14703 // mark characters to delete with false
14704 $chardata2[($charAL[($x-1)]['i'])]['char'] = false;
14706 } // end if AL (Arabic Letter)
14707 } // end for each char
14709 * Combining characters that can occur with Arabic Shadda (0651 HEX, 1617 DEC) are replaced.
14710 * Putting the combining mark and shadda in the same glyph allows us to avoid the two marks overlapping each other in an illegible manner.
14712 for ($i = 0; $i < ($numchars-1); ++$i) {
14713 if (($chardata2[$i]['char'] == 1617) AND (isset($this->unicode->uni_diacritics[($chardata2[$i+1]['char'])]))) {
14714 // check if the subtitution font is defined on current font
14715 if (isset($this->CurrentFont['cw'][($this->unicode->uni_diacritics[($chardata2[$i+1]['char'])])])) {
14716 $chardata2[$i]['char'] = false;
14717 $chardata2[$i+1]['char'] = $this->unicode->uni_diacritics[($chardata2[$i+1]['char'])];
14721 // remove marked characters
14722 foreach ($chardata2 as $key => $value) {
14723 if ($value['char'] === false) {
14724 unset($chardata2[$key]);
14727 $chardata = array_values($chardata2);
14728 $numchars = count($chardata);
14729 unset($chardata2);
14730 unset($arabicarr);
14731 unset($laaletter);
14732 unset($charAL);
14735 // L2. From the highest level found in the text to the lowest odd level on each line, including intermediate levels not actually present in the text, reverse any contiguous sequence of characters that are at that level or higher.
14736 for ($j=$maxlevel; $j > 0; $j--) {
14737 $ordarray = Array();
14738 $revarr = Array();
14739 $onlevel = false;
14740 for ($i=0; $i < $numchars; ++$i) {
14741 if ($chardata[$i]['level'] >= $j) {
14742 $onlevel = true;
14743 if (isset($this->unicode->uni_mirror[$chardata[$i]['char']])) {
14744 // L4. A character is depicted by a mirrored glyph if and only if (a) the resolved directionality of that character is R, and (b) the Bidi_Mirrored property value of that character is true.
14745 $chardata[$i]['char'] = $this->unicode->uni_mirror[$chardata[$i]['char']];
14747 $revarr[] = $chardata[$i];
14748 } else {
14749 if ($onlevel) {
14750 $revarr = array_reverse($revarr);
14751 $ordarray = array_merge($ordarray, $revarr);
14752 $revarr = Array();
14753 $onlevel = false;
14755 $ordarray[] = $chardata[$i];
14758 if ($onlevel) {
14759 $revarr = array_reverse($revarr);
14760 $ordarray = array_merge($ordarray, $revarr);
14762 $chardata = $ordarray;
14765 $ordarray = array();
14766 for ($i=0; $i < $numchars; ++$i) {
14767 $ordarray[] = $chardata[$i]['char'];
14768 // store char values for subsetting
14769 $this->CurrentFont['subsetchars'][$chardata[$i]['char']] = true;
14771 // update font subsetchars
14772 $this->setFontSubBuffer($this->CurrentFont['fontkey'], 'subsetchars', $this->CurrentFont['subsetchars']);
14773 return $ordarray;
14776 // END OF BIDIRECTIONAL TEXT SECTION -------------------
14779 * Encode a name object.
14780 * @param $name (string) Name object to encode.
14781 * @return (string) Encoded name object.
14782 * @protected
14783 * @author Nicola Asuni
14784 * @since 5.9.097 (2011-06-23)
14786 protected function encodeNameObject($name) {
14787 $escname = '';
14788 $length = strlen($name);
14789 for ($i = 0; $i < $length; ++$i) {
14790 $chr = $name{$i};
14791 if (preg_match('/[0-9a-zA-Z]/', $chr) == 1) {
14792 $escname .= $chr;
14793 } else {
14794 $escname .= sprintf('#%02X', ord($chr));
14797 return $escname;
14801 * Add a Named Destination.
14802 * NOTE: destination names are unique, so only last entry will be saved.
14803 * @param $name (string) Destination name.
14804 * @param $y (float) Y position in user units of the destiantion on the selected page (default = -1 = current position; 0 = page start;).
14805 * @param $page (int) Target page number (leave empty for current page).
14806 * @return (string) Stripped named destination identifier or false in case of error.
14807 * @public
14808 * @author Christian Deligant, Nicola Asuni
14809 * @since 5.9.097 (2011-06-23)
14811 public function setDestination($name, $y=-1, $page='') {
14812 // remove unsupported characters
14813 $name = $this->encodeNameObject($name);
14814 if ($this->empty_string($name)) {
14815 return false;
14817 if ($y == -1) {
14818 $y = $this->GetY();
14820 if (empty($page)) {
14821 $page = $this->PageNo();
14822 if (empty($page)) {
14823 return;
14826 $this->dests[$name] = array('y' => $y, 'p' => $page);
14827 return $name;
14831 * Return the Named Destination array.
14832 * @return (array) Named Destination array.
14833 * @public
14834 * @author Nicola Asuni
14835 * @since 5.9.097 (2011-06-23)
14837 public function getDestination() {
14838 return $this->dests;
14842 * Create a javascript PDF string.
14843 * @protected
14844 * @author Johannes Güntert, Nicola Asuni
14845 * @since 5.9.098 (2011-06-23)
14847 protected function _putdests() {
14848 if (empty($this->dests)) {
14849 return;
14851 $this->n_dests = $this->_newobj();
14852 $out = ' <<';
14853 foreach($this->dests as $name => $o) {
14854 $out .= ' /'.$name.' '.sprintf('[%u 0 R /XYZ 0 %.2F null]', $this->page_obj_id[($o['p'])], ($this->pagedim[$o['p']]['h'] - ($o['y'] * $this->k)));
14856 $out .= ' >>';
14857 $out .= "\n".'endobj';
14858 $this->_out($out);
14862 * Adds a bookmark - alias for Bookmark().
14863 * @param $txt (string) Bookmark description.
14864 * @param $level (int) Bookmark level (minimum value is 0).
14865 * @param $y (float) Y position in user units of the bookmark on the selected page (default = -1 = current position; 0 = page start;).
14866 * @param $page (int) Target page number (leave empty for current page).
14867 * @param $style (string) Font style: B = Bold, I = Italic, BI = Bold + Italic.
14868 * @param $color (array) RGB color array (values from 0 to 255).
14869 * @public
14871 public function setBookmark($txt, $level=0, $y=-1, $page='', $style='', $color=array(0,0,0)) {
14872 $this->Bookmark($txt, $level, $y, $page, $style, $color);
14876 * Adds a bookmark.
14877 * @param $txt (string) Bookmark description.
14878 * @param $level (int) Bookmark level (minimum value is 0).
14879 * @param $y (float) Y position in user units of the bookmark on the selected page (default = -1 = current position; 0 = page start;).
14880 * @param $page (int) Target page number (leave empty for current page).
14881 * @param $style (string) Font style: B = Bold, I = Italic, BI = Bold + Italic.
14882 * @param $color (array) RGB color array (values from 0 to 255).
14883 * @public
14884 * @author Olivier Plathey, Nicola Asuni
14885 * @since 2.1.002 (2008-02-12)
14887 public function Bookmark($txt, $level=0, $y=-1, $page='', $style='', $color=array(0,0,0)) {
14888 if ($level < 0) {
14889 $level = 0;
14891 if (isset($this->outlines[0])) {
14892 $lastoutline = end($this->outlines);
14893 $maxlevel = $lastoutline['l'] + 1;
14894 } else {
14895 $maxlevel = 0;
14897 if ($level > $maxlevel) {
14898 $level = $maxlevel;
14900 if ($y == -1) {
14901 $y = $this->GetY();
14903 if (empty($page)) {
14904 $page = $this->PageNo();
14905 if (empty($page)) {
14906 return;
14909 $this->outlines[] = array('t' => $txt, 'l' => $level, 'y' => $y, 'p' => $page, 's' => strtoupper($style), 'c' => $color);
14913 * Create a bookmark PDF string.
14914 * @protected
14915 * @author Olivier Plathey, Nicola Asuni
14916 * @since 2.1.002 (2008-02-12)
14918 protected function _putbookmarks() {
14919 $nb = count($this->outlines);
14920 if ($nb == 0) {
14921 return;
14923 // get sorting columns
14924 $outline_p = array();
14925 $outline_y = array();
14926 foreach ($this->outlines as $key => $row) {
14927 $outline_p[$key] = $row['p'];
14928 $outline_k[$key] = $key;
14930 // sort outlines by page and original position
14931 array_multisort($outline_p, SORT_NUMERIC, SORT_ASC, $outline_k, SORT_NUMERIC, SORT_ASC, $this->outlines);
14932 $lru = array();
14933 $level = 0;
14934 foreach ($this->outlines as $i => $o) {
14935 if ($o['l'] > 0) {
14936 $parent = $lru[($o['l'] - 1)];
14937 //Set parent and last pointers
14938 $this->outlines[$i]['parent'] = $parent;
14939 $this->outlines[$parent]['last'] = $i;
14940 if ($o['l'] > $level) {
14941 //Level increasing: set first pointer
14942 $this->outlines[$parent]['first'] = $i;
14944 } else {
14945 $this->outlines[$i]['parent'] = $nb;
14947 if (($o['l'] <= $level) AND ($i > 0)) {
14948 //Set prev and next pointers
14949 $prev = $lru[$o['l']];
14950 $this->outlines[$prev]['next'] = $i;
14951 $this->outlines[$i]['prev'] = $prev;
14953 $lru[$o['l']] = $i;
14954 $level = $o['l'];
14956 //Outline items
14957 $n = $this->n + 1;
14958 $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';
14959 foreach ($this->outlines as $i => $o) {
14960 if (isset($this->page_obj_id[($o['p'])])) {
14961 $oid = $this->_newobj();
14962 // covert HTML title to string
14963 $title = preg_replace($nltags, "\n", $o['t']);
14964 $title = preg_replace("/[\r]+/si", '', $title);
14965 $title = preg_replace("/[\n]+/si", "\n", $title);
14966 $title = strip_tags($title);
14967 $title = $this->stringTrim($title);
14968 $out = '<</Title '.$this->_textstring($title, $oid);
14969 $out .= ' /Parent '.($n + $o['parent']).' 0 R';
14970 if (isset($o['prev'])) {
14971 $out .= ' /Prev '.($n + $o['prev']).' 0 R';
14973 if (isset($o['next'])) {
14974 $out .= ' /Next '.($n + $o['next']).' 0 R';
14976 if (isset($o['first'])) {
14977 $out .= ' /First '.($n + $o['first']).' 0 R';
14979 if (isset($o['last'])) {
14980 $out .= ' /Last '.($n + $o['last']).' 0 R';
14982 $out .= ' '.sprintf('/Dest [%u 0 R /XYZ 0 %.2F null]', $this->page_obj_id[($o['p'])], ($this->pagedim[$o['p']]['h'] - ($o['y'] * $this->k)));
14983 // set font style
14984 $style = 0;
14985 if (!empty($o['s'])) {
14986 // bold
14987 if (strpos($o['s'], 'B') !== false) {
14988 $style |= 2;
14990 // oblique
14991 if (strpos($o['s'], 'I') !== false) {
14992 $style |= 1;
14995 $out .= sprintf(' /F %d', $style);
14996 // set bookmark color
14997 if (isset($o['c']) AND is_array($o['c']) AND (count($o['c']) == 3)) {
14998 $color = array_values($o['c']);
14999 $out .= sprintf(' /C [%.3F %.3F %.3F]', ($color[0] / 255), ($color[1] / 255), ($color[2] / 255));
15000 } else {
15001 // black
15002 $out .= ' /C [0.0 0.0 0.0]';
15004 $out .= ' /Count 0'; // normally closed item
15005 $out .= ' >>';
15006 $out .= "\n".'endobj';
15007 $this->_out($out);
15010 //Outline root
15011 $this->OutlineRoot = $this->_newobj();
15012 $this->_out('<< /Type /Outlines /First '.$n.' 0 R /Last '.($n + $lru[0]).' 0 R >>'."\n".'endobj');
15015 // --- JAVASCRIPT ------------------------------------------------------
15018 * Adds a javascript
15019 * @param $script (string) Javascript code
15020 * @public
15021 * @author Johannes Güntert, Nicola Asuni
15022 * @since 2.1.002 (2008-02-12)
15024 public function IncludeJS($script) {
15025 $this->javascript .= $script;
15029 * Adds a javascript object and return object ID
15030 * @param $script (string) Javascript code
15031 * @param $onload (boolean) if true executes this object when opening the document
15032 * @return int internal object ID
15033 * @public
15034 * @author Nicola Asuni
15035 * @since 4.8.000 (2009-09-07)
15037 public function addJavascriptObject($script, $onload=false) {
15038 ++$this->n;
15039 $this->js_objects[$this->n] = array('n' => $this->n, 'js' => $script, 'onload' => $onload);
15040 return $this->n;
15044 * Create a javascript PDF string.
15045 * @protected
15046 * @author Johannes Güntert, Nicola Asuni
15047 * @since 2.1.002 (2008-02-12)
15049 protected function _putjavascript() {
15050 if (empty($this->javascript) AND empty($this->js_objects)) {
15051 return;
15053 if (strpos($this->javascript, 'this.addField') > 0) {
15054 if (!$this->ur['enabled']) {
15055 //$this->setUserRights();
15057 // the following two lines are used to avoid form fields duplication after saving
15058 // The addField method only works when releasing user rights (UR3)
15059 $jsa = sprintf("ftcpdfdocsaved=this.addField('%s','%s',%d,[%.2F,%.2F,%.2F,%.2F]);", 'tcpdfdocsaved', 'text', 0, 0, 1, 0, 1);
15060 $jsb = "getField('tcpdfdocsaved').value='saved';";
15061 $this->javascript = $jsa."\n".$this->javascript."\n".$jsb;
15063 $this->n_js = $this->_newobj();
15064 $out = ' << /Names [';
15065 if (!empty($this->javascript)) {
15066 $out .= ' (EmbeddedJS) '.($this->n + 1).' 0 R';
15068 if (!empty($this->js_objects)) {
15069 foreach ($this->js_objects as $key => $val) {
15070 if ($val['onload']) {
15071 $out .= ' (JS'.$key.') '.$key.' 0 R';
15075 $out .= ' ] >>';
15076 $out .= "\n".'endobj';
15077 $this->_out($out);
15078 // default Javascript object
15079 if (!empty($this->javascript)) {
15080 $obj_id = $this->_newobj();
15081 $out = '<< /S /JavaScript';
15082 $out .= ' /JS '.$this->_textstring($this->javascript, $obj_id);
15083 $out .= ' >>';
15084 $out .= "\n".'endobj';
15085 $this->_out($out);
15087 // additional Javascript objects
15088 if (!empty($this->js_objects)) {
15089 foreach ($this->js_objects as $key => $val) {
15090 $out = $this->_getobj($key)."\n".' << /S /JavaScript /JS '.$this->_textstring($val['js'], $key).' >>'."\n".'endobj';
15091 $this->_out($out);
15097 * Convert color to javascript color.
15098 * @param $color (string) color name or "#RRGGBB"
15099 * @protected
15100 * @author Denis Van Nuffelen, Nicola Asuni
15101 * @since 2.1.002 (2008-02-12)
15103 protected function _JScolor($color) {
15104 static $aColors = array('transparent', 'black', 'white', 'red', 'green', 'blue', 'cyan', 'magenta', 'yellow', 'dkGray', 'gray', 'ltGray');
15105 if (substr($color,0,1) == '#') {
15106 return sprintf("['RGB',%.3F,%.3F,%.3F]", hexdec(substr($color,1,2))/255, hexdec(substr($color,3,2))/255, hexdec(substr($color,5,2))/255);
15108 if (!in_array($color,$aColors)) {
15109 $this->Error('Invalid color: '.$color);
15111 return 'color.'.$color;
15115 * Adds a javascript form field.
15116 * @param $type (string) field type
15117 * @param $name (string) field name
15118 * @param $x (int) horizontal position
15119 * @param $y (int) vertical position
15120 * @param $w (int) width
15121 * @param $h (int) height
15122 * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
15123 * @protected
15124 * @author Denis Van Nuffelen, Nicola Asuni
15125 * @since 2.1.002 (2008-02-12)
15127 protected function _addfield($type, $name, $x, $y, $w, $h, $prop) {
15128 if ($this->rtl) {
15129 $x = $x - $w;
15131 // the followind avoid fields duplication after saving the document
15132 $this->javascript .= "if (getField('tcpdfdocsaved').value != 'saved') {";
15133 $k = $this->k;
15134 $this->javascript .= sprintf("f".$name."=this.addField('%s','%s',%u,[%.2F,%.2F,%.2F,%.2F]);", $name, $type, $this->PageNo()-1, $x*$k, ($this->h-$y)*$k+1, ($x+$w)*$k, ($this->h-$y-$h)*$k+1)."\n";
15135 $this->javascript .= 'f'.$name.'.textSize='.$this->FontSizePt.";\n";
15136 while (list($key, $val) = each($prop)) {
15137 if (strcmp(substr($key, -5), 'Color') == 0) {
15138 $val = $this->_JScolor($val);
15139 } else {
15140 $val = "'".$val."'";
15142 $this->javascript .= 'f'.$name.'.'.$key.'='.$val.";\n";
15144 if ($this->rtl) {
15145 $this->x -= $w;
15146 } else {
15147 $this->x += $w;
15149 $this->javascript .= '}';
15152 // --- FORM FIELDS -----------------------------------------------------
15155 * Convert JavaScript form fields properties array to Annotation Properties array.
15156 * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
15157 * @return array of annotation properties
15158 * @protected
15159 * @author Nicola Asuni
15160 * @since 4.8.000 (2009-09-06)
15162 protected function getAnnotOptFromJSProp($prop) {
15163 if (isset($prop['aopt']) AND is_array($prop['aopt'])) {
15164 // the annotation options area lready defined
15165 return $prop['aopt'];
15167 $opt = array(); // value to be returned
15168 // alignment: Controls how the text is laid out within the text field.
15169 if (isset($prop['alignment'])) {
15170 switch ($prop['alignment']) {
15171 case 'left': {
15172 $opt['q'] = 0;
15173 break;
15175 case 'center': {
15176 $opt['q'] = 1;
15177 break;
15179 case 'right': {
15180 $opt['q'] = 2;
15181 break;
15183 default: {
15184 $opt['q'] = ($this->rtl)?2:0;
15185 break;
15189 // lineWidth: Specifies the thickness of the border when stroking the perimeter of a field's rectangle.
15190 if (isset($prop['lineWidth'])) {
15191 $linewidth = intval($prop['lineWidth']);
15192 } else {
15193 $linewidth = 1;
15195 // borderStyle: The border style for a field.
15196 if (isset($prop['borderStyle'])) {
15197 switch ($prop['borderStyle']) {
15198 case 'border.d':
15199 case 'dashed': {
15200 $opt['border'] = array(0, 0, $linewidth, array(3, 2));
15201 $opt['bs'] = array('w'=>$linewidth, 's'=>'D', 'd'=>array(3, 2));
15202 break;
15204 case 'border.b':
15205 case 'beveled': {
15206 $opt['border'] = array(0, 0, $linewidth);
15207 $opt['bs'] = array('w'=>$linewidth, 's'=>'B');
15208 break;
15210 case 'border.i':
15211 case 'inset': {
15212 $opt['border'] = array(0, 0, $linewidth);
15213 $opt['bs'] = array('w'=>$linewidth, 's'=>'I');
15214 break;
15216 case 'border.u':
15217 case 'underline': {
15218 $opt['border'] = array(0, 0, $linewidth);
15219 $opt['bs'] = array('w'=>$linewidth, 's'=>'U');
15220 break;
15222 case 'border.s':
15223 case 'solid': {
15224 $opt['border'] = array(0, 0, $linewidth);
15225 $opt['bs'] = array('w'=>$linewidth, 's'=>'S');
15226 break;
15228 default: {
15229 break;
15233 if (isset($prop['border']) AND is_array($prop['border'])) {
15234 $opt['border'] = $prop['border'];
15236 if (!isset($opt['mk'])) {
15237 $opt['mk'] = array();
15239 if (!isset($opt['mk']['if'])) {
15240 $opt['mk']['if'] = array();
15242 $opt['mk']['if']['a'] = array(0.5, 0.5);
15243 // buttonAlignX: Controls how space is distributed from the left of the button face with respect to the icon.
15244 if (isset($prop['buttonAlignX'])) {
15245 $opt['mk']['if']['a'][0] = $prop['buttonAlignX'];
15247 // buttonAlignY: Controls how unused space is distributed from the bottom of the button face with respect to the icon.
15248 if (isset($prop['buttonAlignY'])) {
15249 $opt['mk']['if']['a'][1] = $prop['buttonAlignY'];
15251 // buttonFitBounds: If true, the extent to which the icon may be scaled is set to the bounds of the button field.
15252 if (isset($prop['buttonFitBounds']) AND ($prop['buttonFitBounds'] == 'true')) {
15253 $opt['mk']['if']['fb'] = true;
15255 // buttonScaleHow: Controls how the icon is scaled (if necessary) to fit inside the button face.
15256 if (isset($prop['buttonScaleHow'])) {
15257 switch ($prop['buttonScaleHow']) {
15258 case 'scaleHow.proportional': {
15259 $opt['mk']['if']['s'] = 'P';
15260 break;
15262 case 'scaleHow.anamorphic': {
15263 $opt['mk']['if']['s'] = 'A';
15264 break;
15268 // buttonScaleWhen: Controls when an icon is scaled to fit inside the button face.
15269 if (isset($prop['buttonScaleWhen'])) {
15270 switch ($prop['buttonScaleWhen']) {
15271 case 'scaleWhen.always': {
15272 $opt['mk']['if']['sw'] = 'A';
15273 break;
15275 case 'scaleWhen.never': {
15276 $opt['mk']['if']['sw'] = 'N';
15277 break;
15279 case 'scaleWhen.tooBig': {
15280 $opt['mk']['if']['sw'] = 'B';
15281 break;
15283 case 'scaleWhen.tooSmall': {
15284 $opt['mk']['if']['sw'] = 'S';
15285 break;
15289 // buttonPosition: Controls how the text and the icon of the button are positioned with respect to each other within the button face.
15290 if (isset($prop['buttonPosition'])) {
15291 switch ($prop['buttonPosition']) {
15292 case 0:
15293 case 'position.textOnly': {
15294 $opt['mk']['tp'] = 0;
15295 break;
15297 case 1:
15298 case 'position.iconOnly': {
15299 $opt['mk']['tp'] = 1;
15300 break;
15302 case 2:
15303 case 'position.iconTextV': {
15304 $opt['mk']['tp'] = 2;
15305 break;
15307 case 3:
15308 case 'position.textIconV': {
15309 $opt['mk']['tp'] = 3;
15310 break;
15312 case 4:
15313 case 'position.iconTextH': {
15314 $opt['mk']['tp'] = 4;
15315 break;
15317 case 5:
15318 case 'position.textIconH': {
15319 $opt['mk']['tp'] = 5;
15320 break;
15322 case 6:
15323 case 'position.overlay': {
15324 $opt['mk']['tp'] = 6;
15325 break;
15329 // fillColor: Specifies the background color for a field.
15330 if (isset($prop['fillColor'])) {
15331 if (is_array($prop['fillColor'])) {
15332 $opt['mk']['bg'] = $prop['fillColor'];
15333 } else {
15334 $opt['mk']['bg'] = $this->convertHTMLColorToDec($prop['fillColor']);
15337 // strokeColor: Specifies the stroke color for a field that is used to stroke the rectangle of the field with a line as large as the line width.
15338 if (isset($prop['strokeColor'])) {
15339 if (is_array($prop['strokeColor'])) {
15340 $opt['mk']['bc'] = $prop['strokeColor'];
15341 } else {
15342 $opt['mk']['bc'] = $this->convertHTMLColorToDec($prop['strokeColor']);
15345 // rotation: The rotation of a widget in counterclockwise increments.
15346 if (isset($prop['rotation'])) {
15347 $opt['mk']['r'] = $prop['rotation'];
15349 // charLimit: Limits the number of characters that a user can type into a text field.
15350 if (isset($prop['charLimit'])) {
15351 $opt['maxlen'] = intval($prop['charLimit']);
15353 if (!isset($ff)) {
15354 $ff = 0;
15356 // readonly: The read-only characteristic of a field. If a field is read-only, the user can see the field but cannot change it.
15357 if (isset($prop['readonly']) AND ($prop['readonly'] == 'true')) {
15358 $ff += 1 << 0;
15360 // required: Specifies whether a field requires a value.
15361 if (isset($prop['required']) AND ($prop['required'] == 'true')) {
15362 $ff += 1 << 1;
15364 // multiline: Controls how text is wrapped within the field.
15365 if (isset($prop['multiline']) AND ($prop['multiline'] == 'true')) {
15366 $ff += 1 << 12;
15368 // password: Specifies whether the field should display asterisks when data is entered in the field.
15369 if (isset($prop['password']) AND ($prop['password'] == 'true')) {
15370 $ff += 1 << 13;
15372 // NoToggleToOff: If set, exactly one radio button shall be selected at all times; selecting the currently selected button has no effect.
15373 if (isset($prop['NoToggleToOff']) AND ($prop['NoToggleToOff'] == 'true')) {
15374 $ff += 1 << 14;
15376 // Radio: If set, the field is a set of radio buttons.
15377 if (isset($prop['Radio']) AND ($prop['Radio'] == 'true')) {
15378 $ff += 1 << 15;
15380 // Pushbutton: If set, the field is a pushbutton that does not retain a permanent value.
15381 if (isset($prop['Pushbutton']) AND ($prop['Pushbutton'] == 'true')) {
15382 $ff += 1 << 16;
15384 // Combo: If set, the field is a combo box; if clear, the field is a list box.
15385 if (isset($prop['Combo']) AND ($prop['Combo'] == 'true')) {
15386 $ff += 1 << 17;
15388 // editable: Controls whether a combo box is editable.
15389 if (isset($prop['editable']) AND ($prop['editable'] == 'true')) {
15390 $ff += 1 << 18;
15392 // Sort: If set, the field's option items shall be sorted alphabetically.
15393 if (isset($prop['Sort']) AND ($prop['Sort'] == 'true')) {
15394 $ff += 1 << 19;
15396 // fileSelect: If true, sets the file-select flag in the Options tab of the text field (Field is Used for File Selection).
15397 if (isset($prop['fileSelect']) AND ($prop['fileSelect'] == 'true')) {
15398 $ff += 1 << 20;
15400 // multipleSelection: If true, indicates that a list box allows a multiple selection of items.
15401 if (isset($prop['multipleSelection']) AND ($prop['multipleSelection'] == 'true')) {
15402 $ff += 1 << 21;
15404 // doNotSpellCheck: If true, spell checking is not performed on this editable text field.
15405 if (isset($prop['doNotSpellCheck']) AND ($prop['doNotSpellCheck'] == 'true')) {
15406 $ff += 1 << 22;
15408 // doNotScroll: If true, the text field does not scroll and the user, therefore, is limited by the rectangular region designed for the field.
15409 if (isset($prop['doNotScroll']) AND ($prop['doNotScroll'] == 'true')) {
15410 $ff += 1 << 23;
15412 // comb: If set to true, the field background is drawn as series of boxes (one for each character in the value of the field) and each character of the content is drawn within those boxes. The number of boxes drawn is determined from the charLimit property. It applies only to text fields. The setter will also raise if any of the following field properties are also set multiline, password, and fileSelect. A side-effect of setting this property is that the doNotScroll property is also set.
15413 if (isset($prop['comb']) AND ($prop['comb'] == 'true')) {
15414 $ff += 1 << 24;
15416 // radiosInUnison: If false, even if a group of radio buttons have the same name and export value, they behave in a mutually exclusive fashion, like HTML radio buttons.
15417 if (isset($prop['radiosInUnison']) AND ($prop['radiosInUnison'] == 'true')) {
15418 $ff += 1 << 25;
15420 // richText: If true, the field allows rich text formatting.
15421 if (isset($prop['richText']) AND ($prop['richText'] == 'true')) {
15422 $ff += 1 << 25;
15424 // commitOnSelChange: Controls whether a field value is committed after a selection change.
15425 if (isset($prop['commitOnSelChange']) AND ($prop['commitOnSelChange'] == 'true')) {
15426 $ff += 1 << 26;
15428 $opt['ff'] = $ff;
15429 // defaultValue: The default value of a field - that is, the value that the field is set to when the form is reset.
15430 if (isset($prop['defaultValue'])) {
15431 $opt['dv'] = $prop['defaultValue'];
15433 $f = 4; // default value for annotation flags
15434 // readonly: The read-only characteristic of a field. If a field is read-only, the user can see the field but cannot change it.
15435 if (isset($prop['readonly']) AND ($prop['readonly'] == 'true')) {
15436 $f += 1 << 6;
15438 // display: Controls whether the field is hidden or visible on screen and in print.
15439 if (isset($prop['display'])) {
15440 if ($prop['display'] == 'display.visible') {
15442 } elseif ($prop['display'] == 'display.hidden') {
15443 $f += 1 << 1;
15444 } elseif ($prop['display'] == 'display.noPrint') {
15445 $f -= 1 << 2;
15446 } elseif ($prop['display'] == 'display.noView') {
15447 $f += 1 << 5;
15450 $opt['f'] = $f;
15451 // currentValueIndices: Reads and writes single or multiple values of a list box or combo box.
15452 if (isset($prop['currentValueIndices']) AND is_array($prop['currentValueIndices'])) {
15453 $opt['i'] = $prop['currentValueIndices'];
15455 // value: The value of the field data that the user has entered.
15456 if (isset($prop['value'])) {
15457 if (is_array($prop['value'])) {
15458 $opt['opt'] = array();
15459 foreach ($prop['value'] AS $key => $optval) {
15460 // exportValues: An array of strings representing the export values for the field.
15461 if (isset($prop['exportValues'][$key])) {
15462 $opt['opt'][$key] = array($prop['exportValues'][$key], $prop['value'][$key]);
15463 } else {
15464 $opt['opt'][$key] = $prop['value'][$key];
15467 } else {
15468 $opt['v'] = $prop['value'];
15471 // richValue: This property specifies the text contents and formatting of a rich text field.
15472 if (isset($prop['richValue'])) {
15473 $opt['rv'] = $prop['richValue'];
15475 // submitName: If nonempty, used during form submission instead of name. Only applicable if submitting in HTML format (that is, URL-encoded).
15476 if (isset($prop['submitName'])) {
15477 $opt['tm'] = $prop['submitName'];
15479 // name: Fully qualified field name.
15480 if (isset($prop['name'])) {
15481 $opt['t'] = $prop['name'];
15483 // userName: The user name (short description string) of the field.
15484 if (isset($prop['userName'])) {
15485 $opt['tu'] = $prop['userName'];
15487 // highlight: Defines how a button reacts when a user clicks it.
15488 if (isset($prop['highlight'])) {
15489 switch ($prop['highlight']) {
15490 case 'none':
15491 case 'highlight.n': {
15492 $opt['h'] = 'N';
15493 break;
15495 case 'invert':
15496 case 'highlight.i': {
15497 $opt['h'] = 'i';
15498 break;
15500 case 'push':
15501 case 'highlight.p': {
15502 $opt['h'] = 'P';
15503 break;
15505 case 'outline':
15506 case 'highlight.o': {
15507 $opt['h'] = 'O';
15508 break;
15512 // Unsupported options:
15513 // - calcOrderIndex: Changes the calculation order of fields in the document.
15514 // - delay: Delays the redrawing of a field's appearance.
15515 // - defaultStyle: This property defines the default style attributes for the form field.
15516 // - style: Allows the user to set the glyph style of a check box or radio button.
15517 // - textColor, textFont, textSize
15518 return $opt;
15522 * Set default properties for form fields.
15523 * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
15524 * @public
15525 * @author Nicola Asuni
15526 * @since 4.8.000 (2009-09-06)
15528 public function setFormDefaultProp($prop=array()) {
15529 $this->default_form_prop = $prop;
15533 * Return the default properties for form fields.
15534 * @return array $prop javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
15535 * @public
15536 * @author Nicola Asuni
15537 * @since 4.8.000 (2009-09-06)
15539 public function getFormDefaultProp() {
15540 return $this->default_form_prop;
15544 * Creates a text field
15545 * @param $name (string) field name
15546 * @param $w (float) Width of the rectangle
15547 * @param $h (float) Height of the rectangle
15548 * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
15549 * @param $opt (array) annotation parameters. Possible values are described on official PDF32000_2008 reference.
15550 * @param $x (float) Abscissa of the upper-left corner of the rectangle
15551 * @param $y (float) Ordinate of the upper-left corner of the rectangle
15552 * @param $js (boolean) if true put the field using JavaScript (requires Acrobat Writer to be rendered).
15553 * @public
15554 * @author Nicola Asuni
15555 * @since 4.8.000 (2009-09-07)
15557 public function TextField($name, $w, $h, $prop=array(), $opt=array(), $x='', $y='', $js=false) {
15558 if ($x === '') {
15559 $x = $this->x;
15561 if ($y === '') {
15562 $y = $this->y;
15564 // check page for no-write regions and adapt page margins if necessary
15565 list($x, $y) = $this->checkPageRegions($h, $x, $y);
15566 if ($js) {
15567 $this->_addfield('text', $name, $x, $y, $w, $h, $prop);
15568 return;
15570 // get default style
15571 $prop = array_merge($this->getFormDefaultProp(), $prop);
15572 // get annotation data
15573 $popt = $this->getAnnotOptFromJSProp($prop);
15574 // set default appearance stream
15575 $this->annotation_fonts[$this->CurrentFont['fontkey']] = $this->CurrentFont['i'];
15576 $fontstyle = sprintf('/F%d %.2F Tf %s', $this->CurrentFont['i'], $this->FontSizePt, $this->TextColor);
15577 $popt['da'] = $fontstyle;
15578 $popt['ap'] = array();
15579 $popt['ap']['n'] = 'q BT '.$fontstyle.' ET Q';
15580 // merge options
15581 $opt = array_merge($popt, $opt);
15582 // remove some conflicting options
15583 unset($opt['bs']);
15584 // set remaining annotation data
15585 $opt['Subtype'] = 'Widget';
15586 $opt['ft'] = 'Tx';
15587 $opt['t'] = $name;
15589 Additional annotation's parameters (check _putannotsobj() method):
15590 //$opt['f']
15591 //$opt['ap']
15592 //$opt['as']
15593 //$opt['bs']
15594 //$opt['be']
15595 //$opt['c']
15596 //$opt['border']
15597 //$opt['h']
15598 //$opt['mk']
15599 //$opt['mk']['r']
15600 //$opt['mk']['bc']
15601 //$opt['mk']['bg']
15602 //$opt['mk']['ca']
15603 //$opt['mk']['rc']
15604 //$opt['mk']['ac']
15605 //$opt['mk']['i']
15606 //$opt['mk']['ri']
15607 //$opt['mk']['ix']
15608 //$opt['mk']['if']
15609 //$opt['mk']['if']['sw']
15610 //$opt['mk']['if']['s']
15611 //$opt['mk']['if']['a']
15612 //$opt['mk']['if']['fb']
15613 //$opt['mk']['tp']
15614 //$opt['tu']
15615 //$opt['tm']
15616 //$opt['ff']
15617 //$opt['v']
15618 //$opt['dv']
15619 //$opt['a']
15620 //$opt['aa']
15621 //$opt['q']
15623 $this->Annotation($x, $y, $w, $h, $name, $opt, 0);
15624 if ($this->rtl) {
15625 $this->x -= $w;
15626 } else {
15627 $this->x += $w;
15632 * Creates a RadioButton field
15633 * @param $name (string) field name
15634 * @param $w (int) width
15635 * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
15636 * @param $opt (array) annotation parameters. Possible values are described on official PDF32000_2008 reference.
15637 * @param $onvalue (string) value to be returned if selected.
15638 * @param $checked (boolean) define the initial state.
15639 * @param $x (float) Abscissa of the upper-left corner of the rectangle
15640 * @param $y (float) Ordinate of the upper-left corner of the rectangle
15641 * @param $js (boolean) if true put the field using JavaScript (requires Acrobat Writer to be rendered).
15642 * @public
15643 * @author Nicola Asuni
15644 * @since 4.8.000 (2009-09-07)
15646 public function RadioButton($name, $w, $prop=array(), $opt=array(), $onvalue='On', $checked=false, $x='', $y='', $js=false) {
15647 if ($x === '') {
15648 $x = $this->x;
15650 if ($y === '') {
15651 $y = $this->y;
15653 // check page for no-write regions and adapt page margins if necessary
15654 list($x, $y) = $this->checkPageRegions($w, $x, $y);
15655 if ($js) {
15656 $this->_addfield('radiobutton', $name, $x, $y, $w, $w, $prop);
15657 return;
15659 if ($this->empty_string($onvalue)) {
15660 $onvalue = 'On';
15662 if ($checked) {
15663 $defval = $onvalue;
15664 } else {
15665 $defval = 'Off';
15667 // set data for parent group
15668 if (!isset($this->radiobutton_groups[$this->page])) {
15669 $this->radiobutton_groups[$this->page] = array();
15671 if (!isset($this->radiobutton_groups[$this->page][$name])) {
15672 $this->radiobutton_groups[$this->page][$name] = array();
15673 ++$this->n;
15674 $this->radiobutton_groups[$this->page][$name]['n'] = $this->n;
15675 $this->radio_groups[] = $this->n;
15676 $kid = ($this->n + 2);
15677 } else {
15678 $kid = ($this->n + 1);
15680 // save object ID to be added on Kids entry on parent object
15681 $this->radiobutton_groups[$this->page][$name][] = array('kid' => $kid, 'def' => $defval);
15682 // get default style
15683 $prop = array_merge($this->getFormDefaultProp(), $prop);
15684 $prop['NoToggleToOff'] = 'true';
15685 $prop['Radio'] = 'true';
15686 $prop['borderStyle'] = 'inset';
15687 // get annotation data
15688 $popt = $this->getAnnotOptFromJSProp($prop);
15689 // set additional default values
15690 $font = 'zapfdingbats';
15691 $this->AddFont($font);
15692 $tmpfont = $this->getFontBuffer($font);
15693 $this->annotation_fonts[$tmpfont['fontkey']] = $tmpfont['i'];
15694 $fontstyle = sprintf('/F%d %.2F Tf %s', $tmpfont['i'], $this->FontSizePt, $this->TextColor);
15695 $popt['da'] = $fontstyle;
15696 $popt['ap'] = array();
15697 $popt['ap']['n'] = array();
15698 $popt['ap']['n'][$onvalue] = 'q BT '.$fontstyle.' 0 0 Td (8) Tj ET Q';
15699 $popt['ap']['n']['Off'] = 'q BT '.$fontstyle.' 0 0 Td (8) Tj ET Q';
15700 if (!isset($popt['mk'])) {
15701 $popt['mk'] = array();
15703 $popt['mk']['ca'] = '(l)';
15704 // merge options
15705 $opt = array_merge($popt, $opt);
15706 // set remaining annotation data
15707 $opt['Subtype'] = 'Widget';
15708 $opt['ft'] = 'Btn';
15709 if ($checked) {
15710 $opt['v'] = array('/'.$onvalue);
15711 $opt['as'] = $onvalue;
15712 } else {
15713 $opt['as'] = 'Off';
15715 $this->Annotation($x, $y, $w, $w, $name, $opt, 0);
15716 if ($this->rtl) {
15717 $this->x -= $w;
15718 } else {
15719 $this->x += $w;
15724 * Creates a List-box field
15725 * @param $name (string) field name
15726 * @param $w (int) width
15727 * @param $h (int) height
15728 * @param $values (array) array containing the list of values.
15729 * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
15730 * @param $opt (array) annotation parameters. Possible values are described on official PDF32000_2008 reference.
15731 * @param $x (float) Abscissa of the upper-left corner of the rectangle
15732 * @param $y (float) Ordinate of the upper-left corner of the rectangle
15733 * @param $js (boolean) if true put the field using JavaScript (requires Acrobat Writer to be rendered).
15734 * @public
15735 * @author Nicola Asuni
15736 * @since 4.8.000 (2009-09-07)
15738 public function ListBox($name, $w, $h, $values, $prop=array(), $opt=array(), $x='', $y='', $js=false) {
15739 if ($x === '') {
15740 $x = $this->x;
15742 if ($y === '') {
15743 $y = $this->y;
15745 // check page for no-write regions and adapt page margins if necessary
15746 list($x, $y) = $this->checkPageRegions($h, $x, $y);
15747 if ($js) {
15748 $this->_addfield('listbox', $name, $x, $y, $w, $h, $prop);
15749 $s = '';
15750 foreach ($values as $value) {
15751 $s .= "'".addslashes($value)."',";
15753 $this->javascript .= 'f'.$name.'.setItems(['.substr($s, 0, -1)."]);\n";
15754 return;
15756 // get default style
15757 $prop = array_merge($this->getFormDefaultProp(), $prop);
15758 // get annotation data
15759 $popt = $this->getAnnotOptFromJSProp($prop);
15760 // set additional default values
15761 $this->annotation_fonts[$this->CurrentFont['fontkey']] = $this->CurrentFont['i'];
15762 $fontstyle = sprintf('/F%d %.2F Tf %s', $this->CurrentFont['i'], $this->FontSizePt, $this->TextColor);
15763 $popt['da'] = $fontstyle;
15764 $popt['ap'] = array();
15765 $popt['ap']['n'] = 'q BT '.$fontstyle.' ET Q';
15766 // merge options
15767 $opt = array_merge($popt, $opt);
15768 // set remaining annotation data
15769 $opt['Subtype'] = 'Widget';
15770 $opt['ft'] = 'Ch';
15771 $opt['t'] = $name;
15772 $opt['opt'] = $values;
15773 $this->Annotation($x, $y, $w, $h, $name, $opt, 0);
15774 if ($this->rtl) {
15775 $this->x -= $w;
15776 } else {
15777 $this->x += $w;
15782 * Creates a Combo-box field
15783 * @param $name (string) field name
15784 * @param $w (int) width
15785 * @param $h (int) height
15786 * @param $values (array) array containing the list of values.
15787 * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
15788 * @param $opt (array) annotation parameters. Possible values are described on official PDF32000_2008 reference.
15789 * @param $x (float) Abscissa of the upper-left corner of the rectangle
15790 * @param $y (float) Ordinate of the upper-left corner of the rectangle
15791 * @param $js (boolean) if true put the field using JavaScript (requires Acrobat Writer to be rendered).
15792 * @public
15793 * @author Nicola Asuni
15794 * @since 4.8.000 (2009-09-07)
15796 public function ComboBox($name, $w, $h, $values, $prop=array(), $opt=array(), $x='', $y='', $js=false) {
15797 if ($x === '') {
15798 $x = $this->x;
15800 if ($y === '') {
15801 $y = $this->y;
15803 // check page for no-write regions and adapt page margins if necessary
15804 list($x, $y) = $this->checkPageRegions($h, $x, $y);
15805 if ($js) {
15806 $this->_addfield('combobox', $name, $x, $y, $w, $h, $prop);
15807 $s = '';
15808 foreach ($values as $value) {
15809 $s .= "'".addslashes($value)."',";
15811 $this->javascript .= 'f'.$name.'.setItems(['.substr($s, 0, -1)."]);\n";
15812 return;
15814 // get default style
15815 $prop = array_merge($this->getFormDefaultProp(), $prop);
15816 $prop['Combo'] = true;
15817 // get annotation data
15818 $popt = $this->getAnnotOptFromJSProp($prop);
15819 // set additional default options
15820 $this->annotation_fonts[$this->CurrentFont['fontkey']] = $this->CurrentFont['i'];
15821 $fontstyle = sprintf('/F%d %.2F Tf %s', $this->CurrentFont['i'], $this->FontSizePt, $this->TextColor);
15822 $popt['da'] = $fontstyle;
15823 $popt['ap'] = array();
15824 $popt['ap']['n'] = 'q BT '.$fontstyle.' ET Q';
15825 // merge options
15826 $opt = array_merge($popt, $opt);
15827 // set remaining annotation data
15828 $opt['Subtype'] = 'Widget';
15829 $opt['ft'] = 'Ch';
15830 $opt['t'] = $name;
15831 $opt['opt'] = $values;
15832 $this->Annotation($x, $y, $w, $h, $name, $opt, 0);
15833 if ($this->rtl) {
15834 $this->x -= $w;
15835 } else {
15836 $this->x += $w;
15841 * Creates a CheckBox field
15842 * @param $name (string) field name
15843 * @param $w (int) width
15844 * @param $checked (boolean) define the initial state.
15845 * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
15846 * @param $opt (array) annotation parameters. Possible values are described on official PDF32000_2008 reference.
15847 * @param $onvalue (string) value to be returned if selected.
15848 * @param $x (float) Abscissa of the upper-left corner of the rectangle
15849 * @param $y (float) Ordinate of the upper-left corner of the rectangle
15850 * @param $js (boolean) if true put the field using JavaScript (requires Acrobat Writer to be rendered).
15851 * @public
15852 * @author Nicola Asuni
15853 * @since 4.8.000 (2009-09-07)
15855 public function CheckBox($name, $w, $checked=false, $prop=array(), $opt=array(), $onvalue='Yes', $x='', $y='', $js=false) {
15856 if ($x === '') {
15857 $x = $this->x;
15859 if ($y === '') {
15860 $y = $this->y;
15862 // check page for no-write regions and adapt page margins if necessary
15863 list($x, $y) = $this->checkPageRegions($w, $x, $y);
15864 if ($js) {
15865 $this->_addfield('checkbox', $name, $x, $y, $w, $w, $prop);
15866 return;
15868 if (!isset($prop['value'])) {
15869 $prop['value'] = array('Yes');
15871 // get default style
15872 $prop = array_merge($this->getFormDefaultProp(), $prop);
15873 $prop['borderStyle'] = 'inset';
15874 // get annotation data
15875 $popt = $this->getAnnotOptFromJSProp($prop);
15876 // set additional default options
15877 $font = 'zapfdingbats';
15878 $this->AddFont($font);
15879 $tmpfont = $this->getFontBuffer($font);
15880 $this->annotation_fonts[$tmpfont['fontkey']] = $tmpfont['i'];
15881 $fontstyle = sprintf('/F%d %.2F Tf %s', $tmpfont['i'], $this->FontSizePt, $this->TextColor);
15882 $popt['da'] = $fontstyle;
15883 $popt['ap'] = array();
15884 $popt['ap']['n'] = array();
15885 $popt['ap']['n']['Yes'] = 'q BT '.$fontstyle.' 0 0 Td (8) Tj ET Q';
15886 $popt['ap']['n']['Off'] = 'q BT '.$fontstyle.' 0 0 Td (8) Tj ET Q';
15887 // merge options
15888 $opt = array_merge($popt, $opt);
15889 // set remaining annotation data
15890 $opt['Subtype'] = 'Widget';
15891 $opt['ft'] = 'Btn';
15892 $opt['t'] = $name;
15893 $opt['opt'] = array($onvalue);
15894 if ($checked) {
15895 $opt['v'] = array('/Yes');
15896 $opt['as'] = 'Yes';
15897 } else {
15898 $opt['v'] = array('/Off');
15899 $opt['as'] = 'Off';
15901 $this->Annotation($x, $y, $w, $w, $name, $opt, 0);
15902 if ($this->rtl) {
15903 $this->x -= $w;
15904 } else {
15905 $this->x += $w;
15910 * Creates a button field
15911 * @param $name (string) field name
15912 * @param $w (int) width
15913 * @param $h (int) height
15914 * @param $caption (string) caption.
15915 * @param $action (mixed) action triggered by pressing the button. Use a string to specify a javascript action. Use an array to specify a form action options as on section 12.7.5 of PDF32000_2008.
15916 * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
15917 * @param $opt (array) annotation parameters. Possible values are described on official PDF32000_2008 reference.
15918 * @param $x (float) Abscissa of the upper-left corner of the rectangle
15919 * @param $y (float) Ordinate of the upper-left corner of the rectangle
15920 * @param $js (boolean) if true put the field using JavaScript (requires Acrobat Writer to be rendered).
15921 * @public
15922 * @author Nicola Asuni
15923 * @since 4.8.000 (2009-09-07)
15925 public function Button($name, $w, $h, $caption, $action, $prop=array(), $opt=array(), $x='', $y='', $js=false) {
15926 if ($x === '') {
15927 $x = $this->x;
15929 if ($y === '') {
15930 $y = $this->y;
15932 // check page for no-write regions and adapt page margins if necessary
15933 list($x, $y) = $this->checkPageRegions($h, $x, $y);
15934 if ($js) {
15935 $this->_addfield('button', $name, $this->x, $this->y, $w, $h, $prop);
15936 $this->javascript .= 'f'.$name.".buttonSetCaption('".addslashes($caption)."');\n";
15937 $this->javascript .= 'f'.$name.".setAction('MouseUp','".addslashes($action)."');\n";
15938 $this->javascript .= 'f'.$name.".highlight='push';\n";
15939 $this->javascript .= 'f'.$name.".print=false;\n";
15940 return;
15942 // get default style
15943 $prop = array_merge($this->getFormDefaultProp(), $prop);
15944 $prop['Pushbutton'] = 'true';
15945 $prop['highlight'] = 'push';
15946 $prop['display'] = 'display.noPrint';
15947 // get annotation data
15948 $popt = $this->getAnnotOptFromJSProp($prop);
15949 $this->annotation_fonts[$this->CurrentFont['fontkey']] = $this->CurrentFont['i'];
15950 $fontstyle = sprintf('/F%d %.2F Tf %s', $this->CurrentFont['i'], $this->FontSizePt, $this->TextColor);
15951 $popt['da'] = $fontstyle;
15952 $popt['ap'] = array();
15953 $popt['ap']['n'] = 'q BT '.$fontstyle.' ET Q';
15954 // set additional default options
15955 if (!isset($popt['mk'])) {
15956 $popt['mk'] = array();
15958 $ann_obj_id = ($this->n + 1);
15959 if (!empty($action) AND !is_array($action)) {
15960 $ann_obj_id = ($this->n + 2);
15962 $popt['mk']['ca'] = $this->_textstring($caption, $ann_obj_id);
15963 $popt['mk']['rc'] = $this->_textstring($caption, $ann_obj_id);
15964 $popt['mk']['ac'] = $this->_textstring($caption, $ann_obj_id);
15965 // merge options
15966 $opt = array_merge($popt, $opt);
15967 // set remaining annotation data
15968 $opt['Subtype'] = 'Widget';
15969 $opt['ft'] = 'Btn';
15970 $opt['t'] = $caption;
15971 $opt['v'] = $name;
15972 if (!empty($action)) {
15973 if (is_array($action)) {
15974 // form action options as on section 12.7.5 of PDF32000_2008.
15975 $opt['aa'] = '/D <<';
15976 $bmode = array('SubmitForm', 'ResetForm', 'ImportData');
15977 foreach ($action AS $key => $val) {
15978 if (($key == 'S') AND in_array($val, $bmode)) {
15979 $opt['aa'] .= ' /S /'.$val;
15980 } elseif (($key == 'F') AND (!empty($val))) {
15981 $opt['aa'] .= ' /F '.$this->_datastring($val, $ann_obj_id);
15982 } elseif (($key == 'Fields') AND is_array($val) AND !empty($val)) {
15983 $opt['aa'] .= ' /Fields [';
15984 foreach ($val AS $field) {
15985 $opt['aa'] .= ' '.$this->_textstring($field, $ann_obj_id);
15987 $opt['aa'] .= ']';
15988 } elseif (($key == 'Flags')) {
15989 $ff = 0;
15990 if (is_array($val)) {
15991 foreach ($val AS $flag) {
15992 switch ($flag) {
15993 case 'Include/Exclude': {
15994 $ff += 1 << 0;
15995 break;
15997 case 'IncludeNoValueFields': {
15998 $ff += 1 << 1;
15999 break;
16001 case 'ExportFormat': {
16002 $ff += 1 << 2;
16003 break;
16005 case 'GetMethod': {
16006 $ff += 1 << 3;
16007 break;
16009 case 'SubmitCoordinates': {
16010 $ff += 1 << 4;
16011 break;
16013 case 'XFDF': {
16014 $ff += 1 << 5;
16015 break;
16017 case 'IncludeAppendSaves': {
16018 $ff += 1 << 6;
16019 break;
16021 case 'IncludeAnnotations': {
16022 $ff += 1 << 7;
16023 break;
16025 case 'SubmitPDF': {
16026 $ff += 1 << 8;
16027 break;
16029 case 'CanonicalFormat': {
16030 $ff += 1 << 9;
16031 break;
16033 case 'ExclNonUserAnnots': {
16034 $ff += 1 << 10;
16035 break;
16037 case 'ExclFKey': {
16038 $ff += 1 << 11;
16039 break;
16041 case 'EmbedForm': {
16042 $ff += 1 << 13;
16043 break;
16047 } else {
16048 $ff = intval($val);
16050 $opt['aa'] .= ' /Flags '.$ff;
16053 $opt['aa'] .= ' >>';
16054 } else {
16055 // Javascript action or raw action command
16056 $js_obj_id = $this->addJavascriptObject($action);
16057 $opt['aa'] = '/D '.$js_obj_id.' 0 R';
16060 $this->Annotation($x, $y, $w, $h, $name, $opt, 0);
16061 if ($this->rtl) {
16062 $this->x -= $w;
16063 } else {
16064 $this->x += $w;
16068 // --- END FORMS FIELDS ------------------------------------------------
16071 * Add certification signature (DocMDP or UR3)
16072 * You can set only one signature type
16073 * @protected
16074 * @author Nicola Asuni
16075 * @since 4.6.008 (2009-05-07)
16077 protected function _putsignature() {
16078 if ((!$this->sign) OR (!isset($this->signature_data['cert_type']))) {
16079 return;
16081 $sigobjid = ($this->sig_obj_id + 1);
16082 $out = $this->_getobj($sigobjid)."\n";
16083 $out .= '<< /Type /Sig';
16084 $out .= ' /Filter /Adobe.PPKLite';
16085 $out .= ' /SubFilter /adbe.pkcs7.detached';
16086 $out .= ' '.$this->byterange_string;
16087 $out .= ' /Contents<'.str_repeat('0', $this->signature_max_length).'>';
16088 $out .= ' /Reference ['; // array of signature reference dictionaries
16089 $out .= ' << /Type /SigRef';
16090 if ($this->signature_data['cert_type'] > 0) {
16091 $out .= ' /TransformMethod /DocMDP';
16092 $out .= ' /TransformParams <<';
16093 $out .= ' /Type /TransformParams';
16094 $out .= ' /P '.$this->signature_data['cert_type'];
16095 $out .= ' /V /1.2';
16096 } else {
16097 $out .= ' /TransformMethod /UR3';
16098 $out .= ' /TransformParams <<';
16099 $out .= ' /Type /TransformParams';
16100 $out .= ' /V /2.2';
16101 if (!$this->empty_string($this->ur['document'])) {
16102 $out .= ' /Document['.$this->ur['document'].']';
16104 if (!$this->empty_string($this->ur['form'])) {
16105 $out .= ' /Form['.$this->ur['form'].']';
16107 if (!$this->empty_string($this->ur['signature'])) {
16108 $out .= ' /Signature['.$this->ur['signature'].']';
16110 if (!$this->empty_string($this->ur['annots'])) {
16111 $out .= ' /Annots['.$this->ur['annots'].']';
16113 if (!$this->empty_string($this->ur['ef'])) {
16114 $out .= ' /EF['.$this->ur['ef'].']';
16116 if (!$this->empty_string($this->ur['formex'])) {
16117 $out .= ' /FormEX['.$this->ur['formex'].']';
16120 $out .= ' >>'; // close TransformParams
16121 // optional digest data (values must be calculated and replaced later)
16122 //$out .= ' /Data ********** 0 R';
16123 //$out .= ' /DigestMethod/MD5';
16124 //$out .= ' /DigestLocation[********** 34]';
16125 //$out .= ' /DigestValue<********************************>';
16126 $out .= ' >>';
16127 $out .= ' ]'; // end of reference
16128 if (isset($this->signature_data['info']['Name']) AND !$this->empty_string($this->signature_data['info']['Name'])) {
16129 $out .= ' /Name '.$this->_textstring($this->signature_data['info']['Name'], $sigobjid);
16131 if (isset($this->signature_data['info']['Location']) AND !$this->empty_string($this->signature_data['info']['Location'])) {
16132 $out .= ' /Location '.$this->_textstring($this->signature_data['info']['Location'], $sigobjid);
16134 if (isset($this->signature_data['info']['Reason']) AND !$this->empty_string($this->signature_data['info']['Reason'])) {
16135 $out .= ' /Reason '.$this->_textstring($this->signature_data['info']['Reason'], $sigobjid);
16137 if (isset($this->signature_data['info']['ContactInfo']) AND !$this->empty_string($this->signature_data['info']['ContactInfo'])) {
16138 $out .= ' /ContactInfo '.$this->_textstring($this->signature_data['info']['ContactInfo'], $sigobjid);
16140 $out .= ' /M '.$this->_datestring($sigobjid);
16141 $out .= ' >>';
16142 $out .= "\n".'endobj';
16143 $this->_out($out);
16147 * Set User's Rights for PDF Reader
16148 * WARNING: This is experimental and currently do not work.
16149 * Check the PDF Reference 8.7.1 Transform Methods,
16150 * Table 8.105 Entries in the UR transform parameters dictionary
16151 * @param $enable (boolean) if true enable user's rights on PDF reader
16152 * @param $document (string) Names specifying additional document-wide usage rights for the document. The only defined value is "/FullSave", which permits a user to save the document along with modified form and/or annotation data.
16153 * @param $annots (string) Names specifying additional annotation-related usage rights for the document. Valid names in PDF 1.5 and later are /Create/Delete/Modify/Copy/Import/Export, which permit the user to perform the named operation on annotations.
16154 * @param $form (string) Names specifying additional form-field-related usage rights for the document. Valid names are: /Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate
16155 * @param $signature (string) Names specifying additional signature-related usage rights for the document. The only defined value is /Modify, which permits a user to apply a digital signature to an existing signature form field or clear a signed signature form field.
16156 * @param $ef (string) Names specifying additional usage rights for named embedded files in the document. Valid names are /Create/Delete/Modify/Import, which permit the user to perform the named operation on named embedded files
16157 Names specifying additional embedded-files-related usage rights for the document.
16158 * @param $formex (string) Names specifying additional form-field-related usage rights. The only valid name is BarcodePlaintext, which permits text form field data to be encoded as a plaintext two-dimensional barcode.
16159 * @public
16160 * @author Nicola Asuni
16161 * @since 2.9.000 (2008-03-26)
16163 public function setUserRights(
16164 $enable=true,
16165 $document='/FullSave',
16166 $annots='/Create/Delete/Modify/Copy/Import/Export',
16167 $form='/Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate',
16168 $signature='/Modify',
16169 $ef='/Create/Delete/Modify/Import',
16170 $formex='') {
16171 $this->ur['enabled'] = $enable;
16172 $this->ur['document'] = $document;
16173 $this->ur['annots'] = $annots;
16174 $this->ur['form'] = $form;
16175 $this->ur['signature'] = $signature;
16176 $this->ur['ef'] = $ef;
16177 $this->ur['formex'] = $formex;
16178 if (!$this->sign) {
16179 $this->setSignature('', '', '', '', 0, array());
16184 * Enable document signature (requires the OpenSSL Library).
16185 * The digital signature improve document authenticity and integrity and allows o enable extra features on Acrobat Reader.
16186 * To create self-signed signature: openssl req -x509 -nodes -days 365000 -newkey rsa:1024 -keyout tcpdf.crt -out tcpdf.crt
16187 * To export crt to p12: openssl pkcs12 -export -in tcpdf.crt -out tcpdf.p12
16188 * To convert pfx certificate to pem: openssl pkcs12 -in tcpdf.pfx -out tcpdf.crt -nodes
16189 * @param $signing_cert (mixed) signing certificate (string or filename prefixed with 'file://')
16190 * @param $private_key (mixed) private key (string or filename prefixed with 'file://')
16191 * @param $private_key_password (string) password
16192 * @param $extracerts (string) specifies the name of a file containing a bunch of extra certificates to include in the signature which can for example be used to help the recipient to verify the certificate that you used.
16193 * @param $cert_type (int) The access permissions granted for this document. Valid values shall be: 1 = No changes to the document shall be permitted; any change to the document shall invalidate the signature; 2 = Permitted changes shall be filling in forms, instantiating page templates, and signing; other changes shall invalidate the signature; 3 = Permitted changes shall be the same as for 2, as well as annotation creation, deletion, and modification; other changes shall invalidate the signature.
16194 * @param $info (array) array of option information: Name, Location, Reason, ContactInfo.
16195 * @public
16196 * @author Nicola Asuni
16197 * @since 4.6.005 (2009-04-24)
16199 public function setSignature($signing_cert='', $private_key='', $private_key_password='', $extracerts='', $cert_type=2, $info=array()) {
16200 // to create self-signed signature: openssl req -x509 -nodes -days 365000 -newkey rsa:1024 -keyout tcpdf.crt -out tcpdf.crt
16201 // to export crt to p12: openssl pkcs12 -export -in tcpdf.crt -out tcpdf.p12
16202 // to convert pfx certificate to pem: openssl
16203 // OpenSSL> pkcs12 -in <cert.pfx> -out <cert.crt> -nodes
16204 $this->sign = true;
16205 ++$this->n;
16206 $this->sig_obj_id = $this->n; // signature widget
16207 ++$this->n; // signature object ($this->sig_obj_id + 1)
16208 $this->signature_data = array();
16209 if (strlen($signing_cert) == 0) {
16210 $signing_cert = 'file://'.dirname(__FILE__).'/tcpdf.crt';
16211 $private_key_password = 'tcpdfdemo';
16213 if (strlen($private_key) == 0) {
16214 $private_key = $signing_cert;
16216 $this->signature_data['signcert'] = $signing_cert;
16217 $this->signature_data['privkey'] = $private_key;
16218 $this->signature_data['password'] = $private_key_password;
16219 $this->signature_data['extracerts'] = $extracerts;
16220 $this->signature_data['cert_type'] = $cert_type;
16221 $this->signature_data['info'] = $info;
16225 * Set the digital signature appearance (a cliccable rectangle area to get signature properties)
16226 * @param $x (float) Abscissa of the upper-left corner.
16227 * @param $y (float) Ordinate of the upper-left corner.
16228 * @param $w (float) Width of the signature area.
16229 * @param $h (float) Height of the signature area.
16230 * @param $page (int) option page number (if < 0 the current page is used).
16231 * @public
16232 * @author Nicola Asuni
16233 * @since 5.3.011 (2010-06-17)
16235 public function setSignatureAppearance($x=0, $y=0, $w=0, $h=0, $page=-1) {
16236 $this->signature_appearance = $this->getSignatureAppearanceArray($x, $y, $w, $h, $page);
16240 * Add an empty digital signature appearance (a cliccable rectangle area to get signature properties)
16241 * @param $x (float) Abscissa of the upper-left corner.
16242 * @param $y (float) Ordinate of the upper-left corner.
16243 * @param $w (float) Width of the signature area.
16244 * @param $h (float) Height of the signature area.
16245 * @param $page (int) option page number (if < 0 the current page is used).
16246 * @public
16247 * @author Nicola Asuni
16248 * @since 5.9.101 (2011-07-06)
16250 public function addEmptySignatureAppearance($x=0, $y=0, $w=0, $h=0, $page=-1) {
16251 ++$this->n;
16252 $this->empty_signature_appearance[] = array('objid' => $this->n) + $this->getSignatureAppearanceArray($x, $y, $w, $h, $page);
16256 * Get the array that defines the signature appearance (page and rectangle coordinates).
16257 * @param $x (float) Abscissa of the upper-left corner.
16258 * @param $y (float) Ordinate of the upper-left corner.
16259 * @param $w (float) Width of the signature area.
16260 * @param $h (float) Height of the signature area.
16261 * @param $page (int) option page number (if < 0 the current page is used).
16262 * @return (array) Array defining page and rectangle coordinates of signature appearance.
16263 * @protected
16264 * @author Nicola Asuni
16265 * @since 5.9.101 (2011-07-06)
16267 protected function getSignatureAppearanceArray($x=0, $y=0, $w=0, $h=0, $page=-1) {
16268 $sigapp = array();
16269 if (($page < 1) OR ($page > $this->numpages)) {
16270 $sigapp['page'] = $this->page;
16271 } else {
16272 $sigapp['page'] = intval($page);
16274 $a = $x * $this->k;
16275 $b = $this->pagedim[($sigapp['page'])]['h'] - (($y + $h) * $this->k);
16276 $c = $w * $this->k;
16277 $d = $h * $this->k;
16278 $sigapp['rect'] = sprintf('%.2F %.2F %.2F %.2F', $a, $b, ($a + $c), ($b + $d));
16279 return $sigapp;
16283 * Create a new page group.
16284 * NOTE: call this function before calling AddPage()
16285 * @param $page (int) starting group page (leave empty for next page).
16286 * @public
16287 * @since 3.0.000 (2008-03-27)
16289 public function startPageGroup($page='') {
16290 if (empty($page)) {
16291 $page = $this->page + 1;
16293 $this->newpagegroup[$page] = sizeof($this->newpagegroup) + 1;
16297 * This method is DEPRECATED and doesn't have any effect.
16298 * Please remove any reference to this method.
16299 * @param $s (string) Empty parameter.
16300 * @deprecated deprecated since version 5.9.089 (2011-06-13)
16301 * @public
16303 public function AliasNbPages($s='') {}
16306 * This method is DEPRECATED and doesn't have any effect.
16307 * Please remove any reference to this method.
16308 * @param $s (string) Empty parameter.
16309 * @deprecated deprecated since version 5.9.089 (2011-06-13)
16310 * @public
16312 public function AliasNumPage($s='') {}
16315 * Set the starting page number.
16316 * @param $num (int) Starting page number.
16317 * @since 5.9.093 (2011-06-16)
16318 * @public
16320 public function setStartingPageNumber($num=1) {
16321 $this->starting_page_number = max(0, intval($num));
16325 * Returns the string alias used right align page numbers.
16326 * If the current font is unicode type, the returned string wil contain an additional open curly brace.
16327 * @return string
16328 * @since 5.9.099 (2011-06-27)
16329 * @public
16331 public function getAliasRightShift() {
16332 // calculate aproximatively the ratio between widths of aliases and replacements.
16333 $ref = '{'.$this->alias_right_shift.'}{'.$this->alias_tot_pages.'}{'.$this->alias_num_page.'}';
16334 $rep = str_repeat(' ', $this->GetNumChars($ref));
16335 $wdiff = max(1, ($this->GetStringWidth($ref) / $this->GetStringWidth($rep)));
16336 $sdiff = sprintf('%.3F', $wdiff);
16337 $alias = $this->alias_right_shift.$sdiff.'}';
16338 if ($this->isUnicodeFont()) {
16339 $alias = '{'.$alias;
16341 return $alias;
16345 * Returns the string alias used for the total number of pages.
16346 * If the current font is unicode type, the returned string is surrounded by additional curly braces.
16347 * This alias will be replaced by the total number of pages in the document.
16348 * @return string
16349 * @since 4.0.018 (2008-08-08)
16350 * @public
16352 public function getAliasNbPages() {
16353 if ($this->isUnicodeFont()) {
16354 return '{'.$this->alias_tot_pages.'}';
16356 return $this->alias_tot_pages;
16360 * Returns the string alias used for the page number.
16361 * If the current font is unicode type, the returned string is surrounded by additional curly braces.
16362 * This alias will be replaced by the page number.
16363 * @return string
16364 * @since 4.5.000 (2009-01-02)
16365 * @public
16367 public function getAliasNumPage() {
16368 if ($this->isUnicodeFont()) {
16369 return '{'.$this->alias_num_page.'}';
16371 return $this->alias_num_page;
16375 * Return the alias for the total number of pages in the current page group.
16376 * If the current font is unicode type, the returned string is surrounded by additional curly braces.
16377 * This alias will be replaced by the total number of pages in this group.
16378 * @return alias of the current page group
16379 * @public
16380 * @since 3.0.000 (2008-03-27)
16382 public function getPageGroupAlias() {
16383 if ($this->isUnicodeFont()) {
16384 return '{'.$this->alias_group_tot_pages.'}';
16386 return $this->alias_group_tot_pages;
16390 * Return the alias for the page number on the current page group.
16391 * If the current font is unicode type, the returned string is surrounded by additional curly braces.
16392 * This alias will be replaced by the page number (relative to the belonging group).
16393 * @return alias of the current page group
16394 * @public
16395 * @since 4.5.000 (2009-01-02)
16397 public function getPageNumGroupAlias() {
16398 if ($this->isUnicodeFont()) {
16399 return '{'.$this->alias_group_num_page.'}';
16401 return $this->alias_group_num_page;
16405 * Return the current page in the group.
16406 * @return current page in the group
16407 * @public
16408 * @since 3.0.000 (2008-03-27)
16410 public function getGroupPageNo() {
16411 return $this->pagegroups[$this->currpagegroup];
16415 * Returns the current group page number formatted as a string.
16416 * @public
16417 * @since 4.3.003 (2008-11-18)
16418 * @see PaneNo(), formatPageNumber()
16420 public function getGroupPageNoFormatted() {
16421 return $this->formatPageNumber($this->getGroupPageNo());
16425 * Format the page numbers.
16426 * This method can be overriden for custom formats.
16427 * @param $num (int) page number
16428 * @protected
16429 * @since 4.2.005 (2008-11-06)
16431 protected function formatPageNumber($num) {
16432 return number_format((float)$num, 0, '', '.');
16436 * Format the page numbers on the Table Of Content.
16437 * This method can be overriden for custom formats.
16438 * @param $num (int) page number
16439 * @protected
16440 * @since 4.5.001 (2009-01-04)
16441 * @see addTOC(), addHTMLTOC()
16443 protected function formatTOCPageNumber($num) {
16444 return number_format((float)$num, 0, '', '.');
16448 * Returns the current page number formatted as a string.
16449 * @public
16450 * @since 4.2.005 (2008-11-06)
16451 * @see PaneNo(), formatPageNumber()
16453 public function PageNoFormatted() {
16454 return $this->formatPageNumber($this->PageNo());
16458 * Put pdf layers.
16459 * @protected
16460 * @since 3.0.000 (2008-03-27)
16462 protected function _putocg() {
16463 if (empty($this->pdflayers)) {
16464 return;
16466 foreach ($this->pdflayers as $key => $layer) {
16467 $this->pdflayers[$key]['objid'] = $this->_newobj();
16468 $out = '<< /Type /OCG';
16469 $out .= ' /Name '.$this->_textstring($layer['name'], $this->pdflayers[$key]['objid']);
16470 $out .= ' /Usage <<';
16471 $out .= ' /Print <</PrintState /'.($layer['print']?'ON':'OFF').'>>';
16472 $out .= ' /View <</ViewState /'.($layer['view']?'ON':'OFF').'>>';
16473 $out .= ' >> >>';
16474 $out .= "\n".'endobj';
16475 $this->_out($out);
16480 * Start a new pdf layer.
16481 * @param $name (string) Layer name (only a-z letters and numbers). Leave empty for automatic name.
16482 * @param $print (boolean) Set to true to print this layer.
16483 * @param $view (boolean) Set to true to view this layer.
16484 * @public
16485 * @since 5.9.102 (2011-07-13)
16487 public function startLayer($name='', $print=true, $view=true) {
16488 $layer = sprintf('LYR%03d', (count($this->pdflayers) + 1));
16489 if (empty($name)) {
16490 $name = $layer;
16491 } else {
16492 $name = preg_replace('/[^a-zA-Z0-9_\-]/', '', $name);
16494 $this->pdflayers[] = array('layer' => $layer, 'name' => $name, 'print' => $print, 'view' => $view);
16495 $this->openMarkedContent = true;
16496 $this->_out('/OC /'.$layer.' BDC');
16500 * End the current PDF layer.
16501 * @public
16502 * @since 5.9.102 (2011-07-13)
16504 public function endLayer() {
16505 if ($this->openMarkedContent) {
16506 // close existing open marked-content layer
16507 $this->_out('EMC');
16508 $this->openMarkedContent = false;
16513 * Set the visibility of the successive elements.
16514 * This can be useful, for instance, to put a background
16515 * image or color that will show on screen but won't print.
16516 * @param $v (string) visibility mode. Legal values are: all, print, screen or view.
16517 * @public
16518 * @since 3.0.000 (2008-03-27)
16520 public function setVisibility($v) {
16521 $this->endLayer();
16522 switch($v) {
16523 case 'print': {
16524 $this->startLayer('Print', true, false);
16525 break;
16527 case 'view':
16528 case 'screen': {
16529 $this->startLayer('View', false, true);
16530 break;
16532 case 'all': {
16533 $this->_out('');
16534 break;
16536 default: {
16537 $this->Error('Incorrect visibility: '.$v);
16538 break;
16544 * Add transparency parameters to the current extgstate
16545 * @param $parms (array) parameters
16546 * @return the number of extgstates
16547 * @protected
16548 * @since 3.0.000 (2008-03-27)
16550 protected function addExtGState($parms) {
16551 $n = count($this->extgstates) + 1;
16552 // check if this ExtGState already exist
16553 for ($i = 1; $i < $n; ++$i) {
16554 if ($this->extgstates[$i]['parms'] == $parms) {
16555 // return reference to existing ExtGState
16556 return $i;
16559 $this->extgstates[$n]['parms'] = $parms;
16560 return $n;
16564 * Add an extgstate
16565 * @param $gs (array) extgstate
16566 * @protected
16567 * @since 3.0.000 (2008-03-27)
16569 protected function setExtGState($gs) {
16570 $this->_out(sprintf('/GS%d gs', $gs));
16574 * Put extgstates for object transparency
16575 * @protected
16576 * @since 3.0.000 (2008-03-27)
16578 protected function _putextgstates() {
16579 $ne = count($this->extgstates);
16580 for ($i = 1; $i <= $ne; ++$i) {
16581 $this->extgstates[$i]['n'] = $this->_newobj();
16582 $out = '<< /Type /ExtGState';
16583 foreach ($this->extgstates[$i]['parms'] as $k => $v) {
16584 if (is_float($v)) {
16585 $v = sprintf('%.2F', $v);
16587 $out .= ' /'.$k.' '.$v;
16589 $out .= ' >>';
16590 $out .= "\n".'endobj';
16591 $this->_out($out);
16596 * Set alpha for stroking (CA) and non-stroking (ca) operations.
16597 * @param $alpha (float) real value from 0 (transparent) to 1 (opaque)
16598 * @param $bm (string) blend mode, one of the following: Normal, Multiply, Screen, Overlay, Darken, Lighten, ColorDodge, ColorBurn, HardLight, SoftLight, Difference, Exclusion, Hue, Saturation, Color, Luminosity
16599 * @public
16600 * @since 3.0.000 (2008-03-27)
16602 public function setAlpha($alpha, $bm='Normal') {
16603 $gs = $this->addExtGState(array('ca' => $alpha, 'CA' => $alpha, 'BM' => '/'.$bm, 'AIS' => 'false'));
16604 $this->setExtGState($gs);
16608 * Set the default JPEG compression quality (1-100)
16609 * @param $quality (int) JPEG quality, integer between 1 and 100
16610 * @public
16611 * @since 3.0.000 (2008-03-27)
16613 public function setJPEGQuality($quality) {
16614 if (($quality < 1) OR ($quality > 100)) {
16615 $quality = 75;
16617 $this->jpeg_quality = intval($quality);
16621 * Set the default number of columns in a row for HTML tables.
16622 * @param $cols (int) number of columns
16623 * @public
16624 * @since 3.0.014 (2008-06-04)
16626 public function setDefaultTableColumns($cols=4) {
16627 $this->default_table_columns = intval($cols);
16631 * Set the height of the cell (line height) respect the font height.
16632 * @param $h (int) cell proportion respect font height (typical value = 1.25).
16633 * @public
16634 * @since 3.0.014 (2008-06-04)
16636 public function setCellHeightRatio($h) {
16637 $this->cell_height_ratio = $h;
16641 * return the height of cell repect font height.
16642 * @public
16643 * @since 4.0.012 (2008-07-24)
16645 public function getCellHeightRatio() {
16646 return $this->cell_height_ratio;
16650 * Set the PDF version (check PDF reference for valid values).
16651 * @param $version (string) PDF document version.
16652 * @public
16653 * @since 3.1.000 (2008-06-09)
16655 public function setPDFVersion($version='1.7') {
16656 $this->PDFVersion = $version;
16660 * Set the viewer preferences dictionary controlling the way the document is to be presented on the screen or in print.
16661 * (see Section 8.1 of PDF reference, "Viewer Preferences").
16662 * <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>
16663 * @param $preferences (array) array of options.
16664 * @author Nicola Asuni
16665 * @public
16666 * @since 3.1.000 (2008-06-09)
16668 public function setViewerPreferences($preferences) {
16669 $this->viewer_preferences = $preferences;
16673 * Paints color transition registration bars
16674 * @param $x (float) abscissa of the top left corner of the rectangle.
16675 * @param $y (float) ordinate of the top left corner of the rectangle.
16676 * @param $w (float) width of the rectangle.
16677 * @param $h (float) height of the rectangle.
16678 * @param $transition (boolean) if true prints tcolor transitions to white.
16679 * @param $vertical (boolean) if true prints bar vertically.
16680 * @param $colors (string) colors to print, one letter per color separated by comma (for example 'A,W,R,G,B,C,M,Y,K'): A=black, W=white, R=red, G=green, B=blue, C=cyan, M=magenta, Y=yellow, K=black.
16681 * @author Nicola Asuni
16682 * @since 4.9.000 (2010-03-26)
16683 * @public
16685 public function colorRegistrationBar($x, $y, $w, $h, $transition=true, $vertical=false, $colors='A,R,G,B,C,M,Y,K') {
16686 $bars = explode(',', $colors);
16687 $numbars = count($bars); // number of bars to print
16688 // set bar measures
16689 if ($vertical) {
16690 $coords = array(0, 0, 0, 1);
16691 $wb = $w / $numbars; // bar width
16692 $hb = $h; // bar height
16693 $xd = $wb; // delta x
16694 $yd = 0; // delta y
16695 } else {
16696 $coords = array(1, 0, 0, 0);
16697 $wb = $w; // bar width
16698 $hb = $h / $numbars; // bar height
16699 $xd = 0; // delta x
16700 $yd = $hb; // delta y
16702 $xb = $x;
16703 $yb = $y;
16704 foreach ($bars as $col) {
16705 switch ($col) {
16706 // set transition colors
16707 case 'A': { // BLACK
16708 $col_a = array(255);
16709 $col_b = array(0);
16710 break;
16712 case 'W': { // WHITE
16713 $col_a = array(0);
16714 $col_b = array(255);
16715 break;
16717 case 'R': { // R
16718 $col_a = array(255,255,255);
16719 $col_b = array(255,0,0);
16720 break;
16722 case 'G': { // G
16723 $col_a = array(255,255,255);
16724 $col_b = array(0,255,0);
16725 break;
16727 case 'B': { // B
16728 $col_a = array(255,255,255);
16729 $col_b = array(0,0,255);
16730 break;
16732 case 'C': { // C
16733 $col_a = array(0,0,0,0);
16734 $col_b = array(100,0,0,0);
16735 break;
16737 case 'M': { // M
16738 $col_a = array(0,0,0,0);
16739 $col_b = array(0,100,0,0);
16740 break;
16742 case 'Y': { // Y
16743 $col_a = array(0,0,0,0);
16744 $col_b = array(0,0,100,0);
16745 break;
16747 case 'K': { // K
16748 $col_a = array(0,0,0,0);
16749 $col_b = array(0,0,0,100);
16750 break;
16752 default: { // GRAY
16753 $col_a = array(255);
16754 $col_b = array(0);
16755 break;
16758 if ($transition) {
16759 // color gradient
16760 $this->LinearGradient($xb, $yb, $wb, $hb, $col_a, $col_b, $coords);
16761 } else {
16762 // color rectangle
16763 $this->SetFillColorArray($col_b);
16764 $this->Rect($xb, $yb, $wb, $hb, 'F', array());
16766 $xb += $xd;
16767 $yb += $yd;
16772 * Paints crop mark
16773 * @param $x (float) abscissa of the crop mark center.
16774 * @param $y (float) ordinate of the crop mark center.
16775 * @param $w (float) width of the crop mark.
16776 * @param $h (float) height of the crop mark.
16777 * @param $type (string) type of crop mark, one sybol per type separated by comma: A = top left, B = top right, C = bottom left, D = bottom right.
16778 * @param $color (array) crop mark color (default black).
16779 * @author Nicola Asuni
16780 * @since 4.9.000 (2010-03-26)
16781 * @public
16783 public function cropMark($x, $y, $w, $h, $type='A,B,C,D', $color=array(0,0,0)) {
16784 $this->SetLineStyle(array('width' => (0.5 / $this->k), 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => $color));
16785 $crops = explode(',', $type);
16786 $numcrops = count($crops); // number of crop marks to print
16787 $dw = $w / 4; // horizontal space to leave before the intersection point
16788 $dh = $h / 4; // vertical space to leave before the intersection point
16789 foreach ($crops as $crop) {
16790 switch ($crop) {
16791 case 'A': {
16792 $x1 = $x;
16793 $y1 = $y - $h;
16794 $x2 = $x;
16795 $y2 = $y - $dh;
16796 $x3 = $x - $w;
16797 $y3 = $y;
16798 $x4 = $x - $dw;
16799 $y4 = $y;
16800 break;
16802 case 'B': {
16803 $x1 = $x;
16804 $y1 = $y - $h;
16805 $x2 = $x;
16806 $y2 = $y - $dh;
16807 $x3 = $x + $dw;
16808 $y3 = $y;
16809 $x4 = $x + $w;
16810 $y4 = $y;
16811 break;
16813 case 'C': {
16814 $x1 = $x - $w;
16815 $y1 = $y;
16816 $x2 = $x - $dw;
16817 $y2 = $y;
16818 $x3 = $x;
16819 $y3 = $y + $dh;
16820 $x4 = $x;
16821 $y4 = $y + $h;
16822 break;
16824 case 'D': {
16825 $x1 = $x + $dw;
16826 $y1 = $y;
16827 $x2 = $x + $w;
16828 $y2 = $y;
16829 $x3 = $x;
16830 $y3 = $y + $dh;
16831 $x4 = $x;
16832 $y4 = $y + $h;
16833 break;
16836 $this->Line($x1, $y1, $x2, $y2);
16837 $this->Line($x3, $y3, $x4, $y4);
16842 * Paints a registration mark
16843 * @param $x (float) abscissa of the registration mark center.
16844 * @param $y (float) ordinate of the registration mark center.
16845 * @param $r (float) radius of the crop mark.
16846 * @param $double (boolean) if true print two concentric crop marks.
16847 * @param $cola (array) crop mark color (default black).
16848 * @param $colb (array) second crop mark color.
16849 * @author Nicola Asuni
16850 * @since 4.9.000 (2010-03-26)
16851 * @public
16853 public function registrationMark($x, $y, $r, $double=false, $cola=array(0,0,0), $colb=array(255,255,255)) {
16854 $line_style = array('width' => (0.5 / $this->k), 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => $cola);
16855 $this->SetFillColorArray($cola);
16856 $this->PieSector($x, $y, $r, 90, 180, 'F');
16857 $this->PieSector($x, $y, $r, 270, 360, 'F');
16858 $this->Circle($x, $y, $r, 0, 360, 'C', $line_style, array(), 8);
16859 if ($double) {
16860 $r2 = $r * 0.5;
16861 $this->SetFillColorArray($colb);
16862 $this->PieSector($x, $y, $r2, 90, 180, 'F');
16863 $this->PieSector($x, $y, $r2, 270, 360, 'F');
16864 $this->SetFillColorArray($cola);
16865 $this->PieSector($x, $y, $r2, 0, 90, 'F');
16866 $this->PieSector($x, $y, $r2, 180, 270, 'F');
16867 $this->Circle($x, $y, $r2, 0, 360, 'C', $line_style, array(), 8);
16872 * Paints a linear colour gradient.
16873 * @param $x (float) abscissa of the top left corner of the rectangle.
16874 * @param $y (float) ordinate of the top left corner of the rectangle.
16875 * @param $w (float) width of the rectangle.
16876 * @param $h (float) height of the rectangle.
16877 * @param $col1 (array) first color (Grayscale, RGB or CMYK components).
16878 * @param $col2 (array) second color (Grayscale, RGB or CMYK components).
16879 * @param $coords (array) array of the form (x1, y1, x2, y2) which defines the gradient vector (see linear_gradient_coords.jpg). The default value is from left to right (x1=0, y1=0, x2=1, y2=0).
16880 * @author Andreas Würmser, Nicola Asuni
16881 * @since 3.1.000 (2008-06-09)
16882 * @public
16884 public function LinearGradient($x, $y, $w, $h, $col1=array(), $col2=array(), $coords=array(0,0,1,0)) {
16885 $this->Clip($x, $y, $w, $h);
16886 $this->Gradient(2, $coords, array(array('color' => $col1, 'offset' => 0, 'exponent' => 1), array('color' => $col2, 'offset' => 1, 'exponent' => 1)), array(), false);
16890 * Paints a radial colour gradient.
16891 * @param $x (float) abscissa of the top left corner of the rectangle.
16892 * @param $y (float) ordinate of the top left corner of the rectangle.
16893 * @param $w (float) width of the rectangle.
16894 * @param $h (float) height of the rectangle.
16895 * @param $col1 (array) first color (Grayscale, RGB or CMYK components).
16896 * @param $col2 (array) second color (Grayscale, RGB or CMYK components).
16897 * @param $coords (array) array of the form (fx, fy, cx, cy, r) where (fx, fy) is the starting point of the gradient with color1, (cx, cy) is the center of the circle with color2, and r is the radius of the circle (see radial_gradient_coords.jpg). (fx, fy) should be inside the circle, otherwise some areas will not be defined.
16898 * @author Andreas Würmser, Nicola Asuni
16899 * @since 3.1.000 (2008-06-09)
16900 * @public
16902 public function RadialGradient($x, $y, $w, $h, $col1=array(), $col2=array(), $coords=array(0.5,0.5,0.5,0.5,1)) {
16903 $this->Clip($x, $y, $w, $h);
16904 $this->Gradient(3, $coords, array(array('color' => $col1, 'offset' => 0, 'exponent' => 1), array('color' => $col2, 'offset' => 1, 'exponent' => 1)), array(), false);
16908 * Paints a coons patch mesh.
16909 * @param $x (float) abscissa of the top left corner of the rectangle.
16910 * @param $y (float) ordinate of the top left corner of the rectangle.
16911 * @param $w (float) width of the rectangle.
16912 * @param $h (float) height of the rectangle.
16913 * @param $col1 (array) first color (lower left corner) (RGB components).
16914 * @param $col2 (array) second color (lower right corner) (RGB components).
16915 * @param $col3 (array) third color (upper right corner) (RGB components).
16916 * @param $col4 (array) fourth color (upper left corner) (RGB components).
16917 * @param $coords (array) <ul><li>for one patch mesh: array(float x1, float y1, .... float x12, float y12): 12 pairs of coordinates (normally from 0 to 1) which specify the Bezier control points that define the patch. First pair is the lower left edge point, next is its right control point (control point 2). Then the other points are defined in the order: control point 1, edge point, control point 2 going counter-clockwise around the patch. Last (x12, y12) is the first edge point's left control point (control point 1).</li><li>for two or more patch meshes: array[number of patches]: arrays with the following keys for each patch: f: where to put that patch (0 = first patch, 1, 2, 3 = right, top and left of precedent patch - I didn't figure this out completely - just try and error ;-) points: 12 pairs of coordinates of the Bezier control points as above for the first patch, 8 pairs of coordinates for the following patches, ignoring the coordinates already defined by the precedent patch (I also didn't figure out the order of these - also: try and see what's happening) colors: must be 4 colors for the first patch, 2 colors for the following patches</li></ul>
16918 * @param $coords_min (array) minimum value used by the coordinates. If a coordinate's value is smaller than this it will be cut to coords_min. default: 0
16919 * @param $coords_max (array) maximum value used by the coordinates. If a coordinate's value is greater than this it will be cut to coords_max. default: 1
16920 * @param $antialias (boolean) A flag indicating whether to filter the shading function to prevent aliasing artifacts.
16921 * @author Andreas Würmser, Nicola Asuni
16922 * @since 3.1.000 (2008-06-09)
16923 * @public
16925 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) {
16926 $this->Clip($x, $y, $w, $h);
16927 $n = count($this->gradients) + 1;
16928 $this->gradients[$n] = array();
16929 $this->gradients[$n]['type'] = 6; //coons patch mesh
16930 $this->gradients[$n]['coords'] = array();
16931 $this->gradients[$n]['antialias'] = $antialias;
16932 $this->gradients[$n]['colors'] = array();
16933 $this->gradients[$n]['transparency'] = false;
16934 //check the coords array if it is the simple array or the multi patch array
16935 if (!isset($coords[0]['f'])) {
16936 //simple array -> convert to multi patch array
16937 if (!isset($col1[1])) {
16938 $col1[1] = $col1[2] = $col1[0];
16940 if (!isset($col2[1])) {
16941 $col2[1] = $col2[2] = $col2[0];
16943 if (!isset($col3[1])) {
16944 $col3[1] = $col3[2] = $col3[0];
16946 if (!isset($col4[1])) {
16947 $col4[1] = $col4[2] = $col4[0];
16949 $patch_array[0]['f'] = 0;
16950 $patch_array[0]['points'] = $coords;
16951 $patch_array[0]['colors'][0]['r'] = $col1[0];
16952 $patch_array[0]['colors'][0]['g'] = $col1[1];
16953 $patch_array[0]['colors'][0]['b'] = $col1[2];
16954 $patch_array[0]['colors'][1]['r'] = $col2[0];
16955 $patch_array[0]['colors'][1]['g'] = $col2[1];
16956 $patch_array[0]['colors'][1]['b'] = $col2[2];
16957 $patch_array[0]['colors'][2]['r'] = $col3[0];
16958 $patch_array[0]['colors'][2]['g'] = $col3[1];
16959 $patch_array[0]['colors'][2]['b'] = $col3[2];
16960 $patch_array[0]['colors'][3]['r'] = $col4[0];
16961 $patch_array[0]['colors'][3]['g'] = $col4[1];
16962 $patch_array[0]['colors'][3]['b'] = $col4[2];
16963 } else {
16964 //multi patch array
16965 $patch_array = $coords;
16967 $bpcd = 65535; //16 bits per coordinate
16968 //build the data stream
16969 $this->gradients[$n]['stream'] = '';
16970 $count_patch = count($patch_array);
16971 for ($i=0; $i < $count_patch; ++$i) {
16972 $this->gradients[$n]['stream'] .= chr($patch_array[$i]['f']); //start with the edge flag as 8 bit
16973 $count_points = count($patch_array[$i]['points']);
16974 for ($j=0; $j < $count_points; ++$j) {
16975 //each point as 16 bit
16976 $patch_array[$i]['points'][$j] = (($patch_array[$i]['points'][$j] - $coords_min) / ($coords_max - $coords_min)) * $bpcd;
16977 if ($patch_array[$i]['points'][$j] < 0) {
16978 $patch_array[$i]['points'][$j] = 0;
16980 if ($patch_array[$i]['points'][$j] > $bpcd) {
16981 $patch_array[$i]['points'][$j] = $bpcd;
16983 $this->gradients[$n]['stream'] .= chr(floor($patch_array[$i]['points'][$j] / 256));
16984 $this->gradients[$n]['stream'] .= chr(floor($patch_array[$i]['points'][$j] % 256));
16986 $count_cols = count($patch_array[$i]['colors']);
16987 for ($j=0; $j < $count_cols; ++$j) {
16988 //each color component as 8 bit
16989 $this->gradients[$n]['stream'] .= chr($patch_array[$i]['colors'][$j]['r']);
16990 $this->gradients[$n]['stream'] .= chr($patch_array[$i]['colors'][$j]['g']);
16991 $this->gradients[$n]['stream'] .= chr($patch_array[$i]['colors'][$j]['b']);
16994 //paint the gradient
16995 $this->_out('/Sh'.$n.' sh');
16996 //restore previous Graphic State
16997 $this->_out('Q');
17001 * Set a rectangular clipping area.
17002 * @param $x (float) abscissa of the top left corner of the rectangle (or top right corner for RTL mode).
17003 * @param $y (float) ordinate of the top left corner of the rectangle.
17004 * @param $w (float) width of the rectangle.
17005 * @param $h (float) height of the rectangle.
17006 * @author Andreas Würmser, Nicola Asuni
17007 * @since 3.1.000 (2008-06-09)
17008 * @protected
17010 protected function Clip($x, $y, $w, $h) {
17011 if ($this->rtl) {
17012 $x = $this->w - $x - $w;
17014 //save current Graphic State
17015 $s = 'q';
17016 //set clipping area
17017 $s .= sprintf(' %.2F %.2F %.2F %.2F re W n', $x*$this->k, ($this->h-$y)*$this->k, $w*$this->k, -$h*$this->k);
17018 //set up transformation matrix for gradient
17019 $s .= sprintf(' %.3F 0 0 %.3F %.3F %.3F cm', $w*$this->k, $h*$this->k, $x*$this->k, ($this->h-($y+$h))*$this->k);
17020 $this->_out($s);
17024 * Output gradient.
17025 * @param $type (int) type of gradient (1 Function-based shading; 2 Axial shading; 3 Radial shading; 4 Free-form Gouraud-shaded triangle mesh; 5 Lattice-form Gouraud-shaded triangle mesh; 6 Coons patch mesh; 7 Tensor-product patch mesh). (Not all types are currently supported)
17026 * @param $coords (array) array of coordinates.
17027 * @param $stops (array) array gradient color components: color = array of GRAY, RGB or CMYK color components; offset = (0 to 1) represents a location along the gradient vector; exponent = exponent of the exponential interpolation function (default = 1).
17028 * @param $background (array) An array of colour components appropriate to the colour space, specifying a single background colour value.
17029 * @param $antialias (boolean) A flag indicating whether to filter the shading function to prevent aliasing artifacts.
17030 * @author Nicola Asuni
17031 * @since 3.1.000 (2008-06-09)
17032 * @public
17034 public function Gradient($type, $coords, $stops, $background=array(), $antialias=false) {
17035 $n = count($this->gradients) + 1;
17036 $this->gradients[$n] = array();
17037 $this->gradients[$n]['type'] = $type;
17038 $this->gradients[$n]['coords'] = $coords;
17039 $this->gradients[$n]['antialias'] = $antialias;
17040 $this->gradients[$n]['colors'] = array();
17041 $this->gradients[$n]['transparency'] = false;
17042 // color space
17043 $numcolspace = count($stops[0]['color']);
17044 $bcolor = array_values($background);
17045 switch($numcolspace) {
17046 case 4: { // CMYK
17047 $this->gradients[$n]['colspace'] = 'DeviceCMYK';
17048 if (!empty($background)) {
17049 $this->gradients[$n]['background'] = sprintf('%.3F %.3F %.3F %.3F', $bcolor[0]/100, $bcolor[1]/100, $bcolor[2]/100, $bcolor[3]/100);
17051 break;
17053 case 3: { // RGB
17054 $this->gradients[$n]['colspace'] = 'DeviceRGB';
17055 if (!empty($background)) {
17056 $this->gradients[$n]['background'] = sprintf('%.3F %.3F %.3F', $bcolor[0]/255, $bcolor[1]/255, $bcolor[2]/255);
17058 break;
17060 case 1: { // Gray scale
17061 $this->gradients[$n]['colspace'] = 'DeviceGray';
17062 if (!empty($background)) {
17063 $this->gradients[$n]['background'] = sprintf('%.3F', $bcolor[0]/255);
17065 break;
17068 $num_stops = count($stops);
17069 $last_stop_id = $num_stops - 1;
17070 foreach ($stops as $key => $stop) {
17071 $this->gradients[$n]['colors'][$key] = array();
17072 // offset represents a location along the gradient vector
17073 if (isset($stop['offset'])) {
17074 $this->gradients[$n]['colors'][$key]['offset'] = $stop['offset'];
17075 } else {
17076 if ($key == 0) {
17077 $this->gradients[$n]['colors'][$key]['offset'] = 0;
17078 } elseif ($key == $last_stop_id) {
17079 $this->gradients[$n]['colors'][$key]['offset'] = 1;
17080 } else {
17081 $offsetstep = (1 - $this->gradients[$n]['colors'][($key - 1)]['offset']) / ($num_stops - $key);
17082 $this->gradients[$n]['colors'][$key]['offset'] = $this->gradients[$n]['colors'][($key - 1)]['offset'] + $offsetstep;
17085 if (isset($stop['opacity'])) {
17086 $this->gradients[$n]['colors'][$key]['opacity'] = $stop['opacity'];
17087 if ($stop['opacity'] < 1) {
17088 $this->gradients[$n]['transparency'] = true;
17090 } else {
17091 $this->gradients[$n]['colors'][$key]['opacity'] = 1;
17093 // exponent for the exponential interpolation function
17094 if (isset($stop['exponent'])) {
17095 $this->gradients[$n]['colors'][$key]['exponent'] = $stop['exponent'];
17096 } else {
17097 $this->gradients[$n]['colors'][$key]['exponent'] = 1;
17099 // set colors
17100 $color = array_values($stop['color']);
17101 switch($numcolspace) {
17102 case 4: { // CMYK
17103 $this->gradients[$n]['colors'][$key]['color'] = sprintf('%.3F %.3F %.3F %.3F', $color[0]/100, $color[1]/100, $color[2]/100, $color[3]/100);
17104 break;
17106 case 3: { // RGB
17107 $this->gradients[$n]['colors'][$key]['color'] = sprintf('%.3F %.3F %.3F', $color[0]/255, $color[1]/255, $color[2]/255);
17108 break;
17110 case 1: { // Gray scale
17111 $this->gradients[$n]['colors'][$key]['color'] = sprintf('%.3F', $color[0]/255);
17112 break;
17116 if ($this->gradients[$n]['transparency']) {
17117 // paint luminosity gradient
17118 $this->_out('/TGS'.$n.' gs');
17120 //paint the gradient
17121 $this->_out('/Sh'.$n.' sh');
17122 //restore previous Graphic State
17123 $this->_out('Q');
17127 * Output gradient shaders.
17128 * @author Nicola Asuni
17129 * @since 3.1.000 (2008-06-09)
17130 * @protected
17132 function _putshaders() {
17133 $idt = count($this->gradients); //index for transparency gradients
17134 foreach ($this->gradients as $id => $grad) {
17135 if (($grad['type'] == 2) OR ($grad['type'] == 3)) {
17136 $fc = $this->_newobj();
17137 $out = '<<';
17138 $out .= ' /FunctionType 3';
17139 $out .= ' /Domain [0 1]';
17140 $functions = '';
17141 $bounds = '';
17142 $encode = '';
17143 $i = 1;
17144 $num_cols = count($grad['colors']);
17145 $lastcols = $num_cols - 1;
17146 for ($i = 1; $i < $num_cols; ++$i) {
17147 $functions .= ($fc + $i).' 0 R ';
17148 if ($i < $lastcols) {
17149 $bounds .= sprintf('%.3F ', $grad['colors'][$i]['offset']);
17151 $encode .= '0 1 ';
17153 $out .= ' /Functions ['.trim($functions).']';
17154 $out .= ' /Bounds ['.trim($bounds).']';
17155 $out .= ' /Encode ['.trim($encode).']';
17156 $out .= ' >>';
17157 $out .= "\n".'endobj';
17158 $this->_out($out);
17159 for ($i = 1; $i < $num_cols; ++$i) {
17160 $this->_newobj();
17161 $out = '<<';
17162 $out .= ' /FunctionType 2';
17163 $out .= ' /Domain [0 1]';
17164 $out .= ' /C0 ['.$grad['colors'][($i - 1)]['color'].']';
17165 $out .= ' /C1 ['.$grad['colors'][$i]['color'].']';
17166 $out .= ' /N '.$grad['colors'][$i]['exponent'];
17167 $out .= ' >>';
17168 $out .= "\n".'endobj';
17169 $this->_out($out);
17171 // set transparency fuctions
17172 if ($grad['transparency']) {
17173 $ft = $this->_newobj();
17174 $out = '<<';
17175 $out .= ' /FunctionType 3';
17176 $out .= ' /Domain [0 1]';
17177 $functions = '';
17178 $i = 1;
17179 $num_cols = count($grad['colors']);
17180 for ($i = 1; $i < $num_cols; ++$i) {
17181 $functions .= ($ft + $i).' 0 R ';
17183 $out .= ' /Functions ['.trim($functions).']';
17184 $out .= ' /Bounds ['.trim($bounds).']';
17185 $out .= ' /Encode ['.trim($encode).']';
17186 $out .= ' >>';
17187 $out .= "\n".'endobj';
17188 $this->_out($out);
17189 for ($i = 1; $i < $num_cols; ++$i) {
17190 $this->_newobj();
17191 $out = '<<';
17192 $out .= ' /FunctionType 2';
17193 $out .= ' /Domain [0 1]';
17194 $out .= ' /C0 ['.$grad['colors'][($i - 1)]['opacity'].']';
17195 $out .= ' /C1 ['.$grad['colors'][$i]['opacity'].']';
17196 $out .= ' /N '.$grad['colors'][$i]['exponent'];
17197 $out .= ' >>';
17198 $out .= "\n".'endobj';
17199 $this->_out($out);
17203 // set shading object
17204 $this->_newobj();
17205 $out = '<< /ShadingType '.$grad['type'];
17206 if (isset($grad['colspace'])) {
17207 $out .= ' /ColorSpace /'.$grad['colspace'];
17208 } else {
17209 $out .= ' /ColorSpace /DeviceRGB';
17211 if (isset($grad['background']) AND !empty($grad['background'])) {
17212 $out .= ' /Background ['.$grad['background'].']';
17214 if (isset($grad['antialias']) AND ($grad['antialias'] === true)) {
17215 $out .= ' /AntiAlias true';
17217 if ($grad['type'] == 2) {
17218 $out .= ' '.sprintf('/Coords [%.3F %.3F %.3F %.3F]', $grad['coords'][0], $grad['coords'][1], $grad['coords'][2], $grad['coords'][3]);
17219 $out .= ' /Domain [0 1]';
17220 $out .= ' /Function '.$fc.' 0 R';
17221 $out .= ' /Extend [true true]';
17222 $out .= ' >>';
17223 } elseif ($grad['type'] == 3) {
17224 //x0, y0, r0, x1, y1, r1
17225 //at this this time radius of inner circle is 0
17226 $out .= ' '.sprintf('/Coords [%.3F %.3F 0 %.3F %.3F %.3F]', $grad['coords'][0], $grad['coords'][1], $grad['coords'][2], $grad['coords'][3], $grad['coords'][4]);
17227 $out .= ' /Domain [0 1]';
17228 $out .= ' /Function '.$fc.' 0 R';
17229 $out .= ' /Extend [true true]';
17230 $out .= ' >>';
17231 } elseif ($grad['type'] == 6) {
17232 $out .= ' /BitsPerCoordinate 16';
17233 $out .= ' /BitsPerComponent 8';
17234 $out .= ' /Decode[0 1 0 1 0 1 0 1 0 1]';
17235 $out .= ' /BitsPerFlag 8';
17236 $stream = $this->_getrawstream($grad['stream']);
17237 $out .= ' /Length '.strlen($stream);
17238 $out .= ' >>';
17239 $out .= ' stream'."\n".$stream."\n".'endstream';
17241 $out .= "\n".'endobj';
17242 $this->_out($out);
17243 if ($grad['transparency']) {
17244 $shading_transparency = preg_replace('/\/ColorSpace \/[^\s]+/si', '/ColorSpace /DeviceGray', $out);
17245 $shading_transparency = preg_replace('/\/Function [0-9]+ /si', '/Function '.$ft.' ', $shading_transparency);
17247 $this->gradients[$id]['id'] = $this->n;
17248 // set pattern object
17249 $this->_newobj();
17250 $out = '<< /Type /Pattern /PatternType 2';
17251 $out .= ' /Shading '.$this->gradients[$id]['id'].' 0 R';
17252 $out .= ' >>';
17253 $out .= "\n".'endobj';
17254 $this->_out($out);
17255 $this->gradients[$id]['pattern'] = $this->n;
17256 // set shading and pattern for transparency mask
17257 if ($grad['transparency']) {
17258 // luminosity pattern
17259 $idgs = $id + $idt;
17260 $this->_newobj();
17261 $this->_out($shading_transparency);
17262 $this->gradients[$idgs]['id'] = $this->n;
17263 $this->_newobj();
17264 $out = '<< /Type /Pattern /PatternType 2';
17265 $out .= ' /Shading '.$this->gradients[$idgs]['id'].' 0 R';
17266 $out .= ' >>';
17267 $out .= "\n".'endobj';
17268 $this->_out($out);
17269 $this->gradients[$idgs]['pattern'] = $this->n;
17270 // luminosity XObject
17271 $oid = $this->_newobj();
17272 $this->xobjects['LX'.$oid] = array('n' => $oid);
17273 $filter = '';
17274 $stream = 'q /a0 gs /Pattern cs /p'.$idgs.' scn 0 0 '.$this->wPt.' '.$this->hPt.' re f Q';
17275 if ($this->compress) {
17276 $filter = ' /Filter /FlateDecode';
17277 $stream = gzcompress($stream);
17279 $stream = $this->_getrawstream($stream);
17280 $out = '<< /Type /XObject /Subtype /Form /FormType 1'.$filter;
17281 $out .= ' /Length '.strlen($stream);
17282 $rect = sprintf('%.2F %.2F', $this->wPt, $this->hPt);
17283 $out .= ' /BBox [0 0 '.$rect.']';
17284 $out .= ' /Group << /Type /Group /S /Transparency /CS /DeviceGray >>';
17285 $out .= ' /Resources <<';
17286 $out .= ' /ExtGState << /a0 << /ca 1 /CA 1 >> >>';
17287 $out .= ' /Pattern << /p'.$idgs.' '.$this->gradients[$idgs]['pattern'].' 0 R >>';
17288 $out .= ' >>';
17289 $out .= ' >> ';
17290 $out .= ' stream'."\n".$stream."\n".'endstream';
17291 $out .= "\n".'endobj';
17292 $this->_out($out);
17293 // SMask
17294 $this->_newobj();
17295 $out = '<< /Type /Mask /S /Luminosity /G '.($this->n - 1).' 0 R >>'."\n".'endobj';
17296 $this->_out($out);
17297 // ExtGState
17298 $this->_newobj();
17299 $out = '<< /Type /ExtGState /SMask '.($this->n - 1).' 0 R /AIS false >>'."\n".'endobj';
17300 $this->_out($out);
17301 $this->extgstates[] = array('n' => $this->n, 'name' => 'TGS'.$id);
17307 * Draw the sector of a circle.
17308 * It can be used for instance to render pie charts.
17309 * @param $xc (float) abscissa of the center.
17310 * @param $yc (float) ordinate of the center.
17311 * @param $r (float) radius.
17312 * @param $a (float) start angle (in degrees).
17313 * @param $b (float) end angle (in degrees).
17314 * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
17315 * @param $cw: (float) indicates whether to go clockwise (default: true).
17316 * @param $o: (float) origin of angles (0 for 3 o'clock, 90 for noon, 180 for 9 o'clock, 270 for 6 o'clock). Default: 90.
17317 * @author Maxime Delorme, Nicola Asuni
17318 * @since 3.1.000 (2008-06-09)
17319 * @public
17321 public function PieSector($xc, $yc, $r, $a, $b, $style='FD', $cw=true, $o=90) {
17322 $this->PieSectorXY($xc, $yc, $r, $r, $a, $b, $style, $cw, $o);
17326 * Draw the sector of an ellipse.
17327 * It can be used for instance to render pie charts.
17328 * @param $xc (float) abscissa of the center.
17329 * @param $yc (float) ordinate of the center.
17330 * @param $rx (float) the x-axis radius.
17331 * @param $ry (float) the y-axis radius.
17332 * @param $a (float) start angle (in degrees).
17333 * @param $b (float) end angle (in degrees).
17334 * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
17335 * @param $cw: (float) indicates whether to go clockwise.
17336 * @param $o: (float) origin of angles (0 for 3 o'clock, 90 for noon, 180 for 9 o'clock, 270 for 6 o'clock).
17337 * @param $nc (integer) Number of curves used to draw a 90 degrees portion of arc.
17338 * @author Maxime Delorme, Nicola Asuni
17339 * @since 3.1.000 (2008-06-09)
17340 * @public
17342 public function PieSectorXY($xc, $yc, $rx, $ry, $a, $b, $style='FD', $cw=false, $o=0, $nc=2) {
17343 if ($this->rtl) {
17344 $xc = $this->w - $xc;
17346 $op = $this->getPathPaintOperator($style);
17347 if ($op == 'f') {
17348 $line_style = array();
17350 if ($cw) {
17351 $d = $b;
17352 $b = 360 - $a + $o;
17353 $a = 360 - $d + $o;
17354 } else {
17355 $b += $o;
17356 $a += $o;
17358 $this->_outellipticalarc($xc, $yc, $rx, $ry, 0, $a, $b, true, $nc);
17359 $this->_out($op);
17363 * Embed vector-based Adobe Illustrator (AI) or AI-compatible EPS files.
17364 * NOTE: EPS is not yet fully implemented, use the setRasterizeVectorImages() method to enable/disable rasterization of vector images using ImageMagick library.
17365 * Only vector drawing is supported, not text or bitmap.
17366 * 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).
17367 * @param $file (string) Name of the file containing the image or a '@' character followed by the EPS/AI data string.
17368 * @param $x (float) Abscissa of the upper-left corner.
17369 * @param $y (float) Ordinate of the upper-left corner.
17370 * @param $w (float) Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
17371 * @param $h (float) Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
17372 * @param $link (mixed) URL or identifier returned by AddLink().
17373 * @param $useBoundingBox (boolean) specifies whether to position the bounding box (true) or the complete canvas (false) at location (x,y). Default value is true.
17374 * @param $align (string) Indicates the alignment of the pointer next to image insertion relative to image height. The value can be:<ul><li>T: top-right for LTR or top-left for RTL</li><li>M: middle-right for LTR or middle-left for RTL</li><li>B: bottom-right for LTR or bottom-left for RTL</li><li>N: next line</li></ul>
17375 * @param $palign (string) Allows to center or align the image on the current line. Possible values are:<ul><li>L : left align</li><li>C : center</li><li>R : right align</li><li>'' : empty string : left for LTR or right for RTL</li></ul>
17376 * @param $border (mixed) Indicates if borders must be drawn around the cell. The value can be a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul> or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul> or an array of line styles for each border group - for example: array('LTRB' => array('width' => 2, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0)))
17377 * @param $fitonpage (boolean) if true the image is resized to not exceed page dimensions.
17378 * @param $fixoutvals (boolean) if true remove values outside the bounding box.
17379 * @author Valentin Schmidt, Nicola Asuni
17380 * @since 3.1.000 (2008-06-09)
17381 * @public
17383 public function ImageEps($file, $x='', $y='', $w=0, $h=0, $link='', $useBoundingBox=true, $align='', $palign='', $border=0, $fitonpage=false, $fixoutvals=false) {
17384 if ($this->rasterize_vector_images AND ($w > 0) AND ($h > 0)) {
17385 // convert EPS to raster image using GD or ImageMagick libraries
17386 return $this->Image($file, $x, $y, $w, $h, 'EPS', $link, $align, true, 300, $palign, false, false, $border, false, false, $fitonpage);
17388 if ($x === '') {
17389 $x = $this->x;
17391 if ($y === '') {
17392 $y = $this->y;
17394 // check page for no-write regions and adapt page margins if necessary
17395 list($x, $y) = $this->checkPageRegions($h, $x, $y);
17396 $k = $this->k;
17397 if ($file{0} === '@') { // image from string
17398 $data = substr($file, 1);
17399 } else { // EPS/AI file
17400 $data = file_get_contents($file);
17402 if ($data === false) {
17403 $this->Error('EPS file not found: '.$file);
17405 $regs = array();
17406 // EPS/AI compatibility check (only checks files created by Adobe Illustrator!)
17407 preg_match("/%%Creator:([^\r\n]+)/", $data, $regs); # find Creator
17408 if (count($regs) > 1) {
17409 $version_str = trim($regs[1]); # e.g. "Adobe Illustrator(R) 8.0"
17410 if (strpos($version_str, 'Adobe Illustrator') !== false) {
17411 $versexp = explode(' ', $version_str);
17412 $version = (float)array_pop($versexp);
17413 if ($version >= 9) {
17414 $this->Error('This version of Adobe Illustrator file is not supported: '.$file);
17418 // strip binary bytes in front of PS-header
17419 $start = strpos($data, '%!PS-Adobe');
17420 if ($start > 0) {
17421 $data = substr($data, $start);
17423 // find BoundingBox params
17424 preg_match("/%%BoundingBox:([^\r\n]+)/", $data, $regs);
17425 if (count($regs) > 1) {
17426 list($x1, $y1, $x2, $y2) = explode(' ', trim($regs[1]));
17427 } else {
17428 $this->Error('No BoundingBox found in EPS/AI file: '.$file);
17430 $start = strpos($data, '%%EndSetup');
17431 if ($start === false) {
17432 $start = strpos($data, '%%EndProlog');
17434 if ($start === false) {
17435 $start = strpos($data, '%%BoundingBox');
17437 $data = substr($data, $start);
17438 $end = strpos($data, '%%PageTrailer');
17439 if ($end===false) {
17440 $end = strpos($data, 'showpage');
17442 if ($end) {
17443 $data = substr($data, 0, $end);
17445 // calculate image width and height on document
17446 if (($w <= 0) AND ($h <= 0)) {
17447 $w = ($x2 - $x1) / $k;
17448 $h = ($y2 - $y1) / $k;
17449 } elseif ($w <= 0) {
17450 $w = ($x2-$x1) / $k * ($h / (($y2 - $y1) / $k));
17451 } elseif ($h <= 0) {
17452 $h = ($y2 - $y1) / $k * ($w / (($x2 - $x1) / $k));
17454 // fit the image on available space
17455 list($w, $h, $x, $y) = $this->fitBlock($w, $h, $x, $y, $fitonpage);
17456 if ($this->rasterize_vector_images) {
17457 // convert EPS to raster image using GD or ImageMagick libraries
17458 return $this->Image($file, $x, $y, $w, $h, 'EPS', $link, $align, true, 300, $palign, false, false, $border, false, false, $fitonpage);
17460 // set scaling factors
17461 $scale_x = $w / (($x2 - $x1) / $k);
17462 $scale_y = $h / (($y2 - $y1) / $k);
17463 // set alignment
17464 $this->img_rb_y = $y + $h;
17465 // set alignment
17466 if ($this->rtl) {
17467 if ($palign == 'L') {
17468 $ximg = $this->lMargin;
17469 } elseif ($palign == 'C') {
17470 $ximg = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
17471 } elseif ($palign == 'R') {
17472 $ximg = $this->w - $this->rMargin - $w;
17473 } else {
17474 $ximg = $x - $w;
17476 $this->img_rb_x = $ximg;
17477 } else {
17478 if ($palign == 'L') {
17479 $ximg = $this->lMargin;
17480 } elseif ($palign == 'C') {
17481 $ximg = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
17482 } elseif ($palign == 'R') {
17483 $ximg = $this->w - $this->rMargin - $w;
17484 } else {
17485 $ximg = $x;
17487 $this->img_rb_x = $ximg + $w;
17489 if ($useBoundingBox) {
17490 $dx = $ximg * $k - $x1;
17491 $dy = $y * $k - $y1;
17492 } else {
17493 $dx = $ximg * $k;
17494 $dy = $y * $k;
17496 // save the current graphic state
17497 $this->_out('q'.$this->epsmarker);
17498 // translate
17499 $this->_out(sprintf('%.3F %.3F %.3F %.3F %.3F %.3F cm', 1, 0, 0, 1, $dx, $dy + ($this->hPt - (2 * $y * $k) - ($y2 - $y1))));
17500 // scale
17501 if (isset($scale_x)) {
17502 $this->_out(sprintf('%.3F %.3F %.3F %.3F %.3F %.3F cm', $scale_x, 0, 0, $scale_y, $x1 * (1 - $scale_x), $y2 * (1 - $scale_y)));
17504 // handle pc/unix/mac line endings
17505 $lines = preg_split('/[\r\n]+/si', $data, -1, PREG_SPLIT_NO_EMPTY);
17506 $u=0;
17507 $cnt = count($lines);
17508 for ($i=0; $i < $cnt; ++$i) {
17509 $line = $lines[$i];
17510 if (($line == '') OR ($line{0} == '%')) {
17511 continue;
17513 $len = strlen($line);
17514 // check for spot color names
17515 $color_name = '';
17516 if (strcasecmp('x', substr(trim($line), -1)) == 0) {
17517 if (preg_match('/\([^\)]*\)/', $line, $matches) > 0) {
17518 // extract spot color name
17519 $color_name = $matches[0];
17520 // remove color name from string
17521 $line = str_replace(' '.$color_name, '', $line);
17522 // remove pharentesis from color name
17523 $color_name = substr($color_name, 1, -1);
17526 $chunks = explode(' ', $line);
17527 $cmd = trim(array_pop($chunks));
17528 // RGB
17529 if (($cmd == 'Xa') OR ($cmd == 'XA')) {
17530 $b = array_pop($chunks);
17531 $g = array_pop($chunks);
17532 $r = array_pop($chunks);
17533 $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!
17534 continue;
17536 $skip = false;
17537 if ($fixoutvals) {
17538 // check for values outside the bounding box
17539 switch ($cmd) {
17540 case 'm':
17541 case 'l':
17542 case 'L': {
17543 // skip values outside bounding box
17544 foreach ($chunks as $key => $val) {
17545 if ((($key % 2) == 0) AND (($val < $x1) OR ($val > $x2))) {
17546 $skip = true;
17547 } elseif ((($key % 2) != 0) AND (($val < $y1) OR ($val > $y2))) {
17548 $skip = true;
17554 switch ($cmd) {
17555 case 'm':
17556 case 'l':
17557 case 'v':
17558 case 'y':
17559 case 'c':
17560 case 'k':
17561 case 'K':
17562 case 'g':
17563 case 'G':
17564 case 's':
17565 case 'S':
17566 case 'J':
17567 case 'j':
17568 case 'w':
17569 case 'M':
17570 case 'd':
17571 case 'n': {
17572 if ($skip) {
17573 break;
17575 $this->_out($line);
17576 break;
17578 case 'x': {// custom fill color
17579 if (empty($color_name)) {
17580 // CMYK color
17581 list($col_c, $col_m, $col_y, $col_k) = $chunks;
17582 $this->_out(''.$col_c.' '.$col_m.' '.$col_y.' '.$col_k.' k');
17583 } else {
17584 // Spot Color (CMYK + tint)
17585 list($col_c, $col_m, $col_y, $col_k, $col_t) = $chunks;
17586 $this->AddSpotColor($color_name, ($col_c * 100), ($col_m * 100), ($col_y * 100), ($col_k * 100));
17587 $color_cmd = sprintf('/CS%d cs %.3F scn', $this->spot_colors[$color_name]['i'], (1 - $col_t));
17588 $this->_out($color_cmd);
17590 break;
17592 case 'X': { // custom stroke color
17593 if (empty($color_name)) {
17594 // CMYK color
17595 list($col_c, $col_m, $col_y, $col_k) = $chunks;
17596 $this->_out(''.$col_c.' '.$col_m.' '.$col_y.' '.$col_k.' K');
17597 } else {
17598 // Spot Color (CMYK + tint)
17599 list($col_c, $col_m, $col_y, $col_k, $col_t) = $chunks;
17600 $this->AddSpotColor($color_name, ($col_c * 100), ($col_m * 100), ($col_y * 100), ($col_k * 100));
17601 $color_cmd = sprintf('/CS%d CS %.3F SCN', $this->spot_colors[$color_name]['i'], (1 - $col_t));
17602 $this->_out($color_cmd);
17604 break;
17606 case 'Y':
17607 case 'N':
17608 case 'V':
17609 case 'L':
17610 case 'C': {
17611 if ($skip) {
17612 break;
17614 $line{$len-1} = strtolower($cmd);
17615 $this->_out($line);
17616 break;
17618 case 'b':
17619 case 'B': {
17620 $this->_out($cmd . '*');
17621 break;
17623 case 'f':
17624 case 'F': {
17625 if ($u > 0) {
17626 $isU = false;
17627 $max = min(($i + 5), $cnt);
17628 for ($j = ($i + 1); $j < $max; ++$j) {
17629 $isU = ($isU OR (($lines[$j] == 'U') OR ($lines[$j] == '*U')));
17631 if ($isU) {
17632 $this->_out('f*');
17634 } else {
17635 $this->_out('f*');
17637 break;
17639 case '*u': {
17640 ++$u;
17641 break;
17643 case '*U': {
17644 --$u;
17645 break;
17649 // restore previous graphic state
17650 $this->_out($this->epsmarker.'Q');
17651 if (!empty($border)) {
17652 $bx = $this->x;
17653 $by = $this->y;
17654 $this->x = $ximg;
17655 if ($this->rtl) {
17656 $this->x += $w;
17658 $this->y = $y;
17659 $this->Cell($w, $h, '', $border, 0, '', 0, '', 0, true);
17660 $this->x = $bx;
17661 $this->y = $by;
17663 if ($link) {
17664 $this->Link($ximg, $y, $w, $h, $link, 0);
17666 // set pointer to align the next text/objects
17667 switch($align) {
17668 case 'T':{
17669 $this->y = $y;
17670 $this->x = $this->img_rb_x;
17671 break;
17673 case 'M':{
17674 $this->y = $y + round($h/2);
17675 $this->x = $this->img_rb_x;
17676 break;
17678 case 'B':{
17679 $this->y = $this->img_rb_y;
17680 $this->x = $this->img_rb_x;
17681 break;
17683 case 'N':{
17684 $this->SetY($this->img_rb_y);
17685 break;
17687 default:{
17688 break;
17691 $this->endlinex = $this->img_rb_x;
17695 * Set document barcode.
17696 * @param $bc (string) barcode
17697 * @public
17699 public function setBarcode($bc='') {
17700 $this->barcode = $bc;
17704 * Get current barcode.
17705 * @return string
17706 * @public
17707 * @since 4.0.012 (2008-07-24)
17709 public function getBarcode() {
17710 return $this->barcode;
17714 * Print a Linear Barcode.
17715 * @param $code (string) code to print
17716 * @param $type (string) type of barcode (see barcodes.php for supported formats).
17717 * @param $x (int) x position in user units (empty string = current x position)
17718 * @param $y (int) y position in user units (empty string = current y position)
17719 * @param $w (int) width in user units (empty string = remaining page width)
17720 * @param $h (int) height in user units (empty string = remaining page height)
17721 * @param $xres (float) width of the smallest bar in user units (empty string = default value = 0.4mm)
17722 * @param $style (array) array of options:<ul>
17723 * <li>boolean $style['border'] if true prints a border</li>
17724 * <li>int $style['padding'] padding to leave around the barcode in user units (set to 'auto' for automatic padding)</li>
17725 * <li>int $style['hpadding'] horizontal padding in user units (set to 'auto' for automatic padding)</li>
17726 * <li>int $style['vpadding'] vertical padding in user units (set to 'auto' for automatic padding)</li>
17727 * <li>array $style['fgcolor'] color array for bars and text</li>
17728 * <li>mixed $style['bgcolor'] color array for background (set to false for transparent)</li>
17729 * <li>boolean $style['text'] if true prints text below the barcode</li>
17730 * <li>string $style['label'] override default label</li>
17731 * <li>string $style['font'] font name for text</li><li>int $style['fontsize'] font size for text</li>
17732 * <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>
17733 * <li>string $style['position'] horizontal position of the containing barcode cell on the page: L = left margin; C = center; R = right margin.</li>
17734 * <li>string $style['align'] horizontal position of the barcode on the containing rectangle: L = left; C = center; R = right.</li>
17735 * <li>string $style['stretch'] if true stretch the barcode to best fit the available width, otherwise uses $xres resolution for a single bar.</li>
17736 * <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>
17737 * <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>
17738 * @param $align (string) Indicates the alignment of the pointer next to barcode insertion relative to barcode height. The value can be:<ul><li>T: top-right for LTR or top-left for RTL</li><li>M: middle-right for LTR or middle-left for RTL</li><li>B: bottom-right for LTR or bottom-left for RTL</li><li>N: next line</li></ul>
17739 * @author Nicola Asuni
17740 * @since 3.1.000 (2008-06-09)
17741 * @public
17743 public function write1DBarcode($code, $type, $x='', $y='', $w='', $h='', $xres='', $style='', $align='') {
17744 if ($this->empty_string(trim($code))) {
17745 return;
17747 require_once(dirname(__FILE__).'/barcodes.php');
17748 // save current graphic settings
17749 $gvars = $this->getGraphicVars();
17750 // create new barcode object
17751 $barcodeobj = new TCPDFBarcode($code, $type);
17752 $arrcode = $barcodeobj->getBarcodeArray();
17753 if ($arrcode === false) {
17754 $this->Error('Error in 1D barcode string');
17756 // set default values
17757 if (!isset($style['position'])) {
17758 $style['position'] = '';
17759 } elseif ($style['position'] == 'S') {
17760 // keep this for backward compatibility
17761 $style['position'] = '';
17762 $style['stretch'] = true;
17764 if (!isset($style['fitwidth'])) {
17765 if (!isset($style['stretch'])) {
17766 $style['fitwidth'] = true;
17767 } else {
17768 $style['fitwidth'] = false;
17771 if ($style['fitwidth']) {
17772 // disable stretch
17773 $style['stretch'] = false;
17775 if (!isset($style['stretch'])) {
17776 if (($w === '') OR ($w <= 0)) {
17777 $style['stretch'] = false;
17778 } else {
17779 $style['stretch'] = true;
17782 if (!isset($style['fgcolor'])) {
17783 $style['fgcolor'] = array(0,0,0); // default black
17785 if (!isset($style['bgcolor'])) {
17786 $style['bgcolor'] = false; // default transparent
17788 if (!isset($style['border'])) {
17789 $style['border'] = false;
17791 $fontsize = 0;
17792 if (!isset($style['text'])) {
17793 $style['text'] = false;
17795 if ($style['text'] AND isset($style['font'])) {
17796 if (isset($style['fontsize'])) {
17797 $fontsize = $style['fontsize'];
17799 $this->SetFont($style['font'], '', $fontsize);
17801 if (!isset($style['stretchtext'])) {
17802 $style['stretchtext'] = 4;
17804 if ($x === '') {
17805 $x = $this->x;
17807 if ($y === '') {
17808 $y = $this->y;
17810 // check page for no-write regions and adapt page margins if necessary
17811 list($x, $y) = $this->checkPageRegions($h, $x, $y);
17812 if (($w === '') OR ($w <= 0)) {
17813 if ($this->rtl) {
17814 $w = $x - $this->lMargin;
17815 } else {
17816 $w = $this->w - $this->rMargin - $x;
17819 // padding
17820 if (!isset($style['padding'])) {
17821 $padding = 0;
17822 } elseif ($style['padding'] === 'auto') {
17823 $padding = 10 * ($w / ($arrcode['maxw'] + 20));
17824 } else {
17825 $padding = floatval($style['padding']);
17827 // horizontal padding
17828 if (!isset($style['hpadding'])) {
17829 $hpadding = $padding;
17830 } elseif ($style['hpadding'] === 'auto') {
17831 $hpadding = 10 * ($w / ($arrcode['maxw'] + 20));
17832 } else {
17833 $hpadding = floatval($style['hpadding']);
17835 // vertical padding
17836 if (!isset($style['vpadding'])) {
17837 $vpadding = $padding;
17838 } elseif ($style['vpadding'] === 'auto') {
17839 $vpadding = ($hpadding / 2);
17840 } else {
17841 $vpadding = floatval($style['vpadding']);
17843 // calculate xres (single bar width)
17844 $max_xres = ($w - (2 * $hpadding)) / $arrcode['maxw'];
17845 if ($style['stretch']) {
17846 $xres = $max_xres;
17847 } else {
17848 if ($this->empty_string($xres)) {
17849 $xres = (0.141 * $this->k); // default bar width = 0.4 mm
17851 if ($xres > $max_xres) {
17852 // correct xres to fit on $w
17853 $xres = $max_xres;
17855 if ((isset($style['padding']) AND ($style['padding'] === 'auto'))
17856 OR (isset($style['hpadding']) AND ($style['hpadding'] === 'auto'))) {
17857 $hpadding = 10 * $xres;
17858 if (isset($style['vpadding']) AND ($style['vpadding'] === 'auto')) {
17859 $vpadding = ($hpadding / 2);
17863 if ($style['fitwidth']) {
17864 $wold = $w;
17865 $w = (($arrcode['maxw'] * $xres) + (2 * $hpadding));
17866 if (isset($style['cellfitalign'])) {
17867 switch ($style['cellfitalign']) {
17868 case 'L': {
17869 if ($this->rtl) {
17870 $x -= ($wold - $w);
17872 break;
17874 case 'R': {
17875 if (!$this->rtl) {
17876 $x += ($wold - $w);
17878 break;
17880 case 'C': {
17881 if ($this->rtl) {
17882 $x -= (($wold - $w) / 2);
17883 } else {
17884 $x += (($wold - $w) / 2);
17886 break;
17888 default : {
17889 break;
17894 $text_height = ($this->cell_height_ratio * $fontsize / $this->k);
17895 // height
17896 if (($h === '') OR ($h <= 0)) {
17897 // set default height
17898 $h = (($arrcode['maxw'] * $xres) / 3) + (2 * $vpadding) + $text_height;
17900 $barh = $h - $text_height - (2 * $vpadding);
17901 if ($barh <=0) {
17902 // try to reduce font or padding to fit barcode on available height
17903 if ($text_height > $h) {
17904 $fontsize = (($h * $this->k) / (4 * $this->cell_height_ratio));
17905 $text_height = ($this->cell_height_ratio * $fontsize / $this->k);
17906 $this->SetFont($style['font'], '', $fontsize);
17908 if ($vpadding > 0) {
17909 $vpadding = (($h - $text_height) / 4);
17911 $barh = $h - $text_height - (2 * $vpadding);
17913 // fit the barcode on available space
17914 list($w, $h, $x, $y) = $this->fitBlock($w, $h, $x, $y, false);
17915 // set alignment
17916 $this->img_rb_y = $y + $h;
17917 // set alignment
17918 if ($this->rtl) {
17919 if ($style['position'] == 'L') {
17920 $xpos = $this->lMargin;
17921 } elseif ($style['position'] == 'C') {
17922 $xpos = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
17923 } elseif ($style['position'] == 'R') {
17924 $xpos = $this->w - $this->rMargin - $w;
17925 } else {
17926 $xpos = $x - $w;
17928 $this->img_rb_x = $xpos;
17929 } else {
17930 if ($style['position'] == 'L') {
17931 $xpos = $this->lMargin;
17932 } elseif ($style['position'] == 'C') {
17933 $xpos = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
17934 } elseif ($style['position'] == 'R') {
17935 $xpos = $this->w - $this->rMargin - $w;
17936 } else {
17937 $xpos = $x;
17939 $this->img_rb_x = $xpos + $w;
17941 $xpos_rect = $xpos;
17942 if (!isset($style['align'])) {
17943 $style['align'] = 'C';
17945 switch ($style['align']) {
17946 case 'L': {
17947 $xpos = $xpos_rect + $hpadding;
17948 break;
17950 case 'R': {
17951 $xpos = $xpos_rect + ($w - ($arrcode['maxw'] * $xres)) - $hpadding;
17952 break;
17954 case 'C':
17955 default : {
17956 $xpos = $xpos_rect + (($w - ($arrcode['maxw'] * $xres)) / 2);
17957 break;
17960 $xpos_text = $xpos;
17961 // barcode is always printed in LTR direction
17962 $tempRTL = $this->rtl;
17963 $this->rtl = false;
17964 // print background color
17965 if ($style['bgcolor']) {
17966 $this->Rect($xpos_rect, $y, $w, $h, $style['border'] ? 'DF' : 'F', '', $style['bgcolor']);
17967 } elseif ($style['border']) {
17968 $this->Rect($xpos_rect, $y, $w, $h, 'D');
17970 // set foreground color
17971 $this->SetDrawColorArray($style['fgcolor']);
17972 $this->SetTextColorArray($style['fgcolor']);
17973 // print bars
17974 foreach ($arrcode['bcode'] as $k => $v) {
17975 $bw = ($v['w'] * $xres);
17976 if ($v['t']) {
17977 // draw a vertical bar
17978 $ypos = $y + $vpadding + ($v['p'] * $barh / $arrcode['maxh']);
17979 $this->Rect($xpos, $ypos, $bw, ($v['h'] * $barh / $arrcode['maxh']), 'F', array(), $style['fgcolor']);
17981 $xpos += $bw;
17983 // print text
17984 if ($style['text']) {
17985 if (isset($style['label']) AND !$this->empty_string($style['label'])) {
17986 $label = $style['label'];
17987 } else {
17988 $label = $code;
17990 $txtwidth = ($arrcode['maxw'] * $xres);
17991 if ($this->GetStringWidth($label) > $txtwidth) {
17992 $style['stretchtext'] = 2;
17994 // print text
17995 $this->x = $xpos_text;
17996 $this->y = $y + $vpadding + $barh;
17997 $cellpadding = $this->cell_padding;
17998 $this->SetCellPadding(0);
17999 $this->Cell($txtwidth, '', $label, 0, 0, 'C', 0, '', $style['stretchtext'], false, 'T', 'T');
18000 $this->cell_padding = $cellpadding;
18002 // restore original direction
18003 $this->rtl = $tempRTL;
18004 // restore previous settings
18005 $this->setGraphicVars($gvars);
18006 // set pointer to align the next text/objects
18007 switch($align) {
18008 case 'T':{
18009 $this->y = $y;
18010 $this->x = $this->img_rb_x;
18011 break;
18013 case 'M':{
18014 $this->y = $y + round($h / 2);
18015 $this->x = $this->img_rb_x;
18016 break;
18018 case 'B':{
18019 $this->y = $this->img_rb_y;
18020 $this->x = $this->img_rb_x;
18021 break;
18023 case 'N':{
18024 $this->SetY($this->img_rb_y);
18025 break;
18027 default:{
18028 break;
18031 $this->endlinex = $this->img_rb_x;
18035 * This function is DEPRECATED, please use the new write1DBarcode() function.
18036 * @param $x (int) x position in user units
18037 * @param $y (int) y position in user units
18038 * @param $w (int) width in user units
18039 * @param $h (int) height position in user units
18040 * @param $type (string) type of barcode
18041 * @param $style (string) barcode style
18042 * @param $font (string) font for text
18043 * @param $xres (int) x resolution
18044 * @param $code (string) code to print
18045 * @deprecated deprecated since version 3.1.000 (2008-06-10)
18046 * @public
18047 * @see write1DBarcode()
18049 public function writeBarcode($x, $y, $w, $h, $type, $style, $font, $xres, $code) {
18050 // convert old settings for the new write1DBarcode() function.
18051 $xres = 1 / $xres;
18052 $newstyle = array(
18053 'position' => '',
18054 'align' => '',
18055 'stretch' => false,
18056 'fitwidth' => false,
18057 'cellfitalign' => '',
18058 'border' => false,
18059 'padding' => 0,
18060 'fgcolor' => array(0,0,0),
18061 'bgcolor' => false,
18062 'text' => true,
18063 'font' => $font,
18064 'fontsize' => 8,
18065 'stretchtext' => 4
18067 if ($style & 1) {
18068 $newstyle['border'] = true;
18070 if ($style & 2) {
18071 $newstyle['bgcolor'] = false;
18073 if ($style & 4) {
18074 $newstyle['position'] = 'C';
18075 } elseif ($style & 8) {
18076 $newstyle['position'] = 'L';
18077 } elseif ($style & 16) {
18078 $newstyle['position'] = 'R';
18080 if ($style & 128) {
18081 $newstyle['text'] = true;
18083 if ($style & 256) {
18084 $newstyle['stretchtext'] = 4;
18086 $this->write1DBarcode($code, $type, $x, $y, $w, $h, $xres, $newstyle, '');
18090 * Print 2D Barcode.
18091 * @param $code (string) code to print
18092 * @param $type (string) type of barcode (see 2dbarcodes.php for supported formats).
18093 * @param $x (int) x position in user units
18094 * @param $y (int) y position in user units
18095 * @param $w (int) width in user units
18096 * @param $h (int) height in user units
18097 * @param $style (array) array of options:<ul>
18098 * <li>boolean $style['border'] if true prints a border around the barcode</li>
18099 * <li>int $style['padding'] padding to leave around the barcode in barcode units (set to 'auto' for automatic padding)</li>
18100 * <li>int $style['hpadding'] horizontal padding in barcode units (set to 'auto' for automatic padding)</li>
18101 * <li>int $style['vpadding'] vertical padding in barcode units (set to 'auto' for automatic padding)</li>
18102 * <li>int $style['module_width'] width of a single module in points</li>
18103 * <li>int $style['module_height'] height of a single module in points</li>
18104 * <li>array $style['fgcolor'] color array for bars and text</li>
18105 * <li>mixed $style['bgcolor'] color array for background or false for transparent</li>
18106 * <li>string $style['position'] barcode position on the page: L = left margin; C = center; R = right margin; S = stretch</li><li>$style['module_width'] width of a single module in points</li>
18107 * <li>$style['module_height'] height of a single module in points</li></ul>
18108 * @param $align (string) Indicates the alignment of the pointer next to barcode insertion relative to barcode height. The value can be:<ul><li>T: top-right for LTR or top-left for RTL</li><li>M: middle-right for LTR or middle-left for RTL</li><li>B: bottom-right for LTR or bottom-left for RTL</li><li>N: next line</li></ul>
18109 * @param $distort (boolean) if true distort the barcode to fit width and height, otherwise preserve aspect ratio
18110 * @author Nicola Asuni
18111 * @since 4.5.037 (2009-04-07)
18112 * @public
18114 public function write2DBarcode($code, $type, $x='', $y='', $w='', $h='', $style='', $align='', $distort=false) {
18115 if ($this->empty_string(trim($code))) {
18116 return;
18118 require_once(dirname(__FILE__).'/2dbarcodes.php');
18119 // save current graphic settings
18120 $gvars = $this->getGraphicVars();
18121 // create new barcode object
18122 $barcodeobj = new TCPDF2DBarcode($code, $type);
18123 $arrcode = $barcodeobj->getBarcodeArray();
18124 if (($arrcode === false) OR empty($arrcode)) {
18125 $this->Error('Error in 2D barcode string');
18127 // set default values
18128 if (!isset($style['position'])) {
18129 $style['position'] = '';
18131 if (!isset($style['fgcolor'])) {
18132 $style['fgcolor'] = array(0,0,0); // default black
18134 if (!isset($style['bgcolor'])) {
18135 $style['bgcolor'] = false; // default transparent
18137 if (!isset($style['border'])) {
18138 $style['border'] = false;
18140 // padding
18141 if (!isset($style['padding'])) {
18142 $style['padding'] = 0;
18143 } elseif ($style['padding'] === 'auto') {
18144 $style['padding'] = 4;
18146 if (!isset($style['hpadding'])) {
18147 $style['hpadding'] = $style['padding'];
18148 } elseif ($style['hpadding'] === 'auto') {
18149 $style['hpadding'] = 4;
18151 if (!isset($style['vpadding'])) {
18152 $style['vpadding'] = $style['padding'];
18153 } elseif ($style['vpadding'] === 'auto') {
18154 $style['vpadding'] = 4;
18156 // cell (module) dimension
18157 if (!isset($style['module_width'])) {
18158 $style['module_width'] = 1; // width of a single module in points
18160 if (!isset($style['module_height'])) {
18161 $style['module_height'] = 1; // height of a single module in points
18163 if ($x === '') {
18164 $x = $this->x;
18166 if ($y === '') {
18167 $y = $this->y;
18169 // check page for no-write regions and adapt page margins if necessary
18170 list($x, $y) = $this->checkPageRegions($h, $x, $y);
18171 // number of barcode columns and rows
18172 $rows = $arrcode['num_rows'];
18173 $cols = $arrcode['num_cols'];
18174 // module width and height
18175 $mw = $style['module_width'];
18176 $mh = $style['module_height'];
18177 // get max dimensions
18178 if ($this->rtl) {
18179 $maxw = $x - $this->lMargin;
18180 } else {
18181 $maxw = $this->w - $this->rMargin - $x;
18183 $maxh = ($this->h - $this->tMargin - $this->bMargin);
18184 $ratioHW = ($rows * $mh) / ($cols * $mw);
18185 $ratioWH = ($cols * $mw) / ($rows * $mh);
18186 if (!$distort) {
18187 if (($maxw * $ratioHW) > $maxh) {
18188 $maxw = $maxh * $ratioWH;
18190 if (($maxh * $ratioWH) > $maxw) {
18191 $maxh = $maxw * $ratioHW;
18194 // set maximum dimesions
18195 if ($w > $maxw) {
18196 $w = $maxw;
18198 if ($h > $maxh) {
18199 $h = $maxh;
18201 $hpad = (2 * $style['hpadding']);
18202 $vpad = (2 * $style['vpadding']);
18203 // set dimensions
18204 if ((($w === '') OR ($w <= 0)) AND (($h === '') OR ($h <= 0))) {
18205 $w = ($cols + $hpad) * ($mw / $this->k);
18206 $h = ($rows + $vpad) * ($mh / $this->k);
18207 } elseif (($w === '') OR ($w <= 0)) {
18208 $w = $h * $ratioWH;
18209 } elseif (($h === '') OR ($h <= 0)) {
18210 $h = $w * $ratioHW;
18212 // barcode size (excluding padding)
18213 $bw = ($w * $cols) / ($cols + $hpad);
18214 $bh = ($h * $rows) / ($rows + $vpad);
18215 // dimension of single barcode cell unit
18216 $cw = $bw / $cols;
18217 $ch = $bh / $rows;
18218 if (!$distort) {
18219 if (($cw / $ch) > ($mw / $mh)) {
18220 // correct horizontal distortion
18221 $cw = $ch * $mw / $mh;
18222 $bw = $cw * $cols;
18223 $style['hpadding'] = ($w - $bw) / (2 * $cw);
18224 } else {
18225 // correct vertical distortion
18226 $ch = $cw * $mh / $mw;
18227 $bh = $ch * $rows;
18228 $style['vpadding'] = ($h - $bh) / (2 * $ch);
18231 // fit the barcode on available space
18232 list($w, $h, $x, $y) = $this->fitBlock($w, $h, $x, $y, false);
18233 // set alignment
18234 $this->img_rb_y = $y + $h;
18235 // set alignment
18236 if ($this->rtl) {
18237 if ($style['position'] == 'L') {
18238 $xpos = $this->lMargin;
18239 } elseif ($style['position'] == 'C') {
18240 $xpos = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
18241 } elseif ($style['position'] == 'R') {
18242 $xpos = $this->w - $this->rMargin - $w;
18243 } else {
18244 $xpos = $x - $w;
18246 $this->img_rb_x = $xpos;
18247 } else {
18248 if ($style['position'] == 'L') {
18249 $xpos = $this->lMargin;
18250 } elseif ($style['position'] == 'C') {
18251 $xpos = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
18252 } elseif ($style['position'] == 'R') {
18253 $xpos = $this->w - $this->rMargin - $w;
18254 } else {
18255 $xpos = $x;
18257 $this->img_rb_x = $xpos + $w;
18259 $xstart = $xpos + ($style['hpadding'] * $cw);
18260 $ystart = $y + ($style['vpadding'] * $ch);
18261 // barcode is always printed in LTR direction
18262 $tempRTL = $this->rtl;
18263 $this->rtl = false;
18264 // print background color
18265 if ($style['bgcolor']) {
18266 $this->Rect($xpos, $y, $w, $h, $style['border'] ? 'DF' : 'F', '', $style['bgcolor']);
18267 } elseif ($style['border']) {
18268 $this->Rect($xpos, $y, $w, $h, 'D');
18270 // set foreground color
18271 $this->SetDrawColorArray($style['fgcolor']);
18272 // print barcode cells
18273 // for each row
18274 for ($r = 0; $r < $rows; ++$r) {
18275 $xr = $xstart;
18276 // for each column
18277 for ($c = 0; $c < $cols; ++$c) {
18278 if ($arrcode['bcode'][$r][$c] == 1) {
18279 // draw a single barcode cell
18280 $this->Rect($xr, $ystart, $cw, $ch, 'F', array(), $style['fgcolor']);
18282 $xr += $cw;
18284 $ystart += $ch;
18286 // restore original direction
18287 $this->rtl = $tempRTL;
18288 // restore previous settings
18289 $this->setGraphicVars($gvars);
18290 // set pointer to align the next text/objects
18291 switch($align) {
18292 case 'T':{
18293 $this->y = $y;
18294 $this->x = $this->img_rb_x;
18295 break;
18297 case 'M':{
18298 $this->y = $y + round($h/2);
18299 $this->x = $this->img_rb_x;
18300 break;
18302 case 'B':{
18303 $this->y = $this->img_rb_y;
18304 $this->x = $this->img_rb_x;
18305 break;
18307 case 'N':{
18308 $this->SetY($this->img_rb_y);
18309 break;
18311 default:{
18312 break;
18315 $this->endlinex = $this->img_rb_x;
18319 * Returns an array containing current margins:
18320 * <ul>
18321 <li>$ret['left'] = left margin</li>
18322 <li>$ret['right'] = right margin</li>
18323 <li>$ret['top'] = top margin</li>
18324 <li>$ret['bottom'] = bottom margin</li>
18325 <li>$ret['header'] = header margin</li>
18326 <li>$ret['footer'] = footer margin</li>
18327 <li>$ret['cell'] = cell padding array</li>
18328 <li>$ret['padding_left'] = cell left padding</li>
18329 <li>$ret['padding_top'] = cell top padding</li>
18330 <li>$ret['padding_right'] = cell right padding</li>
18331 <li>$ret['padding_bottom'] = cell bottom padding</li>
18332 * </ul>
18333 * @return array containing all margins measures
18334 * @public
18335 * @since 3.2.000 (2008-06-23)
18337 public function getMargins() {
18338 $ret = array(
18339 'left' => $this->lMargin,
18340 'right' => $this->rMargin,
18341 'top' => $this->tMargin,
18342 'bottom' => $this->bMargin,
18343 'header' => $this->header_margin,
18344 'footer' => $this->footer_margin,
18345 'cell' => $this->cell_padding,
18346 'padding_left' => $this->cell_padding['L'],
18347 'padding_top' => $this->cell_padding['T'],
18348 'padding_right' => $this->cell_padding['R'],
18349 'padding_bottom' => $this->cell_padding['B']
18351 return $ret;
18355 * Returns an array containing original margins:
18356 * <ul>
18357 <li>$ret['left'] = left margin</li>
18358 <li>$ret['right'] = right margin</li>
18359 * </ul>
18360 * @return array containing all margins measures
18361 * @public
18362 * @since 4.0.012 (2008-07-24)
18364 public function getOriginalMargins() {
18365 $ret = array(
18366 'left' => $this->original_lMargin,
18367 'right' => $this->original_rMargin
18369 return $ret;
18373 * Returns the current font size.
18374 * @return current font size
18375 * @public
18376 * @since 3.2.000 (2008-06-23)
18378 public function getFontSize() {
18379 return $this->FontSize;
18383 * Returns the current font size in points unit.
18384 * @return current font size in points unit
18385 * @public
18386 * @since 3.2.000 (2008-06-23)
18388 public function getFontSizePt() {
18389 return $this->FontSizePt;
18393 * Returns the current font family name.
18394 * @return string current font family name
18395 * @public
18396 * @since 4.3.008 (2008-12-05)
18398 public function getFontFamily() {
18399 return $this->FontFamily;
18403 * Returns the current font style.
18404 * @return string current font style
18405 * @public
18406 * @since 4.3.008 (2008-12-05)
18408 public function getFontStyle() {
18409 return $this->FontStyle;
18413 * Cleanup HTML code (requires HTML Tidy library).
18414 * @param $html (string) htmlcode to fix
18415 * @param $default_css (string) CSS commands to add
18416 * @param $tagvs (array) parameters for setHtmlVSpace method
18417 * @param $tidy_options (array) options for tidy_parse_string function
18418 * @return string XHTML code cleaned up
18419 * @author Nicola Asuni
18420 * @public
18421 * @since 5.9.017 (2010-11-16)
18422 * @see setHtmlVSpace()
18424 public function fixHTMLCode($html, $default_css='', $tagvs='', $tidy_options='') {
18425 // configure parameters for HTML Tidy
18426 if ($tidy_options === '') {
18427 $tidy_options = array (
18428 'clean' => 1,
18429 'drop-empty-paras' => 0,
18430 'drop-proprietary-attributes' => 1,
18431 'fix-backslash' => 1,
18432 'hide-comments' => 1,
18433 'join-styles' => 1,
18434 'lower-literals' => 1,
18435 'merge-divs' => 1,
18436 'merge-spans' => 1,
18437 'output-xhtml' => 1,
18438 'word-2000' => 1,
18439 'wrap' => 0,
18440 'output-bom' => 0,
18441 //'char-encoding' => 'utf8',
18442 //'input-encoding' => 'utf8',
18443 //'output-encoding' => 'utf8'
18446 // clean up the HTML code
18447 $tidy = tidy_parse_string($html, $tidy_options);
18448 // fix the HTML
18449 $tidy->cleanRepair();
18450 // get the CSS part
18451 $tidy_head = tidy_get_head($tidy);
18452 $css = $tidy_head->value;
18453 $css = preg_replace('/<style([^>]+)>/ims', '<style>', $css);
18454 $css = preg_replace('/<\/style>(.*)<style>/ims', "\n", $css);
18455 $css = str_replace('/*<![CDATA[*/', '', $css);
18456 $css = str_replace('/*]]>*/', '', $css);
18457 preg_match('/<style>(.*)<\/style>/ims', $css, $matches);
18458 if (isset($matches[1])) {
18459 $css = strtolower($matches[1]);
18460 } else {
18461 $css = '';
18463 // include default css
18464 $css = '<style>'.$default_css.$css.'</style>';
18465 // get the body part
18466 $tidy_body = tidy_get_body($tidy);
18467 $html = $tidy_body->value;
18468 // fix some self-closing tags
18469 $html = str_replace('<br>', '<br />', $html);
18470 // remove some empty tag blocks
18471 $html = preg_replace('/<div([^\>]*)><\/div>/', '', $html);
18472 $html = preg_replace('/<p([^\>]*)><\/p>/', '', $html);
18473 if ($tagvs !== '') {
18474 // set vertical space for some XHTML tags
18475 $this->setHtmlVSpace($tagvs);
18477 // return the cleaned XHTML code + CSS
18478 return $css.$html;
18482 * Extracts the CSS properties from a CSS string.
18483 * @param $cssdata (string) string containing CSS definitions.
18484 * @return An array where the keys are the CSS selectors and the values are the CSS properties.
18485 * @author Nicola Asuni
18486 * @since 5.1.000 (2010-05-25)
18487 * @protected
18489 protected function extractCSSproperties($cssdata) {
18490 if (empty($cssdata)) {
18491 return array();
18493 // remove comments
18494 $cssdata = preg_replace('/\/\*[^\*]*\*\//', '', $cssdata);
18495 // remove newlines and multiple spaces
18496 $cssdata = preg_replace('/[\s]+/', ' ', $cssdata);
18497 // remove some spaces
18498 $cssdata = preg_replace('/[\s]*([;:\{\}]{1})[\s]*/', '\\1', $cssdata);
18499 // remove empty blocks
18500 $cssdata = preg_replace('/([^\}\{]+)\{\}/', '', $cssdata);
18501 // replace media type parenthesis
18502 $cssdata = preg_replace('/@media[\s]+([^\{]*)\{/i', '@media \\1§', $cssdata);
18503 $cssdata = preg_replace('/\}\}/si', '}§', $cssdata);
18504 // trim string
18505 $cssdata = trim($cssdata);
18506 // find media blocks (all, braille, embossed, handheld, print, projection, screen, speech, tty, tv)
18507 $cssblocks = array();
18508 $matches = array();
18509 if (preg_match_all('/@media[\s]+([^\§]*)§([^§]*)§/i', $cssdata, $matches) > 0) {
18510 foreach ($matches[1] as $key => $type) {
18511 $cssblocks[$type] = $matches[2][$key];
18513 // remove media blocks
18514 $cssdata = preg_replace('/@media[\s]+([^\§]*)§([^§]*)§/i', '', $cssdata);
18516 // keep 'all' and 'print' media, other media types are discarded
18517 if (isset($cssblocks['all']) AND !empty($cssblocks['all'])) {
18518 $cssdata .= $cssblocks['all'];
18520 if (isset($cssblocks['print']) AND !empty($cssblocks['print'])) {
18521 $cssdata .= $cssblocks['print'];
18523 // reset css blocks array
18524 $cssblocks = array();
18525 $matches = array();
18526 // explode css data string into array
18527 if (substr($cssdata, -1) == '}') {
18528 // remove last parethesis
18529 $cssdata = substr($cssdata, 0, -1);
18531 $matches = explode('}', $cssdata);
18532 foreach ($matches as $key => $block) {
18533 // index 0 contains the CSS selector, index 1 contains CSS properties
18534 $cssblocks[$key] = explode('{', $block);
18535 if (!isset($cssblocks[$key][1])) {
18536 // remove empty definitions
18537 unset($cssblocks[$key]);
18540 // split groups of selectors (comma-separated list of selectors)
18541 foreach ($cssblocks as $key => $block) {
18542 if (strpos($block[0], ',') > 0) {
18543 $selectors = explode(',', $block[0]);
18544 foreach ($selectors as $sel) {
18545 $cssblocks[] = array(0 => trim($sel), 1 => $block[1]);
18547 unset($cssblocks[$key]);
18550 // covert array to selector => properties
18551 $cssdata = array();
18552 foreach ($cssblocks as $block) {
18553 $selector = $block[0];
18554 // calculate selector's specificity
18555 $matches = array();
18556 $a = 0; // the declaration is not from is a 'style' attribute
18557 $b = intval(preg_match_all('/[\#]/', $selector, $matches)); // number of ID attributes
18558 $c = intval(preg_match_all('/[\[\.]/', $selector, $matches)); // number of other attributes
18559 $c += intval(preg_match_all('/[\:]link|visited|hover|active|focus|target|lang|enabled|disabled|checked|indeterminate|root|nth|first|last|only|empty|contains|not/i', $selector, $matches)); // number of pseudo-classes
18560 $d = intval(preg_match_all('/[\>\+\~\s]{1}[a-zA-Z0-9]+/', ' '.$selector, $matches)); // number of element names
18561 $d += intval(preg_match_all('/[\:][\:]/', $selector, $matches)); // number of pseudo-elements
18562 $specificity = $a.$b.$c.$d;
18563 // add specificity to the beginning of the selector
18564 $cssdata[$specificity.' '.$selector] = $block[1];
18566 // sort selectors alphabetically to account for specificity
18567 ksort($cssdata, SORT_STRING);
18568 // return array
18569 return $cssdata;
18573 * Returns true if the CSS selector is valid for the selected HTML tag
18574 * @param $dom (array) array of HTML tags and properties
18575 * @param $key (int) key of the current HTML tag
18576 * @param $selector (string) CSS selector string
18577 * @return true if the selector is valid, false otherwise
18578 * @protected
18579 * @since 5.1.000 (2010-05-25)
18581 protected function isValidCSSSelectorForTag($dom, $key, $selector) {
18582 $valid = false; // value to be returned
18583 $tag = $dom[$key]['value'];
18584 $class = array();
18585 if (isset($dom[$key]['attribute']['class']) AND !empty($dom[$key]['attribute']['class'])) {
18586 $class = explode(' ', strtolower($dom[$key]['attribute']['class']));
18588 $id = '';
18589 if (isset($dom[$key]['attribute']['id']) AND !empty($dom[$key]['attribute']['id'])) {
18590 $id = strtolower($dom[$key]['attribute']['id']);
18592 $selector = preg_replace('/([\>\+\~\s]{1})([\.]{1})([^\>\+\~\s]*)/si', '\\1*.\\3', $selector);
18593 $matches = array();
18594 if (preg_match_all('/([\>\+\~\s]{1})([a-zA-Z0-9\*]+)([^\>\+\~\s]*)/si', $selector, $matches, PREG_PATTERN_ORDER | PREG_OFFSET_CAPTURE) > 0) {
18595 $parentop = array_pop($matches[1]);
18596 $operator = $parentop[0];
18597 $offset = $parentop[1];
18598 $lasttag = array_pop($matches[2]);
18599 $lasttag = strtolower(trim($lasttag[0]));
18600 if (($lasttag == '*') OR ($lasttag == $tag)) {
18601 // the last element on selector is our tag or 'any tag'
18602 $attrib = array_pop($matches[3]);
18603 $attrib = strtolower(trim($attrib[0]));
18604 if (!empty($attrib)) {
18605 // check if matches class, id, attribute, pseudo-class or pseudo-element
18606 switch ($attrib{0}) {
18607 case '.': { // class
18608 if (in_array(substr($attrib, 1), $class)) {
18609 $valid = true;
18611 break;
18613 case '#': { // ID
18614 if (substr($attrib, 1) == $id) {
18615 $valid = true;
18617 break;
18619 case '[': { // attribute
18620 $attrmatch = array();
18621 if (preg_match('/\[([a-zA-Z0-9]*)[\s]*([\~\^\$\*\|\=]*)[\s]*["]?([^"\]]*)["]?\]/i', $attrib, $attrmatch) > 0) {
18622 $att = strtolower($attrmatch[1]);
18623 $val = $attrmatch[3];
18624 if (isset($dom[$key]['attribute'][$att])) {
18625 switch ($attrmatch[2]) {
18626 case '=': {
18627 if ($dom[$key]['attribute'][$att] == $val) {
18628 $valid = true;
18630 break;
18632 case '~=': {
18633 if (in_array($val, explode(' ', $dom[$key]['attribute'][$att]))) {
18634 $valid = true;
18636 break;
18638 case '^=': {
18639 if ($val == substr($dom[$key]['attribute'][$att], 0, strlen($val))) {
18640 $valid = true;
18642 break;
18644 case '$=': {
18645 if ($val == substr($dom[$key]['attribute'][$att], -strlen($val))) {
18646 $valid = true;
18648 break;
18650 case '*=': {
18651 if (strpos($dom[$key]['attribute'][$att], $val) !== false) {
18652 $valid = true;
18654 break;
18656 case '|=': {
18657 if ($dom[$key]['attribute'][$att] == $val) {
18658 $valid = true;
18659 } elseif (preg_match('/'.$val.'[\-]{1}/i', $dom[$key]['attribute'][$att]) > 0) {
18660 $valid = true;
18662 break;
18664 default: {
18665 $valid = true;
18670 break;
18672 case ':': { // pseudo-class or pseudo-element
18673 if ($attrib{1} == ':') { // pseudo-element
18674 // pseudo-elements are not supported!
18675 // (::first-line, ::first-letter, ::before, ::after)
18676 } else { // pseudo-class
18677 // pseudo-classes are not supported!
18678 // (:root, :nth-child(n), :nth-last-child(n), :nth-of-type(n), :nth-last-of-type(n), :first-child, :last-child, :first-of-type, :last-of-type, :only-child, :only-of-type, :empty, :link, :visited, :active, :hover, :focus, :target, :lang(fr), :enabled, :disabled, :checked)
18680 break;
18682 } // end of switch
18683 } else {
18684 $valid = true;
18686 if ($valid AND ($offset > 0)) {
18687 $valid = false;
18688 // check remaining selector part
18689 $selector = substr($selector, 0, $offset);
18690 switch ($operator) {
18691 case ' ': { // descendant of an element
18692 while ($dom[$key]['parent'] > 0) {
18693 if ($this->isValidCSSSelectorForTag($dom, $dom[$key]['parent'], $selector)) {
18694 $valid = true;
18695 break;
18696 } else {
18697 $key = $dom[$key]['parent'];
18700 break;
18702 case '>': { // child of an element
18703 $valid = $this->isValidCSSSelectorForTag($dom, $dom[$key]['parent'], $selector);
18704 break;
18706 case '+': { // immediately preceded by an element
18707 for ($i = ($key - 1); $i > $dom[$key]['parent']; --$i) {
18708 if ($dom[$i]['tag'] AND $dom[$i]['opening']) {
18709 $valid = $this->isValidCSSSelectorForTag($dom, $i, $selector);
18710 break;
18713 break;
18715 case '~': { // preceded by an element
18716 for ($i = ($key - 1); $i > $dom[$key]['parent']; --$i) {
18717 if ($dom[$i]['tag'] AND $dom[$i]['opening']) {
18718 if ($this->isValidCSSSelectorForTag($dom, $i, $selector)) {
18719 break;
18723 break;
18729 return $valid;
18733 * Returns the styles array that apply for the selected HTML tag.
18734 * @param $dom (array) array of HTML tags and properties
18735 * @param $key (int) key of the current HTML tag
18736 * @param $css (array) array of CSS properties
18737 * @return array containing CSS properties
18738 * @protected
18739 * @since 5.1.000 (2010-05-25)
18741 protected function getCSSdataArray($dom, $key, $css) {
18742 $cssarray = array(); // style to be returned
18743 // get parent CSS selectors
18744 $selectors = array();
18745 if (isset($dom[($dom[$key]['parent'])]['csssel'])) {
18746 $selectors = $dom[($dom[$key]['parent'])]['csssel'];
18748 // get all styles that apply
18749 foreach($css as $selector => $style) {
18750 $pos = strpos($selector, ' ');
18751 // get specificity
18752 $specificity = substr($selector, 0, $pos);
18753 // remove specificity
18754 $selector = substr($selector, $pos);
18755 // check if this selector apply to current tag
18756 if ($this->isValidCSSSelectorForTag($dom, $key, $selector)) {
18757 if (!in_array($selector, $selectors)) {
18758 // add style if not already added on parent selector
18759 $cssarray[] = array('k' => $selector, 's' => $specificity, 'c' => $style);
18760 $selectors[] = $selector;
18764 if (isset($dom[$key]['attribute']['style'])) {
18765 // attach inline style (latest properties have high priority)
18766 $cssarray[] = array('k' => '', 's' => '1000', 'c' => $dom[$key]['attribute']['style']);
18768 // order the css array to account for specificity
18769 $cssordered = array();
18770 foreach ($cssarray as $key => $val) {
18771 $skey = sprintf('%04d', $key);
18772 $cssordered[$val['s'].'_'.$skey] = $val;
18774 // sort selectors alphabetically to account for specificity
18775 ksort($cssordered, SORT_STRING);
18776 return array($selectors, $cssordered);
18780 * Compact CSS data array into single string.
18781 * @param $css (array) array of CSS properties
18782 * @return string containing merged CSS properties
18783 * @protected
18784 * @since 5.9.070 (2011-04-19)
18786 protected function getTagStyleFromCSSarray($css) {
18787 $tagstyle = ''; // value to be returned
18788 foreach ($css as $style) {
18789 // split single css commands
18790 $csscmds = explode(';', $style['c']);
18791 foreach ($csscmds as $cmd) {
18792 if (!empty($cmd)) {
18793 $pos = strpos($cmd, ':');
18794 if ($pos !== false) {
18795 $cmd = substr($cmd, 0, ($pos + 1));
18796 if (strpos($tagstyle, $cmd) !== false) {
18797 // remove duplicate commands (last commands have high priority)
18798 $tagstyle = preg_replace('/'.$cmd.'[^;]+/i', '', $tagstyle);
18803 $tagstyle .= ';'.$style['c'];
18805 // remove multiple semicolons
18806 $tagstyle = preg_replace('/[;]+/', ';', $tagstyle);
18807 return $tagstyle;
18811 * Returns the border width from CSS property
18812 * @param $width (string) border width
18813 * @return int with in user units
18814 * @protected
18815 * @since 5.7.000 (2010-08-02)
18817 protected function getCSSBorderWidth($width) {
18818 if ($width == 'thin') {
18819 $width = (2 / $this->k);
18820 } elseif ($width == 'medium') {
18821 $width = (4 / $this->k);
18822 } elseif ($width == 'thick') {
18823 $width = (6 / $this->k);
18824 } else {
18825 $width = $this->getHTMLUnitToUnits($width, 1, 'px', false);
18827 return $width;
18831 * Returns the border dash style from CSS property
18832 * @param $style (string) border style to convert
18833 * @return int sash style (return -1 in case of none or hidden border)
18834 * @protected
18835 * @since 5.7.000 (2010-08-02)
18837 protected function getCSSBorderDashStyle($style) {
18838 switch (strtolower($style)) {
18839 case 'none':
18840 case 'hidden': {
18841 $dash = -1;
18842 break;
18844 case 'dotted': {
18845 $dash = 1;
18846 break;
18848 case 'dashed': {
18849 $dash = 3;
18850 break;
18852 case 'double':
18853 case 'groove':
18854 case 'ridge':
18855 case 'inset':
18856 case 'outset':
18857 case 'solid':
18858 default: {
18859 $dash = 0;
18860 break;
18863 return $dash;
18867 * Returns the border style array from CSS border properties
18868 * @param $cssborder (string) border properties
18869 * @return array containing border properties
18870 * @protected
18871 * @since 5.7.000 (2010-08-02)
18873 protected function getCSSBorderStyle($cssborder) {
18874 $bprop = preg_split('/[\s]+/', trim($cssborder));
18875 $border = array(); // value to be returned
18876 switch (count($bprop)) {
18877 case 3: {
18878 $width = $bprop[0];
18879 $style = $bprop[1];
18880 $color = $bprop[2];
18881 break;
18883 case 2: {
18884 $width = 'medium';
18885 $style = $bprop[0];
18886 $color = $bprop[1];
18887 break;
18889 case 1: {
18890 $width = 'medium';
18891 $style = $bprop[0];
18892 $color = 'black';
18893 break;
18895 default: {
18896 $width = 'medium';
18897 $style = 'solid';
18898 $color = 'black';
18899 break;
18902 if ($style == 'none') {
18903 return array();
18905 $border['cap'] = 'square';
18906 $border['join'] = 'miter';
18907 $border['dash'] = $this->getCSSBorderDashStyle($style);
18908 if ($border['dash'] < 0) {
18909 return array();
18911 $border['width'] = $this->getCSSBorderWidth($width);
18912 $border['color'] = $this->convertHTMLColorToDec($color);
18913 return $border;
18917 * Get the internal Cell padding from CSS attribute.
18918 * @param $csspadding (string) padding properties
18919 * @param $width (float) width of the containing element
18920 * @return array of cell paddings
18921 * @public
18922 * @since 5.9.000 (2010-10-04)
18924 public function getCSSPadding($csspadding, $width=0) {
18925 $padding = preg_split('/[\s]+/', trim($csspadding));
18926 $cell_padding = array(); // value to be returned
18927 switch (count($padding)) {
18928 case 4: {
18929 $cell_padding['T'] = $padding[0];
18930 $cell_padding['R'] = $padding[1];
18931 $cell_padding['B'] = $padding[2];
18932 $cell_padding['L'] = $padding[3];
18933 break;
18935 case 3: {
18936 $cell_padding['T'] = $padding[0];
18937 $cell_padding['R'] = $padding[1];
18938 $cell_padding['B'] = $padding[2];
18939 $cell_padding['L'] = $padding[1];
18940 break;
18942 case 2: {
18943 $cell_padding['T'] = $padding[0];
18944 $cell_padding['R'] = $padding[1];
18945 $cell_padding['B'] = $padding[0];
18946 $cell_padding['L'] = $padding[1];
18947 break;
18949 case 1: {
18950 $cell_padding['T'] = $padding[0];
18951 $cell_padding['R'] = $padding[0];
18952 $cell_padding['B'] = $padding[0];
18953 $cell_padding['L'] = $padding[0];
18954 break;
18956 default: {
18957 return $this->cell_padding;
18960 if ($width == 0) {
18961 $width = $this->w - $this->lMargin - $this->rMargin;
18963 $cell_padding['T'] = $this->getHTMLUnitToUnits($cell_padding['T'], $width, 'px', false);
18964 $cell_padding['R'] = $this->getHTMLUnitToUnits($cell_padding['R'], $width, 'px', false);
18965 $cell_padding['B'] = $this->getHTMLUnitToUnits($cell_padding['B'], $width, 'px', false);
18966 $cell_padding['L'] = $this->getHTMLUnitToUnits($cell_padding['L'], $width, 'px', false);
18967 return $cell_padding;
18971 * Get the internal Cell margin from CSS attribute.
18972 * @param $cssmargin (string) margin properties
18973 * @param $width (float) width of the containing element
18974 * @return array of cell margins
18975 * @public
18976 * @since 5.9.000 (2010-10-04)
18978 public function getCSSMargin($cssmargin, $width=0) {
18979 $margin = preg_split('/[\s]+/', trim($cssmargin));
18980 $cell_margin = array(); // value to be returned
18981 switch (count($margin)) {
18982 case 4: {
18983 $cell_margin['T'] = $margin[0];
18984 $cell_margin['R'] = $margin[1];
18985 $cell_margin['B'] = $margin[2];
18986 $cell_margin['L'] = $margin[3];
18987 break;
18989 case 3: {
18990 $cell_margin['T'] = $margin[0];
18991 $cell_margin['R'] = $margin[1];
18992 $cell_margin['B'] = $margin[2];
18993 $cell_margin['L'] = $margin[1];
18994 break;
18996 case 2: {
18997 $cell_margin['T'] = $margin[0];
18998 $cell_margin['R'] = $margin[1];
18999 $cell_margin['B'] = $margin[0];
19000 $cell_margin['L'] = $margin[1];
19001 break;
19003 case 1: {
19004 $cell_margin['T'] = $margin[0];
19005 $cell_margin['R'] = $margin[0];
19006 $cell_margin['B'] = $margin[0];
19007 $cell_margin['L'] = $margin[0];
19008 break;
19010 default: {
19011 return $this->cell_margin;
19014 if ($width == 0) {
19015 $width = $this->w - $this->lMargin - $this->rMargin;
19017 $cell_margin['T'] = $this->getHTMLUnitToUnits(str_replace('auto', '0', $cell_margin['T']), $width, 'px', false);
19018 $cell_margin['R'] = $this->getHTMLUnitToUnits(str_replace('auto', '0', $cell_margin['R']), $width, 'px', false);
19019 $cell_margin['B'] = $this->getHTMLUnitToUnits(str_replace('auto', '0', $cell_margin['B']), $width, 'px', false);
19020 $cell_margin['L'] = $this->getHTMLUnitToUnits(str_replace('auto', '0', $cell_margin['L']), $width, 'px', false);
19021 return $cell_margin;
19025 * Get the border-spacing from CSS attribute.
19026 * @param $cssbspace (string) border-spacing CSS properties
19027 * @param $width (float) width of the containing element
19028 * @return array of border spacings
19029 * @public
19030 * @since 5.9.010 (2010-10-27)
19032 public function getCSSBorderMargin($cssbspace, $width=0) {
19033 $space = preg_split('/[\s]+/', trim($cssbspace));
19034 $border_spacing = array(); // value to be returned
19035 switch (count($space)) {
19036 case 2: {
19037 $border_spacing['H'] = $space[0];
19038 $border_spacing['V'] = $space[1];
19039 break;
19041 case 1: {
19042 $border_spacing['H'] = $space[0];
19043 $border_spacing['V'] = $space[0];
19044 break;
19046 default: {
19047 return array('H' => 0, 'V' => 0);
19050 if ($width == 0) {
19051 $width = $this->w - $this->lMargin - $this->rMargin;
19053 $border_spacing['H'] = $this->getHTMLUnitToUnits($border_spacing['H'], $width, 'px', false);
19054 $border_spacing['V'] = $this->getHTMLUnitToUnits($border_spacing['V'], $width, 'px', false);
19055 return $border_spacing;
19059 * Returns the letter-spacing value from CSS value
19060 * @param $spacing (string) letter-spacing value
19061 * @param $parent (float) font spacing (tracking/kerning) value of the parent element
19062 * @return float quantity to increases or decreases the space between characters in a text.
19063 * @protected
19064 * @since 5.9.000 (2010-10-02)
19066 protected function getCSSFontSpacing($spacing, $parent=0) {
19067 $val = 0; // value to be returned
19068 $spacing = trim($spacing);
19069 switch ($spacing) {
19070 case 'normal': {
19071 $val = 0;
19072 break;
19074 case 'inherit': {
19075 if ($parent == 'normal') {
19076 $val = 0;
19077 } else {
19078 $val = $parent;
19080 break;
19082 default: {
19083 $val = $this->getHTMLUnitToUnits($spacing, 0, 'px', false);
19086 return $val;
19090 * Returns the percentage of font stretching from CSS value
19091 * @param $stretch (string) stretch mode
19092 * @param $parent (float) stretch value of the parent element
19093 * @return float font stretching percentage
19094 * @protected
19095 * @since 5.9.000 (2010-10-02)
19097 protected function getCSSFontStretching($stretch, $parent=100) {
19098 $val = 100; // value to be returned
19099 $stretch = trim($stretch);
19100 switch ($stretch) {
19101 case 'ultra-condensed': {
19102 $val = 40;
19103 break;
19105 case 'extra-condensed': {
19106 $val = 55;
19107 break;
19109 case 'condensed': {
19110 $val = 70;
19111 break;
19113 case 'semi-condensed': {
19114 $val = 85;
19115 break;
19117 case 'normal': {
19118 $val = 100;
19119 break;
19121 case 'semi-expanded': {
19122 $val = 115;
19123 break;
19125 case 'expanded': {
19126 $val = 130;
19127 break;
19129 case 'extra-expanded': {
19130 $val = 145;
19131 break;
19133 case 'ultra-expanded': {
19134 $val = 160;
19135 break;
19137 case 'wider': {
19138 $val = $parent + 10;
19139 break;
19141 case 'narrower': {
19142 $val = $parent - 10;
19143 break;
19145 case 'inherit': {
19146 if ($parent == 'normal') {
19147 $val = 100;
19148 } else {
19149 $val = $parent;
19151 break;
19153 default: {
19154 $val = $this->getHTMLUnitToUnits($stretch, 100, '%', false);
19157 return $val;
19161 * Returns the HTML DOM array.
19162 * @param $html (string) html code
19163 * @return array
19164 * @protected
19165 * @since 3.2.000 (2008-06-20)
19167 protected function getHtmlDomArray($html) {
19168 // array of CSS styles ( selector => properties).
19169 $css = array();
19170 // get CSS array defined at previous call
19171 $matches = array();
19172 if (preg_match_all('/<cssarray>([^\<]*)<\/cssarray>/isU', $html, $matches) > 0) {
19173 if (isset($matches[1][0])) {
19174 $css = array_merge($css, unserialize($this->unhtmlentities($matches[1][0])));
19176 $html = preg_replace('/<cssarray>(.*?)<\/cssarray>/isU', '', $html);
19178 // extract external CSS files
19179 $matches = array();
19180 if (preg_match_all('/<link([^\>]*)>/isU', $html, $matches) > 0) {
19181 foreach ($matches[1] as $key => $link) {
19182 $type = array();
19183 if (preg_match('/type[\s]*=[\s]*"text\/css"/', $link, $type)) {
19184 $type = array();
19185 preg_match('/media[\s]*=[\s]*"([^"]*)"/', $link, $type);
19186 // get 'all' and 'print' media, other media types are discarded
19187 // (all, braille, embossed, handheld, print, projection, screen, speech, tty, tv)
19188 if (empty($type) OR (isset($type[1]) AND (($type[1] == 'all') OR ($type[1] == 'print')))) {
19189 $type = array();
19190 if (preg_match('/href[\s]*=[\s]*"([^"]*)"/', $link, $type) > 0) {
19191 // read CSS data file
19192 $cssdata = file_get_contents(trim($type[1]));
19193 $css = array_merge($css, $this->extractCSSproperties($cssdata));
19199 // extract style tags
19200 $matches = array();
19201 if (preg_match_all('/<style([^\>]*)>([^\<]*)<\/style>/isU', $html, $matches) > 0) {
19202 foreach ($matches[1] as $key => $media) {
19203 $type = array();
19204 preg_match('/media[\s]*=[\s]*"([^"]*)"/', $media, $type);
19205 // get 'all' and 'print' media, other media types are discarded
19206 // (all, braille, embossed, handheld, print, projection, screen, speech, tty, tv)
19207 if (empty($type) OR (isset($type[1]) AND (($type[1] == 'all') OR ($type[1] == 'print')))) {
19208 $cssdata = $matches[2][$key];
19209 $css = array_merge($css, $this->extractCSSproperties($cssdata));
19213 // create a special tag to contain the CSS array (used for table content)
19214 $csstagarray = '<cssarray>'.htmlentities(serialize($css)).'</cssarray>';
19215 // remove head and style blocks
19216 $html = preg_replace('/<head([^\>]*)>(.*?)<\/head>/siU', '', $html);
19217 $html = preg_replace('/<style([^\>]*)>([^\<]*)<\/style>/isU', '', $html);
19218 // define block tags
19219 $blocktags = array('blockquote','br','dd','dl','div','dt','h1','h2','h3','h4','h5','h6','hr','li','ol','p','pre','ul','tcpdf','table','tr','td');
19220 // define self-closing tags
19221 $selfclosingtags = array('area','base','basefont','br','hr','input','img','link','meta');
19222 // remove all unsupported tags (the line below lists all supported tags)
19223 $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>');
19224 //replace some blank characters
19225 $html = preg_replace('/<pre/', '<xre', $html); // preserve pre tag
19226 $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);
19227 $html = preg_replace('@(\r\n|\r)@', "\n", $html);
19228 $repTable = array("\t" => ' ', "\0" => ' ', "\x0B" => ' ', "\\" => "\\\\");
19229 $html = strtr($html, $repTable);
19230 $offset = 0;
19231 while (($offset < strlen($html)) AND ($pos = strpos($html, '</pre>', $offset)) !== false) {
19232 $html_a = substr($html, 0, $offset);
19233 $html_b = substr($html, $offset, ($pos - $offset + 6));
19234 while (preg_match("'<xre([^\>]*)>(.*?)\n(.*?)</pre>'si", $html_b)) {
19235 // preserve newlines on <pre> tag
19236 $html_b = preg_replace("'<xre([^\>]*)>(.*?)\n(.*?)</pre>'si", "<xre\\1>\\2<br />\\3</pre>", $html_b);
19238 while (preg_match("'<xre([^\>]*)>(.*?)".$this->re_space['p']."(.*?)</pre>'".$this->re_space['m'], $html_b)) {
19239 // preserve spaces on <pre> tag
19240 $html_b = preg_replace("'<xre([^\>]*)>(.*?)".$this->re_space['p']."(.*?)</pre>'".$this->re_space['m'], "<xre\\1>\\2&nbsp;\\3</pre>", $html_b);
19242 $html = $html_a.$html_b.substr($html, $pos + 6);
19243 $offset = strlen($html_a.$html_b);
19245 $offset = 0;
19246 while (($offset < strlen($html)) AND ($pos = strpos($html, '</textarea>', $offset)) !== false) {
19247 $html_a = substr($html, 0, $offset);
19248 $html_b = substr($html, $offset, ($pos - $offset + 11));
19249 while (preg_match("'<textarea([^\>]*)>(.*?)\n(.*?)</textarea>'si", $html_b)) {
19250 // preserve newlines on <textarea> tag
19251 $html_b = preg_replace("'<textarea([^\>]*)>(.*?)\n(.*?)</textarea>'si", "<textarea\\1>\\2<TBR>\\3</textarea>", $html_b);
19252 $html_b = preg_replace("'<textarea([^\>]*)>(.*?)[\"](.*?)</textarea>'si", "<textarea\\1>\\2''\\3</textarea>", $html_b);
19254 $html = $html_a.$html_b.substr($html, $pos + 11);
19255 $offset = strlen($html_a.$html_b);
19257 $html = preg_replace('/([\s]*)<option/si', '<option', $html);
19258 $html = preg_replace('/<\/option>([\s]*)/si', '</option>', $html);
19259 $offset = 0;
19260 while (($offset < strlen($html)) AND ($pos = strpos($html, '</option>', $offset)) !== false) {
19261 $html_a = substr($html, 0, $offset);
19262 $html_b = substr($html, $offset, ($pos - $offset + 9));
19263 while (preg_match("'<option([^\>]*)>(.*?)</option>'si", $html_b)) {
19264 $html_b = preg_replace("'<option([\s]+)value=\"([^\"]*)\"([^\>]*)>(.*?)</option>'si", "\\2#!TaB!#\\4#!NwL!#", $html_b);
19265 $html_b = preg_replace("'<option([^\>]*)>(.*?)</option>'si", "\\2#!NwL!#", $html_b);
19267 $html = $html_a.$html_b.substr($html, $pos + 9);
19268 $offset = strlen($html_a.$html_b);
19270 if (preg_match("'</select'si", $html)) {
19271 $html = preg_replace("'<select([^\>]*)>'si", "<select\\1 opt=\"", $html);
19272 $html = preg_replace("'#!NwL!#</select>'si", "\" />", $html);
19274 $html = str_replace("\n", ' ', $html);
19275 // restore textarea newlines
19276 $html = str_replace('<TBR>', "\n", $html);
19277 // remove extra spaces from code
19278 $html = preg_replace('/[\s]+<\/(table|tr|ul|ol|dl)>/', '</\\1>', $html);
19279 $html = preg_replace('/'.$this->re_space['p'].'+<\/(td|th|li|dt|dd)>/'.$this->re_space['m'], '</\\1>', $html);
19280 $html = preg_replace('/[\s]+<(tr|td|th|li|dt|dd)/', '<\\1', $html);
19281 $html = preg_replace('/'.$this->re_space['p'].'+<(ul|ol|dl|br)/'.$this->re_space['m'], '<\\1', $html);
19282 $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);
19283 $html = preg_replace('/<\/(td|th)>/', '<marker style="font-size:0"/></\\1>', $html);
19284 $html = preg_replace('/<\/table>([\s]*)<marker style="font-size:0"\/>/', '</table>', $html);
19285 $html = preg_replace('/'.$this->re_space['p'].'+<img/'.$this->re_space['m'], chr(32).'<img', $html);
19286 $html = preg_replace('/<img([^\>]*)>[\s]+([^\<])/xi', '<img\\1>&nbsp;\\2', $html);
19287 $html = preg_replace('/<img([^\>]*)>/xi', '<img\\1><span><marker style="font-size:0"/></span>', $html);
19288 $html = preg_replace('/<xre/', '<pre', $html); // restore pre tag
19289 $html = preg_replace('/<textarea([^\>]*)>([^\<]*)<\/textarea>/xi', '<textarea\\1 value="\\2" />', $html);
19290 $html = preg_replace('/<li([^\>]*)><\/li>/', '<li\\1>&nbsp;</li>', $html);
19291 $html = preg_replace('/<li([^\>]*)>'.$this->re_space['p'].'*<img/'.$this->re_space['m'], '<li\\1><font size="1">&nbsp;</font><img', $html);
19292 $html = preg_replace('/<([^\>\/]*)>[\s]/', '<\\1>&nbsp;', $html); // preserve some spaces
19293 $html = preg_replace('/[\s]<\/([^\>]*)>/', '&nbsp;</\\1>', $html); // preserve some spaces
19294 $html = preg_replace('/'.$this->re_space['p'].'+/'.$this->re_space['m'], chr(32), $html); // replace multiple spaces with a single space
19295 // trim string
19296 $html = $this->stringTrim($html);
19297 // fix first image tag alignment
19298 $html = preg_replace('/^<img/', '<span style="font-size:0"><br /></span> <img', $html, 1);
19299 // pattern for generic tag
19300 $tagpattern = '/(<[^>]+>)/';
19301 // explodes the string
19302 $a = preg_split($tagpattern, $html, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
19303 // count elements
19304 $maxel = count($a);
19305 $elkey = 0;
19306 $key = 0;
19307 // create an array of elements
19308 $dom = array();
19309 $dom[$key] = array();
19310 // set inheritable properties fot the first void element
19311 // 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
19312 $dom[$key]['tag'] = false;
19313 $dom[$key]['block'] = false;
19314 $dom[$key]['value'] = '';
19315 $dom[$key]['parent'] = 0;
19316 $dom[$key]['hide'] = false;
19317 $dom[$key]['fontname'] = $this->FontFamily;
19318 $dom[$key]['fontstyle'] = $this->FontStyle;
19319 $dom[$key]['fontsize'] = $this->FontSizePt;
19320 $dom[$key]['font-stretch'] = $this->font_stretching;
19321 $dom[$key]['letter-spacing'] = $this->font_spacing;
19322 $dom[$key]['stroke'] = $this->textstrokewidth;
19323 $dom[$key]['fill'] = (($this->textrendermode % 2) == 0);
19324 $dom[$key]['clip'] = ($this->textrendermode > 3);
19325 $dom[$key]['line-height'] = $this->cell_height_ratio;
19326 $dom[$key]['bgcolor'] = false;
19327 $dom[$key]['fgcolor'] = $this->fgcolor; // color
19328 $dom[$key]['strokecolor'] = $this->strokecolor;
19329 $dom[$key]['align'] = '';
19330 $dom[$key]['listtype'] = '';
19331 $dom[$key]['text-indent'] = 0;
19332 $dom[$key]['border'] = array();
19333 $dom[$key]['dir'] = $this->rtl?'rtl':'ltr';
19334 $thead = false; // true when we are inside the THEAD tag
19335 ++$key;
19336 $level = array();
19337 array_push($level, 0); // root
19338 while ($elkey < $maxel) {
19339 $dom[$key] = array();
19340 $element = $a[$elkey];
19341 $dom[$key]['elkey'] = $elkey;
19342 if (preg_match($tagpattern, $element)) {
19343 // html tag
19344 $element = substr($element, 1, -1);
19345 // get tag name
19346 preg_match('/[\/]?([a-zA-Z0-9]*)/', $element, $tag);
19347 $tagname = strtolower($tag[1]);
19348 // check if we are inside a table header
19349 if ($tagname == 'thead') {
19350 if ($element{0} == '/') {
19351 $thead = false;
19352 } else {
19353 $thead = true;
19355 ++$elkey;
19356 continue;
19358 $dom[$key]['tag'] = true;
19359 $dom[$key]['value'] = $tagname;
19360 if (in_array($dom[$key]['value'], $blocktags)) {
19361 $dom[$key]['block'] = true;
19362 } else {
19363 $dom[$key]['block'] = false;
19365 if ($element{0} == '/') {
19366 // *** closing html tag
19367 $dom[$key]['opening'] = false;
19368 $dom[$key]['parent'] = end($level);
19369 array_pop($level);
19370 $dom[$key]['hide'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['hide'];
19371 $dom[$key]['fontname'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fontname'];
19372 $dom[$key]['fontstyle'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fontstyle'];
19373 $dom[$key]['fontsize'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fontsize'];
19374 $dom[$key]['font-stretch'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['font-stretch'];
19375 $dom[$key]['letter-spacing'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['letter-spacing'];
19376 $dom[$key]['stroke'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['stroke'];
19377 $dom[$key]['fill'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fill'];
19378 $dom[$key]['clip'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['clip'];
19379 $dom[$key]['line-height'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['line-height'];
19380 $dom[$key]['bgcolor'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['bgcolor'];
19381 $dom[$key]['fgcolor'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fgcolor'];
19382 $dom[$key]['strokecolor'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['strokecolor'];
19383 $dom[$key]['align'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['align'];
19384 $dom[$key]['dir'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['dir'];
19385 if (isset($dom[($dom[($dom[$key]['parent'])]['parent'])]['listtype'])) {
19386 $dom[$key]['listtype'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['listtype'];
19388 // set the number of columns in table tag
19389 if (($dom[$key]['value'] == 'tr') AND (!isset($dom[($dom[($dom[$key]['parent'])]['parent'])]['cols']))) {
19390 $dom[($dom[($dom[$key]['parent'])]['parent'])]['cols'] = $dom[($dom[$key]['parent'])]['cols'];
19392 if (($dom[$key]['value'] == 'td') OR ($dom[$key]['value'] == 'th')) {
19393 $dom[($dom[$key]['parent'])]['content'] = $csstagarray;
19394 for ($i = ($dom[$key]['parent'] + 1); $i < $key; ++$i) {
19395 $dom[($dom[$key]['parent'])]['content'] .= $a[$dom[$i]['elkey']];
19397 $key = $i;
19398 // mark nested tables
19399 $dom[($dom[$key]['parent'])]['content'] = str_replace('<table', '<table nested="true"', $dom[($dom[$key]['parent'])]['content']);
19400 // remove thead sections from nested tables
19401 $dom[($dom[$key]['parent'])]['content'] = str_replace('<thead>', '', $dom[($dom[$key]['parent'])]['content']);
19402 $dom[($dom[$key]['parent'])]['content'] = str_replace('</thead>', '', $dom[($dom[$key]['parent'])]['content']);
19404 // store header rows on a new table
19405 if (($dom[$key]['value'] == 'tr') AND ($dom[($dom[$key]['parent'])]['thead'] === true)) {
19406 if ($this->empty_string($dom[($dom[($dom[$key]['parent'])]['parent'])]['thead'])) {
19407 $dom[($dom[($dom[$key]['parent'])]['parent'])]['thead'] = $csstagarray.$a[$dom[($dom[($dom[$key]['parent'])]['parent'])]['elkey']];
19409 for ($i = $dom[$key]['parent']; $i <= $key; ++$i) {
19410 $dom[($dom[($dom[$key]['parent'])]['parent'])]['thead'] .= $a[$dom[$i]['elkey']];
19412 if (!isset($dom[($dom[$key]['parent'])]['attribute'])) {
19413 $dom[($dom[$key]['parent'])]['attribute'] = array();
19415 // header elements must be always contained in a single page
19416 $dom[($dom[$key]['parent'])]['attribute']['nobr'] = 'true';
19418 if (($dom[$key]['value'] == 'table') AND (!$this->empty_string($dom[($dom[$key]['parent'])]['thead']))) {
19419 // remove the nobr attributes from the table header
19420 $dom[($dom[$key]['parent'])]['thead'] = str_replace(' nobr="true"', '', $dom[($dom[$key]['parent'])]['thead']);
19421 $dom[($dom[$key]['parent'])]['thead'] .= '</tablehead>';
19423 } else {
19424 // *** opening or self-closing html tag
19425 $dom[$key]['opening'] = true;
19426 $dom[$key]['parent'] = end($level);
19427 if ((substr($element, -1, 1) == '/') OR (in_array($dom[$key]['value'], $selfclosingtags))) {
19428 // self-closing tag
19429 $dom[$key]['self'] = true;
19430 } else {
19431 // opening tag
19432 array_push($level, $key);
19433 $dom[$key]['self'] = false;
19435 // copy some values from parent
19436 $parentkey = 0;
19437 if ($key > 0) {
19438 $parentkey = $dom[$key]['parent'];
19439 $dom[$key]['hide'] = $dom[$parentkey]['hide'];
19440 $dom[$key]['fontname'] = $dom[$parentkey]['fontname'];
19441 $dom[$key]['fontstyle'] = $dom[$parentkey]['fontstyle'];
19442 $dom[$key]['fontsize'] = $dom[$parentkey]['fontsize'];
19443 $dom[$key]['font-stretch'] = $dom[$parentkey]['font-stretch'];
19444 $dom[$key]['letter-spacing'] = $dom[$parentkey]['letter-spacing'];
19445 $dom[$key]['stroke'] = $dom[$parentkey]['stroke'];
19446 $dom[$key]['fill'] = $dom[$parentkey]['fill'];
19447 $dom[$key]['clip'] = $dom[$parentkey]['clip'];
19448 $dom[$key]['line-height'] = $dom[$parentkey]['line-height'];
19449 $dom[$key]['bgcolor'] = $dom[$parentkey]['bgcolor'];
19450 $dom[$key]['fgcolor'] = $dom[$parentkey]['fgcolor'];
19451 $dom[$key]['strokecolor'] = $dom[$parentkey]['strokecolor'];
19452 $dom[$key]['align'] = $dom[$parentkey]['align'];
19453 $dom[$key]['listtype'] = $dom[$parentkey]['listtype'];
19454 $dom[$key]['text-indent'] = $dom[$parentkey]['text-indent'];
19455 $dom[$key]['border'] = array();
19456 $dom[$key]['dir'] = $dom[$parentkey]['dir'];
19458 // get attributes
19459 preg_match_all('/([^=\s]*)[\s]*=[\s]*"([^"]*)"/', $element, $attr_array, PREG_PATTERN_ORDER);
19460 $dom[$key]['attribute'] = array(); // reset attribute array
19461 while (list($id, $name) = each($attr_array[1])) {
19462 $dom[$key]['attribute'][strtolower($name)] = $attr_array[2][$id];
19464 if (!empty($css)) {
19465 // merge CSS style to current style
19466 list($dom[$key]['csssel'], $dom[$key]['cssdata']) = $this->getCSSdataArray($dom, $key, $css);
19467 $dom[$key]['attribute']['style'] = $this->getTagStyleFromCSSarray($dom[$key]['cssdata']);
19469 // split style attributes
19470 if (isset($dom[$key]['attribute']['style']) AND !empty($dom[$key]['attribute']['style'])) {
19471 // get style attributes
19472 preg_match_all('/([^;:\s]*):([^;]*)/', $dom[$key]['attribute']['style'], $style_array, PREG_PATTERN_ORDER);
19473 $dom[$key]['style'] = array(); // reset style attribute array
19474 while (list($id, $name) = each($style_array[1])) {
19475 // in case of duplicate attribute the last replace the previous
19476 $dom[$key]['style'][strtolower($name)] = trim($style_array[2][$id]);
19478 // --- get some style attributes ---
19479 // text direction
19480 if (isset($dom[$key]['style']['direction'])) {
19481 $dom[$key]['dir'] = $dom[$key]['style']['direction'];
19483 // display
19484 if (isset($dom[$key]['style']['display'])) {
19485 $dom[$key]['hide'] = (trim(strtolower($dom[$key]['style']['display'])) == 'none');
19487 // font family
19488 if (isset($dom[$key]['style']['font-family'])) {
19489 $dom[$key]['fontname'] = $this->getFontFamilyName($dom[$key]['style']['font-family']);
19491 // list-style-type
19492 if (isset($dom[$key]['style']['list-style-type'])) {
19493 $dom[$key]['listtype'] = trim(strtolower($dom[$key]['style']['list-style-type']));
19494 if ($dom[$key]['listtype'] == 'inherit') {
19495 $dom[$key]['listtype'] = $dom[$parentkey]['listtype'];
19498 // text-indent
19499 if (isset($dom[$key]['style']['text-indent'])) {
19500 $dom[$key]['text-indent'] = $this->getHTMLUnitToUnits($dom[$key]['style']['text-indent']);
19501 if ($dom[$key]['text-indent'] == 'inherit') {
19502 $dom[$key]['text-indent'] = $dom[$parentkey]['text-indent'];
19505 // font size
19506 if (isset($dom[$key]['style']['font-size'])) {
19507 $fsize = trim($dom[$key]['style']['font-size']);
19508 switch ($fsize) {
19509 // absolute-size
19510 case 'xx-small': {
19511 $dom[$key]['fontsize'] = $dom[0]['fontsize'] - 4;
19512 break;
19514 case 'x-small': {
19515 $dom[$key]['fontsize'] = $dom[0]['fontsize'] - 3;
19516 break;
19518 case 'small': {
19519 $dom[$key]['fontsize'] = $dom[0]['fontsize'] - 2;
19520 break;
19522 case 'medium': {
19523 $dom[$key]['fontsize'] = $dom[0]['fontsize'];
19524 break;
19526 case 'large': {
19527 $dom[$key]['fontsize'] = $dom[0]['fontsize'] + 2;
19528 break;
19530 case 'x-large': {
19531 $dom[$key]['fontsize'] = $dom[0]['fontsize'] + 4;
19532 break;
19534 case 'xx-large': {
19535 $dom[$key]['fontsize'] = $dom[0]['fontsize'] + 6;
19536 break;
19538 // relative-size
19539 case 'smaller': {
19540 $dom[$key]['fontsize'] = $dom[$parentkey]['fontsize'] - 3;
19541 break;
19543 case 'larger': {
19544 $dom[$key]['fontsize'] = $dom[$parentkey]['fontsize'] + 3;
19545 break;
19547 default: {
19548 $dom[$key]['fontsize'] = $this->getHTMLUnitToUnits($fsize, $dom[$parentkey]['fontsize'], 'pt', true);
19552 // font-stretch
19553 if (isset($dom[$key]['style']['font-stretch'])) {
19554 $dom[$key]['font-stretch'] = $this->getCSSFontStretching($dom[$key]['style']['font-stretch'], $dom[$parentkey]['font-stretch']);
19556 // letter-spacing
19557 if (isset($dom[$key]['style']['letter-spacing'])) {
19558 $dom[$key]['letter-spacing'] = $this->getCSSFontSpacing($dom[$key]['style']['letter-spacing'], $dom[$parentkey]['letter-spacing']);
19560 // line-height
19561 if (isset($dom[$key]['style']['line-height'])) {
19562 $lineheight = trim($dom[$key]['style']['line-height']);
19563 switch ($lineheight) {
19564 // A normal line height. This is default
19565 case 'normal': {
19566 $dom[$key]['line-height'] = $dom[0]['line-height'];
19567 break;
19569 default: {
19570 if (is_numeric($lineheight)) {
19571 $lineheight = $lineheight * 100;
19573 $dom[$key]['line-height'] = $this->getHTMLUnitToUnits($lineheight, 1, '%', true);
19577 // font style
19578 if (isset($dom[$key]['style']['font-weight'])) {
19579 if (strtolower($dom[$key]['style']['font-weight']{0}) == 'n') {
19580 if (strpos($dom[$key]['fontstyle'], 'B') !== false) {
19581 $dom[$key]['fontstyle'] = str_replace('B', '', $dom[$key]['fontstyle']);
19583 } elseif (strtolower($dom[$key]['style']['font-weight']{0}) == 'b') {
19584 $dom[$key]['fontstyle'] .= 'B';
19587 if (isset($dom[$key]['style']['font-style']) AND (strtolower($dom[$key]['style']['font-style']{0}) == 'i')) {
19588 $dom[$key]['fontstyle'] .= 'I';
19590 // font color
19591 if (isset($dom[$key]['style']['color']) AND (!$this->empty_string($dom[$key]['style']['color']))) {
19592 $dom[$key]['fgcolor'] = $this->convertHTMLColorToDec($dom[$key]['style']['color']);
19593 } elseif ($dom[$key]['value'] == 'a') {
19594 $dom[$key]['fgcolor'] = $this->htmlLinkColorArray;
19596 // background color
19597 if (isset($dom[$key]['style']['background-color']) AND (!$this->empty_string($dom[$key]['style']['background-color']))) {
19598 $dom[$key]['bgcolor'] = $this->convertHTMLColorToDec($dom[$key]['style']['background-color']);
19600 // text-decoration
19601 if (isset($dom[$key]['style']['text-decoration'])) {
19602 $decors = explode(' ', strtolower($dom[$key]['style']['text-decoration']));
19603 foreach ($decors as $dec) {
19604 $dec = trim($dec);
19605 if (!$this->empty_string($dec)) {
19606 if ($dec{0} == 'u') {
19607 // underline
19608 $dom[$key]['fontstyle'] .= 'U';
19609 } elseif ($dec{0} == 'l') {
19610 // line-trough
19611 $dom[$key]['fontstyle'] .= 'D';
19612 } elseif ($dec{0} == 'o') {
19613 // overline
19614 $dom[$key]['fontstyle'] .= 'O';
19618 } elseif ($dom[$key]['value'] == 'a') {
19619 $dom[$key]['fontstyle'] = $this->htmlLinkFontStyle;
19621 // check for width attribute
19622 if (isset($dom[$key]['style']['width'])) {
19623 $dom[$key]['width'] = $dom[$key]['style']['width'];
19625 // check for height attribute
19626 if (isset($dom[$key]['style']['height'])) {
19627 $dom[$key]['height'] = $dom[$key]['style']['height'];
19629 // check for text alignment
19630 if (isset($dom[$key]['style']['text-align'])) {
19631 $dom[$key]['align'] = strtoupper($dom[$key]['style']['text-align']{0});
19633 // check for CSS border properties
19634 if (isset($dom[$key]['style']['border'])) {
19635 $borderstyle = $this->getCSSBorderStyle($dom[$key]['style']['border']);
19636 if (!empty($borderstyle)) {
19637 $dom[$key]['border']['LTRB'] = $borderstyle;
19640 if (isset($dom[$key]['style']['border-color'])) {
19641 $brd_colors = preg_split('/[\s]+/', trim($dom[$key]['style']['border-color']));
19642 if (isset($brd_colors[3])) {
19643 $dom[$key]['border']['L']['color'] = $this->convertHTMLColorToDec($brd_colors[3]);
19645 if (isset($brd_colors[1])) {
19646 $dom[$key]['border']['R']['color'] = $this->convertHTMLColorToDec($brd_colors[1]);
19648 if (isset($brd_colors[0])) {
19649 $dom[$key]['border']['T']['color'] = $this->convertHTMLColorToDec($brd_colors[0]);
19651 if (isset($brd_colors[2])) {
19652 $dom[$key]['border']['B']['color'] = $this->convertHTMLColorToDec($brd_colors[2]);
19655 if (isset($dom[$key]['style']['border-width'])) {
19656 $brd_widths = preg_split('/[\s]+/', trim($dom[$key]['style']['border-width']));
19657 if (isset($brd_widths[3])) {
19658 $dom[$key]['border']['L']['width'] = $this->getCSSBorderWidth($brd_widths[3]);
19660 if (isset($brd_widths[1])) {
19661 $dom[$key]['border']['R']['width'] = $this->getCSSBorderWidth($brd_widths[1]);
19663 if (isset($brd_widths[0])) {
19664 $dom[$key]['border']['T']['width'] = $this->getCSSBorderWidth($brd_widths[0]);
19666 if (isset($brd_widths[2])) {
19667 $dom[$key]['border']['B']['width'] = $this->getCSSBorderWidth($brd_widths[2]);
19670 if (isset($dom[$key]['style']['border-style'])) {
19671 $brd_styles = preg_split('/[\s]+/', trim($dom[$key]['style']['border-style']));
19672 if (isset($brd_styles[3])) {
19673 $dom[$key]['border']['L']['cap'] = 'square';
19674 $dom[$key]['border']['L']['join'] = 'miter';
19675 $dom[$key]['border']['L']['dash'] = $this->getCSSBorderDashStyle($brd_styles[3]);
19676 if ($dom[$key]['border']['L']['dash'] < 0) {
19677 $dom[$key]['border']['L'] = array();
19680 if (isset($brd_styles[1])) {
19681 $dom[$key]['border']['R']['cap'] = 'square';
19682 $dom[$key]['border']['R']['join'] = 'miter';
19683 $dom[$key]['border']['R']['dash'] = $this->getCSSBorderDashStyle($brd_styles[1]);
19684 if ($dom[$key]['border']['R']['dash'] < 0) {
19685 $dom[$key]['border']['R'] = array();
19688 if (isset($brd_styles[0])) {
19689 $dom[$key]['border']['T']['cap'] = 'square';
19690 $dom[$key]['border']['T']['join'] = 'miter';
19691 $dom[$key]['border']['T']['dash'] = $this->getCSSBorderDashStyle($brd_styles[0]);
19692 if ($dom[$key]['border']['T']['dash'] < 0) {
19693 $dom[$key]['border']['T'] = array();
19696 if (isset($brd_styles[2])) {
19697 $dom[$key]['border']['B']['cap'] = 'square';
19698 $dom[$key]['border']['B']['join'] = 'miter';
19699 $dom[$key]['border']['B']['dash'] = $this->getCSSBorderDashStyle($brd_styles[2]);
19700 if ($dom[$key]['border']['B']['dash'] < 0) {
19701 $dom[$key]['border']['B'] = array();
19705 $cellside = array('L' => 'left', 'R' => 'right', 'T' => 'top', 'B' => 'bottom');
19706 foreach ($cellside as $bsk => $bsv) {
19707 if (isset($dom[$key]['style']['border-'.$bsv])) {
19708 $borderstyle = $this->getCSSBorderStyle($dom[$key]['style']['border-'.$bsv]);
19709 if (!empty($borderstyle)) {
19710 $dom[$key]['border'][$bsk] = $borderstyle;
19713 if (isset($dom[$key]['style']['border-'.$bsv.'-color'])) {
19714 $dom[$key]['border'][$bsk]['color'] = $this->convertHTMLColorToDec($dom[$key]['style']['border-'.$bsv.'-color']);
19716 if (isset($dom[$key]['style']['border-'.$bsv.'-width'])) {
19717 $dom[$key]['border'][$bsk]['width'] = $this->getCSSBorderWidth($dom[$key]['style']['border-'.$bsv.'-width']);
19719 if (isset($dom[$key]['style']['border-'.$bsv.'-style'])) {
19720 $dom[$key]['border'][$bsk]['dash'] = $this->getCSSBorderDashStyle($dom[$key]['style']['border-'.$bsv.'-style']);
19721 if ($dom[$key]['border'][$bsk]['dash'] < 0) {
19722 $dom[$key]['border'][$bsk] = array();
19726 // check for CSS padding properties
19727 if (isset($dom[$key]['style']['padding'])) {
19728 $dom[$key]['padding'] = $this->getCSSPadding($dom[$key]['style']['padding']);
19729 } else {
19730 $dom[$key]['padding'] = $this->cell_padding;
19732 foreach ($cellside as $psk => $psv) {
19733 if (isset($dom[$key]['style']['padding-'.$psv])) {
19734 $dom[$key]['padding'][$psk] = $this->getHTMLUnitToUnits($dom[$key]['style']['padding-'.$psv], 0, 'px', false);
19737 // check for CSS margin properties
19738 if (isset($dom[$key]['style']['margin'])) {
19739 $dom[$key]['margin'] = $this->getCSSMargin($dom[$key]['style']['margin']);
19740 } else {
19741 $dom[$key]['margin'] = $this->cell_margin;
19743 foreach ($cellside as $psk => $psv) {
19744 if (isset($dom[$key]['style']['margin-'.$psv])) {
19745 $dom[$key]['margin'][$psk] = $this->getHTMLUnitToUnits(str_replace('auto', '0', $dom[$key]['style']['margin-'.$psv]), 0, 'px', false);
19748 // check for CSS border-spacing properties
19749 if (isset($dom[$key]['style']['border-spacing'])) {
19750 $dom[$key]['border-spacing'] = $this->getCSSBorderMargin($dom[$key]['style']['border-spacing']);
19752 // page-break-inside
19753 if (isset($dom[$key]['style']['page-break-inside']) AND ($dom[$key]['style']['page-break-inside'] == 'avoid')) {
19754 $dom[$key]['attribute']['nobr'] = 'true';
19756 // page-break-before
19757 if (isset($dom[$key]['style']['page-break-before'])) {
19758 if ($dom[$key]['style']['page-break-before'] == 'always') {
19759 $dom[$key]['attribute']['pagebreak'] = 'true';
19760 } elseif ($dom[$key]['style']['page-break-before'] == 'left') {
19761 $dom[$key]['attribute']['pagebreak'] = 'left';
19762 } elseif ($dom[$key]['style']['page-break-before'] == 'right') {
19763 $dom[$key]['attribute']['pagebreak'] = 'right';
19766 // page-break-after
19767 if (isset($dom[$key]['style']['page-break-after'])) {
19768 if ($dom[$key]['style']['page-break-after'] == 'always') {
19769 $dom[$key]['attribute']['pagebreakafter'] = 'true';
19770 } elseif ($dom[$key]['style']['page-break-after'] == 'left') {
19771 $dom[$key]['attribute']['pagebreakafter'] = 'left';
19772 } elseif ($dom[$key]['style']['page-break-after'] == 'right') {
19773 $dom[$key]['attribute']['pagebreakafter'] = 'right';
19777 if (isset($dom[$key]['attribute']['display'])) {
19778 $dom[$key]['hide'] = (trim(strtolower($dom[$key]['attribute']['display'])) == 'none');
19780 if (isset($dom[$key]['attribute']['border']) AND ($dom[$key]['attribute']['border'] != 0)) {
19781 $borderstyle = $this->getCSSBorderStyle($dom[$key]['attribute']['border'].' solid black');
19782 if (!empty($borderstyle)) {
19783 $dom[$key]['border']['LTRB'] = $borderstyle;
19786 // check for font tag
19787 if ($dom[$key]['value'] == 'font') {
19788 // font family
19789 if (isset($dom[$key]['attribute']['face'])) {
19790 $dom[$key]['fontname'] = $this->getFontFamilyName($dom[$key]['attribute']['face']);
19792 // font size
19793 if (isset($dom[$key]['attribute']['size'])) {
19794 if ($key > 0) {
19795 if ($dom[$key]['attribute']['size']{0} == '+') {
19796 $dom[$key]['fontsize'] = $dom[($dom[$key]['parent'])]['fontsize'] + intval(substr($dom[$key]['attribute']['size'], 1));
19797 } elseif ($dom[$key]['attribute']['size']{0} == '-') {
19798 $dom[$key]['fontsize'] = $dom[($dom[$key]['parent'])]['fontsize'] - intval(substr($dom[$key]['attribute']['size'], 1));
19799 } else {
19800 $dom[$key]['fontsize'] = intval($dom[$key]['attribute']['size']);
19802 } else {
19803 $dom[$key]['fontsize'] = intval($dom[$key]['attribute']['size']);
19807 // force natural alignment for lists
19808 if ((($dom[$key]['value'] == 'ul') OR ($dom[$key]['value'] == 'ol') OR ($dom[$key]['value'] == 'dl'))
19809 AND (!isset($dom[$key]['align']) OR $this->empty_string($dom[$key]['align']) OR ($dom[$key]['align'] != 'J'))) {
19810 if ($this->rtl) {
19811 $dom[$key]['align'] = 'R';
19812 } else {
19813 $dom[$key]['align'] = 'L';
19816 if (($dom[$key]['value'] == 'small') OR ($dom[$key]['value'] == 'sup') OR ($dom[$key]['value'] == 'sub')) {
19817 if (!isset($dom[$key]['attribute']['size']) AND !isset($dom[$key]['style']['font-size'])) {
19818 $dom[$key]['fontsize'] = $dom[$key]['fontsize'] * K_SMALL_RATIO;
19821 if (($dom[$key]['value'] == 'strong') OR ($dom[$key]['value'] == 'b')) {
19822 $dom[$key]['fontstyle'] .= 'B';
19824 if (($dom[$key]['value'] == 'em') OR ($dom[$key]['value'] == 'i')) {
19825 $dom[$key]['fontstyle'] .= 'I';
19827 if ($dom[$key]['value'] == 'u') {
19828 $dom[$key]['fontstyle'] .= 'U';
19830 if (($dom[$key]['value'] == 'del') OR ($dom[$key]['value'] == 's') OR ($dom[$key]['value'] == 'strike')) {
19831 $dom[$key]['fontstyle'] .= 'D';
19833 if (!isset($dom[$key]['style']['text-decoration']) AND ($dom[$key]['value'] == 'a')) {
19834 $dom[$key]['fontstyle'] = $this->htmlLinkFontStyle;
19836 if (($dom[$key]['value'] == 'pre') OR ($dom[$key]['value'] == 'tt')) {
19837 $dom[$key]['fontname'] = $this->default_monospaced_font;
19839 if (($dom[$key]['value']{0} == 'h') AND (intval($dom[$key]['value']{1}) > 0) AND (intval($dom[$key]['value']{1}) < 7)) {
19840 // headings h1, h2, h3, h4, h5, h6
19841 if (!isset($dom[$key]['attribute']['size']) AND !isset($dom[$key]['style']['font-size'])) {
19842 $headsize = (4 - intval($dom[$key]['value']{1})) * 2;
19843 $dom[$key]['fontsize'] = $dom[0]['fontsize'] + $headsize;
19845 if (!isset($dom[$key]['style']['font-weight'])) {
19846 $dom[$key]['fontstyle'] .= 'B';
19849 if (($dom[$key]['value'] == 'table')) {
19850 $dom[$key]['rows'] = 0; // number of rows
19851 $dom[$key]['trids'] = array(); // IDs of TR elements
19852 $dom[$key]['thead'] = ''; // table header rows
19854 if (($dom[$key]['value'] == 'tr')) {
19855 $dom[$key]['cols'] = 0;
19856 if ($thead) {
19857 $dom[$key]['thead'] = true;
19858 // rows on thead block are printed as a separate table
19859 } else {
19860 $dom[$key]['thead'] = false;
19861 // store the number of rows on table element
19862 ++$dom[($dom[$key]['parent'])]['rows'];
19863 // store the TR elements IDs on table element
19864 array_push($dom[($dom[$key]['parent'])]['trids'], $key);
19867 if (($dom[$key]['value'] == 'th') OR ($dom[$key]['value'] == 'td')) {
19868 if (isset($dom[$key]['attribute']['colspan'])) {
19869 $colspan = intval($dom[$key]['attribute']['colspan']);
19870 } else {
19871 $colspan = 1;
19873 $dom[$key]['attribute']['colspan'] = $colspan;
19874 $dom[($dom[$key]['parent'])]['cols'] += $colspan;
19876 // text direction
19877 if (isset($dom[$key]['attribute']['dir'])) {
19878 $dom[$key]['dir'] = $dom[$key]['attribute']['dir'];
19880 // set foreground color attribute
19881 if (isset($dom[$key]['attribute']['color']) AND (!$this->empty_string($dom[$key]['attribute']['color']))) {
19882 $dom[$key]['fgcolor'] = $this->convertHTMLColorToDec($dom[$key]['attribute']['color']);
19883 } elseif (!isset($dom[$key]['style']['color']) AND ($dom[$key]['value'] == 'a')) {
19884 $dom[$key]['fgcolor'] = $this->htmlLinkColorArray;
19886 // set background color attribute
19887 if (isset($dom[$key]['attribute']['bgcolor']) AND (!$this->empty_string($dom[$key]['attribute']['bgcolor']))) {
19888 $dom[$key]['bgcolor'] = $this->convertHTMLColorToDec($dom[$key]['attribute']['bgcolor']);
19890 // set stroke color attribute
19891 if (isset($dom[$key]['attribute']['strokecolor']) AND (!$this->empty_string($dom[$key]['attribute']['strokecolor']))) {
19892 $dom[$key]['strokecolor'] = $this->convertHTMLColorToDec($dom[$key]['attribute']['strokecolor']);
19894 // check for width attribute
19895 if (isset($dom[$key]['attribute']['width'])) {
19896 $dom[$key]['width'] = $dom[$key]['attribute']['width'];
19898 // check for height attribute
19899 if (isset($dom[$key]['attribute']['height'])) {
19900 $dom[$key]['height'] = $dom[$key]['attribute']['height'];
19902 // check for text alignment
19903 if (isset($dom[$key]['attribute']['align']) AND (!$this->empty_string($dom[$key]['attribute']['align'])) AND ($dom[$key]['value'] !== 'img')) {
19904 $dom[$key]['align'] = strtoupper($dom[$key]['attribute']['align']{0});
19906 // check for text rendering mode (the following attributes do not exist in HTML)
19907 if (isset($dom[$key]['attribute']['stroke'])) {
19908 // font stroke width
19909 $dom[$key]['stroke'] = $this->getHTMLUnitToUnits($dom[$key]['attribute']['stroke'], $dom[$key]['fontsize'], 'pt', true);
19911 if (isset($dom[$key]['attribute']['fill'])) {
19912 // font fill
19913 if ($dom[$key]['attribute']['fill'] == 'true') {
19914 $dom[$key]['fill'] = true;
19915 } else {
19916 $dom[$key]['fill'] = false;
19919 if (isset($dom[$key]['attribute']['clip'])) {
19920 // clipping mode
19921 if ($dom[$key]['attribute']['clip'] == 'true') {
19922 $dom[$key]['clip'] = true;
19923 } else {
19924 $dom[$key]['clip'] = false;
19927 } // end opening tag
19928 } else {
19929 // text
19930 $dom[$key]['tag'] = false;
19931 $dom[$key]['block'] = false;
19932 //$element = str_replace('&nbsp;', $this->unichr(160), $element);
19933 $dom[$key]['value'] = stripslashes($this->unhtmlentities($element));
19934 $dom[$key]['parent'] = end($level);
19935 $dom[$key]['dir'] = $dom[$dom[$key]['parent']]['dir'];
19937 ++$elkey;
19938 ++$key;
19940 return $dom;
19944 * Returns the string used to find spaces
19945 * @return string
19946 * @protected
19947 * @author Nicola Asuni
19948 * @since 4.8.024 (2010-01-15)
19950 protected function getSpaceString() {
19951 $spacestr = chr(32);
19952 if ($this->isUnicodeFont()) {
19953 $spacestr = chr(0).chr(32);
19955 return $spacestr;
19959 * Prints a cell (rectangular area) with optional borders, background color and html text string.
19960 * 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 />
19961 * If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting.
19962 * @param $w (float) Cell width. If 0, the cell extends up to the right margin.
19963 * @param $h (float) Cell minimum height. The cell extends automatically if needed.
19964 * @param $x (float) upper-left corner X coordinate
19965 * @param $y (float) upper-left corner Y coordinate
19966 * @param $html (string) html text to print. Default value: empty string.
19967 * @param $border (mixed) Indicates if borders must be drawn around the cell. The value can be a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul> or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul> or an array of line styles for each border group - for example: array('LTRB' => array('width' => 2, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0)))
19968 * @param $ln (int) Indicates where the current position should go after the call. Possible values are:<ul><li>0: to the right (or left for RTL language)</li><li>1: to the beginning of the next line</li><li>2: below</li></ul>
19969 Putting 1 is equivalent to putting 0 and calling Ln() just after. Default value: 0.
19970 * @param $fill (boolean) Indicates if the cell background must be painted (true) or transparent (false).
19971 * @param $reseth (boolean) if true reset the last cell height (default true).
19972 * @param $align (string) Allows to center or align the text. Possible values are:<ul><li>L : left align</li><li>C : center</li><li>R : right align</li><li>'' : empty string : left for LTR or right for RTL</li></ul>
19973 * @param $autopadding (boolean) if true, uses internal padding and automatically adjust it to account for line width.
19974 * @see Multicell(), writeHTML()
19975 * @public
19977 public function writeHTMLCell($w, $h, $x, $y, $html='', $border=0, $ln=0, $fill=false, $reseth=true, $align='', $autopadding=true) {
19978 return $this->MultiCell($w, $h, $html, $border, $align, $fill, $ln, $x, $y, $reseth, 0, true, $autopadding, 0, 'T', false);
19982 * Allows to preserve some HTML formatting (limited support).<br />
19983 * IMPORTANT: The HTML must be well formatted - try to clean-up it using an application like HTML-Tidy before submitting.
19984 * 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
19985 * @param $html (string) text to display
19986 * @param $ln (boolean) if true add a new line after text (default = true)
19987 * @param $fill (boolean) Indicates if the background must be painted (true) or transparent (false).
19988 * @param $reseth (boolean) if true reset the last cell height (default false).
19989 * @param $cell (boolean) if true add the current left (or right for RTL) padding to each Write (default false).
19990 * @param $align (string) Allows to center or align the text. Possible values are:<ul><li>L : left align</li><li>C : center</li><li>R : right align</li><li>'' : empty string : left for LTR or right for RTL</li></ul>
19991 * @public
19993 public function writeHTML($html, $ln=true, $fill=false, $reseth=false, $cell=false, $align='') {
19994 $gvars = $this->getGraphicVars();
19995 // store current values
19996 $prev_cell_margin = $this->cell_margin;
19997 $prev_cell_padding = $this->cell_padding;
19998 $prevPage = $this->page;
19999 $prevlMargin = $this->lMargin;
20000 $prevrMargin = $this->rMargin;
20001 $curfontname = $this->FontFamily;
20002 $curfontstyle = $this->FontStyle;
20003 $curfontsize = $this->FontSizePt;
20004 $curfontascent = $this->getFontAscent($curfontname, $curfontstyle, $curfontsize);
20005 $curfontdescent = $this->getFontDescent($curfontname, $curfontstyle, $curfontsize);
20006 $curfontstretcing = $this->font_stretching;
20007 $curfontkerning = $this->font_spacing;
20008 $this->newline = true;
20009 $newline = true;
20010 $startlinepage = $this->page;
20011 $minstartliney = $this->y;
20012 $maxbottomliney = 0;
20013 $startlinex = $this->x;
20014 $startliney = $this->y;
20015 $yshift = 0;
20016 $loop = 0;
20017 $curpos = 0;
20018 $this_method_vars = array();
20019 $undo = false;
20020 $fontaligned = false;
20021 $reverse_dir = false; // true when the text direction is reversed
20022 $this->premode = false;
20023 if ($this->inxobj) {
20024 // we are inside an XObject template
20025 $pask = count($this->xobjects[$this->xobjid]['annotations']);
20026 } elseif (isset($this->PageAnnots[$this->page])) {
20027 $pask = count($this->PageAnnots[$this->page]);
20028 } else {
20029 $pask = 0;
20031 if ($this->inxobj) {
20032 // we are inside an XObject template
20033 $startlinepos = strlen($this->xobjects[$this->xobjid]['outdata']);
20034 } elseif (!$this->InFooter) {
20035 if (isset($this->footerlen[$this->page])) {
20036 $this->footerpos[$this->page] = $this->pagelen[$this->page] - $this->footerlen[$this->page];
20037 } else {
20038 $this->footerpos[$this->page] = $this->pagelen[$this->page];
20040 $startlinepos = $this->footerpos[$this->page];
20041 } else {
20042 // we are inside the footer
20043 $startlinepos = $this->pagelen[$this->page];
20045 $lalign = $align;
20046 $plalign = $align;
20047 if ($this->rtl) {
20048 $w = $this->x - $this->lMargin;
20049 } else {
20050 $w = $this->w - $this->rMargin - $this->x;
20052 $w -= ($this->cell_padding['L'] + $this->cell_padding['R']);
20053 if ($cell) {
20054 if ($this->rtl) {
20055 $this->x -= $this->cell_padding['R'];
20056 $this->lMargin += $this->cell_padding['R'];
20057 } else {
20058 $this->x += $this->cell_padding['L'];
20059 $this->rMargin += $this->cell_padding['L'];
20062 if ($this->customlistindent >= 0) {
20063 $this->listindent = $this->customlistindent;
20064 } else {
20065 $this->listindent = $this->GetStringWidth('000000');
20067 $this->listindentlevel = 0;
20068 // save previous states
20069 $prev_cell_height_ratio = $this->cell_height_ratio;
20070 $prev_listnum = $this->listnum;
20071 $prev_listordered = $this->listordered;
20072 $prev_listcount = $this->listcount;
20073 $prev_lispacer = $this->lispacer;
20074 $this->listnum = 0;
20075 $this->listordered = array();
20076 $this->listcount = array();
20077 $this->lispacer = '';
20078 if (($this->empty_string($this->lasth)) OR ($reseth)) {
20079 // reset row height
20080 $this->resetLastH();
20082 $dom = $this->getHtmlDomArray($html);
20083 $maxel = count($dom);
20084 $key = 0;
20085 $hidden_node_key = -1;
20086 while ($key < $maxel) {
20087 if ($dom[$key]['tag']) {
20088 if ($dom[$key]['opening']) {
20089 if (($hidden_node_key <= 0) AND $dom[$key]['hide']) {
20090 // store the node key
20091 $hidden_node_key = $key;
20093 } elseif (($hidden_node_key > 0) AND ($dom[$key]['parent'] == $hidden_node_key)) {
20094 // we have reached the closing tag of the hidden node
20095 $hidden_node_key = 0;
20098 if ($hidden_node_key >= 0) {
20099 // skip this node
20100 ++$key;
20101 if ($hidden_node_key == 0) {
20102 // reset hidden mode
20103 $hidden_node_key = -1;
20105 continue;
20107 if ($dom[$key]['tag'] AND isset($dom[$key]['attribute']['pagebreak'])) {
20108 // check for pagebreak
20109 if (($dom[$key]['attribute']['pagebreak'] == 'true') OR ($dom[$key]['attribute']['pagebreak'] == 'left') OR ($dom[$key]['attribute']['pagebreak'] == 'right')) {
20110 // add a page (or trig AcceptPageBreak() for multicolumn mode)
20111 $this->checkPageBreak($this->PageBreakTrigger + 1);
20113 if ((($dom[$key]['attribute']['pagebreak'] == 'left') AND (((!$this->rtl) AND (($this->page % 2) == 0)) OR (($this->rtl) AND (($this->page % 2) != 0))))
20114 OR (($dom[$key]['attribute']['pagebreak'] == 'right') AND (((!$this->rtl) AND (($this->page % 2) != 0)) OR (($this->rtl) AND (($this->page % 2) == 0))))) {
20115 // add a page (or trig AcceptPageBreak() for multicolumn mode)
20116 $this->checkPageBreak($this->PageBreakTrigger + 1);
20119 if ($dom[$key]['tag'] AND $dom[$key]['opening'] AND isset($dom[$key]['attribute']['nobr']) AND ($dom[$key]['attribute']['nobr'] == 'true')) {
20120 if (isset($dom[($dom[$key]['parent'])]['attribute']['nobr']) AND ($dom[($dom[$key]['parent'])]['attribute']['nobr'] == 'true')) {
20121 $dom[$key]['attribute']['nobr'] = false;
20122 } else {
20123 // store current object
20124 $this->startTransaction();
20125 // save this method vars
20126 $this_method_vars['html'] = $html;
20127 $this_method_vars['ln'] = $ln;
20128 $this_method_vars['fill'] = $fill;
20129 $this_method_vars['reseth'] = $reseth;
20130 $this_method_vars['cell'] = $cell;
20131 $this_method_vars['align'] = $align;
20132 $this_method_vars['gvars'] = $gvars;
20133 $this_method_vars['prevPage'] = $prevPage;
20134 $this_method_vars['prev_cell_margin'] = $prev_cell_margin;
20135 $this_method_vars['prev_cell_padding'] = $prev_cell_padding;
20136 $this_method_vars['prevlMargin'] = $prevlMargin;
20137 $this_method_vars['prevrMargin'] = $prevrMargin;
20138 $this_method_vars['curfontname'] = $curfontname;
20139 $this_method_vars['curfontstyle'] = $curfontstyle;
20140 $this_method_vars['curfontsize'] = $curfontsize;
20141 $this_method_vars['curfontascent'] = $curfontascent;
20142 $this_method_vars['curfontdescent'] = $curfontdescent;
20143 $this_method_vars['curfontstretcing'] = $curfontstretcing;
20144 $this_method_vars['curfontkerning'] = $curfontkerning;
20145 $this_method_vars['minstartliney'] = $minstartliney;
20146 $this_method_vars['maxbottomliney'] = $maxbottomliney;
20147 $this_method_vars['yshift'] = $yshift;
20148 $this_method_vars['startlinepage'] = $startlinepage;
20149 $this_method_vars['startlinepos'] = $startlinepos;
20150 $this_method_vars['startlinex'] = $startlinex;
20151 $this_method_vars['startliney'] = $startliney;
20152 $this_method_vars['newline'] = $newline;
20153 $this_method_vars['loop'] = $loop;
20154 $this_method_vars['curpos'] = $curpos;
20155 $this_method_vars['pask'] = $pask;
20156 $this_method_vars['lalign'] = $lalign;
20157 $this_method_vars['plalign'] = $plalign;
20158 $this_method_vars['w'] = $w;
20159 $this_method_vars['prev_cell_height_ratio'] = $prev_cell_height_ratio;
20160 $this_method_vars['prev_listnum'] = $prev_listnum;
20161 $this_method_vars['prev_listordered'] = $prev_listordered;
20162 $this_method_vars['prev_listcount'] = $prev_listcount;
20163 $this_method_vars['prev_lispacer'] = $prev_lispacer;
20164 $this_method_vars['fontaligned'] = $fontaligned;
20165 $this_method_vars['key'] = $key;
20166 $this_method_vars['dom'] = $dom;
20169 // print THEAD block
20170 if (($dom[$key]['value'] == 'tr') AND isset($dom[$key]['thead']) AND $dom[$key]['thead']) {
20171 if (isset($dom[$key]['parent']) AND isset($dom[$dom[$key]['parent']]['thead']) AND !$this->empty_string($dom[$dom[$key]['parent']]['thead'])) {
20172 $this->inthead = true;
20173 // print table header (thead)
20174 $this->writeHTML($this->thead, false, false, false, false, '');
20175 // check if we are on a new page or on a new column
20176 if (($this->y < $this->start_transaction_y) OR ($this->checkPageBreak($this->lasth, '', false))) {
20177 // we are on a new page or on a new column and the total object height is less than the available vertical space.
20178 // restore previous object
20179 $this->rollbackTransaction(true);
20180 // restore previous values
20181 foreach ($this_method_vars as $vkey => $vval) {
20182 $$vkey = $vval;
20184 // disable table header
20185 $tmp_thead = $this->thead;
20186 $this->thead = '';
20187 // add a page (or trig AcceptPageBreak() for multicolumn mode)
20188 $pre_y = $this->y;
20189 if ((!$this->checkPageBreak($this->PageBreakTrigger + 1)) AND ($this->y < $pre_y)) {
20190 // fix for multicolumn mode
20191 $startliney = $this->y;
20193 $this->start_transaction_page = $this->page;
20194 $this->start_transaction_y = $this->y;
20195 // restore table header
20196 $this->thead = $tmp_thead;
20197 // fix table border properties
20198 if (isset($dom[$dom[$key]['parent']]['attribute']['cellspacing'])) {
20199 $tmp_cellspacing = $this->getHTMLUnitToUnits($dom[$dom[$key]['parent']]['attribute']['cellspacing'], 1, 'px');
20200 } elseif (isset($dom[$dom[$key]['parent']]['border-spacing'])) {
20201 $tmp_cellspacing = $dom[$dom[$key]['parent']]['border-spacing']['V'];
20202 } else {
20203 $tmp_cellspacing = 0;
20205 $dom[$dom[$key]['parent']]['borderposition']['page'] = $this->page;
20206 $dom[$dom[$key]['parent']]['borderposition']['column'] = $this->current_column;
20207 $dom[$dom[$key]['parent']]['borderposition']['y'] = $this->y + $tmp_cellspacing;
20208 $xoffset = ($this->x - $dom[$dom[$key]['parent']]['borderposition']['x']);
20209 $dom[$dom[$key]['parent']]['borderposition']['x'] += $xoffset;
20210 $dom[$dom[$key]['parent']]['borderposition']['xmax'] += $xoffset;
20211 // print table header (thead)
20212 $this->writeHTML($this->thead, false, false, false, false, '');
20215 // move $key index forward to skip THEAD block
20216 while ( ($key < $maxel) AND (!(
20217 ($dom[$key]['tag'] AND $dom[$key]['opening'] AND ($dom[$key]['value'] == 'tr') AND (!isset($dom[$key]['thead']) OR !$dom[$key]['thead']))
20218 OR ($dom[$key]['tag'] AND (!$dom[$key]['opening']) AND ($dom[$key]['value'] == 'table'))) )) {
20219 ++$key;
20222 if ($dom[$key]['tag'] OR ($key == 0)) {
20223 if ((($dom[$key]['value'] == 'table') OR ($dom[$key]['value'] == 'tr')) AND (isset($dom[$key]['align']))) {
20224 $dom[$key]['align'] = ($this->rtl) ? 'R' : 'L';
20226 // vertically align image in line
20227 if ((!$this->newline) AND ($dom[$key]['value'] == 'img') AND (isset($dom[$key]['height'])) AND ($dom[$key]['height'] > 0)) {
20228 // get image height
20229 $imgh = $this->getHTMLUnitToUnits($dom[$key]['height'], $this->lasth, 'px');
20230 $autolinebreak = false;
20231 if (isset($dom[$key]['width']) AND ($dom[$key]['width'] > 0)) {
20232 $imgw = $this->getHTMLUnitToUnits($dom[$key]['width'], 1, 'px', false);
20233 if (($imgw <= ($this->w - $this->lMargin - $this->rMargin - $this->cell_padding['L'] - $this->cell_padding['R']))
20234 AND ((($this->rtl) AND (($this->x - $imgw) < ($this->lMargin + $this->cell_padding['L'])))
20235 OR ((!$this->rtl) AND (($this->x + $imgw) > ($this->w - $this->rMargin - $this->cell_padding['R']))))) {
20236 // add automatic line break
20237 $autolinebreak = true;
20238 $this->Ln('', $cell);
20239 if ((!$dom[($key-1)]['tag']) AND ($dom[($key-1)]['value'] == ' ')) {
20240 // go back to evaluate this line break
20241 --$key;
20245 if (!$autolinebreak) {
20246 if ($this->inPageBody()) {
20247 $pre_y = $this->y;
20248 // check for page break
20249 if ((!$this->checkPageBreak($imgh)) AND ($this->y < $pre_y)) {
20250 // fix for multicolumn mode
20251 $startliney = $this->y;
20254 if ($this->page > $startlinepage) {
20255 // fix line splitted over two pages
20256 if (isset($this->footerlen[$startlinepage])) {
20257 $curpos = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
20259 // line to be moved one page forward
20260 $pagebuff = $this->getPageBuffer($startlinepage);
20261 $linebeg = substr($pagebuff, $startlinepos, ($curpos - $startlinepos));
20262 $tstart = substr($pagebuff, 0, $startlinepos);
20263 $tend = substr($this->getPageBuffer($startlinepage), $curpos);
20264 // remove line from previous page
20265 $this->setPageBuffer($startlinepage, $tstart.''.$tend);
20266 $pagebuff = $this->getPageBuffer($this->page);
20267 $tstart = substr($pagebuff, 0, $this->cntmrk[$this->page]);
20268 $tend = substr($pagebuff, $this->cntmrk[$this->page]);
20269 // add line start to current page
20270 $yshift = ($minstartliney - $this->y);
20271 if ($fontaligned) {
20272 $yshift += ($curfontsize / $this->k);
20274 $try = sprintf('1 0 0 1 0 %.3F cm', ($yshift * $this->k));
20275 $this->setPageBuffer($this->page, $tstart."\nq\n".$try."\n".$linebeg."\nQ\n".$tend);
20276 // shift the annotations and links
20277 if (isset($this->PageAnnots[$this->page])) {
20278 $next_pask = count($this->PageAnnots[$this->page]);
20279 } else {
20280 $next_pask = 0;
20282 if (isset($this->PageAnnots[$startlinepage])) {
20283 foreach ($this->PageAnnots[$startlinepage] as $pak => $pac) {
20284 if ($pak >= $pask) {
20285 $this->PageAnnots[$this->page][] = $pac;
20286 unset($this->PageAnnots[$startlinepage][$pak]);
20287 $npak = count($this->PageAnnots[$this->page]) - 1;
20288 $this->PageAnnots[$this->page][$npak]['y'] -= $yshift;
20292 $pask = $next_pask;
20293 $startlinepos = $this->cntmrk[$this->page];
20294 $startlinepage = $this->page;
20295 $startliney = $this->y;
20296 $this->newline = false;
20298 $this->y += ((($curfontsize * $this->cell_height_ratio / $this->k) + $curfontascent - $curfontdescent) / 2) - $imgh;
20299 $minstartliney = min($this->y, $minstartliney);
20300 $maxbottomliney = ($startliney + ($this->FontSize * $this->cell_height_ratio));
20302 } elseif (isset($dom[$key]['fontname']) OR isset($dom[$key]['fontstyle']) OR isset($dom[$key]['fontsize']) OR isset($dom[$key]['line-height'])) {
20303 // account for different font size
20304 $pfontname = $curfontname;
20305 $pfontstyle = $curfontstyle;
20306 $pfontsize = $curfontsize;
20307 $fontname = isset($dom[$key]['fontname']) ? $dom[$key]['fontname'] : $curfontname;
20308 $fontstyle = isset($dom[$key]['fontstyle']) ? $dom[$key]['fontstyle'] : $curfontstyle;
20309 $fontsize = isset($dom[$key]['fontsize']) ? $dom[$key]['fontsize'] : $curfontsize;
20310 $fontascent = $this->getFontAscent($fontname, $fontstyle, $fontsize);
20311 $fontdescent = $this->getFontDescent($fontname, $fontstyle, $fontsize);
20312 if (($fontname != $curfontname) OR ($fontstyle != $curfontstyle) OR ($fontsize != $curfontsize)
20313 OR ($this->cell_height_ratio != $dom[$key]['line-height'])
20314 OR ($dom[$key]['tag'] AND $dom[$key]['opening'] AND ($dom[$key]['value'] == 'li')) ) {
20315 if (($key < ($maxel - 1)) AND (
20316 ($dom[$key]['tag'] AND $dom[$key]['opening'] AND ($dom[$key]['value'] == 'li'))
20317 OR ($this->cell_height_ratio != $dom[$key]['line-height'])
20318 OR (!$this->newline AND is_numeric($fontsize) AND is_numeric($curfontsize) AND ($fontsize >= 0) AND ($curfontsize >= 0) AND ($fontsize != $curfontsize))
20319 )) {
20320 if ($this->page > $startlinepage) {
20321 // fix lines splitted over two pages
20322 if (isset($this->footerlen[$startlinepage])) {
20323 $curpos = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
20325 // line to be moved one page forward
20326 $pagebuff = $this->getPageBuffer($startlinepage);
20327 $linebeg = substr($pagebuff, $startlinepos, ($curpos - $startlinepos));
20328 $tstart = substr($pagebuff, 0, $startlinepos);
20329 $tend = substr($this->getPageBuffer($startlinepage), $curpos);
20330 // remove line start from previous page
20331 $this->setPageBuffer($startlinepage, $tstart.''.$tend);
20332 $pagebuff = $this->getPageBuffer($this->page);
20333 $tstart = substr($pagebuff, 0, $this->cntmrk[$this->page]);
20334 $tend = substr($pagebuff, $this->cntmrk[$this->page]);
20335 // add line start to current page
20336 $yshift = ($minstartliney - $this->y);
20337 $try = sprintf('1 0 0 1 0 %.3F cm', ($yshift * $this->k));
20338 $this->setPageBuffer($this->page, $tstart."\nq\n".$try."\n".$linebeg."\nQ\n".$tend);
20339 // shift the annotations and links
20340 if (isset($this->PageAnnots[$this->page])) {
20341 $next_pask = count($this->PageAnnots[$this->page]);
20342 } else {
20343 $next_pask = 0;
20345 if (isset($this->PageAnnots[$startlinepage])) {
20346 foreach ($this->PageAnnots[$startlinepage] as $pak => $pac) {
20347 if ($pak >= $pask) {
20348 $this->PageAnnots[$this->page][] = $pac;
20349 unset($this->PageAnnots[$startlinepage][$pak]);
20350 $npak = count($this->PageAnnots[$this->page]) - 1;
20351 $this->PageAnnots[$this->page][$npak]['y'] -= $yshift;
20355 $pask = $next_pask;
20356 $startlinepos = $this->cntmrk[$this->page];
20357 $startlinepage = $this->page;
20358 $startliney = $this->y;
20360 if (!isset($dom[$key]['line-height'])) {
20361 $dom[$key]['line-height'] = $this->cell_height_ratio;
20363 if (!$dom[$key]['block']) {
20364 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']))) {
20365 $this->y += (((($curfontsize * $this->cell_height_ratio) - ($fontsize * $dom[$key]['line-height'])) / $this->k) + $curfontascent - $fontascent - $curfontdescent + $fontdescent) / 2;
20367 if (($dom[$key]['value'] != 'sup') AND ($dom[$key]['value'] != 'sub')) {
20368 $current_line_align_data = array($key, $minstartliney, $maxbottomliney);
20369 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)))) {
20370 $minstartliney = min($this->y, $line_align_data[1]);
20371 $maxbottomliney = max(($this->y + (($fontsize * $this->cell_height_ratio) / $this->k)), $line_align_data[2]);
20372 } else {
20373 $minstartliney = min($this->y, $minstartliney);
20374 $maxbottomliney = max(($this->y + (($fontsize * $this->cell_height_ratio) / $this->k)), $maxbottomliney);
20376 $line_align_data = $current_line_align_data;
20379 $this->cell_height_ratio = $dom[$key]['line-height'];
20380 $fontaligned = true;
20382 $this->SetFont($fontname, $fontstyle, $fontsize);
20383 // reset row height
20384 $this->resetLastH();
20385 $curfontname = $fontname;
20386 $curfontstyle = $fontstyle;
20387 $curfontsize = $fontsize;
20388 $curfontascent = $fontascent;
20389 $curfontdescent = $fontdescent;
20392 // set text rendering mode
20393 $textstroke = isset($dom[$key]['stroke']) ? $dom[$key]['stroke'] : $this->textstrokewidth;
20394 $textfill = isset($dom[$key]['fill']) ? $dom[$key]['fill'] : (($this->textrendermode % 2) == 0);
20395 $textclip = isset($dom[$key]['clip']) ? $dom[$key]['clip'] : ($this->textrendermode > 3);
20396 $this->setTextRenderingMode($textstroke, $textfill, $textclip);
20397 if (isset($dom[$key]['font-stretch']) AND ($dom[$key]['font-stretch'] !== false)) {
20398 $this->setFontStretching($dom[$key]['font-stretch']);
20400 if (isset($dom[$key]['letter-spacing']) AND ($dom[$key]['letter-spacing'] !== false)) {
20401 $this->setFontSpacing($dom[$key]['letter-spacing']);
20403 if (($plalign == 'J') AND $dom[$key]['block']) {
20404 $plalign = '';
20406 // get current position on page buffer
20407 $curpos = $this->pagelen[$startlinepage];
20408 if (isset($dom[$key]['bgcolor']) AND ($dom[$key]['bgcolor'] !== false)) {
20409 $this->SetFillColorArray($dom[$key]['bgcolor']);
20410 $wfill = true;
20411 } else {
20412 $wfill = $fill | false;
20414 if (isset($dom[$key]['fgcolor']) AND ($dom[$key]['fgcolor'] !== false)) {
20415 $this->SetTextColorArray($dom[$key]['fgcolor']);
20417 if (isset($dom[$key]['strokecolor']) AND ($dom[$key]['strokecolor'] !== false)) {
20418 $this->SetDrawColorArray($dom[$key]['strokecolor']);
20420 if (isset($dom[$key]['align'])) {
20421 $lalign = $dom[$key]['align'];
20423 if ($this->empty_string($lalign)) {
20424 $lalign = $align;
20427 // align lines
20428 if ($this->newline AND (strlen($dom[$key]['value']) > 0) AND ($dom[$key]['value'] != 'td') AND ($dom[$key]['value'] != 'th')) {
20429 $newline = true;
20430 $fontaligned = false;
20431 // we are at the beginning of a new line
20432 if (isset($startlinex)) {
20433 $yshift = ($minstartliney - $startliney);
20434 if (($yshift > 0) OR ($this->page > $startlinepage)) {
20435 $yshift = 0;
20437 $t_x = 0;
20438 // the last line must be shifted to be aligned as requested
20439 $linew = abs($this->endlinex - $startlinex);
20440 if ($this->inxobj) {
20441 // we are inside an XObject template
20442 $pstart = substr($this->xobjects[$this->xobjid]['outdata'], 0, $startlinepos);
20443 if (isset($opentagpos)) {
20444 $midpos = $opentagpos;
20445 } else {
20446 $midpos = 0;
20448 if ($midpos > 0) {
20449 $pmid = substr($this->xobjects[$this->xobjid]['outdata'], $startlinepos, ($midpos - $startlinepos));
20450 $pend = substr($this->xobjects[$this->xobjid]['outdata'], $midpos);
20451 } else {
20452 $pmid = substr($this->xobjects[$this->xobjid]['outdata'], $startlinepos);
20453 $pend = '';
20455 } else {
20456 $pstart = substr($this->getPageBuffer($startlinepage), 0, $startlinepos);
20457 if (isset($opentagpos) AND isset($this->footerlen[$startlinepage]) AND (!$this->InFooter)) {
20458 $this->footerpos[$startlinepage] = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
20459 $midpos = min($opentagpos, $this->footerpos[$startlinepage]);
20460 } elseif (isset($opentagpos)) {
20461 $midpos = $opentagpos;
20462 } elseif (isset($this->footerlen[$startlinepage]) AND (!$this->InFooter)) {
20463 $this->footerpos[$startlinepage] = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
20464 $midpos = $this->footerpos[$startlinepage];
20465 } else {
20466 $midpos = 0;
20468 if ($midpos > 0) {
20469 $pmid = substr($this->getPageBuffer($startlinepage), $startlinepos, ($midpos - $startlinepos));
20470 $pend = substr($this->getPageBuffer($startlinepage), $midpos);
20471 } else {
20472 $pmid = substr($this->getPageBuffer($startlinepage), $startlinepos);
20473 $pend = '';
20476 if ((isset($plalign) AND ((($plalign == 'C') OR ($plalign == 'J') OR (($plalign == 'R') AND (!$this->rtl)) OR (($plalign == 'L') AND ($this->rtl)))))) {
20477 // calculate shifting amount
20478 $tw = $w;
20479 if (($plalign == 'J') AND $this->isRTLTextDir() AND ($this->num_columns > 1)) {
20480 $tw += $this->cell_padding['R'];
20482 if ($this->lMargin != $prevlMargin) {
20483 $tw += ($prevlMargin - $this->lMargin);
20485 if ($this->rMargin != $prevrMargin) {
20486 $tw += ($prevrMargin - $this->rMargin);
20488 $one_space_width = $this->GetStringWidth(chr(32));
20489 $no = 0; // number of spaces on a line contained on a single block
20490 if ($this->isRTLTextDir()) { // RTL
20491 // remove left space if exist
20492 $pos1 = $this->revstrpos($pmid, '[(');
20493 if ($pos1 > 0) {
20494 $pos1 = intval($pos1);
20495 if ($this->isUnicodeFont()) {
20496 $pos2 = intval($this->revstrpos($pmid, '[('.chr(0).chr(32)));
20497 $spacelen = 2;
20498 } else {
20499 $pos2 = intval($this->revstrpos($pmid, '[('.chr(32)));
20500 $spacelen = 1;
20502 if ($pos1 == $pos2) {
20503 $pmid = substr($pmid, 0, ($pos1 + 2)).substr($pmid, ($pos1 + 2 + $spacelen));
20504 if (substr($pmid, $pos1, 4) == '[()]') {
20505 $linew -= $one_space_width;
20506 } elseif ($pos1 == strpos($pmid, '[(')) {
20507 $no = 1;
20511 } else { // LTR
20512 // remove right space if exist
20513 $pos1 = $this->revstrpos($pmid, ')]');
20514 if ($pos1 > 0) {
20515 $pos1 = intval($pos1);
20516 if ($this->isUnicodeFont()) {
20517 $pos2 = intval($this->revstrpos($pmid, chr(0).chr(32).')]')) + 2;
20518 $spacelen = 2;
20519 } else {
20520 $pos2 = intval($this->revstrpos($pmid, chr(32).')]')) + 1;
20521 $spacelen = 1;
20523 if ($pos1 == $pos2) {
20524 $pmid = substr($pmid, 0, ($pos1 - $spacelen)).substr($pmid, $pos1);
20525 $linew -= $one_space_width;
20529 $mdiff = ($tw - $linew);
20530 if ($plalign == 'C') {
20531 if ($this->rtl) {
20532 $t_x = -($mdiff / 2);
20533 } else {
20534 $t_x = ($mdiff / 2);
20536 } elseif ($plalign == 'R') {
20537 // right alignment on LTR document
20538 $t_x = $mdiff;
20539 } elseif ($plalign == 'L') {
20540 // left alignment on RTL document
20541 $t_x = -$mdiff;
20542 } elseif (($plalign == 'J') AND ($plalign == $lalign)) {
20543 // Justification
20544 if ($this->isRTLTextDir()) {
20545 // align text on the left
20546 $t_x = -$mdiff;
20548 $ns = 0; // number of spaces
20549 $pmidtemp = $pmid;
20550 // escape special characters
20551 $pmidtemp = preg_replace('/[\\\][\(]/x', '\\#!#OP#!#', $pmidtemp);
20552 $pmidtemp = preg_replace('/[\\\][\)]/x', '\\#!#CP#!#', $pmidtemp);
20553 // search spaces
20554 if (preg_match_all('/\[\(([^\)]*)\)\]/x', $pmidtemp, $lnstring, PREG_PATTERN_ORDER)) {
20555 $spacestr = $this->getSpaceString();
20556 $maxkk = count($lnstring[1]) - 1;
20557 for ($kk=0; $kk <= $maxkk; ++$kk) {
20558 // restore special characters
20559 $lnstring[1][$kk] = str_replace('#!#OP#!#', '(', $lnstring[1][$kk]);
20560 $lnstring[1][$kk] = str_replace('#!#CP#!#', ')', $lnstring[1][$kk]);
20561 // store number of spaces on the strings
20562 $lnstring[2][$kk] = substr_count($lnstring[1][$kk], $spacestr);
20563 // count total spaces on line
20564 $ns += $lnstring[2][$kk];
20565 $lnstring[3][$kk] = $ns;
20567 if ($ns == 0) {
20568 $ns = 1;
20570 // calculate additional space to add to each existing space
20571 $spacewidth = ($mdiff / ($ns - $no)) * $this->k;
20572 $spacewidthu = -1000 * ($mdiff + (($ns + $no) * $one_space_width)) / $ns / $this->FontSize;
20573 if ($this->font_spacing != 0) {
20574 // fixed spacing mode
20575 $osw = -1000 * $this->font_spacing / $this->FontSize;
20576 $spacewidthu += $osw;
20578 $nsmax = $ns;
20579 $ns = 0;
20580 reset($lnstring);
20581 $offset = 0;
20582 $strcount = 0;
20583 $prev_epsposbeg = 0;
20584 $textpos = 0;
20585 if ($this->isRTLTextDir()) {
20586 $textpos = $this->wPt;
20588 global $spacew;
20589 while (preg_match('/([0-9\.\+\-]*)[\s](Td|cm|m|l|c|re)[\s]/x', $pmid, $strpiece, PREG_OFFSET_CAPTURE, $offset) == 1) {
20590 // check if we are inside a string section '[( ... )]'
20591 $stroffset = strpos($pmid, '[(', $offset);
20592 if (($stroffset !== false) AND ($stroffset <= $strpiece[2][1])) {
20593 // set offset to the end of string section
20594 $offset = strpos($pmid, ')]', $stroffset);
20595 while (($offset !== false) AND ($pmid{($offset - 1)} == '\\')) {
20596 $offset = strpos($pmid, ')]', ($offset + 1));
20598 if ($offset === false) {
20599 $this->Error('HTML Justification: malformed PDF code.');
20601 continue;
20603 if ($this->isRTLTextDir()) {
20604 $spacew = ($spacewidth * ($nsmax - $ns));
20605 } else {
20606 $spacew = ($spacewidth * $ns);
20608 $offset = $strpiece[2][1] + strlen($strpiece[2][0]);
20609 $epsposbeg = strpos($pmid, 'q'.$this->epsmarker, $offset);
20610 $epsposend = strpos($pmid, $this->epsmarker.'Q', $offset) + strlen($this->epsmarker.'Q');
20611 if ((($epsposbeg > 0) AND ($epsposend > 0) AND ($offset > $epsposbeg) AND ($offset < $epsposend))
20612 OR (($epsposbeg === false) AND ($epsposend > 0) AND ($offset < $epsposend))) {
20613 // shift EPS images
20614 $trx = sprintf('1 0 0 1 %.3F 0 cm', $spacew);
20615 $epsposbeg = strpos($pmid, 'q'.$this->epsmarker, ($prev_epsposbeg - 6));
20616 $pmid_b = substr($pmid, 0, $epsposbeg);
20617 $pmid_m = substr($pmid, $epsposbeg, ($epsposend - $epsposbeg));
20618 $pmid_e = substr($pmid, $epsposend);
20619 $pmid = $pmid_b."\nq\n".$trx."\n".$pmid_m."\nQ\n".$pmid_e;
20620 $offset = $epsposend;
20621 continue;
20624 $prev_epsposbeg = $epsposbeg;
20625 $currentxpos = 0;
20626 // shift blocks of code
20627 switch ($strpiece[2][0]) {
20628 case 'Td':
20629 case 'cm':
20630 case 'm':
20631 case 'l': {
20632 // get current X position
20633 preg_match('/([0-9\.\+\-]*)[\s]('.$strpiece[1][0].')[\s]('.$strpiece[2][0].')([\s]*)/x', $pmid, $xmatches);
20634 $currentxpos = $xmatches[1];
20635 $textpos = $currentxpos;
20636 if (($strcount <= $maxkk) AND ($strpiece[2][0] == 'Td')) {
20637 $ns = $lnstring[3][$strcount];
20638 if ($this->isRTLTextDir()) {
20639 $spacew = ($spacewidth * ($nsmax - $ns));
20641 ++$strcount;
20643 // justify block
20644 $pmid = preg_replace_callback('/([0-9\.\+\-]*)[\s]('.$strpiece[1][0].')[\s]('.$strpiece[2][0].')([\s]*)/x',
20645 create_function('$matches', 'global $spacew;
20646 $newx = sprintf("%.2F",(floatval($matches[1]) + $spacew));
20647 return "".$newx." ".$matches[2]." x*#!#*x".$matches[3].$matches[4];'), $pmid, 1);
20648 break;
20650 case 're': {
20651 // justify block
20652 if (!$this->empty_string($this->lispacer)) {
20653 $this->lispacer = '';
20654 continue;
20656 preg_match('/([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]('.$strpiece[1][0].')[\s](re)([\s]*)/x', $pmid, $xmatches);
20657 $currentxpos = $xmatches[1];
20658 global $x_diff, $w_diff;
20659 $x_diff = 0;
20660 $w_diff = 0;
20661 if ($this->isRTLTextDir()) { // RTL
20662 if ($currentxpos < $textpos) {
20663 $x_diff = ($spacewidth * ($nsmax - $lnstring[3][$strcount]));
20664 $w_diff = ($spacewidth * $lnstring[2][$strcount]);
20665 } else {
20666 if ($strcount > 0) {
20667 $x_diff = ($spacewidth * ($nsmax - $lnstring[3][($strcount - 1)]));
20668 $w_diff = ($spacewidth * $lnstring[2][($strcount - 1)]);
20671 } else { // LTR
20672 if ($currentxpos > $textpos) {
20673 if ($strcount > 0) {
20674 $x_diff = ($spacewidth * $lnstring[3][($strcount - 1)]);
20676 $w_diff = ($spacewidth * $lnstring[2][$strcount]);
20677 } else {
20678 if ($strcount > 1) {
20679 $x_diff = ($spacewidth * $lnstring[3][($strcount - 2)]);
20681 if ($strcount > 0) {
20682 $w_diff = ($spacewidth * $lnstring[2][($strcount - 1)]);
20686 $pmid = preg_replace_callback('/('.$xmatches[1].')[\s]('.$xmatches[2].')[\s]('.$xmatches[3].')[\s]('.$strpiece[1][0].')[\s](re)([\s]*)/x',
20687 create_function('$matches', 'global $x_diff, $w_diff;
20688 $newx = sprintf("%.2F",(floatval($matches[1]) + $x_diff));
20689 $neww = sprintf("%.2F",(floatval($matches[3]) + $w_diff));
20690 return "".$newx." ".$matches[2]." ".$neww." ".$matches[4]." x*#!#*x".$matches[5].$matches[6];'), $pmid, 1);
20691 break;
20693 case 'c': {
20694 // get current X position
20695 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);
20696 $currentxpos = $xmatches[1];
20697 // justify block
20698 $pmid = preg_replace_callback('/('.$xmatches[1].')[\s]('.$xmatches[2].')[\s]('.$xmatches[3].')[\s]('.$xmatches[4].')[\s]('.$xmatches[5].')[\s]('.$strpiece[1][0].')[\s](c)([\s]*)/x',
20699 create_function('$matches', 'global $spacew;
20700 $newx1 = sprintf("%.3F",(floatval($matches[1]) + $spacew));
20701 $newx2 = sprintf("%.3F",(floatval($matches[3]) + $spacew));
20702 $newx3 = sprintf("%.3F",(floatval($matches[5]) + $spacew));
20703 return "".$newx1." ".$matches[2]." ".$newx2." ".$matches[4]." ".$newx3." ".$matches[6]." x*#!#*x".$matches[7].$matches[8];'), $pmid, 1);
20704 break;
20707 // shift the annotations and links
20708 $cxpos = ($currentxpos / $this->k);
20709 $lmpos = ($this->lMargin + $this->cell_padding['L'] + $this->feps);
20710 if ($this->inxobj) {
20711 // we are inside an XObject template
20712 foreach ($this->xobjects[$this->xobjid]['annotations'] as $pak => $pac) {
20713 if (($pac['y'] >= $minstartliney) AND (($pac['x'] * $this->k) >= ($currentxpos - $this->feps)) AND (($pac['x'] * $this->k) <= ($currentxpos + $this->feps))) {
20714 if ($cxpos > $lmpos) {
20715 $this->xobjects[$this->xobjid]['annotations'][$pak]['x'] += ($spacew / $this->k);
20716 $this->xobjects[$this->xobjid]['annotations'][$pak]['w'] += (($spacewidth * $pac['numspaces']) / $this->k);
20717 } else {
20718 $this->xobjects[$this->xobjid]['annotations'][$pak]['w'] += (($spacewidth * $pac['numspaces']) / $this->k);
20720 break;
20723 } elseif (isset($this->PageAnnots[$this->page])) {
20724 foreach ($this->PageAnnots[$this->page] as $pak => $pac) {
20725 if (($pac['y'] >= $minstartliney) AND (($pac['x'] * $this->k) >= ($currentxpos - $this->feps)) AND (($pac['x'] * $this->k) <= ($currentxpos + $this->feps))) {
20726 if ($cxpos > $lmpos) {
20727 $this->PageAnnots[$this->page][$pak]['x'] += ($spacew / $this->k);
20728 $this->PageAnnots[$this->page][$pak]['w'] += (($spacewidth * $pac['numspaces']) / $this->k);
20729 } else {
20730 $this->PageAnnots[$this->page][$pak]['w'] += (($spacewidth * $pac['numspaces']) / $this->k);
20732 break;
20736 } // end of while
20737 // remove markers
20738 $pmid = str_replace('x*#!#*x', '', $pmid);
20739 if ($this->isUnicodeFont()) {
20740 // multibyte characters
20741 $spacew = $spacewidthu;
20742 if ($this->font_stretching != 100) {
20743 // word spacing is affected by stretching
20744 $spacew /= ($this->font_stretching / 100);
20746 $pmidtemp = $pmid;
20747 // escape special characters
20748 $pmidtemp = preg_replace('/[\\\][\(]/x', '\\#!#OP#!#', $pmidtemp);
20749 $pmidtemp = preg_replace('/[\\\][\)]/x', '\\#!#CP#!#', $pmidtemp);
20750 $pmid = preg_replace_callback("/\[\(([^\)]*)\)\]/x",
20751 create_function('$matches', 'global $spacew;
20752 $matches[1] = str_replace("#!#OP#!#", "(", $matches[1]);
20753 $matches[1] = str_replace("#!#CP#!#", ")", $matches[1]);
20754 return "[(".str_replace(chr(0).chr(32), ") ".sprintf("%.3F", $spacew)." (", $matches[1]).")]";'), $pmidtemp);
20755 if ($this->inxobj) {
20756 // we are inside an XObject template
20757 $this->xobjects[$this->xobjid]['outdata'] = $pstart."\n".$pmid."\n".$pend;
20758 } else {
20759 $this->setPageBuffer($startlinepage, $pstart."\n".$pmid."\n".$pend);
20761 $endlinepos = strlen($pstart."\n".$pmid."\n");
20762 } else {
20763 // non-unicode (single-byte characters)
20764 if ($this->font_stretching != 100) {
20765 // word spacing (Tw) is affected by stretching
20766 $spacewidth /= ($this->font_stretching / 100);
20768 $rs = sprintf('%.3F Tw', $spacewidth);
20769 $pmid = preg_replace("/\[\(/x", $rs.' [(', $pmid);
20770 if ($this->inxobj) {
20771 // we are inside an XObject template
20772 $this->xobjects[$this->xobjid]['outdata'] = $pstart."\n".$pmid."\nBT 0 Tw ET\n".$pend;
20773 } else {
20774 $this->setPageBuffer($startlinepage, $pstart."\n".$pmid."\nBT 0 Tw ET\n".$pend);
20776 $endlinepos = strlen($pstart."\n".$pmid."\nBT 0 Tw ET\n");
20779 } // end of J
20780 } // end if $startlinex
20781 if (($t_x != 0) OR ($yshift < 0)) {
20782 // shift the line
20783 $trx = sprintf('1 0 0 1 %.3F %.3F cm', ($t_x * $this->k), ($yshift * $this->k));
20784 $pstart .= "\nq\n".$trx."\n".$pmid."\nQ\n";
20785 $endlinepos = strlen($pstart);
20786 if ($this->inxobj) {
20787 // we are inside an XObject template
20788 $this->xobjects[$this->xobjid]['outdata'] = $pstart.$pend;
20789 foreach ($this->xobjects[$this->xobjid]['annotations'] as $pak => $pac) {
20790 if ($pak >= $pask) {
20791 $this->xobjects[$this->xobjid]['annotations'][$pak]['x'] += $t_x;
20792 $this->xobjects[$this->xobjid]['annotations'][$pak]['y'] -= $yshift;
20795 } else {
20796 $this->setPageBuffer($startlinepage, $pstart.$pend);
20797 // shift the annotations and links
20798 if (isset($this->PageAnnots[$this->page])) {
20799 foreach ($this->PageAnnots[$this->page] as $pak => $pac) {
20800 if ($pak >= $pask) {
20801 $this->PageAnnots[$this->page][$pak]['x'] += $t_x;
20802 $this->PageAnnots[$this->page][$pak]['y'] -= $yshift;
20807 $this->y -= $yshift;
20810 $pbrk = $this->checkPageBreak($this->lasth);
20811 $this->newline = false;
20812 $startlinex = $this->x;
20813 $startliney = $this->y;
20814 if ($dom[$dom[$key]['parent']]['value'] == 'sup') {
20815 $startliney -= ((0.3 * $this->FontSizePt) / $this->k);
20816 } elseif ($dom[$dom[$key]['parent']]['value'] == 'sub') {
20817 $startliney -= (($this->FontSizePt / 0.7) / $this->k);
20818 } else {
20819 $minstartliney = $startliney;
20820 $maxbottomliney = ($this->y + (($fontsize * $this->cell_height_ratio) / $this->k));
20822 $startlinepage = $this->page;
20823 if (isset($endlinepos) AND (!$pbrk)) {
20824 $startlinepos = $endlinepos;
20825 } else {
20826 if ($this->inxobj) {
20827 // we are inside an XObject template
20828 $startlinepos = strlen($this->xobjects[$this->xobjid]['outdata']);
20829 } elseif (!$this->InFooter) {
20830 if (isset($this->footerlen[$this->page])) {
20831 $this->footerpos[$this->page] = $this->pagelen[$this->page] - $this->footerlen[$this->page];
20832 } else {
20833 $this->footerpos[$this->page] = $this->pagelen[$this->page];
20835 $startlinepos = $this->footerpos[$this->page];
20836 } else {
20837 $startlinepos = $this->pagelen[$this->page];
20840 unset($endlinepos);
20841 $plalign = $lalign;
20842 if (isset($this->PageAnnots[$this->page])) {
20843 $pask = count($this->PageAnnots[$this->page]);
20844 } else {
20845 $pask = 0;
20847 if (!($dom[$key]['tag'] AND !$dom[$key]['opening'] AND ($dom[$key]['value'] == 'table')
20848 AND (isset($this->emptypagemrk[$this->page]))
20849 AND ($this->emptypagemrk[$this->page] == $this->pagelen[$this->page]))) {
20850 $this->SetFont($fontname, $fontstyle, $fontsize);
20851 if ($wfill) {
20852 $this->SetFillColorArray($this->bgcolor);
20855 } // end newline
20856 if (isset($opentagpos)) {
20857 unset($opentagpos);
20859 if ($dom[$key]['tag']) {
20860 if ($dom[$key]['opening']) {
20861 // get text indentation (if any)
20862 if (isset($dom[$key]['text-indent']) AND $dom[$key]['block']) {
20863 $this->textindent = $dom[$key]['text-indent'];
20864 $this->newline = true;
20866 // table
20867 if ($dom[$key]['value'] == 'table') {
20868 // available page width
20869 if ($this->rtl) {
20870 $wtmp = $this->x - $this->lMargin;
20871 } else {
20872 $wtmp = $this->w - $this->rMargin - $this->x;
20874 // get cell spacing
20875 if (isset($dom[$key]['attribute']['cellspacing'])) {
20876 $clsp = $this->getHTMLUnitToUnits($dom[$key]['attribute']['cellspacing'], 1, 'px');
20877 $cellspacing = array('H' => $clsp, 'V' => $clsp);
20878 } elseif (isset($dom[$key]['border-spacing'])) {
20879 $cellspacing = $dom[$key]['border-spacing'];
20880 } else {
20881 $cellspacing = array('H' => 0, 'V' => 0);
20883 // table width
20884 if (isset($dom[$key]['width'])) {
20885 $table_width = $this->getHTMLUnitToUnits($dom[$key]['width'], $wtmp, 'px');
20886 } else {
20887 $table_width = $wtmp;
20889 $table_width -= (2 * $cellspacing['H']);
20890 if (!$this->inthead) {
20891 $this->y += $cellspacing['V'];
20893 if ($this->rtl) {
20894 $cellspacingx = -$cellspacing['H'];
20895 } else {
20896 $cellspacingx = $cellspacing['H'];
20898 // total table width without cellspaces
20899 $table_columns_width = ($table_width - ($cellspacing['H'] * ($dom[$key]['cols'] - 1)));
20900 // minimum column width
20901 $table_min_column_width = ($table_columns_width / $dom[$key]['cols']);
20902 // array of custom column widths
20903 $table_colwidths = array_fill(0, $dom[$key]['cols'], $table_min_column_width);
20905 // table row
20906 if ($dom[$key]['value'] == 'tr') {
20907 // reset column counter
20908 $colid = 0;
20910 // table cell
20911 if (($dom[$key]['value'] == 'td') OR ($dom[$key]['value'] == 'th')) {
20912 $trid = $dom[$key]['parent'];
20913 $table_el = $dom[$trid]['parent'];
20914 if (!isset($dom[$table_el]['cols'])) {
20915 $dom[$table_el]['cols'] = $dom[$trid]['cols'];
20917 // store border info
20918 $tdborder = 0;
20919 if (isset($dom[$key]['border']) AND !empty($dom[$key]['border'])) {
20920 $tdborder = $dom[$key]['border'];
20922 $colspan = $dom[$key]['attribute']['colspan'];
20923 $old_cell_padding = $this->cell_padding;
20924 if (isset($dom[($dom[$trid]['parent'])]['attribute']['cellpadding'])) {
20925 $crclpd = $this->getHTMLUnitToUnits($dom[($dom[$trid]['parent'])]['attribute']['cellpadding'], 1, 'px');
20926 $current_cell_padding = array('L' => $crclpd, 'T' => $crclpd, 'R' => $crclpd, 'B' => $crclpd);
20927 } elseif (isset($dom[($dom[$trid]['parent'])]['padding'])) {
20928 $current_cell_padding = $dom[($dom[$trid]['parent'])]['padding'];
20929 } else {
20930 $current_cell_padding = array('L' => 0, 'T' => 0, 'R' => 0, 'B' => 0);
20932 $this->cell_padding = $current_cell_padding;
20933 if (isset($dom[$key]['height'])) {
20934 // minimum cell height
20935 $cellh = $this->getHTMLUnitToUnits($dom[$key]['height'], 0, 'px');
20936 } else {
20937 $cellh = 0;
20939 if (isset($dom[$key]['content'])) {
20940 $cell_content = stripslashes($dom[$key]['content']);
20941 } else {
20942 $cell_content = '&nbsp;';
20944 $tagtype = $dom[$key]['value'];
20945 $parentid = $key;
20946 while (($key < $maxel) AND (!(($dom[$key]['tag']) AND (!$dom[$key]['opening']) AND ($dom[$key]['value'] == $tagtype) AND ($dom[$key]['parent'] == $parentid)))) {
20947 // move $key index forward
20948 ++$key;
20950 if (!isset($dom[$trid]['startpage'])) {
20951 $dom[$trid]['startpage'] = $this->page;
20952 } else {
20953 $this->setPage($dom[$trid]['startpage']);
20955 if (!isset($dom[$trid]['startcolumn'])) {
20956 $dom[$trid]['startcolumn'] = $this->current_column;
20957 } elseif ($this->current_column != $dom[$trid]['startcolumn']) {
20958 $tmpx = $this->x;
20959 $this->selectColumn($dom[$trid]['startcolumn']);
20960 $this->x = $tmpx;
20962 if (!isset($dom[$trid]['starty'])) {
20963 $dom[$trid]['starty'] = $this->y;
20964 } else {
20965 $this->y = $dom[$trid]['starty'];
20967 if (!isset($dom[$trid]['startx'])) {
20968 $dom[$trid]['startx'] = $this->x;
20969 $this->x += $cellspacingx;
20970 } else {
20971 $this->x += ($cellspacingx / 2);
20973 if (isset($dom[$parentid]['attribute']['rowspan'])) {
20974 $rowspan = intval($dom[$parentid]['attribute']['rowspan']);
20975 } else {
20976 $rowspan = 1;
20978 // skip row-spanned cells started on the previous rows
20979 if (isset($dom[$table_el]['rowspans'])) {
20980 $rsk = 0;
20981 $rskmax = count($dom[$table_el]['rowspans']);
20982 while ($rsk < $rskmax) {
20983 $trwsp = $dom[$table_el]['rowspans'][$rsk];
20984 $rsstartx = $trwsp['startx'];
20985 $rsendx = $trwsp['endx'];
20986 // account for margin changes
20987 if ($trwsp['startpage'] < $this->page) {
20988 if (($this->rtl) AND ($this->pagedim[$this->page]['orm'] != $this->pagedim[$trwsp['startpage']]['orm'])) {
20989 $dl = ($this->pagedim[$this->page]['orm'] - $this->pagedim[$trwsp['startpage']]['orm']);
20990 $rsstartx -= $dl;
20991 $rsendx -= $dl;
20992 } elseif ((!$this->rtl) AND ($this->pagedim[$this->page]['olm'] != $this->pagedim[$trwsp['startpage']]['olm'])) {
20993 $dl = ($this->pagedim[$this->page]['olm'] - $this->pagedim[$trwsp['startpage']]['olm']);
20994 $rsstartx += $dl;
20995 $rsendx += $dl;
20998 if (($trwsp['rowspan'] > 0)
20999 AND ($rsstartx > ($this->x - $cellspacing['H'] - $current_cell_padding['L'] - $this->feps))
21000 AND ($rsstartx < ($this->x + $cellspacing['H'] + $current_cell_padding['R'] + $this->feps))
21001 AND (($trwsp['starty'] < ($this->y - $this->feps)) OR ($trwsp['startpage'] < $this->page) OR ($trwsp['startcolumn'] < $this->current_column))) {
21002 // set the starting X position of the current cell
21003 $this->x = $rsendx + $cellspacingx;
21004 // increment column indicator
21005 $colid += $trwsp['colspan'];
21006 if (($trwsp['rowspan'] == 1)
21007 AND (isset($dom[$trid]['endy']))
21008 AND (isset($dom[$trid]['endpage']))
21009 AND (isset($dom[$trid]['endcolumn']))
21010 AND ($trwsp['endpage'] == $dom[$trid]['endpage'])
21011 AND ($trwsp['endcolumn'] == $dom[$trid]['endcolumn'])) {
21012 // set ending Y position for row
21013 $dom[$table_el]['rowspans'][$rsk]['endy'] = max($dom[$trid]['endy'], $trwsp['endy']);
21014 $dom[$trid]['endy'] = $dom[$table_el]['rowspans'][$rsk]['endy'];
21016 $rsk = 0;
21017 } else {
21018 ++$rsk;
21022 if (isset($dom[$parentid]['width'])) {
21023 // user specified width
21024 $cellw = $this->getHTMLUnitToUnits($dom[$parentid]['width'], $table_columns_width, 'px');
21025 $tmpcw = ($cellw / $colspan);
21026 for ($i = 0; $i < $colspan; ++$i) {
21027 $table_colwidths[($colid + $i)] = $tmpcw;
21029 } else {
21030 // inherit column width
21031 $cellw = 0;
21032 for ($i = 0; $i < $colspan; ++$i) {
21033 $cellw += $table_colwidths[($colid + $i)];
21036 $cellw += (($colspan - 1) * $cellspacing['H']);
21037 // increment column indicator
21038 $colid += $colspan;
21039 // add rowspan information to table element
21040 if ($rowspan > 1) {
21041 $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));
21043 $cellid = array_push($dom[$trid]['cellpos'], array('startx' => $this->x));
21044 if ($rowspan > 1) {
21045 $dom[$trid]['cellpos'][($cellid - 1)]['rowspanid'] = ($trsid - 1);
21047 // push background colors
21048 if (isset($dom[$parentid]['bgcolor']) AND ($dom[$parentid]['bgcolor'] !== false)) {
21049 $dom[$trid]['cellpos'][($cellid - 1)]['bgcolor'] = $dom[$parentid]['bgcolor'];
21051 // store border info
21052 if (isset($tdborder) AND !empty($tdborder)) {
21053 $dom[$trid]['cellpos'][($cellid - 1)]['border'] = $tdborder;
21055 $prevLastH = $this->lasth;
21056 // store some info for multicolumn mode
21057 if ($this->rtl) {
21058 $this->colxshift['x'] = $this->w - $this->x - $this->rMargin;
21059 } else {
21060 $this->colxshift['x'] = $this->x - $this->lMargin;
21062 $this->colxshift['s'] = $cellspacing;
21063 $this->colxshift['p'] = $current_cell_padding;
21064 // ****** write the cell content ******
21065 $this->MultiCell($cellw, $cellh, $cell_content, false, $lalign, false, 2, '', '', true, 0, true, true, 0, 'T', false);
21066 // restore some values
21067 $this->colxshift = array('x' => 0, 's' => array('H' => 0, 'V' => 0), 'p' => array('L' => 0, 'T' => 0, 'R' => 0, 'B' => 0));
21068 $this->lasth = $prevLastH;
21069 $this->cell_padding = $old_cell_padding;
21070 $dom[$trid]['cellpos'][($cellid - 1)]['endx'] = $this->x;
21071 // update the end of row position
21072 if ($rowspan <= 1) {
21073 if (isset($dom[$trid]['endy'])) {
21074 if (($this->page == $dom[$trid]['endpage']) AND ($this->current_column == $dom[$trid]['endcolumn'])) {
21075 $dom[$trid]['endy'] = max($this->y, $dom[$trid]['endy']);
21076 } elseif (($this->page > $dom[$trid]['endpage']) OR ($this->current_column > $dom[$trid]['endcolumn'])) {
21077 $dom[$trid]['endy'] = $this->y;
21079 } else {
21080 $dom[$trid]['endy'] = $this->y;
21082 if (isset($dom[$trid]['endpage'])) {
21083 $dom[$trid]['endpage'] = max($this->page, $dom[$trid]['endpage']);
21084 } else {
21085 $dom[$trid]['endpage'] = $this->page;
21087 if (isset($dom[$trid]['endcolumn'])) {
21088 $dom[$trid]['endcolumn'] = max($this->current_column, $dom[$trid]['endcolumn']);
21089 } else {
21090 $dom[$trid]['endcolumn'] = $this->current_column;
21092 } else {
21093 // account for row-spanned cells
21094 $dom[$table_el]['rowspans'][($trsid - 1)]['endx'] = $this->x;
21095 $dom[$table_el]['rowspans'][($trsid - 1)]['endy'] = $this->y;
21096 $dom[$table_el]['rowspans'][($trsid - 1)]['endpage'] = $this->page;
21097 $dom[$table_el]['rowspans'][($trsid - 1)]['endcolumn'] = $this->current_column;
21099 if (isset($dom[$table_el]['rowspans'])) {
21100 // update endy and endpage on rowspanned cells
21101 foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
21102 if ($trwsp['rowspan'] > 0) {
21103 if (isset($dom[$trid]['endpage'])) {
21104 if (($trwsp['endpage'] == $dom[$trid]['endpage']) AND ($trwsp['endcolumn'] == $dom[$trid]['endcolumn'])) {
21105 $dom[$table_el]['rowspans'][$k]['endy'] = max($dom[$trid]['endy'], $trwsp['endy']);
21106 } elseif (($trwsp['endpage'] < $dom[$trid]['endpage']) OR ($trwsp['endcolumn'] < $dom[$trid]['endcolumn'])) {
21107 $dom[$table_el]['rowspans'][$k]['endy'] = $dom[$trid]['endy'];
21108 $dom[$table_el]['rowspans'][$k]['endpage'] = $dom[$trid]['endpage'];
21109 $dom[$table_el]['rowspans'][$k]['endcolumn'] = $dom[$trid]['endcolumn'];
21110 } else {
21111 $dom[$trid]['endy'] = $this->pagedim[$dom[$trid]['endpage']]['hk'] - $this->pagedim[$dom[$trid]['endpage']]['bm'];
21117 $this->x += ($cellspacingx / 2);
21118 } else {
21119 // opening tag (or self-closing tag)
21120 if (!isset($opentagpos)) {
21121 if ($this->inxobj) {
21122 // we are inside an XObject template
21123 $opentagpos = strlen($this->xobjects[$this->xobjid]['outdata']);
21124 } elseif (!$this->InFooter) {
21125 if (isset($this->footerlen[$this->page])) {
21126 $this->footerpos[$this->page] = $this->pagelen[$this->page] - $this->footerlen[$this->page];
21127 } else {
21128 $this->footerpos[$this->page] = $this->pagelen[$this->page];
21130 $opentagpos = $this->footerpos[$this->page];
21133 $dom = $this->openHTMLTagHandler($dom, $key, $cell);
21135 } else { // closing tag
21136 $prev_numpages = $this->numpages;
21137 $old_bordermrk = $this->bordermrk[$this->page];
21138 $dom = $this->closeHTMLTagHandler($dom, $key, $cell, $maxbottomliney);
21139 if ($this->bordermrk[$this->page] > $old_bordermrk) {
21140 $startlinepos += ($this->bordermrk[$this->page] - $old_bordermrk);
21142 if ($prev_numpages > $this->numpages) {
21143 $startlinepage = $this->page;
21146 } elseif (strlen($dom[$key]['value']) > 0) {
21147 // print list-item
21148 if (!$this->empty_string($this->lispacer) AND ($this->lispacer != '^')) {
21149 $this->SetFont($pfontname, $pfontstyle, $pfontsize);
21150 $this->resetLastH();
21151 $minstartliney = $this->y;
21152 $maxbottomliney = ($startliney + ($this->FontSize * $this->cell_height_ratio));
21153 $this->putHtmlListBullet($this->listnum, $this->lispacer, $pfontsize);
21154 $this->SetFont($curfontname, $curfontstyle, $curfontsize);
21155 $this->resetLastH();
21156 if (is_numeric($pfontsize) AND ($pfontsize > 0) AND is_numeric($curfontsize) AND ($curfontsize > 0) AND ($pfontsize != $curfontsize)) {
21157 $pfontascent = $this->getFontAscent($pfontname, $pfontstyle, $pfontsize);
21158 $pfontdescent = $this->getFontDescent($pfontname, $pfontstyle, $pfontsize);
21159 $this->y += ((($pfontsize - $curfontsize) * $this->cell_height_ratio / $this->k) + $pfontascent - $curfontascent - $pfontdescent + $curfontdescent) / 2;
21160 $minstartliney = min($this->y, $minstartliney);
21161 $maxbottomliney = max(($this->y + (($pfontsize * $this->cell_height_ratio) / $this->k)), $maxbottomliney);
21164 // text
21165 $this->htmlvspace = 0;
21166 if ((!$this->premode) AND $this->isRTLTextDir()) {
21167 // reverse spaces order
21168 $lsp = ''; // left spaces
21169 $rsp = ''; // right spaces
21170 if (preg_match('/^('.$this->re_space['p'].'+)/'.$this->re_space['m'], $dom[$key]['value'], $matches)) {
21171 $lsp = $matches[1];
21173 if (preg_match('/('.$this->re_space['p'].'+)$/'.$this->re_space['m'], $dom[$key]['value'], $matches)) {
21174 $rsp = $matches[1];
21176 $dom[$key]['value'] = $rsp.$this->stringTrim($dom[$key]['value']).$lsp;
21178 if ($newline) {
21179 if (!$this->premode) {
21180 $prelen = strlen($dom[$key]['value']);
21181 if ($this->isRTLTextDir()) {
21182 // right trim except non-breaking space
21183 $dom[$key]['value'] = $this->stringRightTrim($dom[$key]['value']);
21184 } else {
21185 // left trim except non-breaking space
21186 $dom[$key]['value'] = $this->stringLeftTrim($dom[$key]['value']);
21188 $postlen = strlen($dom[$key]['value']);
21189 if (($postlen == 0) AND ($prelen > 0)) {
21190 $dom[$key]['trimmed_space'] = true;
21193 $newline = false;
21194 $firstblock = true;
21195 } else {
21196 $firstblock = false;
21197 // replace empty multiple spaces string with a single space
21198 $dom[$key]['value'] = preg_replace('/^'.$this->re_space['p'].'+$/'.$this->re_space['m'], chr(32), $dom[$key]['value']);
21200 $strrest = '';
21201 if ($this->rtl) {
21202 $this->x -= $this->textindent;
21203 } else {
21204 $this->x += $this->textindent;
21206 if (!isset($dom[$key]['trimmed_space']) OR !$dom[$key]['trimmed_space']) {
21207 $strlinelen = $this->GetStringWidth($dom[$key]['value']);
21208 if (!empty($this->HREF) AND (isset($this->HREF['url']))) {
21209 // HTML <a> Link
21210 $hrefcolor = '';
21211 if (isset($dom[($dom[$key]['parent'])]['fgcolor']) AND ($dom[($dom[$key]['parent'])]['fgcolor'] !== false)) {
21212 $hrefcolor = $dom[($dom[$key]['parent'])]['fgcolor'];
21214 $hrefstyle = -1;
21215 if (isset($dom[($dom[$key]['parent'])]['fontstyle']) AND ($dom[($dom[$key]['parent'])]['fontstyle'] !== false)) {
21216 $hrefstyle = $dom[($dom[$key]['parent'])]['fontstyle'];
21218 $strrest = $this->addHtmlLink($this->HREF['url'], $dom[$key]['value'], $wfill, true, $hrefcolor, $hrefstyle, true);
21219 } else {
21220 $wadj = 0; // space to leave for block continuity
21221 if ($this->rtl) {
21222 $cwa = $this->x - $this->lMargin;
21223 } else {
21224 $cwa = $this->w - $this->rMargin - $this->x;
21226 if (($strlinelen < $cwa) AND (isset($dom[($key + 1)])) AND ($dom[($key + 1)]['tag']) AND (!$dom[($key + 1)]['block'])) {
21227 // check the next text blocks for continuity
21228 $nkey = ($key + 1);
21229 $write_block = true;
21230 $same_textdir = true;
21231 $tmp_fontname = $this->FontFamily;
21232 $tmp_fontstyle = $this->FontStyle;
21233 $tmp_fontsize = $this->FontSizePt;
21234 while ($write_block AND isset($dom[$nkey])) {
21235 if ($dom[$nkey]['tag']) {
21236 if ($dom[$nkey]['block']) {
21237 // end of block
21238 $write_block = false;
21240 $tmp_fontname = isset($dom[$nkey]['fontname']) ? $dom[$nkey]['fontname'] : $this->FontFamily;
21241 $tmp_fontstyle = isset($dom[$nkey]['fontstyle']) ? $dom[$nkey]['fontstyle'] : $this->FontStyle;
21242 $tmp_fontsize = isset($dom[$nkey]['fontsize']) ? $dom[$nkey]['fontsize'] : $this->FontSizePt;
21243 $same_textdir = ($dom[$nkey]['dir'] == $dom[$key]['dir']);
21244 } else {
21245 $nextstr = preg_split('/'.$this->re_space['p'].'+/'.$this->re_space['m'], $dom[$nkey]['value']);
21246 if (isset($nextstr[0]) AND $same_textdir) {
21247 $wadj += $this->GetStringWidth($nextstr[0], $tmp_fontname, $tmp_fontstyle, $tmp_fontsize);
21249 if (isset($nextstr[1])) {
21250 $write_block = false;
21253 ++$nkey;
21256 if (($wadj > 0) AND (($strlinelen + $wadj) >= $cwa)) {
21257 $wadj = 0;
21258 $nextstr = preg_split('/'.$this->re_space['p'].'/'.$this->re_space['m'], $dom[$key]['value']);
21259 $numblks = count($nextstr);
21260 if ($numblks > 1) {
21261 // try to split on blank spaces
21262 $wadj = ($cwa - $strlinelen + $this->GetStringWidth($nextstr[($numblks - 1)]));
21265 // check for reversed text direction
21266 if (($wadj > 0) AND (($this->rtl AND ($this->tmprtl === 'L')) OR (!$this->rtl AND ($this->tmprtl === 'R')))) {
21267 // LTR text on RTL direction or RTL text on LTR direction
21268 $reverse_dir = true;
21269 $this->rtl = !$this->rtl;
21270 $revshift = ($strlinelen + $wadj + 0.000001); // add little quantity for rounding problems
21271 if ($this->rtl) {
21272 $this->x += $revshift;
21273 } else {
21274 $this->x -= $revshift;
21276 $xws = $this->x;
21278 // ****** write only until the end of the line and get the rest ******
21279 $strrest = $this->Write($this->lasth, $dom[$key]['value'], '', $wfill, '', false, 0, true, $firstblock, 0, $wadj);
21280 // restore default direction
21281 if ($reverse_dir AND ($wadj == 0)) {
21282 $this->x = $xws;
21283 $this->rtl = !$this->rtl;
21284 $reverse_dir = false;
21288 $this->textindent = 0;
21289 if (strlen($strrest) > 0) {
21290 // store the remaining string on the previous $key position
21291 $this->newline = true;
21292 if ($strrest == $dom[$key]['value']) {
21293 // used to avoid infinite loop
21294 ++$loop;
21295 } else {
21296 $loop = 0;
21298 $dom[$key]['value'] = $strrest;
21299 if ($cell) {
21300 if ($this->rtl) {
21301 $this->x -= $this->cell_padding['R'];
21302 } else {
21303 $this->x += $this->cell_padding['L'];
21306 if ($loop < 3) {
21307 --$key;
21309 } else {
21310 $loop = 0;
21313 ++$key;
21314 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')) {
21315 // check if we are on a new page or on a new column
21316 if ((!$undo) AND (($this->y < $this->start_transaction_y) OR (($dom[$key]['value'] == 'tr') AND ($dom[($dom[$key]['parent'])]['endy'] < $this->start_transaction_y)))) {
21317 // we are on a new page or on a new column and the total object height is less than the available vertical space.
21318 // restore previous object
21319 $this->rollbackTransaction(true);
21320 // restore previous values
21321 foreach ($this_method_vars as $vkey => $vval) {
21322 $$vkey = $vval;
21324 // add a page (or trig AcceptPageBreak() for multicolumn mode)
21325 $pre_y = $this->y;
21326 if ((!$this->checkPageBreak($this->PageBreakTrigger + 1)) AND ($this->y < $pre_y)) {
21327 $startliney = $this->y;
21329 $undo = true; // avoid infinite loop
21330 } else {
21331 $undo = false;
21334 } // end for each $key
21335 // align the last line
21336 if (isset($startlinex)) {
21337 $yshift = ($minstartliney - $startliney);
21338 if (($yshift > 0) OR ($this->page > $startlinepage)) {
21339 $yshift = 0;
21341 $t_x = 0;
21342 // the last line must be shifted to be aligned as requested
21343 $linew = abs($this->endlinex - $startlinex);
21344 if ($this->inxobj) {
21345 // we are inside an XObject template
21346 $pstart = substr($this->xobjects[$this->xobjid]['outdata'], 0, $startlinepos);
21347 if (isset($opentagpos)) {
21348 $midpos = $opentagpos;
21349 } else {
21350 $midpos = 0;
21352 if ($midpos > 0) {
21353 $pmid = substr($this->xobjects[$this->xobjid]['outdata'], $startlinepos, ($midpos - $startlinepos));
21354 $pend = substr($this->xobjects[$this->xobjid]['outdata'], $midpos);
21355 } else {
21356 $pmid = substr($this->xobjects[$this->xobjid]['outdata'], $startlinepos);
21357 $pend = '';
21359 } else {
21360 $pstart = substr($this->getPageBuffer($startlinepage), 0, $startlinepos);
21361 if (isset($opentagpos) AND isset($this->footerlen[$startlinepage]) AND (!$this->InFooter)) {
21362 $this->footerpos[$startlinepage] = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
21363 $midpos = min($opentagpos, $this->footerpos[$startlinepage]);
21364 } elseif (isset($opentagpos)) {
21365 $midpos = $opentagpos;
21366 } elseif (isset($this->footerlen[$startlinepage]) AND (!$this->InFooter)) {
21367 $this->footerpos[$startlinepage] = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
21368 $midpos = $this->footerpos[$startlinepage];
21369 } else {
21370 $midpos = 0;
21372 if ($midpos > 0) {
21373 $pmid = substr($this->getPageBuffer($startlinepage), $startlinepos, ($midpos - $startlinepos));
21374 $pend = substr($this->getPageBuffer($startlinepage), $midpos);
21375 } else {
21376 $pmid = substr($this->getPageBuffer($startlinepage), $startlinepos);
21377 $pend = '';
21380 if ((isset($plalign) AND ((($plalign == 'C') OR (($plalign == 'R') AND (!$this->rtl)) OR (($plalign == 'L') AND ($this->rtl)))))) {
21381 // calculate shifting amount
21382 $tw = $w;
21383 if ($this->lMargin != $prevlMargin) {
21384 $tw += ($prevlMargin - $this->lMargin);
21386 if ($this->rMargin != $prevrMargin) {
21387 $tw += ($prevrMargin - $this->rMargin);
21389 $one_space_width = $this->GetStringWidth(chr(32));
21390 $no = 0; // number of spaces on a line contained on a single block
21391 if ($this->isRTLTextDir()) { // RTL
21392 // remove left space if exist
21393 $pos1 = $this->revstrpos($pmid, '[(');
21394 if ($pos1 > 0) {
21395 $pos1 = intval($pos1);
21396 if ($this->isUnicodeFont()) {
21397 $pos2 = intval($this->revstrpos($pmid, '[('.chr(0).chr(32)));
21398 $spacelen = 2;
21399 } else {
21400 $pos2 = intval($this->revstrpos($pmid, '[('.chr(32)));
21401 $spacelen = 1;
21403 if ($pos1 == $pos2) {
21404 $pmid = substr($pmid, 0, ($pos1 + 2)).substr($pmid, ($pos1 + 2 + $spacelen));
21405 if (substr($pmid, $pos1, 4) == '[()]') {
21406 $linew -= $one_space_width;
21407 } elseif ($pos1 == strpos($pmid, '[(')) {
21408 $no = 1;
21412 } else { // LTR
21413 // remove right space if exist
21414 $pos1 = $this->revstrpos($pmid, ')]');
21415 if ($pos1 > 0) {
21416 $pos1 = intval($pos1);
21417 if ($this->isUnicodeFont()) {
21418 $pos2 = intval($this->revstrpos($pmid, chr(0).chr(32).')]')) + 2;
21419 $spacelen = 2;
21420 } else {
21421 $pos2 = intval($this->revstrpos($pmid, chr(32).')]')) + 1;
21422 $spacelen = 1;
21424 if ($pos1 == $pos2) {
21425 $pmid = substr($pmid, 0, ($pos1 - $spacelen)).substr($pmid, $pos1);
21426 $linew -= $one_space_width;
21430 $mdiff = ($tw - $linew);
21431 if ($plalign == 'C') {
21432 if ($this->rtl) {
21433 $t_x = -($mdiff / 2);
21434 } else {
21435 $t_x = ($mdiff / 2);
21437 } elseif ($plalign == 'R') {
21438 // right alignment on LTR document
21439 $t_x = $mdiff;
21440 } elseif ($plalign == 'L') {
21441 // left alignment on RTL document
21442 $t_x = -$mdiff;
21444 } // end if startlinex
21445 if (($t_x != 0) OR ($yshift < 0)) {
21446 // shift the line
21447 $trx = sprintf('1 0 0 1 %.3F %.3F cm', ($t_x * $this->k), ($yshift * $this->k));
21448 $pstart .= "\nq\n".$trx."\n".$pmid."\nQ\n";
21449 $endlinepos = strlen($pstart);
21450 if ($this->inxobj) {
21451 // we are inside an XObject template
21452 $this->xobjects[$this->xobjid]['outdata'] = $pstart.$pend;
21453 foreach ($this->xobjects[$this->xobjid]['annotations'] as $pak => $pac) {
21454 if ($pak >= $pask) {
21455 $this->xobjects[$this->xobjid]['annotations'][$pak]['x'] += $t_x;
21456 $this->xobjects[$this->xobjid]['annotations'][$pak]['y'] -= $yshift;
21459 } else {
21460 $this->setPageBuffer($startlinepage, $pstart.$pend);
21461 // shift the annotations and links
21462 if (isset($this->PageAnnots[$this->page])) {
21463 foreach ($this->PageAnnots[$this->page] as $pak => $pac) {
21464 if ($pak >= $pask) {
21465 $this->PageAnnots[$this->page][$pak]['x'] += $t_x;
21466 $this->PageAnnots[$this->page][$pak]['y'] -= $yshift;
21471 $this->y -= $yshift;
21472 $yshift = 0;
21475 // restore previous values
21476 $this->setGraphicVars($gvars);
21477 if ($this->num_columns > 1) {
21478 $this->selectColumn();
21479 } elseif ($this->page > $prevPage) {
21480 $this->lMargin = $this->pagedim[$this->page]['olm'];
21481 $this->rMargin = $this->pagedim[$this->page]['orm'];
21483 // restore previous list state
21484 $this->cell_height_ratio = $prev_cell_height_ratio;
21485 $this->listnum = $prev_listnum;
21486 $this->listordered = $prev_listordered;
21487 $this->listcount = $prev_listcount;
21488 $this->lispacer = $prev_lispacer;
21489 if ($ln AND (!($cell AND ($dom[$key-1]['value'] == 'table')))) {
21490 $this->Ln($this->lasth);
21491 if ($this->y < $maxbottomliney) {
21492 $this->y = $maxbottomliney;
21495 unset($dom);
21499 * Process opening tags.
21500 * @param $dom (array) html dom array
21501 * @param $key (int) current element id
21502 * @param $cell (boolean) if true add the default left (or right if RTL) padding to each new line (default false).
21503 * @return $dom array
21504 * @protected
21506 protected function openHTMLTagHandler($dom, $key, $cell) {
21507 $tag = $dom[$key];
21508 $parent = $dom[($dom[$key]['parent'])];
21509 $firsttag = ($key == 1);
21510 // check for text direction attribute
21511 if (isset($tag['dir'])) {
21512 $this->setTempRTL($tag['dir']);
21513 } else {
21514 $this->tmprtl = false;
21516 if ($tag['block']) {
21517 $hbz = 0; // distance from y to line bottom
21518 $hb = 0; // vertical space between block tags
21519 // calculate vertical space for block tags
21520 if (isset($this->tagvspaces[$tag['value']][0]['h']) AND ($this->tagvspaces[$tag['value']][0]['h'] >= 0)) {
21521 $cur_h = $this->tagvspaces[$tag['value']][0]['h'];
21522 } elseif (isset($tag['fontsize'])) {
21523 $cur_h = ($tag['fontsize'] / $this->k) * $this->cell_height_ratio;
21524 } else {
21525 $cur_h = $this->FontSize * $this->cell_height_ratio;
21527 if (isset($this->tagvspaces[$tag['value']][0]['n'])) {
21528 $n = $this->tagvspaces[$tag['value']][0]['n'];
21529 } elseif (preg_match('/[h][0-9]/', $tag['value']) > 0) {
21530 $n = 0.6;
21531 } else {
21532 $n = 1;
21534 if ((!isset($this->tagvspaces[$tag['value']])) AND (in_array($tag['value'], array('div', 'dt', 'dd', 'li', 'br')))) {
21535 $hb = 0;
21536 } else {
21537 $hb = ($n * $cur_h);
21539 if (($this->htmlvspace <= 0) AND ($n > 0)) {
21540 if (isset($parent['fontsize'])) {
21541 $hbz = (($parent['fontsize'] / $this->k) * $this->cell_height_ratio);
21542 } else {
21543 $hbz = $this->FontSize * $this->cell_height_ratio;
21547 // Opening tag
21548 switch($tag['value']) {
21549 case 'table': {
21550 $cp = 0;
21551 $cs = 0;
21552 $dom[$key]['rowspans'] = array();
21553 if (!isset($dom[$key]['attribute']['nested']) OR ($dom[$key]['attribute']['nested'] != 'true')) {
21554 // set table header
21555 if (!$this->empty_string($dom[$key]['thead'])) {
21556 // set table header
21557 $this->thead = $dom[$key]['thead'];
21558 if (!isset($this->theadMargins) OR (empty($this->theadMargins))) {
21559 $this->theadMargins = array();
21560 $this->theadMargins['cell_padding'] = $this->cell_padding;
21561 $this->theadMargins['lmargin'] = $this->lMargin;
21562 $this->theadMargins['rmargin'] = $this->rMargin;
21563 $this->theadMargins['page'] = $this->page;
21564 $this->theadMargins['cell'] = $cell;
21568 // store current margins and page
21569 $dom[$key]['old_cell_padding'] = $this->cell_padding;
21570 if (isset($tag['attribute']['cellpadding'])) {
21571 $pad = $this->getHTMLUnitToUnits($tag['attribute']['cellpadding'], 1, 'px');
21572 $this->SetCellPadding($pad);
21573 } elseif (isset($tag['padding'])) {
21574 $this->cell_padding = $tag['padding'];
21576 if (isset($tag['attribute']['cellspacing'])) {
21577 $cs = $this->getHTMLUnitToUnits($tag['attribute']['cellspacing'], 1, 'px');
21578 } elseif (isset($tag['border-spacing'])) {
21579 $cs = $tag['border-spacing']['V'];
21581 $prev_y = $this->y;
21582 if ($this->checkPageBreak(((2 * $cp) + (2 * $cs) + $this->lasth), '', false) OR ($this->y < $prev_y)) {
21583 $this->inthead = true;
21584 // add a page (or trig AcceptPageBreak() for multicolumn mode)
21585 $this->checkPageBreak($this->PageBreakTrigger + 1);
21587 break;
21589 case 'tr': {
21590 // array of columns positions
21591 $dom[$key]['cellpos'] = array();
21592 break;
21594 case 'hr': {
21595 if ((isset($tag['height'])) AND ($tag['height'] != '')) {
21596 $hrHeight = $this->getHTMLUnitToUnits($tag['height'], 1, 'px');
21597 } else {
21598 $hrHeight = $this->GetLineWidth();
21600 $this->addHTMLVertSpace($hbz, ($hrHeight / 2), $cell, $firsttag);
21601 $x = $this->GetX();
21602 $y = $this->GetY();
21603 $wtmp = $this->w - $this->lMargin - $this->rMargin;
21604 if ($cell) {
21605 $wtmp -= ($this->cell_padding['L'] + $this->cell_padding['R']);
21607 if ((isset($tag['width'])) AND ($tag['width'] != '')) {
21608 $hrWidth = $this->getHTMLUnitToUnits($tag['width'], $wtmp, 'px');
21609 } else {
21610 $hrWidth = $wtmp;
21612 $prevlinewidth = $this->GetLineWidth();
21613 $this->SetLineWidth($hrHeight);
21614 $this->Line($x, $y, $x + $hrWidth, $y);
21615 $this->SetLineWidth($prevlinewidth);
21616 $this->addHTMLVertSpace(($hrHeight / 2), 0, $cell, !isset($dom[($key + 1)]));
21617 break;
21619 case 'a': {
21620 if (array_key_exists('href', $tag['attribute'])) {
21621 $this->HREF['url'] = $tag['attribute']['href'];
21623 break;
21625 case 'img': {
21626 if (isset($tag['attribute']['src'])) {
21627 // check for images without protocol
21628 if (preg_match('%^/{2}%', $tag['attribute']['src'])) {
21629 $tag['attribute']['src'] = 'http:'.$tag['attribute']['src'];
21631 // replace relative path with real server path
21632 if (($tag['attribute']['src'][0] == '/') AND !empty($_SERVER['DOCUMENT_ROOT']) AND ($_SERVER['DOCUMENT_ROOT'] != '/')) {
21633 $findroot = strpos($tag['attribute']['src'], $_SERVER['DOCUMENT_ROOT']);
21634 if (($findroot === false) OR ($findroot > 1)) {
21635 if (substr($_SERVER['DOCUMENT_ROOT'], -1) == '/') {
21636 $tag['attribute']['src'] = substr($_SERVER['DOCUMENT_ROOT'], 0, -1).$tag['attribute']['src'];
21637 } else {
21638 $tag['attribute']['src'] = $_SERVER['DOCUMENT_ROOT'].$tag['attribute']['src'];
21642 $tag['attribute']['src'] = htmlspecialchars_decode(urldecode($tag['attribute']['src']));
21643 $type = $this->getImageFileType($tag['attribute']['src']);
21644 $testscrtype = @parse_url($tag['attribute']['src']);
21645 if (!isset($testscrtype['query']) OR empty($testscrtype['query'])) {
21646 // convert URL to server path
21647 $tag['attribute']['src'] = str_replace(K_PATH_URL, K_PATH_MAIN, $tag['attribute']['src']);
21649 if (!isset($tag['width'])) {
21650 $tag['width'] = 0;
21652 if (!isset($tag['height'])) {
21653 $tag['height'] = 0;
21655 //if (!isset($tag['attribute']['align'])) {
21656 // the only alignment supported is "bottom"
21657 // further development is required for other modes.
21658 $tag['attribute']['align'] = 'bottom';
21660 switch($tag['attribute']['align']) {
21661 case 'top': {
21662 $align = 'T';
21663 break;
21665 case 'middle': {
21666 $align = 'M';
21667 break;
21669 case 'bottom': {
21670 $align = 'B';
21671 break;
21673 default: {
21674 $align = 'B';
21675 break;
21678 $prevy = $this->y;
21679 $xpos = $this->x;
21680 $imglink = '';
21681 if (isset($this->HREF['url']) AND !$this->empty_string($this->HREF['url'])) {
21682 $imglink = $this->HREF['url'];
21683 if ($imglink{0} == '#') {
21684 // convert url to internal link
21685 $lnkdata = explode(',', $imglink);
21686 if (isset($lnkdata[0])) {
21687 $page = intval(substr($lnkdata[0], 1));
21688 if (empty($page) OR ($page <= 0)) {
21689 $page = $this->page;
21691 if (isset($lnkdata[1]) AND (strlen($lnkdata[1]) > 0)) {
21692 $lnky = floatval($lnkdata[1]);
21693 } else {
21694 $lnky = 0;
21696 $imglink = $this->AddLink();
21697 $this->SetLink($imglink, $lnky, $page);
21701 $border = 0;
21702 if (isset($tag['border']) AND !empty($tag['border'])) {
21703 // currently only support 1 (frame) or a combination of 'LTRB'
21704 $border = $tag['border'];
21706 $iw = '';
21707 if (isset($tag['width'])) {
21708 $iw = $this->getHTMLUnitToUnits($tag['width'], 1, 'px', false);
21710 $ih = '';
21711 if (isset($tag['height'])) {
21712 $ih = $this->getHTMLUnitToUnits($tag['height'], 1, 'px', false);
21714 if (($type == 'eps') OR ($type == 'ai')) {
21715 $this->ImageEps($tag['attribute']['src'], $xpos, $this->y, $iw, $ih, $imglink, true, $align, '', $border, true);
21716 } elseif ($type == 'svg') {
21717 $this->ImageSVG($tag['attribute']['src'], $xpos, $this->y, $iw, $ih, $imglink, $align, '', $border, true);
21718 } else {
21719 $this->Image($tag['attribute']['src'], $xpos, $this->y, $iw, $ih, '', $imglink, $align, false, 300, '', false, false, $border, false, false, true);
21721 switch($align) {
21722 case 'T': {
21723 $this->y = $prevy;
21724 break;
21726 case 'M': {
21727 $this->y = (($this->img_rb_y + $prevy - ($tag['fontsize'] / $this->k)) / 2) ;
21728 break;
21730 case 'B': {
21731 $this->y = $this->img_rb_y - ($tag['fontsize'] / $this->k);
21732 break;
21736 break;
21738 case 'dl': {
21739 ++$this->listnum;
21740 if ($this->listnum == 1) {
21741 $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
21742 } else {
21743 $this->addHTMLVertSpace(0, 0, $cell, $firsttag);
21745 break;
21747 case 'dt': {
21748 $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
21749 break;
21751 case 'dd': {
21752 if ($this->rtl) {
21753 $this->rMargin += $this->listindent;
21754 } else {
21755 $this->lMargin += $this->listindent;
21757 ++$this->listindentlevel;
21758 $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
21759 break;
21761 case 'ul':
21762 case 'ol': {
21763 ++$this->listnum;
21764 if ($tag['value'] == 'ol') {
21765 $this->listordered[$this->listnum] = true;
21766 } else {
21767 $this->listordered[$this->listnum] = false;
21769 if (isset($tag['attribute']['start'])) {
21770 $this->listcount[$this->listnum] = intval($tag['attribute']['start']) - 1;
21771 } else {
21772 $this->listcount[$this->listnum] = 0;
21774 if ($this->rtl) {
21775 $this->rMargin += $this->listindent;
21776 $this->x -= $this->listindent;
21777 } else {
21778 $this->lMargin += $this->listindent;
21779 $this->x += $this->listindent;
21781 ++$this->listindentlevel;
21782 if ($this->listnum == 1) {
21783 if ($key > 1) {
21784 $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
21786 } else {
21787 $this->addHTMLVertSpace(0, 0, $cell, $firsttag);
21789 break;
21791 case 'li': {
21792 if ($key > 2) {
21793 $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
21795 if ($this->listordered[$this->listnum]) {
21796 // ordered item
21797 if (isset($parent['attribute']['type']) AND !$this->empty_string($parent['attribute']['type'])) {
21798 $this->lispacer = $parent['attribute']['type'];
21799 } elseif (isset($parent['listtype']) AND !$this->empty_string($parent['listtype'])) {
21800 $this->lispacer = $parent['listtype'];
21801 } elseif (isset($this->lisymbol) AND !$this->empty_string($this->lisymbol)) {
21802 $this->lispacer = $this->lisymbol;
21803 } else {
21804 $this->lispacer = '#';
21806 ++$this->listcount[$this->listnum];
21807 if (isset($tag['attribute']['value'])) {
21808 $this->listcount[$this->listnum] = intval($tag['attribute']['value']);
21810 } else {
21811 // unordered item
21812 if (isset($parent['attribute']['type']) AND !$this->empty_string($parent['attribute']['type'])) {
21813 $this->lispacer = $parent['attribute']['type'];
21814 } elseif (isset($parent['listtype']) AND !$this->empty_string($parent['listtype'])) {
21815 $this->lispacer = $parent['listtype'];
21816 } elseif (isset($this->lisymbol) AND !$this->empty_string($this->lisymbol)) {
21817 $this->lispacer = $this->lisymbol;
21818 } else {
21819 $this->lispacer = '!';
21822 break;
21824 case 'blockquote': {
21825 if ($this->rtl) {
21826 $this->rMargin += $this->listindent;
21827 } else {
21828 $this->lMargin += $this->listindent;
21830 ++$this->listindentlevel;
21831 $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
21832 break;
21834 case 'br': {
21835 $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
21836 break;
21838 case 'div': {
21839 $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
21840 break;
21842 case 'p': {
21843 $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
21844 break;
21846 case 'pre': {
21847 $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
21848 $this->premode = true;
21849 break;
21851 case 'sup': {
21852 $this->SetXY($this->GetX(), $this->GetY() - ((0.7 * $this->FontSizePt) / $this->k));
21853 break;
21855 case 'sub': {
21856 $this->SetXY($this->GetX(), $this->GetY() + ((0.3 * $this->FontSizePt) / $this->k));
21857 break;
21859 case 'h1':
21860 case 'h2':
21861 case 'h3':
21862 case 'h4':
21863 case 'h5':
21864 case 'h6': {
21865 $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
21866 break;
21868 // Form fields (since 4.8.000 - 2009-09-07)
21869 case 'form': {
21870 if (isset($tag['attribute']['action'])) {
21871 $this->form_action = $tag['attribute']['action'];
21872 } else {
21873 $this->form_action = K_PATH_URL.$_SERVER['SCRIPT_NAME'];
21875 if (isset($tag['attribute']['enctype'])) {
21876 $this->form_enctype = $tag['attribute']['enctype'];
21877 } else {
21878 $this->form_enctype = 'application/x-www-form-urlencoded';
21880 if (isset($tag['attribute']['method'])) {
21881 $this->form_mode = $tag['attribute']['method'];
21882 } else {
21883 $this->form_mode = 'post';
21885 break;
21887 case 'input': {
21888 if (isset($tag['attribute']['name']) AND !$this->empty_string($tag['attribute']['name'])) {
21889 $name = $tag['attribute']['name'];
21890 } else {
21891 break;
21893 $prop = array();
21894 $opt = array();
21895 if (isset($tag['attribute']['readonly']) AND !$this->empty_string($tag['attribute']['readonly'])) {
21896 $prop['readonly'] = true;
21898 if (isset($tag['attribute']['value']) AND !$this->empty_string($tag['attribute']['value'])) {
21899 $value = $tag['attribute']['value'];
21901 if (isset($tag['attribute']['maxlength']) AND !$this->empty_string($tag['attribute']['maxlength'])) {
21902 $opt['maxlen'] = intval($tag['attribute']['value']);
21904 $h = $this->FontSize * $this->cell_height_ratio;
21905 if (isset($tag['attribute']['size']) AND !$this->empty_string($tag['attribute']['size'])) {
21906 $w = intval($tag['attribute']['size']) * $this->GetStringWidth(chr(32)) * 2;
21907 } else {
21908 $w = $h;
21910 if (isset($tag['attribute']['checked']) AND (($tag['attribute']['checked'] == 'checked') OR ($tag['attribute']['checked'] == 'true'))) {
21911 $checked = true;
21912 } else {
21913 $checked = false;
21915 switch ($tag['attribute']['type']) {
21916 case 'text': {
21917 if (isset($value)) {
21918 $opt['v'] = $value;
21920 $this->TextField($name, $w, $h, $prop, $opt, '', '', false);
21921 break;
21923 case 'password': {
21924 if (isset($value)) {
21925 $opt['v'] = $value;
21927 $prop['password'] = 'true';
21928 $this->TextField($name, $w, $h, $prop, $opt, '', '', false);
21929 break;
21931 case 'checkbox': {
21932 $this->CheckBox($name, $w, $checked, $prop, $opt, $value, '', '', false);
21933 break;
21935 case 'radio': {
21936 $this->RadioButton($name, $w, $prop, $opt, $value, $checked, '', '', false);
21937 break;
21939 case 'submit': {
21940 $w = $this->GetStringWidth($value) * 1.5;
21941 $h *= 1.6;
21942 $prop = array('lineWidth'=>1, 'borderStyle'=>'beveled', 'fillColor'=>array(196, 196, 196), 'strokeColor'=>array(255, 255, 255));
21943 $action = array();
21944 $action['S'] = 'SubmitForm';
21945 $action['F'] = $this->form_action;
21946 if ($this->form_enctype != 'FDF') {
21947 $action['Flags'] = array('ExportFormat');
21949 if ($this->form_mode == 'get') {
21950 $action['Flags'] = array('GetMethod');
21952 $this->Button($name, $w, $h, $value, $action, $prop, $opt, '', '', false);
21953 break;
21955 case 'reset': {
21956 $w = $this->GetStringWidth($value) * 1.5;
21957 $h *= 1.6;
21958 $prop = array('lineWidth'=>1, 'borderStyle'=>'beveled', 'fillColor'=>array(196, 196, 196), 'strokeColor'=>array(255, 255, 255));
21959 $this->Button($name, $w, $h, $value, array('S'=>'ResetForm'), $prop, $opt, '', '', false);
21960 break;
21962 case 'file': {
21963 $prop['fileSelect'] = 'true';
21964 $this->TextField($name, $w, $h, $prop, $opt, '', '', false);
21965 if (!isset($value)) {
21966 $value = '*';
21968 $w = $this->GetStringWidth($value) * 2;
21969 $h *= 1.2;
21970 $prop = array('lineWidth'=>1, 'borderStyle'=>'beveled', 'fillColor'=>array(196, 196, 196), 'strokeColor'=>array(255, 255, 255));
21971 $jsaction = 'var f=this.getField(\''.$name.'\'); f.browseForFileToSubmit();';
21972 $this->Button('FB_'.$name, $w, $h, $value, $jsaction, $prop, $opt, '', '', false);
21973 break;
21975 case 'hidden': {
21976 if (isset($value)) {
21977 $opt['v'] = $value;
21979 $opt['f'] = array('invisible', 'hidden');
21980 $this->TextField($name, 0, 0, $prop, $opt, '', '', false);
21981 break;
21983 case 'image': {
21984 // THIS TYPE MUST BE FIXED
21985 if (isset($tag['attribute']['src']) AND !$this->empty_string($tag['attribute']['src'])) {
21986 $img = $tag['attribute']['src'];
21987 } else {
21988 break;
21990 $value = 'img';
21991 //$opt['mk'] = array('i'=>$img, 'tp'=>1, 'if'=>array('sw'=>'A', 's'=>'A', 'fb'=>false));
21992 if (isset($tag['attribute']['onclick']) AND !empty($tag['attribute']['onclick'])) {
21993 $jsaction = $tag['attribute']['onclick'];
21994 } else {
21995 $jsaction = '';
21997 $this->Button($name, $w, $h, $value, $jsaction, $prop, $opt, '', '', false);
21998 break;
22000 case 'button': {
22001 $w = $this->GetStringWidth($value) * 1.5;
22002 $h *= 1.6;
22003 $prop = array('lineWidth'=>1, 'borderStyle'=>'beveled', 'fillColor'=>array(196, 196, 196), 'strokeColor'=>array(255, 255, 255));
22004 if (isset($tag['attribute']['onclick']) AND !empty($tag['attribute']['onclick'])) {
22005 $jsaction = $tag['attribute']['onclick'];
22006 } else {
22007 $jsaction = '';
22009 $this->Button($name, $w, $h, $value, $jsaction, $prop, $opt, '', '', false);
22010 break;
22013 break;
22015 case 'textarea': {
22016 $prop = array();
22017 $opt = array();
22018 if (isset($tag['attribute']['readonly']) AND !$this->empty_string($tag['attribute']['readonly'])) {
22019 $prop['readonly'] = true;
22021 if (isset($tag['attribute']['name']) AND !$this->empty_string($tag['attribute']['name'])) {
22022 $name = $tag['attribute']['name'];
22023 } else {
22024 break;
22026 if (isset($tag['attribute']['value']) AND !$this->empty_string($tag['attribute']['value'])) {
22027 $opt['v'] = $tag['attribute']['value'];
22029 if (isset($tag['attribute']['cols']) AND !$this->empty_string($tag['attribute']['cols'])) {
22030 $w = intval($tag['attribute']['cols']) * $this->GetStringWidth(chr(32)) * 2;
22031 } else {
22032 $w = 40;
22034 if (isset($tag['attribute']['rows']) AND !$this->empty_string($tag['attribute']['rows'])) {
22035 $h = intval($tag['attribute']['rows']) * $this->FontSize * $this->cell_height_ratio;
22036 } else {
22037 $h = 10;
22039 $prop['multiline'] = 'true';
22040 $this->TextField($name, $w, $h, $prop, $opt, '', '', false);
22041 break;
22043 case 'select': {
22044 $h = $this->FontSize * $this->cell_height_ratio;
22045 if (isset($tag['attribute']['size']) AND !$this->empty_string($tag['attribute']['size'])) {
22046 $h *= ($tag['attribute']['size'] + 1);
22048 $prop = array();
22049 $opt = array();
22050 if (isset($tag['attribute']['name']) AND !$this->empty_string($tag['attribute']['name'])) {
22051 $name = $tag['attribute']['name'];
22052 } else {
22053 break;
22055 $w = 0;
22056 if (isset($tag['attribute']['opt']) AND !$this->empty_string($tag['attribute']['opt'])) {
22057 $options = explode('#!NwL!#', $tag['attribute']['opt']);
22058 $values = array();
22059 foreach ($options as $val) {
22060 if (strpos($val, '#!TaB!#') !== false) {
22061 $opts = explode('#!TaB!#', $val);
22062 $values[] = $opts;
22063 $w = max($w, $this->GetStringWidth($opts[1]));
22064 } else {
22065 $values[] = $val;
22066 $w = max($w, $this->GetStringWidth($val));
22069 } else {
22070 break;
22072 $w *= 2;
22073 if (isset($tag['attribute']['multiple']) AND ($tag['attribute']['multiple']='multiple')) {
22074 $prop['multipleSelection'] = 'true';
22075 $this->ListBox($name, $w, $h, $values, $prop, $opt, '', '', false);
22076 } else {
22077 $this->ComboBox($name, $w, $h, $values, $prop, $opt, '', '', false);
22079 break;
22081 case 'tcpdf': {
22082 if (defined('K_TCPDF_CALLS_IN_HTML') AND (K_TCPDF_CALLS_IN_HTML === true)) {
22083 // Special tag used to call TCPDF methods
22084 if (isset($tag['attribute']['method'])) {
22085 $tcpdf_method = $tag['attribute']['method'];
22086 if (method_exists($this, $tcpdf_method)) {
22087 if (isset($tag['attribute']['params']) AND (!empty($tag['attribute']['params']))) {
22088 $params = unserialize(urldecode($tag['attribute']['params']));
22089 call_user_func_array(array($this, $tcpdf_method), $params);
22090 } else {
22091 $this->$tcpdf_method();
22093 $this->newline = true;
22097 break;
22099 default: {
22100 break;
22103 // define tags that support borders and background colors
22104 $bordertags = array('blockquote','br','dd','dl','div','dt','h1','h2','h3','h4','h5','h6','hr','li','ol','p','pre','ul','tcpdf','table');
22105 if (in_array($tag['value'], $bordertags)) {
22106 // set border
22107 $dom[$key]['borderposition'] = $this->getBorderStartPosition();
22109 if ($dom[$key]['self'] AND isset($dom[$key]['attribute']['pagebreakafter'])) {
22110 $pba = $dom[$key]['attribute']['pagebreakafter'];
22111 // check for pagebreak
22112 if (($pba == 'true') OR ($pba == 'left') OR ($pba == 'right')) {
22113 // add a page (or trig AcceptPageBreak() for multicolumn mode)
22114 $this->checkPageBreak($this->PageBreakTrigger + 1);
22116 if ((($pba == 'left') AND (((!$this->rtl) AND (($this->page % 2) == 0)) OR (($this->rtl) AND (($this->page % 2) != 0))))
22117 OR (($pba == 'right') AND (((!$this->rtl) AND (($this->page % 2) != 0)) OR (($this->rtl) AND (($this->page % 2) == 0))))) {
22118 // add a page (or trig AcceptPageBreak() for multicolumn mode)
22119 $this->checkPageBreak($this->PageBreakTrigger + 1);
22122 return $dom;
22126 * Process closing tags.
22127 * @param $dom (array) html dom array
22128 * @param $key (int) current element id
22129 * @param $cell (boolean) if true add the default left (or right if RTL) padding to each new line (default false).
22130 * @param $maxbottomliney (int) maximum y value of current line
22131 * @return $dom array
22132 * @protected
22134 protected function closeHTMLTagHandler($dom, $key, $cell, $maxbottomliney=0) {
22135 $tag = $dom[$key];
22136 $parent = $dom[($dom[$key]['parent'])];
22137 $lasttag = ((!isset($dom[($key + 1)])) OR ((!isset($dom[($key + 2)])) AND ($dom[($key + 1)]['value'] == 'marker')));
22138 $in_table_head = false;
22139 // maximum x position (used to draw borders)
22140 if ($this->rtl) {
22141 $xmax = $this->w;
22142 } else {
22143 $xmax = 0;
22145 if ($tag['block']) {
22146 $hbz = 0; // distance from y to line bottom
22147 $hb = 0; // vertical space between block tags
22148 // calculate vertical space for block tags
22149 if (isset($this->tagvspaces[$tag['value']][1]['h']) AND ($this->tagvspaces[$tag['value']][1]['h'] >= 0)) {
22150 $pre_h = $this->tagvspaces[$tag['value']][1]['h'];
22151 } elseif (isset($parent['fontsize'])) {
22152 $pre_h = (($parent['fontsize'] / $this->k) * $this->cell_height_ratio);
22153 } else {
22154 $pre_h = $this->FontSize * $this->cell_height_ratio;
22156 if (isset($this->tagvspaces[$tag['value']][1]['n'])) {
22157 $n = $this->tagvspaces[$tag['value']][1]['n'];
22158 } elseif (preg_match('/[h][0-9]/', $tag['value']) > 0) {
22159 $n = 0.6;
22160 } else {
22161 $n = 1;
22163 if ((!isset($this->tagvspaces[$tag['value']])) AND ($tag['value'] == 'div')) {
22164 $hb = 0;
22165 } else {
22166 $hb = ($n * $pre_h);
22168 if ($maxbottomliney > $this->PageBreakTrigger) {
22169 $hbz = ($this->FontSize * $this->cell_height_ratio);
22170 } elseif ($this->y < $maxbottomliney) {
22171 $hbz = ($maxbottomliney - $this->y);
22174 // Closing tag
22175 switch($tag['value']) {
22176 case 'tr': {
22177 $table_el = $dom[($dom[$key]['parent'])]['parent'];
22178 if (!isset($parent['endy'])) {
22179 $dom[($dom[$key]['parent'])]['endy'] = $this->y;
22180 $parent['endy'] = $this->y;
22182 if (!isset($parent['endpage'])) {
22183 $dom[($dom[$key]['parent'])]['endpage'] = $this->page;
22184 $parent['endpage'] = $this->page;
22186 if (!isset($parent['endcolumn'])) {
22187 $dom[($dom[$key]['parent'])]['endcolumn'] = $this->current_column;
22188 $parent['endcolumn'] = $this->current_column;
22190 // update row-spanned cells
22191 if (isset($dom[$table_el]['rowspans'])) {
22192 foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
22193 $dom[$table_el]['rowspans'][$k]['rowspan'] -= 1;
22194 if ($dom[$table_el]['rowspans'][$k]['rowspan'] == 0) {
22195 if (($dom[$table_el]['rowspans'][$k]['endpage'] == $parent['endpage']) AND ($dom[$table_el]['rowspans'][$k]['endcolumn'] == $parent['endcolumn'])) {
22196 $dom[($dom[$key]['parent'])]['endy'] = max($dom[$table_el]['rowspans'][$k]['endy'], $parent['endy']);
22197 } elseif (($dom[$table_el]['rowspans'][$k]['endpage'] > $parent['endpage']) OR ($dom[$table_el]['rowspans'][$k]['endcolumn'] > $parent['endcolumn'])) {
22198 $dom[($dom[$key]['parent'])]['endy'] = $dom[$table_el]['rowspans'][$k]['endy'];
22199 $dom[($dom[$key]['parent'])]['endpage'] = $dom[$table_el]['rowspans'][$k]['endpage'];
22200 $dom[($dom[$key]['parent'])]['endcolumn'] = $dom[$table_el]['rowspans'][$k]['endcolumn'];
22204 // report new endy and endpage to the rowspanned cells
22205 foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
22206 if ($dom[$table_el]['rowspans'][$k]['rowspan'] == 0) {
22207 $dom[$table_el]['rowspans'][$k]['endpage'] = max($dom[$table_el]['rowspans'][$k]['endpage'], $dom[($dom[$key]['parent'])]['endpage']);
22208 $dom[($dom[$key]['parent'])]['endpage'] = $dom[$table_el]['rowspans'][$k]['endpage'];
22209 $dom[$table_el]['rowspans'][$k]['endcolumn'] = max($dom[$table_el]['rowspans'][$k]['endcolumn'], $dom[($dom[$key]['parent'])]['endcolumn']);
22210 $dom[($dom[$key]['parent'])]['endcolumn'] = $dom[$table_el]['rowspans'][$k]['endcolumn'];
22211 $dom[$table_el]['rowspans'][$k]['endy'] = max($dom[$table_el]['rowspans'][$k]['endy'], $dom[($dom[$key]['parent'])]['endy']);
22212 $dom[($dom[$key]['parent'])]['endy'] = $dom[$table_el]['rowspans'][$k]['endy'];
22215 // update remaining rowspanned cells
22216 foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
22217 if ($dom[$table_el]['rowspans'][$k]['rowspan'] == 0) {
22218 $dom[$table_el]['rowspans'][$k]['endpage'] = $dom[($dom[$key]['parent'])]['endpage'];
22219 $dom[$table_el]['rowspans'][$k]['endcolumn'] = $dom[($dom[$key]['parent'])]['endcolumn'];
22220 $dom[$table_el]['rowspans'][$k]['endy'] = $dom[($dom[$key]['parent'])]['endy'];
22224 $this->setPage($dom[($dom[$key]['parent'])]['endpage']);
22225 if ($this->num_columns > 1) {
22226 $this->selectColumn($dom[($dom[$key]['parent'])]['endcolumn']);
22228 $this->y = $dom[($dom[$key]['parent'])]['endy'];
22229 if (isset($dom[$table_el]['attribute']['cellspacing'])) {
22230 $this->y += $this->getHTMLUnitToUnits($dom[$table_el]['attribute']['cellspacing'], 1, 'px');
22231 } elseif (isset($dom[$table_el]['border-spacing'])) {
22232 $this->y += $dom[$table_el]['border-spacing']['V'];
22234 $this->Ln(0, $cell);
22235 if ($this->current_column == $parent['startcolumn']) {
22236 $this->x = $parent['startx'];
22238 // account for booklet mode
22239 if ($this->page > $parent['startpage']) {
22240 if (($this->rtl) AND ($this->pagedim[$this->page]['orm'] != $this->pagedim[$parent['startpage']]['orm'])) {
22241 $this->x -= ($this->pagedim[$this->page]['orm'] - $this->pagedim[$parent['startpage']]['orm']);
22242 } elseif ((!$this->rtl) AND ($this->pagedim[$this->page]['olm'] != $this->pagedim[$parent['startpage']]['olm'])) {
22243 $this->x += ($this->pagedim[$this->page]['olm'] - $this->pagedim[$parent['startpage']]['olm']);
22246 break;
22248 case 'tablehead':
22249 // closing tag used for the thead part
22250 $in_table_head = true;
22251 $this->inthead = false;
22252 case 'table': {
22253 $table_el = $parent;
22254 // set default border
22255 if (isset($table_el['attribute']['border']) AND ($table_el['attribute']['border'] > 0)) {
22256 // set default border
22257 $border = array('LTRB' => array('width' => $this->getCSSBorderWidth($table_el['attribute']['border']), 'cap'=>'square', 'join'=>'miter', 'dash'=> 0, 'color'=>array(0,0,0)));
22258 } else {
22259 $border = 0;
22261 $default_border = $border;
22262 // fix bottom line alignment of last line before page break
22263 foreach ($dom[($dom[$key]['parent'])]['trids'] as $j => $trkey) {
22264 // update row-spanned cells
22265 if (isset($dom[($dom[$key]['parent'])]['rowspans'])) {
22266 foreach ($dom[($dom[$key]['parent'])]['rowspans'] as $k => $trwsp) {
22267 if ($trwsp['trid'] == $trkey) {
22268 $dom[($dom[$key]['parent'])]['rowspans'][$k]['mrowspan'] -= 1;
22270 if (isset($prevtrkey) AND ($trwsp['trid'] == $prevtrkey) AND ($trwsp['mrowspan'] >= 0)) {
22271 $dom[($dom[$key]['parent'])]['rowspans'][$k]['trid'] = $trkey;
22275 if (isset($prevtrkey) AND ($dom[$trkey]['startpage'] > $dom[$prevtrkey]['endpage'])) {
22276 $pgendy = $this->pagedim[$dom[$prevtrkey]['endpage']]['hk'] - $this->pagedim[$dom[$prevtrkey]['endpage']]['bm'];
22277 $dom[$prevtrkey]['endy'] = $pgendy;
22278 // update row-spanned cells
22279 if (isset($dom[($dom[$key]['parent'])]['rowspans'])) {
22280 foreach ($dom[($dom[$key]['parent'])]['rowspans'] as $k => $trwsp) {
22281 if (($trwsp['trid'] == $trkey) AND ($trwsp['mrowspan'] > 1) AND ($trwsp['endpage'] == $dom[$prevtrkey]['endpage'])) {
22282 $dom[($dom[$key]['parent'])]['rowspans'][$k]['endy'] = $pgendy;
22283 $dom[($dom[$key]['parent'])]['rowspans'][$k]['mrowspan'] = -1;
22288 $prevtrkey = $trkey;
22289 $table_el = $dom[($dom[$key]['parent'])];
22291 // for each row
22292 if (count($table_el['trids']) > 0) {
22293 unset($xmax);
22295 foreach ($table_el['trids'] as $j => $trkey) {
22296 $parent = $dom[$trkey];
22297 if (!isset($xmax)) {
22298 $xmax = $parent['cellpos'][(count($parent['cellpos']) - 1)]['endx'];
22300 // for each cell on the row
22301 foreach ($parent['cellpos'] as $k => $cellpos) {
22302 if (isset($cellpos['rowspanid']) AND ($cellpos['rowspanid'] >= 0)) {
22303 $cellpos['startx'] = $table_el['rowspans'][($cellpos['rowspanid'])]['startx'];
22304 $cellpos['endx'] = $table_el['rowspans'][($cellpos['rowspanid'])]['endx'];
22305 $endy = $table_el['rowspans'][($cellpos['rowspanid'])]['endy'];
22306 $startpage = $table_el['rowspans'][($cellpos['rowspanid'])]['startpage'];
22307 $endpage = $table_el['rowspans'][($cellpos['rowspanid'])]['endpage'];
22308 $startcolumn = $table_el['rowspans'][($cellpos['rowspanid'])]['startcolumn'];
22309 $endcolumn = $table_el['rowspans'][($cellpos['rowspanid'])]['endcolumn'];
22310 } else {
22311 $endy = $parent['endy'];
22312 $startpage = $parent['startpage'];
22313 $endpage = $parent['endpage'];
22314 $startcolumn = $parent['startcolumn'];
22315 $endcolumn = $parent['endcolumn'];
22317 if ($this->num_columns == 0) {
22318 $this->num_columns = 1;
22320 if (isset($cellpos['border'])) {
22321 $border = $cellpos['border'];
22323 if (isset($cellpos['bgcolor']) AND ($cellpos['bgcolor']) !== false) {
22324 $this->SetFillColorArray($cellpos['bgcolor']);
22325 $fill = true;
22326 } else {
22327 $fill = false;
22329 $x = $cellpos['startx'];
22330 $y = $parent['starty'];
22331 $starty = $y;
22332 $w = abs($cellpos['endx'] - $cellpos['startx']);
22333 // get border modes
22334 $border_start = $this->getBorderMode($border, $position='start');
22335 $border_end = $this->getBorderMode($border, $position='end');
22336 $border_middle = $this->getBorderMode($border, $position='middle');
22337 // design borders around HTML cells.
22338 for ($page = $startpage; $page <= $endpage; ++$page) { // for each page
22339 $ccode = '';
22340 $this->setPage($page);
22341 if ($this->num_columns < 2) {
22342 // single-column mode
22343 $this->x = $x;
22344 $this->y = $this->tMargin;
22346 // account for margin changes
22347 if ($page > $startpage) {
22348 if (($this->rtl) AND ($this->pagedim[$page]['orm'] != $this->pagedim[$startpage]['orm'])) {
22349 $this->x -= ($this->pagedim[$page]['orm'] - $this->pagedim[$startpage]['orm']);
22350 } elseif ((!$this->rtl) AND ($this->pagedim[$page]['olm'] != $this->pagedim[$startpage]['olm'])) {
22351 $this->x += ($this->pagedim[$page]['olm'] - $this->pagedim[$startpage]['olm']);
22354 if ($startpage == $endpage) { // single page
22355 $deltacol = 0;
22356 $deltath = 0;
22357 for ($column = $startcolumn; $column <= $endcolumn; ++$column) { // for each column
22358 $this->selectColumn($column);
22359 if ($startcolumn == $endcolumn) { // single column
22360 $cborder = $border;
22361 $h = $endy - $parent['starty'];
22362 $this->y = $y;
22363 $this->x = $x;
22364 } elseif ($column == $startcolumn) { // first column
22365 $cborder = $border_start;
22366 $this->y = $starty;
22367 $this->x = $x;
22368 $h = $this->h - $this->y - $this->bMargin;
22369 if ($this->rtl) {
22370 $deltacol = $this->x + $this->rMargin - $this->w;
22371 } else {
22372 $deltacol = $this->x - $this->lMargin;
22374 } elseif ($column == $endcolumn) { // end column
22375 $cborder = $border_end;
22376 if (isset($this->columns[$column]['th']['\''.$page.'\''])) {
22377 $this->y = $this->columns[$column]['th']['\''.$page.'\''];
22379 $this->x += $deltacol;
22380 $h = $endy - $this->y;
22381 } else { // middle column
22382 $cborder = $border_middle;
22383 if (isset($this->columns[$column]['th']['\''.$page.'\''])) {
22384 $this->y = $this->columns[$column]['th']['\''.$page.'\''];
22386 $this->x += $deltacol;
22387 $h = $this->h - $this->y - $this->bMargin;
22389 $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
22390 } // end for each column
22391 } elseif ($page == $startpage) { // first page
22392 $deltacol = 0;
22393 $deltath = 0;
22394 for ($column = $startcolumn; $column < $this->num_columns; ++$column) { // for each column
22395 $this->selectColumn($column);
22396 if ($column == $startcolumn) { // first column
22397 $cborder = $border_start;
22398 $this->y = $starty;
22399 $this->x = $x;
22400 $h = $this->h - $this->y - $this->bMargin;
22401 if ($this->rtl) {
22402 $deltacol = $this->x + $this->rMargin - $this->w;
22403 } else {
22404 $deltacol = $this->x - $this->lMargin;
22406 } else { // middle column
22407 $cborder = $border_middle;
22408 if (isset($this->columns[$column]['th']['\''.$page.'\''])) {
22409 $this->y = $this->columns[$column]['th']['\''.$page.'\''];
22411 $this->x += $deltacol;
22412 $h = $this->h - $this->y - $this->bMargin;
22414 $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
22415 } // end for each column
22416 } elseif ($page == $endpage) { // last page
22417 $deltacol = 0;
22418 $deltath = 0;
22419 for ($column = 0; $column <= $endcolumn; ++$column) { // for each column
22420 $this->selectColumn($column);
22421 if ($column == $endcolumn) { // end column
22422 $cborder = $border_end;
22423 if (isset($this->columns[$column]['th']['\''.$page.'\''])) {
22424 $this->y = $this->columns[$column]['th']['\''.$page.'\''];
22426 $this->x += $deltacol;
22427 $h = $endy - $this->y;
22428 } else { // middle column
22429 $cborder = $border_middle;
22430 if (isset($this->columns[$column]['th']['\''.$page.'\''])) {
22431 $this->y = $this->columns[$column]['th']['\''.$page.'\''];
22433 $this->x += $deltacol;
22434 $h = $this->h - $this->y - $this->bMargin;
22436 $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
22437 } // end for each column
22438 } else { // middle page
22439 $deltacol = 0;
22440 $deltath = 0;
22441 for ($column = 0; $column < $this->num_columns; ++$column) { // for each column
22442 $this->selectColumn($column);
22443 $cborder = $border_middle;
22444 if (isset($this->columns[$column]['th']['\''.$page.'\''])) {
22445 $this->y = $this->columns[$column]['th']['\''.$page.'\''];
22447 $this->x += $deltacol;
22448 $h = $this->h - $this->y - $this->bMargin;
22449 $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
22450 } // end for each column
22452 if ($cborder OR $fill) {
22453 $offsetlen = strlen($ccode);
22454 // draw border and fill
22455 if ($this->inxobj) {
22456 // we are inside an XObject template
22457 if (end($this->xobjects[$this->xobjid]['transfmrk']) !== false) {
22458 $pagemarkkey = key($this->xobjects[$this->xobjid]['transfmrk']);
22459 $pagemark = $this->xobjects[$this->xobjid]['transfmrk'][$pagemarkkey];
22460 $this->xobjects[$this->xobjid]['transfmrk'][$pagemarkkey] += $offsetlen;
22461 } else {
22462 $pagemark = $this->xobjects[$this->xobjid]['intmrk'];
22463 $this->xobjects[$this->xobjid]['intmrk'] += $offsetlen;
22465 $pagebuff = $this->xobjects[$this->xobjid]['outdata'];
22466 $pstart = substr($pagebuff, 0, $pagemark);
22467 $pend = substr($pagebuff, $pagemark);
22468 $this->xobjects[$this->xobjid]['outdata'] = $pstart.$ccode.$pend;
22469 } else {
22470 // draw border and fill
22471 if (end($this->transfmrk[$this->page]) !== false) {
22472 $pagemarkkey = key($this->transfmrk[$this->page]);
22473 $pagemark = $this->transfmrk[$this->page][$pagemarkkey];
22474 $this->transfmrk[$this->page][$pagemarkkey] += $offsetlen;
22475 } elseif ($this->InFooter) {
22476 $pagemark = $this->footerpos[$this->page];
22477 $this->footerpos[$this->page] += $offsetlen;
22478 } else {
22479 $pagemark = $this->intmrk[$this->page];
22480 $this->intmrk[$this->page] += $offsetlen;
22482 $pagebuff = $this->getPageBuffer($this->page);
22483 $pstart = substr($pagebuff, 0, $pagemark);
22484 $pend = substr($pagebuff, $pagemark);
22485 $this->setPageBuffer($this->page, $pstart.$ccode.$pend);
22488 } // end for each page
22489 // restore default border
22490 $border = $default_border;
22491 } // end for each cell on the row
22492 if (isset($table_el['attribute']['cellspacing'])) {
22493 $this->y += $this->getHTMLUnitToUnits($table_el['attribute']['cellspacing'], 1, 'px');
22494 } elseif (isset($table_el['border-spacing'])) {
22495 $this->y += $table_el['border-spacing']['V'];
22497 $this->Ln(0, $cell);
22498 $this->x = $parent['startx'];
22499 if ($endpage > $startpage) {
22500 if (($this->rtl) AND ($this->pagedim[$endpage]['orm'] != $this->pagedim[$startpage]['orm'])) {
22501 $this->x += ($this->pagedim[$endpage]['orm'] - $this->pagedim[$startpage]['orm']);
22502 } elseif ((!$this->rtl) AND ($this->pagedim[$endpage]['olm'] != $this->pagedim[$startpage]['olm'])) {
22503 $this->x += ($this->pagedim[$endpage]['olm'] - $this->pagedim[$startpage]['olm']);
22507 if (!$in_table_head) { // we are not inside a thead section
22508 $this->cell_padding = $table_el['old_cell_padding'];
22509 // reset row height
22510 $this->resetLastH();
22511 if (($this->page == ($this->numpages - 1)) AND ($this->pageopen[$this->numpages])) {
22512 $plendiff = ($this->pagelen[$this->numpages] - $this->emptypagemrk[$this->numpages]);
22513 if (($plendiff > 0) AND ($plendiff < 60)) {
22514 $pagediff = substr($this->getPageBuffer($this->numpages), $this->emptypagemrk[$this->numpages], $plendiff);
22515 if (substr($pagediff, 0, 5) == 'BT /F') {
22516 // the difference is only a font setting
22517 $plendiff = 0;
22520 if ($plendiff == 0) {
22521 // remove last blank page
22522 $this->deletePage($this->numpages);
22525 if (isset($this->theadMargins['top'])) {
22526 // restore top margin
22527 $this->tMargin = $this->theadMargins['top'];
22529 if (!isset($table_el['attribute']['nested']) OR ($table_el['attribute']['nested'] != 'true')) {
22530 // reset main table header
22531 $this->thead = '';
22532 $this->theadMargins = array();
22533 $this->pagedim[$this->page]['tm'] = $this->tMargin;
22536 $parent = $table_el;
22537 break;
22539 case 'a': {
22540 $this->HREF = '';
22541 break;
22543 case 'sup': {
22544 $this->SetXY($this->GetX(), $this->GetY() + ((0.7 * $parent['fontsize']) / $this->k));
22545 break;
22547 case 'sub': {
22548 $this->SetXY($this->GetX(), $this->GetY() - ((0.3 * $parent['fontsize'])/$this->k));
22549 break;
22551 case 'div': {
22552 $this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
22553 break;
22555 case 'blockquote': {
22556 if ($this->rtl) {
22557 $this->rMargin -= $this->listindent;
22558 } else {
22559 $this->lMargin -= $this->listindent;
22561 --$this->listindentlevel;
22562 $this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
22563 break;
22565 case 'p': {
22566 $this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
22567 break;
22569 case 'pre': {
22570 $this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
22571 $this->premode = false;
22572 break;
22574 case 'dl': {
22575 --$this->listnum;
22576 if ($this->listnum <= 0) {
22577 $this->listnum = 0;
22578 $this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
22579 } else {
22580 $this->addHTMLVertSpace(0, 0, $cell, false, $lasttag);
22582 $this->resetLastH();
22583 break;
22585 case 'dt': {
22586 $this->lispacer = '';
22587 $this->addHTMLVertSpace(0, 0, $cell, false, $lasttag);
22588 break;
22590 case 'dd': {
22591 $this->lispacer = '';
22592 if ($this->rtl) {
22593 $this->rMargin -= $this->listindent;
22594 } else {
22595 $this->lMargin -= $this->listindent;
22597 --$this->listindentlevel;
22598 $this->addHTMLVertSpace(0, 0, $cell, false, $lasttag);
22599 break;
22601 case 'ul':
22602 case 'ol': {
22603 --$this->listnum;
22604 $this->lispacer = '';
22605 if ($this->rtl) {
22606 $this->rMargin -= $this->listindent;
22607 } else {
22608 $this->lMargin -= $this->listindent;
22610 --$this->listindentlevel;
22611 if ($this->listnum <= 0) {
22612 $this->listnum = 0;
22613 $this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
22614 } else {
22615 $this->addHTMLVertSpace(0, 0, $cell, false, $lasttag);
22617 $this->resetLastH();
22618 break;
22620 case 'li': {
22621 $this->lispacer = '';
22622 $this->addHTMLVertSpace(0, 0, $cell, false, $lasttag);
22623 break;
22625 case 'h1':
22626 case 'h2':
22627 case 'h3':
22628 case 'h4':
22629 case 'h5':
22630 case 'h6': {
22631 $this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
22632 break;
22634 // Form fields (since 4.8.000 - 2009-09-07)
22635 case 'form': {
22636 $this->form_action = '';
22637 $this->form_enctype = 'application/x-www-form-urlencoded';
22638 break;
22640 default : {
22641 break;
22644 // draw border and background (if any)
22645 $this->drawHTMLTagBorder($parent, $xmax);
22646 if (isset($dom[($dom[$key]['parent'])]['attribute']['pagebreakafter'])) {
22647 $pba = $dom[($dom[$key]['parent'])]['attribute']['pagebreakafter'];
22648 // check for pagebreak
22649 if (($pba == 'true') OR ($pba == 'left') OR ($pba == 'right')) {
22650 // add a page (or trig AcceptPageBreak() for multicolumn mode)
22651 $this->checkPageBreak($this->PageBreakTrigger + 1);
22653 if ((($pba == 'left') AND (((!$this->rtl) AND (($this->page % 2) == 0)) OR (($this->rtl) AND (($this->page % 2) != 0))))
22654 OR (($pba == 'right') AND (((!$this->rtl) AND (($this->page % 2) != 0)) OR (($this->rtl) AND (($this->page % 2) == 0))))) {
22655 // add a page (or trig AcceptPageBreak() for multicolumn mode)
22656 $this->checkPageBreak($this->PageBreakTrigger + 1);
22659 $this->tmprtl = false;
22660 return $dom;
22664 * Add vertical spaces if needed.
22665 * @param $hbz (string) Distance between current y and line bottom.
22666 * @param $hb (string) The height of the break.
22667 * @param $cell (boolean) if true add the default left (or right if RTL) padding to each new line (default false).
22668 * @param $firsttag (boolean) set to true when the tag is the first.
22669 * @param $lasttag (boolean) set to true when the tag is the last.
22670 * @protected
22672 protected function addHTMLVertSpace($hbz=0, $hb=0, $cell=false, $firsttag=false, $lasttag=false) {
22673 if ($firsttag) {
22674 $this->Ln(0, $cell);
22675 $this->htmlvspace = 0;
22676 return;
22678 if ($lasttag) {
22679 $this->Ln($hbz, $cell);
22680 $this->htmlvspace = 0;
22681 return;
22683 if ($hb < $this->htmlvspace) {
22684 $hd = 0;
22685 } else {
22686 $hd = $hb - $this->htmlvspace;
22687 $this->htmlvspace = $hb;
22689 $this->Ln(($hbz + $hd), $cell);
22693 * Return the starting coordinates to draw an html border
22694 * @return array containing top-left border coordinates
22695 * @protected
22696 * @since 5.7.000 (2010-08-03)
22698 protected function getBorderStartPosition() {
22699 if ($this->rtl) {
22700 $xmax = $this->lMargin;
22701 } else {
22702 $xmax = $this->w - $this->rMargin;
22704 return array('page' => $this->page, 'column' => $this->current_column, 'x' => $this->x, 'y' => $this->y, 'xmax' => $xmax);
22708 * Draw an HTML block border and fill
22709 * @param $tag (array) array of tag properties.
22710 * @param $xmax (int) end X coordinate for border.
22711 * @protected
22712 * @since 5.7.000 (2010-08-03)
22714 protected function drawHTMLTagBorder($tag, $xmax) {
22715 if (!isset($tag['borderposition'])) {
22716 // nothing to draw
22717 return;
22719 $prev_x = $this->x;
22720 $prev_y = $this->y;
22721 $prev_lasth = $this->lasth;
22722 $border = 0;
22723 $fill = false;
22724 $this->lasth = 0;
22725 if (isset($tag['border']) AND !empty($tag['border'])) {
22726 // get border style
22727 $border = $tag['border'];
22728 if (!$this->empty_string($this->thead) AND (!$this->inthead)) {
22729 // border for table header
22730 $border = $this->getBorderMode($border, $position='middle');
22733 if (isset($tag['bgcolor']) AND ($tag['bgcolor'] !== false)) {
22734 // get background color
22735 $old_bgcolor = $this->bgcolor;
22736 $this->SetFillColorArray($tag['bgcolor']);
22737 $fill = true;
22739 if (!$border AND !$fill) {
22740 // nothing to draw
22741 return;
22743 if (isset($tag['attribute']['cellspacing'])) {
22744 $clsp = $this->getHTMLUnitToUnits($tag['attribute']['cellspacing'], 1, 'px');
22745 $cellspacing = array('H' => $clsp, 'V' => $clsp);
22746 } elseif (isset($tag['border-spacing'])) {
22747 $cellspacing = $tag['border-spacing'];
22748 } else {
22749 $cellspacing = array('H' => 0, 'V' => 0);
22751 if (($tag['value'] != 'table') AND (is_array($border)) AND (!empty($border))) {
22752 // draw the border externally respect the sqare edge.
22753 $border['mode'] = 'ext';
22755 if ($this->rtl) {
22756 if ($xmax >= $tag['borderposition']['x']) {
22757 $xmax = $tag['borderposition']['xmax'];
22759 $w = ($tag['borderposition']['x'] - $xmax);
22760 } else {
22761 if ($xmax <= $tag['borderposition']['x']) {
22762 $xmax = $tag['borderposition']['xmax'];
22764 $w = ($xmax - $tag['borderposition']['x']);
22766 if ($w <= 0) {
22767 return;
22769 $w += $cellspacing['H'];
22770 $startpage = $tag['borderposition']['page'];
22771 $startcolumn = $tag['borderposition']['column'];
22772 $x = $tag['borderposition']['x'];
22773 $y = $tag['borderposition']['y'];
22774 $endpage = $this->page;
22775 $starty = $tag['borderposition']['y'] - $cellspacing['V'];
22776 $currentY = $this->y;
22777 $this->x = $x;
22778 // get latest column
22779 $endcolumn = $this->current_column;
22780 if ($this->num_columns == 0) {
22781 $this->num_columns = 1;
22783 // get border modes
22784 $border_start = $this->getBorderMode($border, $position='start');
22785 $border_end = $this->getBorderMode($border, $position='end');
22786 $border_middle = $this->getBorderMode($border, $position='middle');
22787 // temporary disable page regions
22788 $temp_page_regions = $this->page_regions;
22789 $this->page_regions = array();
22790 // design borders around HTML cells.
22791 for ($page = $startpage; $page <= $endpage; ++$page) { // for each page
22792 $ccode = '';
22793 $this->setPage($page);
22794 if ($this->num_columns < 2) {
22795 // single-column mode
22796 $this->x = $x;
22797 $this->y = $this->tMargin;
22799 // account for margin changes
22800 if ($page > $startpage) {
22801 if (($this->rtl) AND ($this->pagedim[$page]['orm'] != $this->pagedim[$startpage]['orm'])) {
22802 $this->x -= ($this->pagedim[$page]['orm'] - $this->pagedim[$startpage]['orm']);
22803 } elseif ((!$this->rtl) AND ($this->pagedim[$page]['olm'] != $this->pagedim[$startpage]['olm'])) {
22804 $this->x += ($this->pagedim[$page]['olm'] - $this->pagedim[$startpage]['olm']);
22807 if ($startpage == $endpage) {
22808 // single page
22809 for ($column = $startcolumn; $column <= $endcolumn; ++$column) { // for each column
22810 $this->selectColumn($column);
22811 if ($startcolumn == $endcolumn) { // single column
22812 $cborder = $border;
22813 $h = ($currentY - $y) + $cellspacing['V'];
22814 $this->y = $starty;
22815 } elseif ($column == $startcolumn) { // first column
22816 $cborder = $border_start;
22817 $this->y = $starty;
22818 $h = $this->h - $this->y - $this->bMargin;
22819 } elseif ($column == $endcolumn) { // end column
22820 $cborder = $border_end;
22821 $h = $currentY - $this->y;
22822 } else { // middle column
22823 $cborder = $border_middle;
22824 $h = $this->h - $this->y - $this->bMargin;
22826 $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
22827 } // end for each column
22828 } elseif ($page == $startpage) { // first page
22829 for ($column = $startcolumn; $column < $this->num_columns; ++$column) { // for each column
22830 $this->selectColumn($column);
22831 if ($column == $startcolumn) { // first column
22832 $cborder = $border_start;
22833 $this->y = $starty;
22834 $h = $this->h - $this->y - $this->bMargin;
22835 } else { // middle column
22836 $cborder = $border_middle;
22837 $h = $this->h - $this->y - $this->bMargin;
22839 $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
22840 } // end for each column
22841 } elseif ($page == $endpage) { // last page
22842 for ($column = 0; $column <= $endcolumn; ++$column) { // for each column
22843 $this->selectColumn($column);
22844 if ($column == $endcolumn) {
22845 // end column
22846 $cborder = $border_end;
22847 $h = $currentY - $this->y;
22848 } else {
22849 // middle column
22850 $cborder = $border_middle;
22851 $h = $this->h - $this->y - $this->bMargin;
22853 $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
22854 } // end for each column
22855 } else { // middle page
22856 for ($column = 0; $column < $this->num_columns; ++$column) { // for each column
22857 $this->selectColumn($column);
22858 $cborder = $border_middle;
22859 $h = $this->h - $this->y - $this->bMargin;
22860 $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
22861 } // end for each column
22863 if ($cborder OR $fill) {
22864 $offsetlen = strlen($ccode);
22865 // draw border and fill
22866 if ($this->inxobj) {
22867 // we are inside an XObject template
22868 if (end($this->xobjects[$this->xobjid]['transfmrk']) !== false) {
22869 $pagemarkkey = key($this->xobjects[$this->xobjid]['transfmrk']);
22870 $pagemark = $this->xobjects[$this->xobjid]['transfmrk'][$pagemarkkey];
22871 $this->xobjects[$this->xobjid]['transfmrk'][$pagemarkkey] += $offsetlen;
22872 } else {
22873 $pagemark = $this->xobjects[$this->xobjid]['intmrk'];
22874 $this->xobjects[$this->xobjid]['intmrk'] += $offsetlen;
22876 $pagebuff = $this->xobjects[$this->xobjid]['outdata'];
22877 $pstart = substr($pagebuff, 0, $pagemark);
22878 $pend = substr($pagebuff, $pagemark);
22879 $this->xobjects[$this->xobjid]['outdata'] = $pstart.$ccode.$pend;
22880 } else {
22881 if (end($this->transfmrk[$this->page]) !== false) {
22882 $pagemarkkey = key($this->transfmrk[$this->page]);
22883 $pagemark = $this->transfmrk[$this->page][$pagemarkkey];
22884 $this->transfmrk[$this->page][$pagemarkkey] += $offsetlen;
22885 } elseif ($this->InFooter) {
22886 $pagemark = $this->footerpos[$this->page];
22887 $this->footerpos[$this->page] += $offsetlen;
22888 } else {
22889 $pagemark = $this->intmrk[$this->page];
22890 $this->intmrk[$this->page] += $offsetlen;
22892 $pagebuff = $this->getPageBuffer($this->page);
22893 $pstart = substr($pagebuff, 0, $this->bordermrk[$this->page]);
22894 $pend = substr($pagebuff, $this->bordermrk[$this->page]);
22895 $this->setPageBuffer($this->page, $pstart.$ccode.$pend);
22896 $this->bordermrk[$this->page] += $offsetlen;
22897 $this->cntmrk[$this->page] += $offsetlen;
22900 } // end for each page
22901 // restore page regions
22902 $this->page_regions = $temp_page_regions;
22903 if (isset($old_bgcolor)) {
22904 // restore background color
22905 $this->SetFillColorArray($old_bgcolor);
22907 // restore pointer position
22908 $this->x = $prev_x;
22909 $this->y = $prev_y;
22910 $this->lasth = $prev_lasth;
22914 * Set the default bullet to be used as LI bullet symbol
22915 * @param $symbol (string) character or string to be used (legal values are: '' = automatic, '!' = auto bullet, '#' = auto numbering, 'disc', 'disc', 'circle', 'square', '1', 'decimal', 'decimal-leading-zero', 'i', 'lower-roman', 'I', 'upper-roman', 'a', 'lower-alpha', 'lower-latin', 'A', 'upper-alpha', 'upper-latin', 'lower-greek', 'img|type|width|height|image.ext')
22916 * @public
22917 * @since 4.0.028 (2008-09-26)
22919 public function setLIsymbol($symbol='!') {
22920 // check for custom image symbol
22921 if (substr($symbol, 0, 4) == 'img|') {
22922 $this->lisymbol = $symbol;
22923 return;
22925 $symbol = strtolower($symbol);
22926 switch ($symbol) {
22927 case '!' :
22928 case '#' :
22929 case 'disc' :
22930 case 'circle' :
22931 case 'square' :
22932 case '1':
22933 case 'decimal':
22934 case 'decimal-leading-zero':
22935 case 'i':
22936 case 'lower-roman':
22937 case 'I':
22938 case 'upper-roman':
22939 case 'a':
22940 case 'lower-alpha':
22941 case 'lower-latin':
22942 case 'A':
22943 case 'upper-alpha':
22944 case 'upper-latin':
22945 case 'lower-greek': {
22946 $this->lisymbol = $symbol;
22947 break;
22949 default : {
22950 $this->lisymbol = '';
22956 * Set the booklet mode for double-sided pages.
22957 * @param $booklet (boolean) true set the booklet mode on, false otherwise.
22958 * @param $inner (float) Inner page margin.
22959 * @param $outer (float) Outer page margin.
22960 * @public
22961 * @since 4.2.000 (2008-10-29)
22963 public function SetBooklet($booklet=true, $inner=-1, $outer=-1) {
22964 $this->booklet = $booklet;
22965 if ($inner >= 0) {
22966 $this->lMargin = $inner;
22968 if ($outer >= 0) {
22969 $this->rMargin = $outer;
22974 * Swap the left and right margins.
22975 * @param $reverse (boolean) if true swap left and right margins.
22976 * @protected
22977 * @since 4.2.000 (2008-10-29)
22979 protected function swapMargins($reverse=true) {
22980 if ($reverse) {
22981 // swap left and right margins
22982 $mtemp = $this->original_lMargin;
22983 $this->original_lMargin = $this->original_rMargin;
22984 $this->original_rMargin = $mtemp;
22985 $deltam = $this->original_lMargin - $this->original_rMargin;
22986 $this->lMargin += $deltam;
22987 $this->rMargin -= $deltam;
22992 * Set the vertical spaces for HTML tags.
22993 * The array must have the following structure (example):
22994 * $tagvs = array('h1' => array(0 => array('h' => '', 'n' => 2), 1 => array('h' => 1.3, 'n' => 1)));
22995 * The first array level contains the tag names,
22996 * the second level contains 0 for opening tags or 1 for closing tags,
22997 * the third level contains the vertical space unit (h) and the number spaces to add (n).
22998 * If the h parameter is not specified, default values are used.
22999 * @param $tagvs (array) array of tags and relative vertical spaces.
23000 * @public
23001 * @since 4.2.001 (2008-10-30)
23003 public function setHtmlVSpace($tagvs) {
23004 $this->tagvspaces = $tagvs;
23008 * Set custom width for list indentation.
23009 * @param $width (float) width of the indentation. Use negative value to disable it.
23010 * @public
23011 * @since 4.2.007 (2008-11-12)
23013 public function setListIndentWidth($width) {
23014 return $this->customlistindent = floatval($width);
23018 * Set the top/bottom cell sides to be open or closed when the cell cross the page.
23019 * @param $isopen (boolean) if true keeps the top/bottom border open for the cell sides that cross the page.
23020 * @public
23021 * @since 4.2.010 (2008-11-14)
23023 public function setOpenCell($isopen) {
23024 $this->opencell = $isopen;
23028 * Set the color and font style for HTML links.
23029 * @param $color (array) RGB array of colors
23030 * @param $fontstyle (string) additional font styles to add
23031 * @public
23032 * @since 4.4.003 (2008-12-09)
23034 public function setHtmlLinksStyle($color=array(0,0,255), $fontstyle='U') {
23035 $this->htmlLinkColorArray = $color;
23036 $this->htmlLinkFontStyle = $fontstyle;
23040 * Convert HTML string containing value and unit of measure to user's units or points.
23041 * @param $htmlval (string) string containing values and unit
23042 * @param $refsize (string) reference value in points
23043 * @param $defaultunit (string) default unit (can be one of the following: %, em, ex, px, in, mm, pc, pt).
23044 * @param $points (boolean) if true returns points, otherwise returns value in user's units
23045 * @return float value in user's unit or point if $points=true
23046 * @public
23047 * @since 4.4.004 (2008-12-10)
23049 public function getHTMLUnitToUnits($htmlval, $refsize=1, $defaultunit='px', $points=false) {
23050 $supportedunits = array('%', 'em', 'ex', 'px', 'in', 'cm', 'mm', 'pc', 'pt');
23051 $retval = 0;
23052 $value = 0;
23053 $unit = 'px';
23054 $k = $this->k;
23055 if ($points) {
23056 $k = 1;
23058 if (in_array($defaultunit, $supportedunits)) {
23059 $unit = $defaultunit;
23061 if (is_numeric($htmlval)) {
23062 $value = floatval($htmlval);
23063 } elseif (preg_match('/([0-9\.\-\+]+)/', $htmlval, $mnum)) {
23064 $value = floatval($mnum[1]);
23065 if (preg_match('/([a-z%]+)/', $htmlval, $munit)) {
23066 if (in_array($munit[1], $supportedunits)) {
23067 $unit = $munit[1];
23071 switch ($unit) {
23072 // percentage
23073 case '%': {
23074 $retval = (($value * $refsize) / 100);
23075 break;
23077 // relative-size
23078 case 'em': {
23079 $retval = ($value * $refsize);
23080 break;
23082 // height of lower case 'x' (about half the font-size)
23083 case 'ex': {
23084 $retval = $value * ($refsize / 2);
23085 break;
23087 // absolute-size
23088 case 'in': {
23089 $retval = ($value * $this->dpi) / $k;
23090 break;
23092 // centimeters
23093 case 'cm': {
23094 $retval = ($value / 2.54 * $this->dpi) / $k;
23095 break;
23097 // millimeters
23098 case 'mm': {
23099 $retval = ($value / 25.4 * $this->dpi) / $k;
23100 break;
23102 // one pica is 12 points
23103 case 'pc': {
23104 $retval = ($value * 12) / $k;
23105 break;
23107 // points
23108 case 'pt': {
23109 $retval = $value / $k;
23110 break;
23112 // pixels
23113 case 'px': {
23114 $retval = $this->pixelsToUnits($value);
23115 break;
23118 return $retval;
23122 * Returns the Roman representation of an integer number
23123 * @param $number (int) number to convert
23124 * @return string roman representation of the specified number
23125 * @since 4.4.004 (2008-12-10)
23126 * @public
23128 public function intToRoman($number) {
23129 $roman = '';
23130 while ($number >= 1000) {
23131 $roman .= 'M';
23132 $number -= 1000;
23134 while ($number >= 900) {
23135 $roman .= 'CM';
23136 $number -= 900;
23138 while ($number >= 500) {
23139 $roman .= 'D';
23140 $number -= 500;
23142 while ($number >= 400) {
23143 $roman .= 'CD';
23144 $number -= 400;
23146 while ($number >= 100) {
23147 $roman .= 'C';
23148 $number -= 100;
23150 while ($number >= 90) {
23151 $roman .= 'XC';
23152 $number -= 90;
23154 while ($number >= 50) {
23155 $roman .= 'L';
23156 $number -= 50;
23158 while ($number >= 40) {
23159 $roman .= 'XL';
23160 $number -= 40;
23162 while ($number >= 10) {
23163 $roman .= 'X';
23164 $number -= 10;
23166 while ($number >= 9) {
23167 $roman .= 'IX';
23168 $number -= 9;
23170 while ($number >= 5) {
23171 $roman .= 'V';
23172 $number -= 5;
23174 while ($number >= 4) {
23175 $roman .= 'IV';
23176 $number -= 4;
23178 while ($number >= 1) {
23179 $roman .= 'I';
23180 --$number;
23182 return $roman;
23186 * Output an HTML list bullet or ordered item symbol
23187 * @param $listdepth (int) list nesting level
23188 * @param $listtype (string) type of list
23189 * @param $size (float) current font size
23190 * @protected
23191 * @since 4.4.004 (2008-12-10)
23193 protected function putHtmlListBullet($listdepth, $listtype='', $size=10) {
23194 $size /= $this->k;
23195 $fill = '';
23196 $bgcolor = $this->bgcolor;
23197 $color = $this->fgcolor;
23198 $strokecolor = $this->strokecolor;
23199 $width = 0;
23200 $textitem = '';
23201 $tmpx = $this->x;
23202 $lspace = $this->GetStringWidth(' ');
23203 if ($listtype == '^') {
23204 // special symbol used for avoid justification of rect bullet
23205 $this->lispacer = '';
23206 return;
23207 } elseif ($listtype == '!') {
23208 // set default list type for unordered list
23209 $deftypes = array('disc', 'circle', 'square');
23210 $listtype = $deftypes[($listdepth - 1) % 3];
23211 } elseif ($listtype == '#') {
23212 // set default list type for ordered list
23213 $listtype = 'decimal';
23214 } elseif (substr($listtype, 0, 4) == 'img|') {
23215 // custom image type ('img|type|width|height|image.ext')
23216 $img = explode('|', $listtype);
23217 $listtype = 'img';
23219 switch ($listtype) {
23220 // unordered types
23221 case 'none': {
23222 break;
23224 case 'disc': {
23225 $r = $size / 6;
23226 $lspace += (2 * $r);
23227 if ($this->rtl) {
23228 $this->x += $lspace;
23229 } else {
23230 $this->x -= $lspace;
23232 $this->Circle(($this->x + $r), ($this->y + ($this->lasth / 2)), $r, 0, 360, 'F', array(), $color, 8);
23233 break;
23235 case 'circle': {
23236 $r = $size / 6;
23237 $lspace += (2 * $r);
23238 if ($this->rtl) {
23239 $this->x += $lspace;
23240 } else {
23241 $this->x -= $lspace;
23243 $prev_line_style = $this->linestyleWidth.' '.$this->linestyleCap.' '.$this->linestyleJoin.' '.$this->linestyleDash.' '.$this->DrawColor;
23244 $new_line_style = array('width' => ($r / 3), 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'phase' => 0, 'color'=>$color);
23245 $this->Circle(($this->x + $r), ($this->y + ($this->lasth / 2)), ($r * (1 - (1/6))), 0, 360, 'D', $new_line_style, array(), 8);
23246 $this->_out($prev_line_style); // restore line settings
23247 break;
23249 case 'square': {
23250 $l = $size / 3;
23251 $lspace += $l;
23252 if ($this->rtl) {;
23253 $this->x += $lspace;
23254 } else {
23255 $this->x -= $lspace;
23257 $this->Rect($this->x, ($this->y + (($this->lasth - $l) / 2)), $l, $l, 'F', array(), $color);
23258 break;
23260 case 'img': {
23261 // 1=>type, 2=>width, 3=>height, 4=>image.ext
23262 $lspace += $img[2];
23263 if ($this->rtl) {;
23264 $this->x += $lspace;
23265 } else {
23266 $this->x -= $lspace;
23268 $imgtype = strtolower($img[1]);
23269 $prev_y = $this->y;
23270 switch ($imgtype) {
23271 case 'svg': {
23272 $this->ImageSVG($img[4], $this->x, ($this->y + (($this->lasth - $img[3]) / 2)), $img[2], $img[3], '', 'T', '', 0, false);
23273 break;
23275 case 'ai':
23276 case 'eps': {
23277 $this->ImageEps($img[4], $this->x, ($this->y + (($this->lasth - $img[3]) / 2)), $img[2], $img[3], '', true, 'T', '', 0, false);
23278 break;
23280 default: {
23281 $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);
23282 break;
23285 $this->y = $prev_y;
23286 break;
23288 // ordered types
23289 // $this->listcount[$this->listnum];
23290 // $textitem
23291 case '1':
23292 case 'decimal': {
23293 $textitem = $this->listcount[$this->listnum];
23294 break;
23296 case 'decimal-leading-zero': {
23297 $textitem = sprintf('%02d', $this->listcount[$this->listnum]);
23298 break;
23300 case 'i':
23301 case 'lower-roman': {
23302 $textitem = strtolower($this->intToRoman($this->listcount[$this->listnum]));
23303 break;
23305 case 'I':
23306 case 'upper-roman': {
23307 $textitem = $this->intToRoman($this->listcount[$this->listnum]);
23308 break;
23310 case 'a':
23311 case 'lower-alpha':
23312 case 'lower-latin': {
23313 $textitem = chr(97 + $this->listcount[$this->listnum] - 1);
23314 break;
23316 case 'A':
23317 case 'upper-alpha':
23318 case 'upper-latin': {
23319 $textitem = chr(65 + $this->listcount[$this->listnum] - 1);
23320 break;
23322 case 'lower-greek': {
23323 $textitem = $this->unichr(945 + $this->listcount[$this->listnum] - 1);
23324 break;
23327 // Types to be implemented (special handling)
23328 case 'hebrew': {
23329 break;
23331 case 'armenian': {
23332 break;
23334 case 'georgian': {
23335 break;
23337 case 'cjk-ideographic': {
23338 break;
23340 case 'hiragana': {
23341 break;
23343 case 'katakana': {
23344 break;
23346 case 'hiragana-iroha': {
23347 break;
23349 case 'katakana-iroha': {
23350 break;
23353 default: {
23354 $textitem = $this->listcount[$this->listnum];
23357 if (!$this->empty_string($textitem)) {
23358 // Check whether we need a new page or new column
23359 $prev_y = $this->y;
23360 $h = ($this->FontSize * $this->cell_height_ratio) + $this->cell_padding['T'] + $this->cell_padding['B'];
23361 if ($this->checkPageBreak($h) OR ($this->y < $prev_y)) {
23362 $tmpx = $this->x;
23364 // print ordered item
23365 if ($this->rtl) {
23366 $textitem = '.'.$textitem;
23367 } else {
23368 $textitem = $textitem.'.';
23370 $lspace += $this->GetStringWidth($textitem);
23371 if ($this->rtl) {
23372 $this->x += $lspace;
23373 } else {
23374 $this->x -= $lspace;
23376 $this->Write($this->lasth, $textitem, '', false, '', false, 0, false);
23378 $this->x = $tmpx;
23379 $this->lispacer = '^';
23380 // restore colors
23381 $this->SetFillColorArray($bgcolor);
23382 $this->SetDrawColorArray($strokecolor);
23383 $this->SettextColorArray($color);
23387 * Returns current graphic variables as array.
23388 * @return array of graphic variables
23389 * @protected
23390 * @since 4.2.010 (2008-11-14)
23392 protected function getGraphicVars() {
23393 $grapvars = array(
23394 'FontFamily' => $this->FontFamily,
23395 'FontStyle' => $this->FontStyle,
23396 'FontSizePt' => $this->FontSizePt,
23397 'rMargin' => $this->rMargin,
23398 'lMargin' => $this->lMargin,
23399 'cell_padding' => $this->cell_padding,
23400 'cell_margin' => $this->cell_margin,
23401 'LineWidth' => $this->LineWidth,
23402 'linestyleWidth' => $this->linestyleWidth,
23403 'linestyleCap' => $this->linestyleCap,
23404 'linestyleJoin' => $this->linestyleJoin,
23405 'linestyleDash' => $this->linestyleDash,
23406 'textrendermode' => $this->textrendermode,
23407 'textstrokewidth' => $this->textstrokewidth,
23408 'DrawColor' => $this->DrawColor,
23409 'FillColor' => $this->FillColor,
23410 'TextColor' => $this->TextColor,
23411 'ColorFlag' => $this->ColorFlag,
23412 'bgcolor' => $this->bgcolor,
23413 'fgcolor' => $this->fgcolor,
23414 'htmlvspace' => $this->htmlvspace,
23415 'listindent' => $this->listindent,
23416 'listindentlevel' => $this->listindentlevel,
23417 'listnum' => $this->listnum,
23418 'listordered' => $this->listordered,
23419 'listcount' => $this->listcount,
23420 'lispacer' => $this->lispacer,
23421 'cell_height_ratio' => $this->cell_height_ratio,
23422 'font_stretching' => $this->font_stretching,
23423 'font_spacing' => $this->font_spacing,
23424 // extended
23425 'lasth' => $this->lasth,
23426 'tMargin' => $this->tMargin,
23427 'bMargin' => $this->bMargin,
23428 'AutoPageBreak' => $this->AutoPageBreak,
23429 'PageBreakTrigger' => $this->PageBreakTrigger,
23430 'x' => $this->x,
23431 'y' => $this->y,
23432 'w' => $this->w,
23433 'h' => $this->h,
23434 'wPt' => $this->wPt,
23435 'hPt' => $this->hPt,
23436 'fwPt' => $this->fwPt,
23437 'fhPt' => $this->fhPt,
23438 'page' => $this->page,
23439 'current_column' => $this->current_column,
23440 'num_columns' => $this->num_columns
23442 return $grapvars;
23446 * Set graphic variables.
23447 * @param $gvars (array) array of graphic variablesto restore
23448 * @param $extended (boolean) if true restore extended graphic variables
23449 * @protected
23450 * @since 4.2.010 (2008-11-14)
23452 protected function setGraphicVars($gvars, $extended=false) {
23453 $this->FontFamily = $gvars['FontFamily'];
23454 $this->FontStyle = $gvars['FontStyle'];
23455 $this->FontSizePt = $gvars['FontSizePt'];
23456 $this->rMargin = $gvars['rMargin'];
23457 $this->lMargin = $gvars['lMargin'];
23458 $this->cell_padding = $gvars['cell_padding'];
23459 $this->cell_margin = $gvars['cell_margin'];
23460 $this->LineWidth = $gvars['LineWidth'];
23461 $this->linestyleWidth = $gvars['linestyleWidth'];
23462 $this->linestyleCap = $gvars['linestyleCap'];
23463 $this->linestyleJoin = $gvars['linestyleJoin'];
23464 $this->linestyleDash = $gvars['linestyleDash'];
23465 $this->textrendermode = $gvars['textrendermode'];
23466 $this->textstrokewidth = $gvars['textstrokewidth'];
23467 $this->DrawColor = $gvars['DrawColor'];
23468 $this->FillColor = $gvars['FillColor'];
23469 $this->TextColor = $gvars['TextColor'];
23470 $this->ColorFlag = $gvars['ColorFlag'];
23471 $this->bgcolor = $gvars['bgcolor'];
23472 $this->fgcolor = $gvars['fgcolor'];
23473 $this->htmlvspace = $gvars['htmlvspace'];
23474 $this->listindent = $gvars['listindent'];
23475 $this->listindentlevel = $gvars['listindentlevel'];
23476 $this->listnum = $gvars['listnum'];
23477 $this->listordered = $gvars['listordered'];
23478 $this->listcount = $gvars['listcount'];
23479 $this->lispacer = $gvars['lispacer'];
23480 $this->cell_height_ratio = $gvars['cell_height_ratio'];
23481 $this->font_stretching = $gvars['font_stretching'];
23482 $this->font_spacing = $gvars['font_spacing'];
23483 if ($extended) {
23484 // restore extended values
23485 $this->lasth = $gvars['lasth'];
23486 $this->tMargin = $gvars['tMargin'];
23487 $this->bMargin = $gvars['bMargin'];
23488 $this->AutoPageBreak = $gvars['AutoPageBreak'];
23489 $this->PageBreakTrigger = $gvars['PageBreakTrigger'];
23490 $this->x = $gvars['x'];
23491 $this->y = $gvars['y'];
23492 $this->w = $gvars['w'];
23493 $this->h = $gvars['h'];
23494 $this->wPt = $gvars['wPt'];
23495 $this->hPt = $gvars['hPt'];
23496 $this->fwPt = $gvars['fwPt'];
23497 $this->fhPt = $gvars['fhPt'];
23498 $this->page = $gvars['page'];
23499 $this->current_column = $gvars['current_column'];
23500 $this->num_columns = $gvars['num_columns'];
23502 $this->_out(''.$this->linestyleWidth.' '.$this->linestyleCap.' '.$this->linestyleJoin.' '.$this->linestyleDash.' '.$this->DrawColor.' '.$this->FillColor.'');
23503 if (!$this->empty_string($this->FontFamily)) {
23504 $this->SetFont($this->FontFamily, $this->FontStyle, $this->FontSizePt);
23509 * Returns a temporary filename for caching object on filesystem.
23510 * @param $name (string) prefix to add to filename
23511 * @return string filename.
23512 * @since 4.5.000 (2008-12-31)
23513 * @protected
23515 protected function getObjFilename($name) {
23516 return tempnam(K_PATH_CACHE, $name.'_');
23520 * Writes data to a temporary file on filesystem.
23521 * @param $filename (string) file name
23522 * @param $data (mixed) data to write on file
23523 * @param $append (boolean) if true append data, false replace.
23524 * @since 4.5.000 (2008-12-31)
23525 * @protected
23527 protected function writeDiskCache($filename, $data, $append=false) {
23528 if ($append) {
23529 $fmode = 'ab+';
23530 } else {
23531 $fmode = 'wb+';
23533 $f = @fopen($filename, $fmode);
23534 if (!$f) {
23535 $this->Error('Unable to write cache file: '.$filename);
23536 } else {
23537 fwrite($f, $data);
23538 fclose($f);
23540 // update file length (needed for transactions)
23541 if (!isset($this->cache_file_length['_'.$filename])) {
23542 $this->cache_file_length['_'.$filename] = strlen($data);
23543 } else {
23544 $this->cache_file_length['_'.$filename] += strlen($data);
23549 * Read data from a temporary file on filesystem.
23550 * @param $filename (string) file name
23551 * @return mixed retrieved data
23552 * @since 4.5.000 (2008-12-31)
23553 * @protected
23555 protected function readDiskCache($filename) {
23556 return file_get_contents($filename);
23560 * Set buffer content (always append data).
23561 * @param $data (string) data
23562 * @protected
23563 * @since 4.5.000 (2009-01-02)
23565 protected function setBuffer($data) {
23566 $this->bufferlen += strlen($data);
23567 if ($this->diskcache) {
23568 if (!isset($this->buffer) OR $this->empty_string($this->buffer)) {
23569 $this->buffer = $this->getObjFilename('buffer');
23571 $this->writeDiskCache($this->buffer, $data, true);
23572 } else {
23573 $this->buffer .= $data;
23578 * Replace the buffer content
23579 * @param $data (string) data
23580 * @protected
23581 * @since 5.5.000 (2010-06-22)
23583 protected function replaceBuffer($data) {
23584 $this->bufferlen = strlen($data);
23585 if ($this->diskcache) {
23586 if (!isset($this->buffer) OR $this->empty_string($this->buffer)) {
23587 $this->buffer = $this->getObjFilename('buffer');
23589 $this->writeDiskCache($this->buffer, $data, false);
23590 } else {
23591 $this->buffer = $data;
23596 * Get buffer content.
23597 * @return string buffer content
23598 * @protected
23599 * @since 4.5.000 (2009-01-02)
23601 protected function getBuffer() {
23602 if ($this->diskcache) {
23603 return $this->readDiskCache($this->buffer);
23604 } else {
23605 return $this->buffer;
23610 * Set page buffer content.
23611 * @param $page (int) page number
23612 * @param $data (string) page data
23613 * @param $append (boolean) if true append data, false replace.
23614 * @protected
23615 * @since 4.5.000 (2008-12-31)
23617 protected function setPageBuffer($page, $data, $append=false) {
23618 if ($this->diskcache) {
23619 if (!isset($this->pages[$page])) {
23620 $this->pages[$page] = $this->getObjFilename('page'.$page);
23622 $this->writeDiskCache($this->pages[$page], $data, $append);
23623 } else {
23624 if ($append) {
23625 $this->pages[$page] .= $data;
23626 } else {
23627 $this->pages[$page] = $data;
23630 if ($append AND isset($this->pagelen[$page])) {
23631 $this->pagelen[$page] += strlen($data);
23632 } else {
23633 $this->pagelen[$page] = strlen($data);
23638 * Get page buffer content.
23639 * @param $page (int) page number
23640 * @return string page buffer content or false in case of error
23641 * @protected
23642 * @since 4.5.000 (2008-12-31)
23644 protected function getPageBuffer($page) {
23645 if ($this->diskcache) {
23646 return $this->readDiskCache($this->pages[$page]);
23647 } elseif (isset($this->pages[$page])) {
23648 return $this->pages[$page];
23650 return false;
23654 * Set image buffer content.
23655 * @param $image (string) image key
23656 * @param $data (array) image data
23657 * @protected
23658 * @since 4.5.000 (2008-12-31)
23660 protected function setImageBuffer($image, $data) {
23661 if ($this->diskcache) {
23662 if (!isset($this->images[$image])) {
23663 $this->images[$image] = $this->getObjFilename('image'.$image);
23665 $this->writeDiskCache($this->images[$image], serialize($data));
23666 } else {
23667 $this->images[$image] = $data;
23669 if (!in_array($image, $this->imagekeys)) {
23670 $this->imagekeys[] = $image;
23671 ++$this->numimages;
23676 * Set image buffer content for a specified sub-key.
23677 * @param $image (string) image key
23678 * @param $key (string) image sub-key
23679 * @param $data (array) image data
23680 * @protected
23681 * @since 4.5.000 (2008-12-31)
23683 protected function setImageSubBuffer($image, $key, $data) {
23684 if (!isset($this->images[$image])) {
23685 $this->setImageBuffer($image, array());
23687 if ($this->diskcache) {
23688 $tmpimg = $this->getImageBuffer($image);
23689 $tmpimg[$key] = $data;
23690 $this->writeDiskCache($this->images[$image], serialize($tmpimg));
23691 } else {
23692 $this->images[$image][$key] = $data;
23697 * Get image buffer content.
23698 * @param $image (string) image key
23699 * @return string image buffer content or false in case of error
23700 * @protected
23701 * @since 4.5.000 (2008-12-31)
23703 protected function getImageBuffer($image) {
23704 if ($this->diskcache AND isset($this->images[$image])) {
23705 return unserialize($this->readDiskCache($this->images[$image]));
23706 } elseif (isset($this->images[$image])) {
23707 return $this->images[$image];
23709 return false;
23713 * Set font buffer content.
23714 * @param $font (string) font key
23715 * @param $data (array) font data
23716 * @protected
23717 * @since 4.5.000 (2009-01-02)
23719 protected function setFontBuffer($font, $data) {
23720 if ($this->diskcache) {
23721 if (!isset($this->fonts[$font])) {
23722 $this->fonts[$font] = $this->getObjFilename('font');
23724 $this->writeDiskCache($this->fonts[$font], serialize($data));
23725 } else {
23726 $this->fonts[$font] = $data;
23728 if (!in_array($font, $this->fontkeys)) {
23729 $this->fontkeys[] = $font;
23730 // store object ID for current font
23731 ++$this->n;
23732 $this->font_obj_ids[$font] = $this->n;
23733 $this->setFontSubBuffer($font, 'n', $this->n);
23738 * Set font buffer content.
23739 * @param $font (string) font key
23740 * @param $key (string) font sub-key
23741 * @param $data (array) font data
23742 * @protected
23743 * @since 4.5.000 (2009-01-02)
23745 protected function setFontSubBuffer($font, $key, $data) {
23746 if (!isset($this->fonts[$font])) {
23747 $this->setFontBuffer($font, array());
23749 if ($this->diskcache) {
23750 $tmpfont = $this->getFontBuffer($font);
23751 $tmpfont[$key] = $data;
23752 $this->writeDiskCache($this->fonts[$font], serialize($tmpfont));
23753 } else {
23754 $this->fonts[$font][$key] = $data;
23759 * Get font buffer content.
23760 * @param $font (string) font key
23761 * @return string font buffer content or false in case of error
23762 * @protected
23763 * @since 4.5.000 (2009-01-02)
23765 protected function getFontBuffer($font) {
23766 if ($this->diskcache AND isset($this->fonts[$font])) {
23767 return unserialize($this->readDiskCache($this->fonts[$font]));
23768 } elseif (isset($this->fonts[$font])) {
23769 return $this->fonts[$font];
23771 return false;
23775 * Move a page to a previous position.
23776 * @param $frompage (int) number of the source page
23777 * @param $topage (int) number of the destination page (must be less than $frompage)
23778 * @return true in case of success, false in case of error.
23779 * @public
23780 * @since 4.5.000 (2009-01-02)
23782 public function movePage($frompage, $topage) {
23783 if (($frompage > $this->numpages) OR ($frompage <= $topage)) {
23784 return false;
23786 if ($frompage == $this->page) {
23787 // close the page before moving it
23788 $this->endPage();
23790 // move all page-related states
23791 $tmppage = $this->pages[$frompage];
23792 $tmppagedim = $this->pagedim[$frompage];
23793 $tmppagelen = $this->pagelen[$frompage];
23794 $tmpintmrk = $this->intmrk[$frompage];
23795 $tmpbordermrk = $this->bordermrk[$frompage];
23796 $tmpcntmrk = $this->cntmrk[$frompage];
23797 if (isset($this->footerpos[$frompage])) {
23798 $tmpfooterpos = $this->footerpos[$frompage];
23800 if (isset($this->footerlen[$frompage])) {
23801 $tmpfooterlen = $this->footerlen[$frompage];
23803 if (isset($this->transfmrk[$frompage])) {
23804 $tmptransfmrk = $this->transfmrk[$frompage];
23806 if (isset($this->PageAnnots[$frompage])) {
23807 $tmpannots = $this->PageAnnots[$frompage];
23809 if (isset($this->newpagegroup) AND !empty($this->newpagegroup)) {
23810 for ($i = $frompage; $i > $topage; --$i) {
23811 if (isset($this->newpagegroup[$i]) AND (($i + $this->pagegroups[$this->newpagegroup[$i]]) > $frompage)) {
23812 --$this->pagegroups[$this->newpagegroup[$i]];
23813 break;
23816 for ($i = $topage; $i > 0; --$i) {
23817 if (isset($this->newpagegroup[$i]) AND (($i + $this->pagegroups[$this->newpagegroup[$i]]) > $topage)) {
23818 ++$this->pagegroups[$this->newpagegroup[$i]];
23819 break;
23823 for ($i = $frompage; $i > $topage; --$i) {
23824 $j = $i - 1;
23825 // shift pages down
23826 $this->pages[$i] = $this->pages[$j];
23827 $this->pagedim[$i] = $this->pagedim[$j];
23828 $this->pagelen[$i] = $this->pagelen[$j];
23829 $this->intmrk[$i] = $this->intmrk[$j];
23830 $this->bordermrk[$i] = $this->bordermrk[$j];
23831 $this->cntmrk[$i] = $this->cntmrk[$j];
23832 if (isset($this->footerpos[$j])) {
23833 $this->footerpos[$i] = $this->footerpos[$j];
23834 } elseif (isset($this->footerpos[$i])) {
23835 unset($this->footerpos[$i]);
23837 if (isset($this->footerlen[$j])) {
23838 $this->footerlen[$i] = $this->footerlen[$j];
23839 } elseif (isset($this->footerlen[$i])) {
23840 unset($this->footerlen[$i]);
23842 if (isset($this->transfmrk[$j])) {
23843 $this->transfmrk[$i] = $this->transfmrk[$j];
23844 } elseif (isset($this->transfmrk[$i])) {
23845 unset($this->transfmrk[$i]);
23847 if (isset($this->PageAnnots[$j])) {
23848 $this->PageAnnots[$i] = $this->PageAnnots[$j];
23849 } elseif (isset($this->PageAnnots[$i])) {
23850 unset($this->PageAnnots[$i]);
23852 if (isset($this->newpagegroup[$j])) {
23853 $this->newpagegroup[$i] = $this->newpagegroup[$j];
23854 unset($this->newpagegroup[$j]);
23856 if ($this->currpagegroup == $j) {
23857 $this->currpagegroup = $i;
23860 $this->pages[$topage] = $tmppage;
23861 $this->pagedim[$topage] = $tmppagedim;
23862 $this->pagelen[$topage] = $tmppagelen;
23863 $this->intmrk[$topage] = $tmpintmrk;
23864 $this->bordermrk[$topage] = $tmpbordermrk;
23865 $this->cntmrk[$topage] = $tmpcntmrk;
23866 if (isset($tmpfooterpos)) {
23867 $this->footerpos[$topage] = $tmpfooterpos;
23868 } elseif (isset($this->footerpos[$topage])) {
23869 unset($this->footerpos[$topage]);
23871 if (isset($tmpfooterlen)) {
23872 $this->footerlen[$topage] = $tmpfooterlen;
23873 } elseif (isset($this->footerlen[$topage])) {
23874 unset($this->footerlen[$topage]);
23876 if (isset($tmptransfmrk)) {
23877 $this->transfmrk[$topage] = $tmptransfmrk;
23878 } elseif (isset($this->transfmrk[$topage])) {
23879 unset($this->transfmrk[$topage]);
23881 if (isset($tmpannots)) {
23882 $this->PageAnnots[$topage] = $tmpannots;
23883 } elseif (isset($this->PageAnnots[$topage])) {
23884 unset($this->PageAnnots[$topage]);
23886 // adjust outlines
23887 $tmpoutlines = $this->outlines;
23888 foreach ($tmpoutlines as $key => $outline) {
23889 if (($outline['p'] >= $topage) AND ($outline['p'] < $frompage)) {
23890 $this->outlines[$key]['p'] = $outline['p'] + 1;
23891 } elseif ($outline['p'] == $frompage) {
23892 $this->outlines[$key]['p'] = $topage;
23895 // adjust dests
23896 $tmpdests = $this->dests;
23897 foreach ($tmpdests as $key => $dest) {
23898 if (($dest['p'] >= $topage) AND ($dest['p'] < $frompage)) {
23899 $this->dests[$key]['p'] = $dest['p'] + 1;
23900 } elseif ($dest['p'] == $frompage) {
23901 $this->dests[$key]['p'] = $topage;
23904 // adjust links
23905 $tmplinks = $this->links;
23906 foreach ($tmplinks as $key => $link) {
23907 if (($link[0] >= $topage) AND ($link[0] < $frompage)) {
23908 $this->links[$key][0] = $link[0] + 1;
23909 } elseif ($link[0] == $frompage) {
23910 $this->links[$key][0] = $topage;
23913 // adjust javascript
23914 $tmpjavascript = $this->javascript;
23915 global $jfrompage, $jtopage;
23916 $jfrompage = $frompage;
23917 $jtopage = $topage;
23918 $this->javascript = preg_replace_callback('/this\.addField\(\'([^\']*)\',\'([^\']*)\',([0-9]+)/',
23919 create_function('$matches', 'global $jfrompage, $jtopage;
23920 $pagenum = intval($matches[3]) + 1;
23921 if (($pagenum >= $jtopage) AND ($pagenum < $jfrompage)) {
23922 $newpage = ($pagenum + 1);
23923 } elseif ($pagenum == $jfrompage) {
23924 $newpage = $jtopage;
23925 } else {
23926 $newpage = $pagenum;
23928 --$newpage;
23929 return "this.addField(\'".$matches[1]."\',\'".$matches[2]."\',".$newpage."";'), $tmpjavascript);
23930 // return to last page
23931 $this->lastPage(true);
23932 return true;
23936 * Remove the specified page.
23937 * @param $page (int) page to remove
23938 * @return true in case of success, false in case of error.
23939 * @public
23940 * @since 4.6.004 (2009-04-23)
23942 public function deletePage($page) {
23943 if (($page < 1) OR ($page > $this->numpages)) {
23944 return false;
23946 // delete current page
23947 unset($this->pages[$page]);
23948 unset($this->pagedim[$page]);
23949 unset($this->pagelen[$page]);
23950 unset($this->intmrk[$page]);
23951 unset($this->bordermrk[$page]);
23952 unset($this->cntmrk[$page]);
23953 if (isset($this->footerpos[$page])) {
23954 unset($this->footerpos[$page]);
23956 if (isset($this->footerlen[$page])) {
23957 unset($this->footerlen[$page]);
23959 if (isset($this->transfmrk[$page])) {
23960 unset($this->transfmrk[$page]);
23962 if (isset($this->PageAnnots[$page])) {
23963 unset($this->PageAnnots[$page]);
23965 if (isset($this->newpagegroup) AND !empty($this->newpagegroup)) {
23966 for ($i = $page; $i > 0; --$i) {
23967 if (isset($this->newpagegroup[$i]) AND (($i + $this->pagegroups[$this->newpagegroup[$i]]) > $page)) {
23968 --$this->pagegroups[$this->newpagegroup[$i]];
23969 break;
23973 if (isset($this->pageopen[$page])) {
23974 unset($this->pageopen[$page]);
23976 if ($page < $this->numpages) {
23977 // update remaining pages
23978 for ($i = $page; $i < $this->numpages; ++$i) {
23979 $j = $i + 1;
23980 // shift pages
23981 $this->pages[$i] = $this->pages[$j];
23982 $this->pagedim[$i] = $this->pagedim[$j];
23983 $this->pagelen[$i] = $this->pagelen[$j];
23984 $this->intmrk[$i] = $this->intmrk[$j];
23985 $this->bordermrk[$i] = $this->bordermrk[$j];
23986 $this->cntmrk[$i] = $this->cntmrk[$j];
23987 if (isset($this->footerpos[$j])) {
23988 $this->footerpos[$i] = $this->footerpos[$j];
23989 } elseif (isset($this->footerpos[$i])) {
23990 unset($this->footerpos[$i]);
23992 if (isset($this->footerlen[$j])) {
23993 $this->footerlen[$i] = $this->footerlen[$j];
23994 } elseif (isset($this->footerlen[$i])) {
23995 unset($this->footerlen[$i]);
23997 if (isset($this->transfmrk[$j])) {
23998 $this->transfmrk[$i] = $this->transfmrk[$j];
23999 } elseif (isset($this->transfmrk[$i])) {
24000 unset($this->transfmrk[$i]);
24002 if (isset($this->PageAnnots[$j])) {
24003 $this->PageAnnots[$i] = $this->PageAnnots[$j];
24004 } elseif (isset($this->PageAnnots[$i])) {
24005 unset($this->PageAnnots[$i]);
24007 if (isset($this->newpagegroup[$j])) {
24008 $this->newpagegroup[$i] = $this->newpagegroup[$j];
24009 unset($this->newpagegroup[$j]);
24011 if ($this->currpagegroup == $j) {
24012 $this->currpagegroup = $i;
24014 if (isset($this->pageopen[$j])) {
24015 $this->pageopen[$i] = $this->pageopen[$j];
24016 } elseif (isset($this->pageopen[$i])) {
24017 unset($this->pageopen[$i]);
24020 // remove last page
24021 unset($this->pages[$this->numpages]);
24022 unset($this->pagedim[$this->numpages]);
24023 unset($this->pagelen[$this->numpages]);
24024 unset($this->intmrk[$this->numpages]);
24025 unset($this->bordermrk[$this->numpages]);
24026 unset($this->cntmrk[$this->numpages]);
24027 if (isset($this->footerpos[$this->numpages])) {
24028 unset($this->footerpos[$this->numpages]);
24030 if (isset($this->footerlen[$this->numpages])) {
24031 unset($this->footerlen[$this->numpages]);
24033 if (isset($this->transfmrk[$this->numpages])) {
24034 unset($this->transfmrk[$this->numpages]);
24036 if (isset($this->PageAnnots[$this->numpages])) {
24037 unset($this->PageAnnots[$this->numpages]);
24039 if (isset($this->newpagegroup[$this->numpages])) {
24040 unset($this->newpagegroup[$this->numpages]);
24042 if ($this->currpagegroup == $this->numpages) {
24043 $this->currpagegroup = ($this->numpages - 1);
24045 if (isset($this->pagegroups[$this->numpages])) {
24046 unset($this->pagegroups[$this->numpages]);
24048 if (isset($this->pageopen[$this->numpages])) {
24049 unset($this->pageopen[$this->numpages]);
24052 --$this->numpages;
24053 $this->page = $this->numpages;
24054 // adjust outlines
24055 $tmpoutlines = $this->outlines;
24056 foreach ($tmpoutlines as $key => $outline) {
24057 if ($outline['p'] > $page) {
24058 $this->outlines[$key]['p'] = $outline['p'] - 1;
24059 } elseif ($outline['p'] == $page) {
24060 unset($this->outlines[$key]);
24063 // adjust dests
24064 $tmpdests = $this->dests;
24065 foreach ($tmpdests as $key => $dest) {
24066 if ($dest['p'] > $page) {
24067 $this->dests[$key]['p'] = $dest['p'] - 1;
24068 } elseif ($dest['p'] == $page) {
24069 unset($this->dests[$key]);
24072 // adjust links
24073 $tmplinks = $this->links;
24074 foreach ($tmplinks as $key => $link) {
24075 if ($link[0] > $page) {
24076 $this->links[$key][0] = $link[0] - 1;
24077 } elseif ($link[0] == $page) {
24078 unset($this->links[$key]);
24081 // adjust javascript
24082 $tmpjavascript = $this->javascript;
24083 global $jpage;
24084 $jpage = $page;
24085 $this->javascript = preg_replace_callback('/this\.addField\(\'([^\']*)\',\'([^\']*)\',([0-9]+)/',
24086 create_function('$matches', 'global $jpage;
24087 $pagenum = intval($matches[3]) + 1;
24088 if ($pagenum >= $jpage) {
24089 $newpage = ($pagenum - 1);
24090 } elseif ($pagenum == $jpage) {
24091 $newpage = 1;
24092 } else {
24093 $newpage = $pagenum;
24095 --$newpage;
24096 return "this.addField(\'".$matches[1]."\',\'".$matches[2]."\',".$newpage."";'), $tmpjavascript);
24097 // return to last page
24098 $this->lastPage(true);
24099 return true;
24103 * Clone the specified page to a new page.
24104 * @param $page (int) number of page to copy (0 = current page)
24105 * @return true in case of success, false in case of error.
24106 * @public
24107 * @since 4.9.015 (2010-04-20)
24109 public function copyPage($page=0) {
24110 if ($page == 0) {
24111 // default value
24112 $page = $this->page;
24114 if (($page < 1) OR ($page > $this->numpages)) {
24115 return false;
24117 // close the last page
24118 $this->endPage();
24119 // copy all page-related states
24120 ++$this->numpages;
24121 $this->page = $this->numpages;
24122 $this->pages[$this->page] = $this->pages[$page];
24123 $this->pagedim[$this->page] = $this->pagedim[$page];
24124 $this->pagelen[$this->page] = $this->pagelen[$page];
24125 $this->intmrk[$this->page] = $this->intmrk[$page];
24126 $this->bordermrk[$this->page] = $this->bordermrk[$page];
24127 $this->cntmrk[$this->page] = $this->cntmrk[$page];
24128 $this->pageopen[$this->page] = false;
24129 if (isset($this->footerpos[$page])) {
24130 $this->footerpos[$this->page] = $this->footerpos[$page];
24132 if (isset($this->footerlen[$page])) {
24133 $this->footerlen[$this->page] = $this->footerlen[$page];
24135 if (isset($this->transfmrk[$page])) {
24136 $this->transfmrk[$this->page] = $this->transfmrk[$page];
24138 if (isset($this->PageAnnots[$page])) {
24139 $this->PageAnnots[$this->page] = $this->PageAnnots[$page];
24141 if (isset($this->newpagegroup[$page])) {
24142 // start a new group
24143 $this->newpagegroup[$this->page] = sizeof($this->newpagegroup) + 1;
24144 $this->currpagegroup = $this->newpagegroup[$this->page];
24145 $this->pagegroups[$this->currpagegroup] = 1;
24146 } elseif (isset($this->currpagegroup) AND ($this->currpagegroup > 0)) {
24147 ++$this->pagegroups[$this->currpagegroup];
24149 // copy outlines
24150 $tmpoutlines = $this->outlines;
24151 foreach ($tmpoutlines as $key => $outline) {
24152 if ($outline['p'] == $page) {
24153 $this->outlines[] = array('t' => $outline['t'], 'l' => $outline['l'], 'y' => $outline['y'], 'p' => $this->page, 's' => $outline['s'], 'c' => $outline['c']);
24156 // copy links
24157 $tmplinks = $this->links;
24158 foreach ($tmplinks as $key => $link) {
24159 if ($link[0] == $page) {
24160 $this->links[] = array($this->page, $link[1]);
24163 // return to last page
24164 $this->lastPage(true);
24165 return true;
24169 * Output a Table of Content Index (TOC).
24170 * Before calling this method you have to open the page using the addTOCPage() method.
24171 * After calling this method you have to call endTOCPage() to close the TOC page.
24172 * You can override this method to achieve different styles.
24173 * @param $page (int) page number where this TOC should be inserted (leave empty for current page).
24174 * @param $numbersfont (string) set the font for page numbers (please use monospaced font for better alignment).
24175 * @param $filler (string) string used to fill the space between text and page number.
24176 * @param $toc_name (string) name to use for TOC bookmark.
24177 * @param $style (string) Font style for title: B = Bold, I = Italic, BI = Bold + Italic.
24178 * @param $color (array) RGB color array for bookmark title (values from 0 to 255).
24179 * @public
24180 * @author Nicola Asuni
24181 * @since 4.5.000 (2009-01-02)
24182 * @see addTOCPage(), endTOCPage(), addHTMLTOC()
24184 public function addTOC($page='', $numbersfont='', $filler='.', $toc_name='TOC', $style='', $color=array(0,0,0)) {
24185 $fontsize = $this->FontSizePt;
24186 $fontfamily = $this->FontFamily;
24187 $fontstyle = $this->FontStyle;
24188 $w = $this->w - $this->lMargin - $this->rMargin;
24189 $spacer = $this->GetStringWidth(chr(32)) * 4;
24190 $page_first = $this->getPage();
24191 $lmargin = $this->lMargin;
24192 $rmargin = $this->rMargin;
24193 $x_start = $this->GetX();
24194 $current_page = $this->page;
24195 $current_column = $this->current_column;
24196 if ($this->empty_string($numbersfont)) {
24197 $numbersfont = $this->default_monospaced_font;
24199 if ($this->empty_string($filler)) {
24200 $filler = ' ';
24202 if ($this->empty_string($page)) {
24203 $gap = ' ';
24204 } else {
24205 $gap = '';
24206 if ($page < 1) {
24207 $page = 1;
24210 $this->SetFont($numbersfont, $fontstyle, $fontsize);
24211 $numwidth = $this->GetStringWidth('00000');
24212 foreach ($this->outlines as $key => $outline) {
24213 if ($this->rtl) {
24214 $aligntext = 'R';
24215 $alignnum = 'L';
24216 } else {
24217 $aligntext = 'L';
24218 $alignnum = 'R';
24220 if ($outline['l'] == 0) {
24221 $this->SetFont($fontfamily, $fontstyle.'B', $fontsize);
24222 } else {
24223 $this->SetFont($fontfamily, $fontstyle, $fontsize - $outline['l']);
24225 // check for page break
24226 $this->checkPageBreak((2 * $this->FontSize * $this->cell_height_ratio));
24227 // set margins and X position
24228 if (($this->page == $current_page) AND ($this->current_column == $current_column)) {
24229 $this->lMargin = $lmargin;
24230 $this->rMargin = $rmargin;
24231 } else {
24232 if ($this->current_column != $current_column) {
24233 if ($this->rtl) {
24234 $x_start = $this->w - $this->columns[$this->current_column]['x'];
24235 } else {
24236 $x_start = $this->columns[$this->current_column]['x'];
24239 $lmargin = $this->lMargin;
24240 $rmargin = $this->rMargin;
24241 $current_page = $this->page;
24242 $current_column = $this->current_column;
24244 $this->SetX($x_start);
24245 $indent = ($spacer * $outline['l']);
24246 if ($this->rtl) {
24247 $this->x -= $indent;
24248 $this->rMargin = $this->w - $this->x;
24249 } else {
24250 $this->x += $indent;
24251 $this->lMargin = $this->x;
24253 $link = $this->AddLink();
24254 $this->SetLink($link, $outline['y'], $outline['p']);
24255 // write the text
24256 if ($this->rtl) {
24257 $txt = ' '.$outline['t'];
24258 } else {
24259 $txt = $outline['t'].' ';
24261 $this->Write(0, $txt, $link, false, $aligntext, false, 0, false, false, 0, $numwidth, '');
24262 if ($this->rtl) {
24263 $tw = $this->x - $this->lMargin;
24264 } else {
24265 $tw = $this->w - $this->rMargin - $this->x;
24267 $this->SetFont($numbersfont, $fontstyle, $fontsize);
24268 if ($this->empty_string($page)) {
24269 $pagenum = $outline['p'];
24270 } else {
24271 // placemark to be replaced with the correct number
24272 $pagenum = '{#'.($outline['p']).'}';
24273 if ($this->isUnicodeFont()) {
24274 $pagenum = '{'.$pagenum.'}';
24277 $fw = ($tw - $this->GetStringWidth($pagenum.$filler));
24278 $numfills = floor($fw / $this->GetStringWidth($filler));
24279 if ($numfills > 0) {
24280 $rowfill = str_repeat($filler, $numfills);
24281 } else {
24282 $rowfill = '';
24284 if ($this->rtl) {
24285 $pagenum = $pagenum.$gap.$rowfill;
24286 } else {
24287 $pagenum = $rowfill.$gap.$pagenum;
24289 // write the number
24290 $this->Cell($tw, 0, $pagenum, 0, 1, $alignnum, 0, $link, 0);
24292 $page_last = $this->getPage();
24293 $numpages = $page_last - $page_first + 1;
24294 if (!$this->empty_string($page)) {
24295 for ($p = $page_first; $p <= $page_last; ++$p) {
24296 // get page data
24297 $temppage = $this->getPageBuffer($p);
24298 for ($n = 1; $n <= $this->numpages; ++$n) {
24299 // update page numbers
24300 $a = '{#'.$n.'}';
24301 // get page number aliases
24302 $pnalias = $this->getInternalPageNumberAliases($a);
24303 // calculate replacement number
24304 if ($n >= $page) {
24305 $np = $n + $numpages;
24306 } else {
24307 $np = $n;
24309 $na = $this->formatTOCPageNumber(($this->starting_page_number + $np - 1));
24310 $nu = $this->UTF8ToUTF16BE($na, false);
24311 // replace aliases with numbers
24312 foreach ($pnalias['u'] as $u) {
24313 $sfill = str_repeat($filler, max(0, (strlen($u) - strlen($nu.' '))));
24314 if ($this->rtl) {
24315 $nr = $nu.$this->UTF8ToUTF16BE(' '.$sfill);
24316 } else {
24317 $nr = $this->UTF8ToUTF16BE($sfill.' ').$nu;
24319 $temppage = str_replace($u, $nr, $temppage);
24321 foreach ($pnalias['a'] as $a) {
24322 $sfill = str_repeat($filler, max(0, (strlen($a) - strlen($na.' '))));
24323 if ($this->rtl) {
24324 $nr = $na.' '.$sfill;
24325 } else {
24326 $nr = $sfill.' '.$na;
24328 $temppage = str_replace($a, $nr, $temppage);
24331 // save changes
24332 $this->setPageBuffer($p, $temppage);
24334 // move pages
24335 $this->Bookmark($toc_name, 0, 0, $page_first, $style, $color);
24336 for ($i = 0; $i < $numpages; ++$i) {
24337 $this->movePage($page_last, $page);
24343 * Output a Table Of Content Index (TOC) using HTML templates.
24344 * Before calling this method you have to open the page using the addTOCPage() method.
24345 * After calling this method you have to call endTOCPage() to close the TOC page.
24346 * @param $page (int) page number where this TOC should be inserted (leave empty for current page).
24347 * @param $toc_name (string) name to use for TOC bookmark.
24348 * @param $templates (array) array of html templates. Use: "#TOC_DESCRIPTION#" for bookmark title, "#TOC_PAGE_NUMBER#" for page number.
24349 * @param $correct_align (boolean) if true correct the number alignment (numbers must be in monospaced font like courier and right aligned on LTR, or left aligned on RTL)
24350 * @param $style (string) Font style for title: B = Bold, I = Italic, BI = Bold + Italic.
24351 * @param $color (array) RGB color array for title (values from 0 to 255).
24352 * @public
24353 * @author Nicola Asuni
24354 * @since 5.0.001 (2010-05-06)
24355 * @see addTOCPage(), endTOCPage(), addTOC()
24357 public function addHTMLTOC($page='', $toc_name='TOC', $templates=array(), $correct_align=true, $style='', $color=array(0,0,0)) {
24358 $filler = ' ';
24359 $prev_htmlLinkColorArray = $this->htmlLinkColorArray;
24360 $prev_htmlLinkFontStyle = $this->htmlLinkFontStyle;
24361 // set new style for link
24362 $this->htmlLinkColorArray = array();
24363 $this->htmlLinkFontStyle = '';
24364 $page_first = $this->getPage();
24365 // get the font type used for numbers in each template
24366 $current_font = $this->FontFamily;
24367 foreach ($templates as $level => $html) {
24368 $dom = $this->getHtmlDomArray($html);
24369 foreach ($dom as $key => $value) {
24370 if ($value['value'] == '#TOC_PAGE_NUMBER#') {
24371 $this->SetFont($dom[($key - 1)]['fontname']);
24372 $templates['F'.$level] = $this->isUnicodeFont();
24376 $this->SetFont($current_font);
24377 foreach ($this->outlines as $key => $outline) {
24378 // get HTML template
24379 $row = $templates[$outline['l']];
24380 if ($this->empty_string($page)) {
24381 $pagenum = $outline['p'];
24382 } else {
24383 // placemark to be replaced with the correct number
24384 $pagenum = '{#'.($outline['p']).'}';
24385 if ($templates['F'.$outline['l']]) {
24386 $pagenum = '{'.$pagenum.'}';
24389 // replace templates with current values
24390 $row = str_replace('#TOC_DESCRIPTION#', $outline['t'], $row);
24391 $row = str_replace('#TOC_PAGE_NUMBER#', $pagenum, $row);
24392 // add link to page
24393 $row = '<a href="#'.$outline['p'].','.$outline['y'].'">'.$row.'</a>';
24394 // write bookmark entry
24395 $this->writeHTML($row, false, false, true, false, '');
24397 // restore link styles
24398 $this->htmlLinkColorArray = $prev_htmlLinkColorArray;
24399 $this->htmlLinkFontStyle = $prev_htmlLinkFontStyle;
24400 // move TOC page and replace numbers
24401 $page_last = $this->getPage();
24402 $numpages = $page_last - $page_first + 1;
24403 if (!$this->empty_string($page)) {
24404 for ($p = $page_first; $p <= $page_last; ++$p) {
24405 // get page data
24406 $temppage = $this->getPageBuffer($p);
24407 for ($n = 1; $n <= $this->numpages; ++$n) {
24408 // update page numbers
24409 $a = '{#'.$n.'}';
24410 // get page number aliases
24411 $pnalias = $this->getInternalPageNumberAliases($a);
24412 // calculate replacement number
24413 if ($n >= $page) {
24414 $np = $n + $numpages;
24415 } else {
24416 $np = $n;
24418 $na = $this->formatTOCPageNumber(($this->starting_page_number + $np - 1));
24419 $nu = $this->UTF8ToUTF16BE($na, false);
24420 // replace aliases with numbers
24421 foreach ($pnalias['u'] as $u) {
24422 if ($correct_align) {
24423 $sfill = str_repeat($filler, (strlen($u) - strlen($nu.' ')));
24424 if ($this->rtl) {
24425 $nr = $nu.$this->UTF8ToUTF16BE(' '.$sfill);
24426 } else {
24427 $nr = $this->UTF8ToUTF16BE($sfill.' ').$nu;
24429 } else {
24430 $nr = $nu;
24432 $temppage = str_replace($u, $nr, $temppage);
24434 foreach ($pnalias['a'] as $a) {
24435 if ($correct_align) {
24436 $sfill = str_repeat($filler, (strlen($a) - strlen($na.' ')));
24437 if ($this->rtl) {
24438 $nr = $na.' '.$sfill;
24439 } else {
24440 $nr = $sfill.' '.$na;
24442 } else {
24443 $nr = $na;
24445 $temppage = str_replace($a, $nr, $temppage);
24448 // save changes
24449 $this->setPageBuffer($p, $temppage);
24451 // move pages
24452 $this->Bookmark($toc_name, 0, 0, $page_first, $style, $color);
24453 for ($i = 0; $i < $numpages; ++$i) {
24454 $this->movePage($page_last, $page);
24460 * Stores a copy of the current TCPDF object used for undo operation.
24461 * @public
24462 * @since 4.5.029 (2009-03-19)
24464 public function startTransaction() {
24465 if (isset($this->objcopy)) {
24466 // remove previous copy
24467 $this->commitTransaction();
24469 // record current page number and Y position
24470 $this->start_transaction_page = $this->page;
24471 $this->start_transaction_y = $this->y;
24472 // clone current object
24473 $this->objcopy = $this->objclone($this);
24477 * Delete the copy of the current TCPDF object used for undo operation.
24478 * @public
24479 * @since 4.5.029 (2009-03-19)
24481 public function commitTransaction() {
24482 if (isset($this->objcopy)) {
24483 $this->objcopy->_destroy(true, true);
24484 unset($this->objcopy);
24489 * This method allows to undo the latest transaction by returning the latest saved TCPDF object with startTransaction().
24490 * @param $self (boolean) if true restores current class object to previous state without the need of reassignment via the returned value.
24491 * @return TCPDF object.
24492 * @public
24493 * @since 4.5.029 (2009-03-19)
24495 public function rollbackTransaction($self=false) {
24496 if (isset($this->objcopy)) {
24497 if (isset($this->objcopy->diskcache) AND $this->objcopy->diskcache) {
24498 // truncate files to previous values
24499 foreach ($this->objcopy->cache_file_length as $file => $length) {
24500 $file = substr($file, 1);
24501 $handle = fopen($file, 'r+');
24502 ftruncate($handle, $length);
24505 $this->_destroy(true, true);
24506 if ($self) {
24507 $objvars = get_object_vars($this->objcopy);
24508 foreach ($objvars as $key => $value) {
24509 $this->$key = $value;
24512 return $this->objcopy;
24514 return $this;
24518 * Creates a copy of a class object
24519 * @param $object (object) class object to be cloned
24520 * @return cloned object
24521 * @public
24522 * @since 4.5.029 (2009-03-19)
24524 public function objclone($object) {
24525 return @clone($object);
24529 * Determine whether a string is empty.
24530 * @param $str (string) string to be checked
24531 * @return boolean true if string is empty
24532 * @public
24533 * @since 4.5.044 (2009-04-16)
24535 public function empty_string($str) {
24536 return (is_null($str) OR (is_string($str) AND (strlen($str) == 0)));
24540 * Find position of last occurrence of a substring in a string
24541 * @param $haystack (string) The string to search in.
24542 * @param $needle (string) substring to search.
24543 * @param $offset (int) May be specified to begin searching an arbitrary number of characters into the string.
24544 * @return Returns the position where the needle exists. Returns FALSE if the needle was not found.
24545 * @public
24546 * @since 4.8.038 (2010-03-13)
24548 public function revstrpos($haystack, $needle, $offset = 0) {
24549 $length = strlen($haystack);
24550 $offset = ($offset > 0)?($length - $offset):abs($offset);
24551 $pos = strpos(strrev($haystack), strrev($needle), $offset);
24552 return ($pos === false)?false:($length - $pos - strlen($needle));
24555 // --- MULTI COLUMNS METHODS -----------------------
24558 * Set multiple columns of the same size
24559 * @param $numcols (int) number of columns (set to zero to disable columns mode)
24560 * @param $width (int) column width
24561 * @param $y (int) column starting Y position (leave empty for current Y position)
24562 * @public
24563 * @since 4.9.001 (2010-03-28)
24565 public function setEqualColumns($numcols=0, $width=0, $y='') {
24566 $this->columns = array();
24567 if ($numcols < 2) {
24568 $numcols = 0;
24569 $this->columns = array();
24570 } else {
24571 // maximum column width
24572 $maxwidth = ($this->w - $this->original_lMargin - $this->original_rMargin) / $numcols;
24573 if (($width == 0) OR ($width > $maxwidth)) {
24574 $width = $maxwidth;
24576 if ($this->empty_string($y)) {
24577 $y = $this->y;
24579 // space between columns
24580 $space = (($this->w - $this->original_lMargin - $this->original_rMargin - ($numcols * $width)) / ($numcols - 1));
24581 // fill the columns array (with, space, starting Y position)
24582 for ($i = 0; $i < $numcols; ++$i) {
24583 $this->columns[$i] = array('w' => $width, 's' => $space, 'y' => $y);
24586 $this->num_columns = $numcols;
24587 $this->current_column = 0;
24588 $this->column_start_page = $this->page;
24589 $this->selectColumn(0);
24593 * Remove columns and reset page margins.
24594 * @public
24595 * @since 5.9.072 (2011-04-26)
24597 public function resetColumns() {
24598 $this->lMargin = $this->original_lMargin;
24599 $this->rMargin = $this->original_rMargin;
24600 $this->setEqualColumns();
24604 * Set columns array.
24605 * Each column is represented by an array of arrays with the following keys: (w = width, s = space between columns, y = column top position).
24606 * @param $columns (array)
24607 * @public
24608 * @since 4.9.001 (2010-03-28)
24610 public function setColumnsArray($columns) {
24611 $this->columns = $columns;
24612 $this->num_columns = count($columns);
24613 $this->current_column = 0;
24614 $this->column_start_page = $this->page;
24615 $this->selectColumn(0);
24619 * Set position at a given column
24620 * @param $col (int) column number (from 0 to getNumberOfColumns()-1); empty string = current column.
24621 * @public
24622 * @since 4.9.001 (2010-03-28)
24624 public function selectColumn($col='') {
24625 if (is_string($col)) {
24626 $col = $this->current_column;
24627 } elseif ($col >= $this->num_columns) {
24628 $col = 0;
24630 $xshift = array('x' => 0, 's' => array('H' => 0, 'V' => 0), 'p' => array('L' => 0, 'T' => 0, 'R' => 0, 'B' => 0));
24631 $enable_thead = false;
24632 if ($this->num_columns > 1) {
24633 if ($col != $this->current_column) {
24634 // move Y pointer at the top of the column
24635 if ($this->column_start_page == $this->page) {
24636 $this->y = $this->columns[$col]['y'];
24637 } else {
24638 $this->y = $this->tMargin;
24640 // Avoid to write table headers more than once
24641 if (($this->page > $this->maxselcol['page']) OR (($this->page == $this->maxselcol['page']) AND ($col > $this->maxselcol['column']))) {
24642 $enable_thead = true;
24643 $this->maxselcol['page'] = $this->page;
24644 $this->maxselcol['column'] = $col;
24647 $xshift = $this->colxshift;
24648 // set X position of the current column by case
24649 $listindent = ($this->listindentlevel * $this->listindent);
24650 $colpos = ($col * ($this->columns[$col]['w'] + $this->columns[$col]['s']));
24651 if ($this->rtl) {
24652 $x = $this->w - $this->original_rMargin - $colpos;
24653 $this->rMargin = ($this->w - $x + $listindent);
24654 $this->lMargin = ($x - $this->columns[$col]['w']);
24655 $this->x = $x - $listindent;
24656 } else {
24657 $x = $this->original_lMargin + $colpos;
24658 $this->lMargin = ($x + $listindent);
24659 $this->rMargin = ($this->w - $x - $this->columns[$col]['w']);
24660 $this->x = $x + $listindent;
24662 $this->columns[$col]['x'] = $x;
24664 $this->current_column = $col;
24665 // fix for HTML mode
24666 $this->newline = true;
24667 // print HTML table header (if any)
24668 if ((!$this->empty_string($this->thead)) AND (!$this->inthead)) {
24669 if ($enable_thead) {
24670 // print table header
24671 $this->writeHTML($this->thead, false, false, false, false, '');
24672 $this->y += $xshift['s']['V'];
24673 // store end of header position
24674 if (!isset($this->columns[$col]['th'])) {
24675 $this->columns[$col]['th'] = array();
24677 $this->columns[$col]['th']['\''.$this->page.'\''] = $this->y;
24678 $this->lasth = 0;
24679 } elseif (isset($this->columns[$col]['th']['\''.$this->page.'\''])) {
24680 $this->y = $this->columns[$col]['th']['\''.$this->page.'\''];
24683 // account for an html table cell over multiple columns
24684 if ($this->rtl) {
24685 $this->rMargin += $xshift['x'];
24686 $this->x -= ($xshift['x'] + $xshift['p']['R']);
24687 } else {
24688 $this->lMargin += $xshift['x'];
24689 $this->x += $xshift['x'] + $xshift['p']['L'];
24694 * Return the current column number
24695 * @return int current column number
24696 * @public
24697 * @since 5.5.011 (2010-07-08)
24699 public function getColumn() {
24700 return $this->current_column;
24704 * Return the current number of columns.
24705 * @return int number of columns
24706 * @public
24707 * @since 5.8.018 (2010-08-25)
24709 public function getNumberOfColumns() {
24710 return $this->num_columns;
24714 * Serialize an array of parameters to be used with TCPDF tag in HTML code.
24715 * @param $pararray (array) parameters array
24716 * @return sting containing serialized data
24717 * @public
24718 * @since 4.9.006 (2010-04-02)
24720 public function serializeTCPDFtagParameters($pararray) {
24721 return urlencode(serialize($pararray));
24725 * Set Text rendering mode.
24726 * @param $stroke (int) outline size in user units (0 = disable).
24727 * @param $fill (boolean) if true fills the text (default).
24728 * @param $clip (boolean) if true activate clipping mode
24729 * @public
24730 * @since 4.9.008 (2009-04-02)
24732 public function setTextRenderingMode($stroke=0, $fill=true, $clip=false) {
24733 // Ref.: PDF 32000-1:2008 - 9.3.6 Text Rendering Mode
24734 // convert text rendering parameters
24735 if ($stroke < 0) {
24736 $stroke = 0;
24738 if ($fill === true) {
24739 if ($stroke > 0) {
24740 if ($clip === true) {
24741 // Fill, then stroke text and add to path for clipping
24742 $textrendermode = 6;
24743 } else {
24744 // Fill, then stroke text
24745 $textrendermode = 2;
24747 $textstrokewidth = $stroke;
24748 } else {
24749 if ($clip === true) {
24750 // Fill text and add to path for clipping
24751 $textrendermode = 4;
24752 } else {
24753 // Fill text
24754 $textrendermode = 0;
24757 } else {
24758 if ($stroke > 0) {
24759 if ($clip === true) {
24760 // Stroke text and add to path for clipping
24761 $textrendermode = 5;
24762 } else {
24763 // Stroke text
24764 $textrendermode = 1;
24766 $textstrokewidth = $stroke;
24767 } else {
24768 if ($clip === true) {
24769 // Add text to path for clipping
24770 $textrendermode = 7;
24771 } else {
24772 // Neither fill nor stroke text (invisible)
24773 $textrendermode = 3;
24777 $this->textrendermode = $textrendermode;
24778 $this->textstrokewidth = $stroke * $this->k;
24782 * Returns an array of chars containing soft hyphens.
24783 * @param $word (array) array of chars
24784 * @param $patterns (array) Array of hypenation patterns.
24785 * @param $dictionary (array) Array of words to be returned without applying the hyphenation algoritm.
24786 * @param $leftmin (int) Minimum number of character to leave on the left of the word without applying the hyphens.
24787 * @param $rightmin (int) Minimum number of character to leave on the right of the word without applying the hyphens.
24788 * @param $charmin (int) Minimum word length to apply the hyphenation algoritm.
24789 * @param $charmax (int) Maximum length of broken piece of word.
24790 * @return array text with soft hyphens
24791 * @author Nicola Asuni
24792 * @since 4.9.012 (2010-04-12)
24793 * @protected
24795 protected function hyphenateWord($word, $patterns, $dictionary=array(), $leftmin=1, $rightmin=2, $charmin=1, $charmax=8) {
24796 $hyphenword = array(); // hyphens positions
24797 $numchars = count($word);
24798 if ($numchars <= $charmin) {
24799 return $word;
24801 $word_string = $this->UTF8ArrSubString($word);
24802 // some words will be returned as-is
24803 $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})(\]?)$/';
24804 if (preg_match($pattern, $word_string) > 0) {
24805 // email
24806 return $word;
24808 $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})(\]?)$/';
24809 if (preg_match($pattern, $word_string) > 0) {
24810 // URL
24811 return $word;
24813 if (isset($dictionary[$word_string])) {
24814 return $this->UTF8StringToArray($dictionary[$word_string]);
24816 // suround word with '_' characters
24817 $tmpword = array_merge(array(95), $word, array(95));
24818 $tmpnumchars = $numchars + 2;
24819 $maxpos = $tmpnumchars - $charmin;
24820 for ($pos = 0; $pos < $maxpos; ++$pos) {
24821 $imax = min(($tmpnumchars - $pos), $charmax);
24822 for ($i = $charmin; $i <= $imax; ++$i) {
24823 $subword = strtolower($this->UTF8ArrSubString($tmpword, $pos, $pos + $i));
24824 if (isset($patterns[$subword])) {
24825 $pattern = $this->UTF8StringToArray($patterns[$subword]);
24826 $pattern_length = count($pattern);
24827 $digits = 1;
24828 for ($j = 0; $j < $pattern_length; ++$j) {
24829 // check if $pattern[$j] is a number
24830 if (($pattern[$j] >= 48) AND ($pattern[$j] <= 57)) {
24831 if ($j == 0) {
24832 $zero = $pos - 1;
24833 } else {
24834 $zero = $pos + $j - $digits;
24836 if (!isset($hyphenword[$zero]) OR ($hyphenword[$zero] != $pattern[$j])) {
24837 $hyphenword[$zero] = $this->unichr($pattern[$j]);
24839 ++$digits;
24845 $inserted = 0;
24846 $maxpos = $numchars - $rightmin;
24847 for ($i = $leftmin; $i <= $maxpos; ++$i) {
24848 if (isset($hyphenword[$i]) AND (($hyphenword[$i] % 2) != 0)) {
24849 // 173 = soft hyphen character
24850 array_splice($word, $i + $inserted, 0, 173);
24851 ++$inserted;
24854 return $word;
24858 * Returns an array of hyphenation patterns.
24859 * @param $file (string) TEX file containing hypenation patterns. TEX pattrns can be downloaded from http://www.ctan.org/tex-archive/language/hyph-utf8/tex/generic/hyph-utf8/patterns/
24860 * @return array of hyphenation patterns
24861 * @author Nicola Asuni
24862 * @since 4.9.012 (2010-04-12)
24863 * @public
24865 public function getHyphenPatternsFromTEX($file) {
24866 // TEX patterns are available at:
24867 // http://www.ctan.org/tex-archive/language/hyph-utf8/tex/generic/hyph-utf8/patterns/
24868 $data = file_get_contents($file);
24869 $patterns = array();
24870 // remove comments
24871 $data = preg_replace('/\%[^\n]*/', '', $data);
24872 // extract the patterns part
24873 preg_match('/\\\\patterns\{([^\}]*)\}/i', $data, $matches);
24874 $data = trim(substr($matches[0], 10, -1));
24875 // extract each pattern
24876 $patterns_array = preg_split('/[\s]+/', $data);
24877 // create new language array of patterns
24878 $patterns = array();
24879 foreach($patterns_array as $val) {
24880 if (!$this->empty_string($val)) {
24881 $val = trim($val);
24882 $val = str_replace('\'', '\\\'', $val);
24883 $key = preg_replace('/[0-9]+/', '', $val);
24884 $patterns[$key] = $val;
24887 return $patterns;
24891 * Returns text with soft hyphens.
24892 * @param $text (string) text to process
24893 * @param $patterns (mixed) Array of hypenation patterns or a TEX file containing hypenation patterns. TEX patterns can be downloaded from http://www.ctan.org/tex-archive/language/hyph-utf8/tex/generic/hyph-utf8/patterns/
24894 * @param $dictionary (array) Array of words to be returned without applying the hyphenation algoritm.
24895 * @param $leftmin (int) Minimum number of character to leave on the left of the word without applying the hyphens.
24896 * @param $rightmin (int) Minimum number of character to leave on the right of the word without applying the hyphens.
24897 * @param $charmin (int) Minimum word length to apply the hyphenation algoritm.
24898 * @param $charmax (int) Maximum length of broken piece of word.
24899 * @return array text with soft hyphens
24900 * @author Nicola Asuni
24901 * @since 4.9.012 (2010-04-12)
24902 * @public
24904 public function hyphenateText($text, $patterns, $dictionary=array(), $leftmin=1, $rightmin=2, $charmin=1, $charmax=8) {
24905 $text = $this->unhtmlentities($text);
24906 $word = array(); // last word
24907 $txtarr = array(); // text to be returned
24908 $intag = false; // true if we are inside an HTML tag
24909 if (!is_array($patterns)) {
24910 $patterns = $this->getHyphenPatternsFromTEX($patterns);
24912 // get array of characters
24913 $unichars = $this->UTF8StringToArray($text);
24914 // for each char
24915 foreach ($unichars as $char) {
24916 if ((!$intag) AND $this->unicode->uni_type[$char] == 'L') {
24917 // letter character
24918 $word[] = $char;
24919 } else {
24920 // other type of character
24921 if (!$this->empty_string($word)) {
24922 // hypenate the word
24923 $txtarr = array_merge($txtarr, $this->hyphenateWord($word, $patterns, $dictionary, $leftmin, $rightmin, $charmin, $charmax));
24924 $word = array();
24926 $txtarr[] = $char;
24927 if (chr($char) == '<') {
24928 // we are inside an HTML tag
24929 $intag = true;
24930 } elseif ($intag AND (chr($char) == '>')) {
24931 // end of HTML tag
24932 $intag = false;
24936 if (!$this->empty_string($word)) {
24937 // hypenate the word
24938 $txtarr = array_merge($txtarr, $this->hyphenateWord($word, $patterns, $dictionary, $leftmin, $rightmin, $charmin, $charmax));
24940 // convert char array to string and return
24941 return $this->UTF8ArrSubString($txtarr);
24945 * Enable/disable rasterization of vector images using ImageMagick library.
24946 * @param $mode (boolean) if true enable rasterization, false otherwise.
24947 * @public
24948 * @since 5.0.000 (2010-04-27)
24950 public function setRasterizeVectorImages($mode) {
24951 $this->rasterize_vector_images = $mode;
24955 * Get the Path-Painting Operators.
24956 * @param $style (string) Style of rendering. Possible values are:
24957 * <ul>
24958 * <li>S or D: Stroke the path.</li>
24959 * <li>s or d: Close and stroke the path.</li>
24960 * <li>f or F: Fill the path, using the nonzero winding number rule to determine the region to fill.</li>
24961 * <li>f* or F*: Fill the path, using the even-odd rule to determine the region to fill.</li>
24962 * <li>B or FD or DF: Fill and then stroke the path, using the nonzero winding number rule to determine the region to fill.</li>
24963 * <li>B* or F*D or DF*: Fill and then stroke the path, using the even-odd rule to determine the region to fill.</li>
24964 * <li>b or fd or df: Close, fill, and then stroke the path, using the nonzero winding number rule to determine the region to fill.</li>
24965 * <li>b or f*d or df*: Close, fill, and then stroke the path, using the even-odd rule to determine the region to fill.</li>
24966 * <li>CNZ: Clipping mode using the even-odd rule to determine which regions lie inside the clipping path.</li>
24967 * <li>CEO: Clipping mode using the nonzero winding number rule to determine which regions lie inside the clipping path</li>
24968 * <li>n: End the path object without filling or stroking it.</li>
24969 * </ul>
24970 * @param $default (string) default style
24971 * @author Nicola Asuni
24972 * @since 5.0.000 (2010-04-30)
24973 * @protected
24975 protected function getPathPaintOperator($style, $default='S') {
24976 $op = '';
24977 switch($style) {
24978 case 'S':
24979 case 'D': {
24980 $op = 'S';
24981 break;
24983 case 's':
24984 case 'd': {
24985 $op = 's';
24986 break;
24988 case 'f':
24989 case 'F': {
24990 $op = 'f';
24991 break;
24993 case 'f*':
24994 case 'F*': {
24995 $op = 'f*';
24996 break;
24998 case 'B':
24999 case 'FD':
25000 case 'DF': {
25001 $op = 'B';
25002 break;
25004 case 'B*':
25005 case 'F*D':
25006 case 'DF*': {
25007 $op = 'B*';
25008 break;
25010 case 'b':
25011 case 'fd':
25012 case 'df': {
25013 $op = 'b';
25014 break;
25016 case 'b*':
25017 case 'f*d':
25018 case 'df*': {
25019 $op = 'b*';
25020 break;
25022 case 'CNZ': {
25023 $op = 'W n';
25024 break;
25026 case 'CEO': {
25027 $op = 'W* n';
25028 break;
25030 case 'n': {
25031 $op = 'n';
25032 break;
25034 default: {
25035 if (!empty($default)) {
25036 $op = $this->getPathPaintOperator($default, '');
25037 } else {
25038 $op = '';
25042 return $op;
25046 * Enable or disable default option for font subsetting.
25047 * @param $enable (boolean) if true enable font subsetting by default.
25048 * @author Nicola Asuni
25049 * @public
25050 * @since 5.3.002 (2010-06-07)
25052 public function setFontSubsetting($enable=true) {
25053 $this->font_subsetting = $enable ? true : false;
25057 * Return the default option for font subsetting.
25058 * @return boolean default font subsetting state.
25059 * @author Nicola Asuni
25060 * @public
25061 * @since 5.3.002 (2010-06-07)
25063 public function getFontSubsetting() {
25064 return $this->font_subsetting;
25068 * Left trim the input string
25069 * @param $str (string) string to trim
25070 * @param $replace (string) string that replace spaces.
25071 * @return left trimmed string
25072 * @author Nicola Asuni
25073 * @public
25074 * @since 5.8.000 (2010-08-11)
25076 public function stringLeftTrim($str, $replace='') {
25077 return preg_replace('/^'.$this->re_space['p'].'+/'.$this->re_space['m'], $replace, $str);
25081 * Right trim the input string
25082 * @param $str (string) string to trim
25083 * @param $replace (string) string that replace spaces.
25084 * @return right trimmed string
25085 * @author Nicola Asuni
25086 * @public
25087 * @since 5.8.000 (2010-08-11)
25089 public function stringRightTrim($str, $replace='') {
25090 return preg_replace('/'.$this->re_space['p'].'+$/'.$this->re_space['m'], $replace, $str);
25094 * Trim the input string
25095 * @param $str (string) string to trim
25096 * @param $replace (string) string that replace spaces.
25097 * @return trimmed string
25098 * @author Nicola Asuni
25099 * @public
25100 * @since 5.8.000 (2010-08-11)
25102 public function stringTrim($str, $replace='') {
25103 $str = $this->stringLeftTrim($str, $replace);
25104 $str = $this->stringRightTrim($str, $replace);
25105 return $str;
25109 * Return true if the current font is unicode type.
25110 * @return true for unicode font, false otherwise.
25111 * @author Nicola Asuni
25112 * @public
25113 * @since 5.8.002 (2010-08-14)
25115 public function isUnicodeFont() {
25116 return (($this->CurrentFont['type'] == 'TrueTypeUnicode') OR ($this->CurrentFont['type'] == 'cidfont0'));
25120 * Return normalized font name
25121 * @param $fontfamily (string) property string containing font family names
25122 * @return string normalized font name
25123 * @author Nicola Asuni
25124 * @public
25125 * @since 5.8.004 (2010-08-17)
25127 public function getFontFamilyName($fontfamily) {
25128 // remove spaces and symbols
25129 $fontfamily = preg_replace('/[^a-z0-9\,]/', '', strtolower($fontfamily));
25130 // extract all font names
25131 $fontslist = preg_split('/[,]/', $fontfamily);
25132 // find first valid font name
25133 foreach ($fontslist as $font) {
25134 // replace font variations
25135 $font = preg_replace('/italic$/', 'I', $font);
25136 $font = preg_replace('/oblique$/', 'I', $font);
25137 $font = preg_replace('/bold([I]?)$/', 'B\\1', $font);
25138 // replace common family names and core fonts
25139 $pattern = array();
25140 $replacement = array();
25141 $pattern[] = '/^serif|^cursive|^fantasy|^timesnewroman/';
25142 $replacement[] = 'times';
25143 $pattern[] = '/^sansserif/';
25144 $replacement[] = 'helvetica';
25145 $pattern[] = '/^monospace/';
25146 $replacement[] = 'courier';
25147 $font = preg_replace($pattern, $replacement, $font);
25148 if (in_array(strtolower($font), $this->fontlist) OR in_array($font, $this->fontkeys)) {
25149 return $font;
25152 // return current font as default
25153 return $this->CurrentFont['fontkey'];
25157 * Start a new XObject Template.
25158 * 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).
25159 * 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.
25160 * Note: X,Y coordinates will be reset to 0,0.
25161 * @param $w (int) Template width in user units (empty string or zero = page width less margins).
25162 * @param $h (int) Template height in user units (empty string or zero = page height less margins).
25163 * @param $group (mixed) Set transparency group. Can be a boolean value or an array specifying optional parameters: 'CS' (solour space name), 'I' (boolean flag to indicate isolated group) and 'K' (boolean flag to indicate knockout group).
25164 * @return int the XObject Template ID in case of success or false in case of error.
25165 * @author Nicola Asuni
25166 * @public
25167 * @since 5.8.017 (2010-08-24)
25168 * @see endTemplate(), printTemplate()
25170 public function startTemplate($w=0, $h=0, $group=false) {
25171 if ($this->inxobj) {
25172 // we are already inside an XObject template
25173 return false;
25175 $this->inxobj = true;
25176 ++$this->n;
25177 // XObject ID
25178 $this->xobjid = 'XT'.$this->n;
25179 // object ID
25180 $this->xobjects[$this->xobjid] = array('n' => $this->n);
25181 // store current graphic state
25182 $this->xobjects[$this->xobjid]['gvars'] = $this->getGraphicVars();
25183 // initialize data
25184 $this->xobjects[$this->xobjid]['intmrk'] = 0;
25185 $this->xobjects[$this->xobjid]['transfmrk'] = array();
25186 $this->xobjects[$this->xobjid]['outdata'] = '';
25187 $this->xobjects[$this->xobjid]['xobjects'] = array();
25188 $this->xobjects[$this->xobjid]['images'] = array();
25189 $this->xobjects[$this->xobjid]['fonts'] = array();
25190 $this->xobjects[$this->xobjid]['annotations'] = array();
25191 // set new environment
25192 $this->num_columns = 1;
25193 $this->current_column = 0;
25194 $this->SetAutoPageBreak(false);
25195 if (($w === '') OR ($w <= 0)) {
25196 $w = $this->w - $this->lMargin - $this->rMargin;
25198 if (($h === '') OR ($h <= 0)) {
25199 $h = $this->h - $this->tMargin - $this->bMargin;
25201 $this->xobjects[$this->xobjid]['x'] = 0;
25202 $this->xobjects[$this->xobjid]['y'] = 0;
25203 $this->xobjects[$this->xobjid]['w'] = $w;
25204 $this->xobjects[$this->xobjid]['h'] = $h;
25205 $this->w = $w;
25206 $this->h = $h;
25207 $this->wPt = $this->w * $this->k;
25208 $this->hPt = $this->h * $this->k;
25209 $this->fwPt = $this->wPt;
25210 $this->fhPt = $this->hPt;
25211 $this->x = 0;
25212 $this->y = 0;
25213 $this->lMargin = 0;
25214 $this->rMargin = 0;
25215 $this->tMargin = 0;
25216 $this->bMargin = 0;
25217 // set group mode
25218 $this->xobjects[$this->xobjid]['group'] = $group;
25219 return $this->xobjid;
25223 * End the current XObject Template started with startTemplate() and restore the previous graphic state.
25224 * 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).
25225 * 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.
25226 * @return int the XObject Template ID in case of success or false in case of error.
25227 * @author Nicola Asuni
25228 * @public
25229 * @since 5.8.017 (2010-08-24)
25230 * @see startTemplate(), printTemplate()
25232 public function endTemplate() {
25233 if (!$this->inxobj) {
25234 // we are not inside a template
25235 return false;
25237 $this->inxobj = false;
25238 // restore previous graphic state
25239 $this->setGraphicVars($this->xobjects[$this->xobjid]['gvars'], true);
25240 return $this->xobjid;
25244 * Print an XObject Template.
25245 * You can print an XObject Template inside the currently opened Template.
25246 * 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).
25247 * 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.
25248 * @param $id (string) The ID of XObject Template to print.
25249 * @param $x (int) X position in user units (empty string = current x position)
25250 * @param $y (int) Y position in user units (empty string = current y position)
25251 * @param $w (int) Width in user units (zero = remaining page width)
25252 * @param $h (int) Height in user units (zero = remaining page height)
25253 * @param $align (string) Indicates the alignment of the pointer next to template insertion relative to template height. The value can be:<ul><li>T: top-right for LTR or top-left for RTL</li><li>M: middle-right for LTR or middle-left for RTL</li><li>B: bottom-right for LTR or bottom-left for RTL</li><li>N: next line</li></ul>
25254 * @param $palign (string) Allows to center or align the template on the current line. Possible values are:<ul><li>L : left align</li><li>C : center</li><li>R : right align</li><li>'' : empty string : left for LTR or right for RTL</li></ul>
25255 * @param $fitonpage (boolean) If true the template is resized to not exceed page dimensions.
25256 * @author Nicola Asuni
25257 * @public
25258 * @since 5.8.017 (2010-08-24)
25259 * @see startTemplate(), endTemplate()
25261 public function printTemplate($id, $x='', $y='', $w=0, $h=0, $align='', $palign='', $fitonpage=false) {
25262 if (!isset($this->xobjects[$id])) {
25263 $this->Error('The XObject Template \''.$id.'\' doesn\'t exist!');
25265 if ($this->inxobj) {
25266 if ($id == $this->xobjid) {
25267 // close current template
25268 $this->endTemplate();
25269 } else {
25270 // use the template as resource for the template currently opened
25271 $this->xobjects[$this->xobjid]['xobjects'][$id] = $this->xobjects[$id];
25274 // set default values
25275 if ($x === '') {
25276 $x = $this->x;
25278 if ($y === '') {
25279 $y = $this->y;
25281 // check page for no-write regions and adapt page margins if necessary
25282 list($x, $y) = $this->checkPageRegions($h, $x, $y);
25283 $ow = $this->xobjects[$id]['w'];
25284 $oh = $this->xobjects[$id]['h'];
25285 // calculate template width and height on document
25286 if (($w <= 0) AND ($h <= 0)) {
25287 $w = $ow;
25288 $h = $oh;
25289 } elseif ($w <= 0) {
25290 $w = $h * $ow / $oh;
25291 } elseif ($h <= 0) {
25292 $h = $w * $oh / $ow;
25294 // fit the template on available space
25295 list($w, $h, $x, $y) = $this->fitBlock($w, $h, $x, $y, $fitonpage);
25296 // set page alignment
25297 $rb_y = $y + $h;
25298 // set alignment
25299 if ($this->rtl) {
25300 if ($palign == 'L') {
25301 $xt = $this->lMargin;
25302 } elseif ($palign == 'C') {
25303 $xt = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
25304 } elseif ($palign == 'R') {
25305 $xt = $this->w - $this->rMargin - $w;
25306 } else {
25307 $xt = $x - $w;
25309 $rb_x = $xt;
25310 } else {
25311 if ($palign == 'L') {
25312 $xt = $this->lMargin;
25313 } elseif ($palign == 'C') {
25314 $xt = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
25315 } elseif ($palign == 'R') {
25316 $xt = $this->w - $this->rMargin - $w;
25317 } else {
25318 $xt = $x;
25320 $rb_x = $xt + $w;
25322 // print XObject Template + Transformation matrix
25323 $this->StartTransform();
25324 // translate and scale
25325 $sx = ($w / $this->xobjects[$id]['w']);
25326 $sy = ($h / $this->xobjects[$id]['h']);
25327 $tm = array();
25328 $tm[0] = $sx;
25329 $tm[1] = 0;
25330 $tm[2] = 0;
25331 $tm[3] = $sy;
25332 $tm[4] = $xt * $this->k;
25333 $tm[5] = ($this->h - $h - $y) * $this->k;
25334 $this->Transform($tm);
25335 // set object
25336 $this->_out('/'.$id.' Do');
25337 $this->StopTransform();
25338 // add annotations
25339 if (!empty($this->xobjects[$id]['annotations'])) {
25340 foreach ($this->xobjects[$id]['annotations'] as $annot) {
25341 // transform original coordinates
25342 $coordlt = $this->getTransformationMatrixProduct($tm, array(1, 0, 0, 1, ($annot['x'] * $this->k), (-$annot['y'] * $this->k)));
25343 $ax = ($coordlt[4] / $this->k);
25344 $ay = ($this->h - $h - ($coordlt[5] / $this->k));
25345 $coordrb = $this->getTransformationMatrixProduct($tm, array(1, 0, 0, 1, (($annot['x'] + $annot['w']) * $this->k), ((-$annot['y'] - $annot['h']) * $this->k)));
25346 $aw = ($coordrb[4] / $this->k) - $ax;
25347 $ah = ($this->h - $h - ($coordrb[5] / $this->k)) - $ay;
25348 $this->Annotation($ax, $ay, $aw, $ah, $annot['text'], $annot['opt'], $annot['spaces']);
25351 // set pointer to align the next text/objects
25352 switch($align) {
25353 case 'T': {
25354 $this->y = $y;
25355 $this->x = $rb_x;
25356 break;
25358 case 'M': {
25359 $this->y = $y + round($h/2);
25360 $this->x = $rb_x;
25361 break;
25363 case 'B': {
25364 $this->y = $rb_y;
25365 $this->x = $rb_x;
25366 break;
25368 case 'N': {
25369 $this->SetY($rb_y);
25370 break;
25372 default:{
25373 break;
25379 * Set the percentage of character stretching.
25380 * @param $perc (int) percentage of stretching (100 = no stretching)
25381 * @author Nicola Asuni
25382 * @public
25383 * @since 5.9.000 (2010-09-29)
25385 public function setFontStretching($perc=100) {
25386 $this->font_stretching = $perc;
25390 * Get the percentage of character stretching.
25391 * @return float stretching value
25392 * @author Nicola Asuni
25393 * @public
25394 * @since 5.9.000 (2010-09-29)
25396 public function getFontStretching() {
25397 return $this->font_stretching;
25401 * Set the amount to increase or decrease the space between characters in a text.
25402 * @param $spacing (float) amount to increase or decrease the space between characters in a text (0 = default spacing)
25403 * @author Nicola Asuni
25404 * @public
25405 * @since 5.9.000 (2010-09-29)
25407 public function setFontSpacing($spacing=0) {
25408 $this->font_spacing = $spacing;
25412 * Get the amount to increase or decrease the space between characters in a text.
25413 * @return int font spacing (tracking/kerning) value
25414 * @author Nicola Asuni
25415 * @public
25416 * @since 5.9.000 (2010-09-29)
25418 public function getFontSpacing() {
25419 return $this->font_spacing;
25423 * Return an array of no-write page regions
25424 * @return array of no-write page regions
25425 * @author Nicola Asuni
25426 * @public
25427 * @since 5.9.003 (2010-10-13)
25428 * @see setPageRegions(), addPageRegion()
25430 public function getPageRegions() {
25431 return $this->page_regions;
25435 * Set no-write regions on page.
25436 * 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.
25437 * A region is always aligned on the left or right side of the page ad is defined using a vertical segment.
25438 * You can set multiple regions for the same page.
25439 * @param $regions (array) array of no-write regions. For each region you can define an array as follow: ('page' => page number or empy for current page, 'xt' => X top, 'yt' => Y top, 'xb' => X bottom, 'yb' => Y bottom, 'side' => page side 'L' = left or 'R' = right). Omit this parameter to remove all regions.
25440 * @author Nicola Asuni
25441 * @public
25442 * @since 5.9.003 (2010-10-13)
25443 * @see addPageRegion(), getPageRegions()
25445 public function setPageRegions($regions=array()) {
25446 // empty current regions array
25447 $this->page_regions = array();
25448 // add regions
25449 foreach ($regions as $data) {
25450 $this->addPageRegion($data);
25455 * Add a single no-write region on selected page.
25456 * 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.
25457 * A region is always aligned on the left or right side of the page ad is defined using a vertical segment.
25458 * You can set multiple regions for the same page.
25459 * @param $region (array) array of a single no-write region array: ('page' => page number or empy for current page, 'xt' => X top, 'yt' => Y top, 'xb' => X bottom, 'yb' => Y bottom, 'side' => page side 'L' = left or 'R' = right).
25460 * @author Nicola Asuni
25461 * @public
25462 * @since 5.9.003 (2010-10-13)
25463 * @see setPageRegions(), getPageRegions()
25465 public function addPageRegion($region) {
25466 if (!isset($region['page']) OR empty($region['page'])) {
25467 $region['page'] = $this->page;
25469 if (isset($region['xt']) AND isset($region['xb']) AND ($region['xt'] > 0) AND ($region['xb'] > 0)
25470 AND isset($region['yt']) AND isset($region['yb']) AND ($region['yt'] >= 0) AND ($region['yt'] < $region['yb'])
25471 AND isset($region['side']) AND (($region['side'] == 'L') OR ($region['side'] == 'R'))) {
25472 $this->page_regions[] = $region;
25477 * Remove a single no-write region.
25478 * @param $key (int) region key
25479 * @author Nicola Asuni
25480 * @public
25481 * @since 5.9.003 (2010-10-13)
25482 * @see setPageRegions(), getPageRegions()
25484 public function removePageRegion($key) {
25485 if (isset($this->page_regions[$key])) {
25486 unset($this->page_regions[$key]);
25491 * Check page for no-write regions and adapt current coordinates and page margins if necessary.
25492 * 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.
25493 * A region is always aligned on the left or right side of the page ad is defined using a vertical segment.
25494 * @param $h (float) height of the text/image/object to print in user units
25495 * @param $x (float) current X coordinate in user units
25496 * @param $y (float) current Y coordinate in user units
25497 * @return array($x, $y)
25498 * @author Nicola Asuni
25499 * @protected
25500 * @since 5.9.003 (2010-10-13)
25502 protected function checkPageRegions($h, $x, $y) {
25503 // set default values
25504 if ($x === '') {
25505 $x = $this->x;
25507 if ($y === '') {
25508 $y = $this->y;
25510 if (empty($this->page_regions)) {
25511 // no page regions defined
25512 return array($x, $y);
25514 if (empty($h)) {
25515 $h = ($this->FontSize * $this->cell_height_ratio) + $this->cell_padding['T'] + $this->cell_padding['B'];
25517 // check for page break
25518 if ($this->checkPageBreak($h, $y)) {
25519 // the content will be printed on a new page
25520 $x = $this->x;
25521 $y = $this->y;
25523 if ($this->num_columns > 1) {
25524 if ($this->rtl) {
25525 $this->lMargin = $this->columns[$this->current_column]['x'] - $this->columns[$this->current_column]['w'];
25526 } else {
25527 $this->rMargin = $this->w - $this->columns[$this->current_column]['x'] - $this->columns[$this->current_column]['w'];
25529 } else {
25530 if ($this->rtl) {
25531 $this->lMargin = $this->original_lMargin;
25532 } else {
25533 $this->rMargin = $this->original_rMargin;
25536 // adjust coordinates and page margins
25537 foreach ($this->page_regions as $regid => $regdata) {
25538 if ($regdata['page'] == $this->page) {
25539 // check region boundaries
25540 if (($y > ($regdata['yt'] - $h)) AND ($y <= $regdata['yb'])) {
25541 // Y is inside the region
25542 $minv = ($regdata['xb'] - $regdata['xt']) / ($regdata['yb'] - $regdata['yt']); // inverse of angular coefficient
25543 $yt = max($y, $regdata['yt']);
25544 $yb = min(($yt + $h), $regdata['yb']);
25545 $xt = (($yt - $regdata['yt']) * $minv) + $regdata['xt'];
25546 $xb = (($yb - $regdata['yt']) * $minv) + $regdata['xt'];
25547 if ($regdata['side'] == 'L') { // left side
25548 $new_margin = max($xt, $xb);
25549 if ($this->lMargin < $new_margin) {
25550 if ($this->rtl) {
25551 // adjust left page margin
25552 $this->lMargin = $new_margin;
25554 if ($x < $new_margin) {
25555 // adjust x position
25556 $x = $new_margin;
25557 if ($new_margin > ($this->w - $this->rMargin)) {
25558 // adjust y position
25559 $y = $regdata['yb'] - $h;
25563 } elseif ($regdata['side'] == 'R') { // right side
25564 $new_margin = min($xt, $xb);
25565 if (($this->w - $this->rMargin) > $new_margin) {
25566 if (!$this->rtl) {
25567 // adjust right page margin
25568 $this->rMargin = ($this->w - $new_margin);
25570 if ($x > $new_margin) {
25571 // adjust x position
25572 $x = $new_margin;
25573 if ($new_margin > $this->lMargin) {
25574 // adjust y position
25575 $y = $regdata['yb'] - $h;
25583 return array($x, $y);
25586 // --- SVG METHODS ---------------------------------------------------------
25589 * Embedd a Scalable Vector Graphics (SVG) image.
25590 * NOTE: SVG standard is not yet fully implemented, use the setRasterizeVectorImages() method to enable/disable rasterization of vector images using ImageMagick library.
25591 * @param $file (string) Name of the SVG file or a '@' character followed by the SVG data string.
25592 * @param $x (float) Abscissa of the upper-left corner.
25593 * @param $y (float) Ordinate of the upper-left corner.
25594 * @param $w (float) Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
25595 * @param $h (float) Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
25596 * @param $link (mixed) URL or identifier returned by AddLink().
25597 * @param $align (string) Indicates the alignment of the pointer next to image insertion relative to image height. The value can be:<ul><li>T: top-right for LTR or top-left for RTL</li><li>M: middle-right for LTR or middle-left for RTL</li><li>B: bottom-right for LTR or bottom-left for RTL</li><li>N: next line</li></ul> If the alignment is an empty string, then the pointer will be restored on the starting SVG position.
25598 * @param $palign (string) Allows to center or align the image on the current line. Possible values are:<ul><li>L : left align</li><li>C : center</li><li>R : right align</li><li>'' : empty string : left for LTR or right for RTL</li></ul>
25599 * @param $border (mixed) Indicates if borders must be drawn around the cell. The value can be a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul> or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul> or an array of line styles for each border group - for example: array('LTRB' => array('width' => 2, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0)))
25600 * @param $fitonpage (boolean) if true the image is resized to not exceed page dimensions.
25601 * @author Nicola Asuni
25602 * @since 5.0.000 (2010-05-02)
25603 * @public
25605 public function ImageSVG($file, $x='', $y='', $w=0, $h=0, $link='', $align='', $palign='', $border=0, $fitonpage=false) {
25606 if ($this->rasterize_vector_images AND ($w > 0) AND ($h > 0)) {
25607 // convert SVG to raster image using GD or ImageMagick libraries
25608 return $this->Image($file, $x, $y, $w, $h, 'SVG', $link, $align, true, 300, $palign, false, false, $border, false, false, false);
25610 if ($file{0} === '@') { // image from string
25611 $this->svgdir = '';
25612 $svgdata = substr($file, 1);
25613 } else { // SVG file
25614 $this->svgdir = dirname($file);
25615 $svgdata = file_get_contents($file);
25617 if ($svgdata === false) {
25618 $this->Error('SVG file not found: '.$file);
25620 if ($x === '') {
25621 $x = $this->x;
25623 if ($y === '') {
25624 $y = $this->y;
25626 // check page for no-write regions and adapt page margins if necessary
25627 list($x, $y) = $this->checkPageRegions($h, $x, $y);
25628 $k = $this->k;
25629 $ox = 0;
25630 $oy = 0;
25631 $ow = $w;
25632 $oh = $h;
25633 $aspect_ratio_align = 'xMidYMid';
25634 $aspect_ratio_ms = 'meet';
25635 $regs = array();
25636 // get original image width and height
25637 preg_match('/<svg([^\>]*)>/si', $svgdata, $regs);
25638 if (isset($regs[1]) AND !empty($regs[1])) {
25639 $tmp = array();
25640 if (preg_match('/[\s]+x[\s]*=[\s]*"([^"]*)"/si', $regs[1], $tmp)) {
25641 $ox = $this->getHTMLUnitToUnits($tmp[1], 0, $this->svgunit, false);
25643 $tmp = array();
25644 if (preg_match('/[\s]+y[\s]*=[\s]*"([^"]*)"/si', $regs[1], $tmp)) {
25645 $oy = $this->getHTMLUnitToUnits($tmp[1], 0, $this->svgunit, false);
25647 $tmp = array();
25648 if (preg_match('/[\s]+width[\s]*=[\s]*"([^"]*)"/si', $regs[1], $tmp)) {
25649 $ow = $this->getHTMLUnitToUnits($tmp[1], 1, $this->svgunit, false);
25651 $tmp = array();
25652 if (preg_match('/[\s]+height[\s]*=[\s]*"([^"]*)"/si', $regs[1], $tmp)) {
25653 $oh = $this->getHTMLUnitToUnits($tmp[1], 1, $this->svgunit, false);
25655 $tmp = array();
25656 $view_box = array();
25657 if (preg_match('/[\s]+viewBox[\s]*=[\s]*"[\s]*([0-9\.\-]+)[\s]+([0-9\.\-]+)[\s]+([0-9\.]+)[\s]+([0-9\.]+)[\s]*"/si', $regs[1], $tmp)) {
25658 if (count($tmp) == 5) {
25659 array_shift($tmp);
25660 foreach ($tmp as $key => $val) {
25661 $view_box[$key] = $this->getHTMLUnitToUnits($val, 0, $this->svgunit, false);
25663 $ox = $view_box[0];
25664 $oy = $view_box[1];
25666 // get aspect ratio
25667 $tmp = array();
25668 if (preg_match('/[\s]+preserveAspectRatio[\s]*=[\s]*"([^"]*)"/si', $regs[1], $tmp)) {
25669 $aspect_ratio = preg_split('/[\s]+/si', $tmp[1]);
25670 switch (count($aspect_ratio)) {
25671 case 3: {
25672 $aspect_ratio_align = $aspect_ratio[1];
25673 $aspect_ratio_ms = $aspect_ratio[2];
25674 break;
25676 case 2: {
25677 $aspect_ratio_align = $aspect_ratio[0];
25678 $aspect_ratio_ms = $aspect_ratio[1];
25679 break;
25681 case 1: {
25682 $aspect_ratio_align = $aspect_ratio[0];
25683 $aspect_ratio_ms = 'meet';
25684 break;
25690 // calculate image width and height on document
25691 if (($w <= 0) AND ($h <= 0)) {
25692 // convert image size to document unit
25693 $w = $ow;
25694 $h = $oh;
25695 } elseif ($w <= 0) {
25696 $w = $h * $ow / $oh;
25697 } elseif ($h <= 0) {
25698 $h = $w * $oh / $ow;
25700 // fit the image on available space
25701 list($w, $h, $x, $y) = $this->fitBlock($w, $h, $x, $y, $fitonpage);
25702 if ($this->rasterize_vector_images) {
25703 // convert SVG to raster image using GD or ImageMagick libraries
25704 return $this->Image($file, $x, $y, $w, $h, 'SVG', $link, $align, true, 300, $palign, false, false, $border, false, false, false);
25706 // set alignment
25707 $this->img_rb_y = $y + $h;
25708 // set alignment
25709 if ($this->rtl) {
25710 if ($palign == 'L') {
25711 $ximg = $this->lMargin;
25712 } elseif ($palign == 'C') {
25713 $ximg = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
25714 } elseif ($palign == 'R') {
25715 $ximg = $this->w - $this->rMargin - $w;
25716 } else {
25717 $ximg = $x - $w;
25719 $this->img_rb_x = $ximg;
25720 } else {
25721 if ($palign == 'L') {
25722 $ximg = $this->lMargin;
25723 } elseif ($palign == 'C') {
25724 $ximg = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
25725 } elseif ($palign == 'R') {
25726 $ximg = $this->w - $this->rMargin - $w;
25727 } else {
25728 $ximg = $x;
25730 $this->img_rb_x = $ximg + $w;
25732 // store current graphic vars
25733 $gvars = $this->getGraphicVars();
25734 // store SVG position and scale factors
25735 $svgoffset_x = ($ximg - $ox) * $this->k;
25736 $svgoffset_y = -($y - $oy) * $this->k;
25737 if (isset($view_box[2]) AND ($view_box[2] > 0) AND ($view_box[3] > 0)) {
25738 $ow = $view_box[2];
25739 $oh = $view_box[3];
25740 } else {
25741 if ($ow <= 0) {
25742 $ow = $w;
25744 if ($oh <= 0) {
25745 $oh = $h;
25748 $svgscale_x = $w / $ow;
25749 $svgscale_y = $h / $oh;
25750 // scaling and alignment
25751 if ($aspect_ratio_align != 'none') {
25752 // store current scaling values
25753 $svgscale_old_x = $svgscale_x;
25754 $svgscale_old_y = $svgscale_y;
25755 // force uniform scaling
25756 if ($aspect_ratio_ms == 'slice') {
25757 // the entire viewport is covered by the viewBox
25758 if ($svgscale_x > $svgscale_y) {
25759 $svgscale_y = $svgscale_x;
25760 } elseif ($svgscale_x < $svgscale_y) {
25761 $svgscale_x = $svgscale_y;
25763 } else { // meet
25764 // the entire viewBox is visible within the viewport
25765 if ($svgscale_x < $svgscale_y) {
25766 $svgscale_y = $svgscale_x;
25767 } elseif ($svgscale_x > $svgscale_y) {
25768 $svgscale_x = $svgscale_y;
25771 // correct X alignment
25772 switch (substr($aspect_ratio_align, 1, 3)) {
25773 case 'Min': {
25774 // do nothing
25775 break;
25777 case 'Max': {
25778 $svgoffset_x += (($w * $this->k) - ($ow * $this->k * $svgscale_x));
25779 break;
25781 default:
25782 case 'Mid': {
25783 $svgoffset_x += ((($w * $this->k) - ($ow * $this->k * $svgscale_x)) / 2);
25784 break;
25787 // correct Y alignment
25788 switch (substr($aspect_ratio_align, 5)) {
25789 case 'Min': {
25790 // do nothing
25791 break;
25793 case 'Max': {
25794 $svgoffset_y -= (($h * $this->k) - ($oh * $this->k * $svgscale_y));
25795 break;
25797 default:
25798 case 'Mid': {
25799 $svgoffset_y -= ((($h * $this->k) - ($oh * $this->k * $svgscale_y)) / 2);
25800 break;
25804 // store current page break mode
25805 $page_break_mode = $this->AutoPageBreak;
25806 $page_break_margin = $this->getBreakMargin();
25807 $cell_padding = $this->cell_padding;
25808 $this->SetCellPadding(0);
25809 $this->SetAutoPageBreak(false);
25810 // save the current graphic state
25811 $this->_out('q'.$this->epsmarker);
25812 // set initial clipping mask
25813 $this->Rect($x, $y, $w, $h, 'CNZ', array(), array());
25814 // scale and translate
25815 $e = $ox * $this->k * (1 - $svgscale_x);
25816 $f = ($this->h - $oy) * $this->k * (1 - $svgscale_y);
25817 $this->_out(sprintf('%.3F %.3F %.3F %.3F %.3F %.3F cm', $svgscale_x, 0, 0, $svgscale_y, $e + $svgoffset_x, $f + $svgoffset_y));
25818 // creates a new XML parser to be used by the other XML functions
25819 $this->parser = xml_parser_create('UTF-8');
25820 // the following function allows to use parser inside object
25821 xml_set_object($this->parser, $this);
25822 // disable case-folding for this XML parser
25823 xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0);
25824 // sets the element handler functions for the XML parser
25825 xml_set_element_handler($this->parser, 'startSVGElementHandler', 'endSVGElementHandler');
25826 // sets the character data handler function for the XML parser
25827 xml_set_character_data_handler($this->parser, 'segSVGContentHandler');
25828 // start parsing an XML document
25829 if (!xml_parse($this->parser, $svgdata)) {
25830 $error_message = sprintf('SVG Error: %s at line %d', xml_error_string(xml_get_error_code($this->parser)), xml_get_current_line_number($this->parser));
25831 $this->Error($error_message);
25833 // free this XML parser
25834 xml_parser_free($this->parser);
25835 // restore previous graphic state
25836 $this->_out($this->epsmarker.'Q');
25837 // restore graphic vars
25838 $this->setGraphicVars($gvars);
25839 $this->lasth = $gvars['lasth'];
25840 if (!empty($border)) {
25841 $bx = $this->x;
25842 $by = $this->y;
25843 $this->x = $ximg;
25844 if ($this->rtl) {
25845 $this->x += $w;
25847 $this->y = $y;
25848 $this->Cell($w, $h, '', $border, 0, '', 0, '', 0, true);
25849 $this->x = $bx;
25850 $this->y = $by;
25852 if ($link) {
25853 $this->Link($ximg, $y, $w, $h, $link, 0);
25855 // set pointer to align the next text/objects
25856 switch($align) {
25857 case 'T':{
25858 $this->y = $y;
25859 $this->x = $this->img_rb_x;
25860 break;
25862 case 'M':{
25863 $this->y = $y + round($h/2);
25864 $this->x = $this->img_rb_x;
25865 break;
25867 case 'B':{
25868 $this->y = $this->img_rb_y;
25869 $this->x = $this->img_rb_x;
25870 break;
25872 case 'N':{
25873 $this->SetY($this->img_rb_y);
25874 break;
25876 default:{
25877 // restore pointer to starting position
25878 $this->x = $gvars['x'];
25879 $this->y = $gvars['y'];
25880 $this->page = $gvars['page'];
25881 $this->current_column = $gvars['current_column'];
25882 $this->tMargin = $gvars['tMargin'];
25883 $this->bMargin = $gvars['bMargin'];
25884 $this->w = $gvars['w'];
25885 $this->h = $gvars['h'];
25886 $this->wPt = $gvars['wPt'];
25887 $this->hPt = $gvars['hPt'];
25888 $this->fwPt = $gvars['fwPt'];
25889 $this->fhPt = $gvars['fhPt'];
25890 break;
25893 $this->endlinex = $this->img_rb_x;
25894 // restore page break
25895 $this->SetAutoPageBreak($page_break_mode, $page_break_margin);
25896 $this->cell_padding = $cell_padding;
25900 * Get the tranformation matrix from SVG transform attribute
25901 * @param $attribute (string) transformation
25902 * @return array of transformations
25903 * @author Nicola Asuni
25904 * @since 5.0.000 (2010-05-02)
25905 * @protected
25907 protected function getSVGTransformMatrix($attribute) {
25908 // identity matrix
25909 $tm = array(1, 0, 0, 1, 0, 0);
25910 $transform = array();
25911 if (preg_match_all('/(matrix|translate|scale|rotate|skewX|skewY)[\s]*\(([^\)]+)\)/si', $attribute, $transform, PREG_SET_ORDER) > 0) {
25912 foreach ($transform as $key => $data) {
25913 if (!empty($data[2])) {
25914 $a = 1;
25915 $b = 0;
25916 $c = 0;
25917 $d = 1;
25918 $e = 0;
25919 $f = 0;
25920 $regs = array();
25921 switch ($data[1]) {
25922 case 'matrix': {
25923 if (preg_match('/([a-z0-9\-\.]+)[\,\s]+([a-z0-9\-\.]+)[\,\s]+([a-z0-9\-\.]+)[\,\s]+([a-z0-9\-\.]+)[\,\s]+([a-z0-9\-\.]+)[\,\s]+([a-z0-9\-\.]+)/si', $data[2], $regs)) {
25924 $a = $regs[1];
25925 $b = $regs[2];
25926 $c = $regs[3];
25927 $d = $regs[4];
25928 $e = $regs[5];
25929 $f = $regs[6];
25931 break;
25933 case 'translate': {
25934 if (preg_match('/([a-z0-9\-\.]+)[\,\s]+([a-z0-9\-\.]+)/si', $data[2], $regs)) {
25935 $e = $regs[1];
25936 $f = $regs[2];
25937 } elseif (preg_match('/([a-z0-9\-\.]+)/si', $data[2], $regs)) {
25938 $e = $regs[1];
25940 break;
25942 case 'scale': {
25943 if (preg_match('/([a-z0-9\-\.]+)[\,\s]+([a-z0-9\-\.]+)/si', $data[2], $regs)) {
25944 $a = $regs[1];
25945 $d = $regs[2];
25946 } elseif (preg_match('/([a-z0-9\-\.]+)/si', $data[2], $regs)) {
25947 $a = $regs[1];
25948 $d = $a;
25950 break;
25952 case 'rotate': {
25953 if (preg_match('/([0-9\-\.]+)[\,\s]+([a-z0-9\-\.]+)[\,\s]+([a-z0-9\-\.]+)/si', $data[2], $regs)) {
25954 $ang = deg2rad($regs[1]);
25955 $x = $regs[2];
25956 $y = $regs[3];
25957 $a = cos($ang);
25958 $b = sin($ang);
25959 $c = -$b;
25960 $d = $a;
25961 $e = ($x * (1 - $a)) - ($y * $c);
25962 $f = ($y * (1 - $d)) - ($x * $b);
25963 } elseif (preg_match('/([0-9\-\.]+)/si', $data[2], $regs)) {
25964 $ang = deg2rad($regs[1]);
25965 $a = cos($ang);
25966 $b = sin($ang);
25967 $c = -$b;
25968 $d = $a;
25969 $e = 0;
25970 $f = 0;
25972 break;
25974 case 'skewX': {
25975 if (preg_match('/([0-9\-\.]+)/si', $data[2], $regs)) {
25976 $c = tan(deg2rad($regs[1]));
25978 break;
25980 case 'skewY': {
25981 if (preg_match('/([0-9\-\.]+)/si', $data[2], $regs)) {
25982 $b = tan(deg2rad($regs[1]));
25984 break;
25987 $tm = $this->getTransformationMatrixProduct($tm, array($a, $b, $c, $d, $e, $f));
25991 return $tm;
25995 * Get the product of two SVG tranformation matrices
25996 * @param $ta (array) first SVG tranformation matrix
25997 * @param $tb (array) second SVG tranformation matrix
25998 * @return transformation array
25999 * @author Nicola Asuni
26000 * @since 5.0.000 (2010-05-02)
26001 * @protected
26003 protected function getTransformationMatrixProduct($ta, $tb) {
26004 $tm = array();
26005 $tm[0] = ($ta[0] * $tb[0]) + ($ta[2] * $tb[1]);
26006 $tm[1] = ($ta[1] * $tb[0]) + ($ta[3] * $tb[1]);
26007 $tm[2] = ($ta[0] * $tb[2]) + ($ta[2] * $tb[3]);
26008 $tm[3] = ($ta[1] * $tb[2]) + ($ta[3] * $tb[3]);
26009 $tm[4] = ($ta[0] * $tb[4]) + ($ta[2] * $tb[5]) + $ta[4];
26010 $tm[5] = ($ta[1] * $tb[4]) + ($ta[3] * $tb[5]) + $ta[5];
26011 return $tm;
26015 * Convert SVG transformation matrix to PDF.
26016 * @param $tm (array) original SVG transformation matrix
26017 * @return array transformation matrix
26018 * @protected
26019 * @since 5.0.000 (2010-05-02)
26021 protected function convertSVGtMatrix($tm) {
26022 $a = $tm[0];
26023 $b = -$tm[1];
26024 $c = -$tm[2];
26025 $d = $tm[3];
26026 $e = $this->getHTMLUnitToUnits($tm[4], 1, $this->svgunit, false) * $this->k;
26027 $f = -$this->getHTMLUnitToUnits($tm[5], 1, $this->svgunit, false) * $this->k;
26028 $x = 0;
26029 $y = $this->h * $this->k;
26030 $e = ($x * (1 - $a)) - ($y * $c) + $e;
26031 $f = ($y * (1 - $d)) - ($x * $b) + $f;
26032 return array($a, $b, $c, $d, $e, $f);
26036 * Apply SVG graphic transformation matrix.
26037 * @param $tm (array) original SVG transformation matrix
26038 * @protected
26039 * @since 5.0.000 (2010-05-02)
26041 protected function SVGTransform($tm) {
26042 $this->Transform($this->convertSVGtMatrix($tm));
26046 * Apply the requested SVG styles (*** TO BE COMPLETED ***)
26047 * @param $svgstyle (array) array of SVG styles to apply
26048 * @param $prevsvgstyle (array) array of previous SVG style
26049 * @param $x (int) X origin of the bounding box
26050 * @param $y (int) Y origin of the bounding box
26051 * @param $w (int) width of the bounding box
26052 * @param $h (int) height of the bounding box
26053 * @param $clip_function (string) clip function
26054 * @param $clip_params (array) array of parameters for clipping function
26055 * @return object style
26056 * @author Nicola Asuni
26057 * @since 5.0.000 (2010-05-02)
26058 * @protected
26060 protected function setSVGStyles($svgstyle, $prevsvgstyle, $x=0, $y=0, $w=1, $h=1, $clip_function='', $clip_params=array()) {
26061 $objstyle = '';
26062 $minlen = (0.01 / $this->k); // minimum acceptable length (3 point)
26063 if (!isset($svgstyle['opacity'])) {
26064 return $objstyle;
26066 // clip-path
26067 $regs = array();
26068 if (preg_match('/url\([\s]*\#([^\)]*)\)/si', $svgstyle['clip-path'], $regs)) {
26069 $clip_path = $this->svgclippaths[$regs[1]];
26070 foreach ($clip_path as $cp) {
26071 $this->startSVGElementHandler('clip-path', $cp['name'], $cp['attribs'], $cp['tm']);
26074 // opacity
26075 if ($svgstyle['opacity'] != 1) {
26076 $this->SetAlpha($svgstyle['opacity']);
26078 // color
26079 $fill_color = $this->convertHTMLColorToDec($svgstyle['color']);
26080 $this->SetFillColorArray($fill_color);
26081 // text color
26082 $text_color = $this->convertHTMLColorToDec($svgstyle['text-color']);
26083 $this->SetTextColorArray($text_color);
26084 // clip
26085 if (preg_match('/rect\(([a-z0-9\-\.]*)[\s]*([a-z0-9\-\.]*)[\s]*([a-z0-9\-\.]*)[\s]*([a-z0-9\-\.]*)\)/si', $svgstyle['clip'], $regs)) {
26086 $top = (isset($regs[1])?$this->getHTMLUnitToUnits($regs[1], 0, $this->svgunit, false):0);
26087 $right = (isset($regs[2])?$this->getHTMLUnitToUnits($regs[2], 0, $this->svgunit, false):0);
26088 $bottom = (isset($regs[3])?$this->getHTMLUnitToUnits($regs[3], 0, $this->svgunit, false):0);
26089 $left = (isset($regs[4])?$this->getHTMLUnitToUnits($regs[4], 0, $this->svgunit, false):0);
26090 $cx = $x + $left;
26091 $cy = $y + $top;
26092 $cw = $w - $left - $right;
26093 $ch = $h - $top - $bottom;
26094 if ($svgstyle['clip-rule'] == 'evenodd') {
26095 $clip_rule = 'CNZ';
26096 } else {
26097 $clip_rule = 'CEO';
26099 $this->Rect($cx, $cy, $cw, $ch, $clip_rule, array(), array());
26101 // fill
26102 $regs = array();
26103 if (preg_match('/url\([\s]*\#([^\)]*)\)/si', $svgstyle['fill'], $regs)) {
26104 // gradient
26105 $gradient = $this->svggradients[$regs[1]];
26106 if (isset($gradient['xref'])) {
26107 // reference to another gradient definition
26108 $newgradient = $this->svggradients[$gradient['xref']];
26109 $newgradient['coords'] = $gradient['coords'];
26110 $newgradient['mode'] = $gradient['mode'];
26111 $newgradient['gradientUnits'] = $gradient['gradientUnits'];
26112 if (isset($gradient['gradientTransform'])) {
26113 $newgradient['gradientTransform'] = $gradient['gradientTransform'];
26115 $gradient = $newgradient;
26117 //save current Graphic State
26118 $this->_out('q');
26119 //set clipping area
26120 if (!empty($clip_function) AND method_exists($this, $clip_function)) {
26121 $bbox = call_user_func_array(array($this, $clip_function), $clip_params);
26122 if (is_array($bbox) AND (count($bbox) == 4)) {
26123 list($x, $y, $w, $h) = $bbox;
26126 if ($gradient['mode'] == 'measure') {
26127 if (isset($gradient['gradientTransform']) AND !empty($gradient['gradientTransform'])) {
26128 $gtm = $gradient['gradientTransform'];
26129 // apply transformation matrix
26130 $xa = ($gtm[0] * $gradient['coords'][0]) + ($gtm[2] * $gradient['coords'][1]) + $gtm[4];
26131 $ya = ($gtm[1] * $gradient['coords'][0]) + ($gtm[3] * $gradient['coords'][1]) + $gtm[5];
26132 $xb = ($gtm[0] * $gradient['coords'][2]) + ($gtm[2] * $gradient['coords'][3]) + $gtm[4];
26133 $yb = ($gtm[1] * $gradient['coords'][2]) + ($gtm[3] * $gradient['coords'][3]) + $gtm[5];
26134 if (isset($gradient['coords'][4])) {
26135 $gradient['coords'][4] = sqrt(pow(($gtm[0] * $gradient['coords'][4]), 2) + pow(($gtm[1] * $gradient['coords'][4]), 2));
26137 $gradient['coords'][0] = $xa;
26138 $gradient['coords'][1] = $ya;
26139 $gradient['coords'][2] = $xb;
26140 $gradient['coords'][3] = $yb;
26142 // convert SVG coordinates to user units
26143 $gradient['coords'][0] = $this->getHTMLUnitToUnits($gradient['coords'][0], 0, $this->svgunit, false);
26144 $gradient['coords'][1] = $this->getHTMLUnitToUnits($gradient['coords'][1], 0, $this->svgunit, false);
26145 $gradient['coords'][2] = $this->getHTMLUnitToUnits($gradient['coords'][2], 0, $this->svgunit, false);
26146 $gradient['coords'][3] = $this->getHTMLUnitToUnits($gradient['coords'][3], 0, $this->svgunit, false);
26147 if (isset($gradient['coords'][4])) {
26148 $gradient['coords'][4] = $this->getHTMLUnitToUnits($gradient['coords'][4], 0, $this->svgunit, false);
26150 // shift units
26151 if ($gradient['gradientUnits'] == 'objectBoundingBox') {
26152 // convert to SVG coordinate system
26153 $gradient['coords'][0] += $x;
26154 $gradient['coords'][1] += $y;
26155 $gradient['coords'][2] += $x;
26156 $gradient['coords'][3] += $y;
26158 if ($w <= $minlen) {
26159 $w = $minlen;
26161 if ($h <= $minlen) {
26162 $h = $minlen;
26164 // calculate percentages
26165 $gradient['coords'][0] = ($gradient['coords'][0] - $x) / $w;
26166 $gradient['coords'][1] = ($gradient['coords'][1] - $y) / $h;
26167 $gradient['coords'][2] = ($gradient['coords'][2] - $x) / $w;
26168 $gradient['coords'][3] = ($gradient['coords'][3] - $y) / $h;
26169 if (isset($gradient['coords'][4])) {
26170 $gradient['coords'][4] /= $w;
26172 } elseif ($gradient['mode'] == 'percentage') {
26173 foreach($gradient['coords'] as $key => $val) {
26174 $gradient['coords'][$key] = (intval($val) / 100);
26177 // fix values
26178 foreach($gradient['coords'] as $key => $val) {
26179 if ($val < 0) {
26180 $gradient['coords'][$key] = 0;
26181 } elseif ($val > 1) {
26182 $gradient['coords'][$key] = 1;
26185 if (($gradient['type'] == 2) AND ($gradient['coords'][0] == $gradient['coords'][2]) AND ($gradient['coords'][1] == $gradient['coords'][3])) {
26186 // single color (no shading)
26187 $gradient['coords'][0] = 1;
26188 $gradient['coords'][1] = 0;
26189 $gradient['coords'][2] = 0.999;
26190 $gradient['coords'][3] = 0;
26192 // swap Y coordinates
26193 $tmp = $gradient['coords'][1];
26194 $gradient['coords'][1] = $gradient['coords'][3];
26195 $gradient['coords'][3] = $tmp;
26196 // set transformation map for gradient
26197 if ($gradient['type'] == 3) {
26198 // gradient is always circular
26199 $cy = $this->h - $y - ($gradient['coords'][1] * ($w + $h));
26200 $this->_out(sprintf('%.3F 0 0 %.3F %.3F %.3F cm', $w*$this->k, $w*$this->k, $x*$this->k, $cy*$this->k));
26201 } else {
26202 $this->_out(sprintf('%.3F 0 0 %.3F %.3F %.3F cm', $w*$this->k, $h*$this->k, $x*$this->k, ($this->h-($y+$h))*$this->k));
26204 if (count($gradient['stops']) > 1) {
26205 $this->Gradient($gradient['type'], $gradient['coords'], $gradient['stops'], array(), false);
26207 } elseif ($svgstyle['fill'] != 'none') {
26208 $fill_color = $this->convertHTMLColorToDec($svgstyle['fill']);
26209 if ($svgstyle['fill-opacity'] != 1) {
26210 $this->SetAlpha($svgstyle['fill-opacity']);
26212 $this->SetFillColorArray($fill_color);
26213 if ($svgstyle['fill-rule'] == 'evenodd') {
26214 $objstyle .= 'F*';
26215 } else {
26216 $objstyle .= 'F';
26219 // stroke
26220 if ($svgstyle['stroke'] != 'none') {
26221 $stroke_style = array(
26222 'color' => $this->convertHTMLColorToDec($svgstyle['stroke']),
26223 'width' => $this->getHTMLUnitToUnits($svgstyle['stroke-width'], 0, $this->svgunit, false),
26224 'cap' => $svgstyle['stroke-linecap'],
26225 'join' => $svgstyle['stroke-linejoin']
26227 if (isset($svgstyle['stroke-dasharray']) AND !empty($svgstyle['stroke-dasharray']) AND ($svgstyle['stroke-dasharray'] != 'none')) {
26228 $stroke_style['dash'] = $svgstyle['stroke-dasharray'];
26230 $this->SetLineStyle($stroke_style);
26231 $objstyle .= 'D';
26233 // font
26234 $regs = array();
26235 if (!empty($svgstyle['font'])) {
26236 if (preg_match('/font-family[\s]*:[\s]*([^\;\"]*)/si', $svgstyle['font'], $regs)) {
26237 $font_family = $this->getFontFamilyName($regs[1]);
26238 } else {
26239 $font_family = $svgstyle['font-family'];
26241 if (preg_match('/font-size[\s]*:[\s]*([^\s\;\"]*)/si', $svgstyle['font'], $regs)) {
26242 $font_size = trim($regs[1]);
26243 } else {
26244 $font_size = $svgstyle['font-size'];
26246 if (preg_match('/font-style[\s]*:[\s]*([^\s\;\"]*)/si', $svgstyle['font'], $regs)) {
26247 $font_style = trim($regs[1]);
26248 } else {
26249 $font_style = $svgstyle['font-style'];
26251 if (preg_match('/font-weight[\s]*:[\s]*([^\s\;\"]*)/si', $svgstyle['font'], $regs)) {
26252 $font_weight = trim($regs[1]);
26253 } else {
26254 $font_weight = $svgstyle['font-weight'];
26256 if (preg_match('/font-stretch[\s]*:[\s]*([^\s\;\"]*)/si', $svgstyle['font'], $regs)) {
26257 $font_stretch = trim($regs[1]);
26258 } else {
26259 $font_stretch = $svgstyle['font-stretch'];
26261 if (preg_match('/letter-spacing[\s]*:[\s]*([^\s\;\"]*)/si', $svgstyle['font'], $regs)) {
26262 $font_spacing = trim($regs[1]);
26263 } else {
26264 $font_spacing = $svgstyle['letter-spacing'];
26266 } else {
26267 $font_family = $this->getFontFamilyName($svgstyle['font-family']);
26268 $font_size = $svgstyle['font-size'];
26269 $font_style = $svgstyle['font-style'];
26270 $font_weight = $svgstyle['font-weight'];
26271 $font_stretch = $svgstyle['font-stretch'];
26272 $font_spacing = $svgstyle['letter-spacing'];
26274 $font_size = $this->getHTMLUnitToUnits($font_size, $prevsvgstyle['font-size'], $this->svgunit, false) * $this->k;
26275 $font_stretch = $this->getCSSFontStretching($font_stretch, $svgstyle['font-stretch']);
26276 $font_spacing = $this->getCSSFontSpacing($font_spacing, $svgstyle['letter-spacing']);
26277 switch ($font_style) {
26278 case 'italic': {
26279 $font_style = 'I';
26280 break;
26282 case 'oblique': {
26283 $font_style = 'I';
26284 break;
26286 default:
26287 case 'normal': {
26288 $font_style = '';
26289 break;
26292 switch ($font_weight) {
26293 case 'bold':
26294 case 'bolder': {
26295 $font_style .= 'B';
26296 break;
26299 switch ($svgstyle['text-decoration']) {
26300 case 'underline': {
26301 $font_style .= 'U';
26302 break;
26304 case 'overline': {
26305 $font_style .= 'O';
26306 break;
26308 case 'line-through': {
26309 $font_style .= 'D';
26310 break;
26312 default:
26313 case 'none': {
26314 break;
26317 $this->SetFont($font_family, $font_style, $font_size);
26318 $this->setFontStretching($font_stretch);
26319 $this->setFontSpacing($font_spacing);
26320 return $objstyle;
26324 * Draws an SVG path
26325 * @param $d (string) attribute d of the path SVG element
26326 * @param $style (string) Style of rendering. Possible values are:
26327 * <ul>
26328 * <li>D or empty string: Draw (default).</li>
26329 * <li>F: Fill.</li>
26330 * <li>F*: Fill using the even-odd rule to determine which regions lie inside the clipping path.</li>
26331 * <li>DF or FD: Draw and fill.</li>
26332 * <li>DF* or FD*: Draw and fill using the even-odd rule to determine which regions lie inside the clipping path.</li>
26333 * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
26334 * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
26335 * </ul>
26336 * @return array of container box measures (x, y, w, h)
26337 * @author Nicola Asuni
26338 * @since 5.0.000 (2010-05-02)
26339 * @protected
26341 protected function SVGPath($d, $style='') {
26342 // set fill/stroke style
26343 $op = $this->getPathPaintOperator($style, '');
26344 if (empty($op)) {
26345 return;
26347 $paths = array();
26348 $d = preg_replace('/([0-9ACHLMQSTVZ])([\-\+])/si', '\\1 \\2', $d);
26349 preg_match_all('/([ACHLMQSTVZ])[\s]*([^ACHLMQSTVZ\"]*)/si', $d, $paths, PREG_SET_ORDER);
26350 $x = 0;
26351 $y = 0;
26352 $x1 = 0;
26353 $y1 = 0;
26354 $x2 = 0;
26355 $y2 = 0;
26356 $xmin = 2147483647;
26357 $xmax = 0;
26358 $ymin = 2147483647;
26359 $ymax = 0;
26360 $relcoord = false;
26361 $minlen = (0.01 / $this->k); // minimum acceptable length (3 point)
26362 $firstcmd = true; // used to print first point
26363 // draw curve pieces
26364 foreach ($paths as $key => $val) {
26365 // get curve type
26366 $cmd = trim($val[1]);
26367 if (strtolower($cmd) == $cmd) {
26368 // use relative coordinated instead of absolute
26369 $relcoord = true;
26370 $xoffset = $x;
26371 $yoffset = $y;
26372 } else {
26373 $relcoord = false;
26374 $xoffset = 0;
26375 $yoffset = 0;
26377 $params = array();
26378 if (isset($val[2])) {
26379 // get curve parameters
26380 $rawparams = preg_split('/([\,\s]+)/si', trim($val[2]));
26381 $params = array();
26382 foreach ($rawparams as $ck => $cp) {
26383 $params[$ck] = $this->getHTMLUnitToUnits($cp, 0, $this->svgunit, false);
26384 if (abs($params[$ck]) < $minlen) {
26385 // aproximate little values to zero
26386 $params[$ck] = 0;
26390 // store current origin point
26391 $x0 = $x;
26392 $y0 = $y;
26393 switch (strtoupper($cmd)) {
26394 case 'M': { // moveto
26395 foreach ($params as $ck => $cp) {
26396 if (($ck % 2) == 0) {
26397 $x = $cp + $xoffset;
26398 } else {
26399 $y = $cp + $yoffset;
26400 if ($firstcmd OR (abs($x0 - $x) >= $minlen) OR (abs($y0 - $y) >= $minlen)) {
26401 if ($ck == 1) {
26402 $this->_outPoint($x, $y);
26403 $firstcmd = false;
26404 } else {
26405 $this->_outLine($x, $y);
26408 $xmin = min($xmin, $x);
26409 $ymin = min($ymin, $y);
26410 $xmax = max($xmax, $x);
26411 $ymax = max($ymax, $y);
26412 if ($relcoord) {
26413 $xoffset = $x;
26414 $yoffset = $y;
26418 break;
26420 case 'L': { // lineto
26421 foreach ($params as $ck => $cp) {
26422 if (($ck % 2) == 0) {
26423 $x = $cp + $xoffset;
26424 } else {
26425 $y = $cp + $yoffset;
26426 if ((abs($x0 - $x) >= $minlen) OR (abs($y0 - $y) >= $minlen)) {
26427 $this->_outLine($x, $y);
26429 $xmin = min($xmin, $x);
26430 $ymin = min($ymin, $y);
26431 $xmax = max($xmax, $x);
26432 $ymax = max($ymax, $y);
26433 if ($relcoord) {
26434 $xoffset = $x;
26435 $yoffset = $y;
26439 break;
26441 case 'H': { // horizontal lineto
26442 foreach ($params as $ck => $cp) {
26443 $x = $cp + $xoffset;
26444 if ((abs($x0 - $x) >= $minlen) OR (abs($y0 - $y) >= $minlen)) {
26445 $this->_outLine($x, $y);
26447 $xmin = min($xmin, $x);
26448 $xmax = max($xmax, $x);
26449 if ($relcoord) {
26450 $xoffset = $x;
26453 break;
26455 case 'V': { // vertical lineto
26456 foreach ($params as $ck => $cp) {
26457 $y = $cp + $yoffset;
26458 if ((abs($x0 - $x) >= $minlen) OR (abs($y0 - $y) >= $minlen)) {
26459 $this->_outLine($x, $y);
26461 $ymin = min($ymin, $y);
26462 $ymax = max($ymax, $y);
26463 if ($relcoord) {
26464 $yoffset = $y;
26467 break;
26469 case 'C': { // curveto
26470 foreach ($params as $ck => $cp) {
26471 $params[$ck] = $cp;
26472 if ((($ck + 1) % 6) == 0) {
26473 $x1 = $params[($ck - 5)] + $xoffset;
26474 $y1 = $params[($ck - 4)] + $yoffset;
26475 $x2 = $params[($ck - 3)] + $xoffset;
26476 $y2 = $params[($ck - 2)] + $yoffset;
26477 $x = $params[($ck - 1)] + $xoffset;
26478 $y = $params[($ck)] + $yoffset;
26479 $this->_outCurve($x1, $y1, $x2, $y2, $x, $y);
26480 $xmin = min($xmin, $x, $x1, $x2);
26481 $ymin = min($ymin, $y, $y1, $y2);
26482 $xmax = max($xmax, $x, $x1, $x2);
26483 $ymax = max($ymax, $y, $y1, $y2);
26484 if ($relcoord) {
26485 $xoffset = $x;
26486 $yoffset = $y;
26490 break;
26492 case 'S': { // shorthand/smooth curveto
26493 foreach ($params as $ck => $cp) {
26494 $params[$ck] = $cp;
26495 if ((($ck + 1) % 4) == 0) {
26496 if (($key > 0) AND ((strtoupper($paths[($key - 1)][1]) == 'C') OR (strtoupper($paths[($key - 1)][1]) == 'S'))) {
26497 $x1 = (2 * $x) - $x2;
26498 $y1 = (2 * $y) - $y2;
26499 } else {
26500 $x1 = $x;
26501 $y1 = $y;
26503 $x2 = $params[($ck - 3)] + $xoffset;
26504 $y2 = $params[($ck - 2)] + $yoffset;
26505 $x = $params[($ck - 1)] + $xoffset;
26506 $y = $params[($ck)] + $yoffset;
26507 $this->_outCurve($x1, $y1, $x2, $y2, $x, $y);
26508 $xmin = min($xmin, $x, $x1, $x2);
26509 $ymin = min($ymin, $y, $y1, $y2);
26510 $xmax = max($xmax, $x, $x1, $x2);
26511 $ymax = max($ymax, $y, $y1, $y2);
26512 if ($relcoord) {
26513 $xoffset = $x;
26514 $yoffset = $y;
26518 break;
26520 case 'Q': { // quadratic Bézier curveto
26521 foreach ($params as $ck => $cp) {
26522 $params[$ck] = $cp;
26523 if ((($ck + 1) % 4) == 0) {
26524 // convert quadratic points to cubic points
26525 $x1 = $params[($ck - 3)] + $xoffset;
26526 $y1 = $params[($ck - 2)] + $yoffset;
26527 $xa = ($x + (2 * $x1)) / 3;
26528 $ya = ($y + (2 * $y1)) / 3;
26529 $x = $params[($ck - 1)] + $xoffset;
26530 $y = $params[($ck)] + $yoffset;
26531 $xb = ($x + (2 * $x1)) / 3;
26532 $yb = ($y + (2 * $y1)) / 3;
26533 $this->_outCurve($xa, $ya, $xb, $yb, $x, $y);
26534 $xmin = min($xmin, $x, $xa, $xb);
26535 $ymin = min($ymin, $y, $ya, $yb);
26536 $xmax = max($xmax, $x, $xa, $xb);
26537 $ymax = max($ymax, $y, $ya, $yb);
26538 if ($relcoord) {
26539 $xoffset = $x;
26540 $yoffset = $y;
26544 break;
26546 case 'T': { // shorthand/smooth quadratic Bézier curveto
26547 foreach ($params as $ck => $cp) {
26548 $params[$ck] = $cp;
26549 if (($ck % 2) != 0) {
26550 if (($key > 0) AND ((strtoupper($paths[($key - 1)][1]) == 'Q') OR (strtoupper($paths[($key - 1)][1]) == 'T'))) {
26551 $x1 = (2 * $x) - $x1;
26552 $y1 = (2 * $y) - $y1;
26553 } else {
26554 $x1 = $x;
26555 $y1 = $y;
26557 // convert quadratic points to cubic points
26558 $xa = ($x + (2 * $x1)) / 3;
26559 $ya = ($y + (2 * $y1)) / 3;
26560 $x = $params[($ck - 1)] + $xoffset;
26561 $y = $params[($ck)] + $yoffset;
26562 $xb = ($x + (2 * $x1)) / 3;
26563 $yb = ($y + (2 * $y1)) / 3;
26564 $this->_outCurve($xa, $ya, $xb, $yb, $x, $y);
26565 $xmin = min($xmin, $x, $xa, $xb);
26566 $ymin = min($ymin, $y, $ya, $yb);
26567 $xmax = max($xmax, $x, $xa, $xb);
26568 $ymax = max($ymax, $y, $ya, $yb);
26569 if ($relcoord) {
26570 $xoffset = $x;
26571 $yoffset = $y;
26575 break;
26577 case 'A': { // elliptical arc
26578 foreach ($params as $ck => $cp) {
26579 $params[$ck] = $cp;
26580 if ((($ck + 1) % 7) == 0) {
26581 $x0 = $x;
26582 $y0 = $y;
26583 $rx = abs($params[($ck - 6)]);
26584 $ry = abs($params[($ck - 5)]);
26585 $ang = -$rawparams[($ck - 4)];
26586 $angle = deg2rad($ang);
26587 $fa = $rawparams[($ck - 3)]; // large-arc-flag
26588 $fs = $rawparams[($ck - 2)]; // sweep-flag
26589 $x = $params[($ck - 1)] + $xoffset;
26590 $y = $params[$ck] + $yoffset;
26591 if ((abs($x0 - $x) < $minlen) AND (abs($y0 - $y) < $minlen)) {
26592 // endpoints are almost identical
26593 $xmin = min($xmin, $x);
26594 $ymin = min($ymin, $y);
26595 $xmax = max($xmax, $x);
26596 $ymax = max($ymax, $y);
26597 } else {
26598 $cos_ang = cos($angle);
26599 $sin_ang = sin($angle);
26600 $a = (($x0 - $x) / 2);
26601 $b = (($y0 - $y) / 2);
26602 $xa = ($a * $cos_ang) - ($b * $sin_ang);
26603 $ya = ($a * $sin_ang) + ($b * $cos_ang);
26604 $rx2 = $rx * $rx;
26605 $ry2 = $ry * $ry;
26606 $xa2 = $xa * $xa;
26607 $ya2 = $ya * $ya;
26608 $delta = ($xa2 / $rx2) + ($ya2 / $ry2);
26609 if ($delta > 1) {
26610 $rx *= sqrt($delta);
26611 $ry *= sqrt($delta);
26612 $rx2 = $rx * $rx;
26613 $ry2 = $ry * $ry;
26615 $numerator = (($rx2 * $ry2) - ($rx2 * $ya2) - ($ry2 * $xa2));
26616 if ($numerator < 0) {
26617 $root = 0;
26618 } else {
26619 $root = sqrt($numerator / (($rx2 * $ya2) + ($ry2 * $xa2)));
26621 if ($fa == $fs){
26622 $root *= -1;
26624 $cax = $root * (($rx * $ya) / $ry);
26625 $cay = -$root * (($ry * $xa) / $rx);
26626 // coordinates of ellipse center
26627 $cx = ($cax * $cos_ang) - ($cay * $sin_ang) + (($x0 + $x) / 2);
26628 $cy = ($cax * $sin_ang) + ($cay * $cos_ang) + (($y0 + $y) / 2);
26629 // get angles
26630 $angs = $this->getVectorsAngle(1, 0, (($xa - $cax) / $rx), (($cay - $ya) / $ry));
26631 $dang = $this->getVectorsAngle((($xa - $cax) / $rx), (($ya - $cay) / $ry), ((-$xa - $cax) / $rx), ((-$ya - $cay) / $ry));
26632 if (($fs == 0) AND ($dang > 0)) {
26633 $dang -= (2 * M_PI);
26634 } elseif (($fs == 1) AND ($dang < 0)) {
26635 $dang += (2 * M_PI);
26637 $angf = $angs - $dang;
26638 if ((($fs == 0) AND ($angs > $angf)) OR (($fs == 1) AND ($angs < $angf))) {
26639 // reverse angles
26640 $tmp = $angs;
26641 $angs = $angf;
26642 $angf = $tmp;
26644 $angs = round(rad2deg($angs), 6);
26645 $angf = round(rad2deg($angf), 6);
26646 // covent angles to positive values
26647 if (($angs < 0) AND ($angf < 0)) {
26648 $angs += 360;
26649 $angf += 360;
26651 $pie = false;
26652 if (($key == 0) AND (isset($paths[($key + 1)][1])) AND (trim($paths[($key + 1)][1]) == 'z')) {
26653 $pie = true;
26655 list($axmin, $aymin, $axmax, $aymax) = $this->_outellipticalarc($cx, $cy, $rx, $ry, $ang, $angs, $angf, $pie, 2, false, ($fs == 0), true);
26656 $xmin = min($xmin, $x, $axmin);
26657 $ymin = min($ymin, $y, $aymin);
26658 $xmax = max($xmax, $x, $axmax);
26659 $ymax = max($ymax, $y, $aymax);
26661 if ($relcoord) {
26662 $xoffset = $x;
26663 $yoffset = $y;
26667 break;
26669 case 'Z': {
26670 $this->_out('h');
26671 break;
26674 $firstcmd = false;
26675 } // end foreach
26676 if (!empty($op)) {
26677 $this->_out($op);
26679 return array($xmin, $ymin, ($xmax - $xmin), ($ymax - $ymin));
26683 * Returns the angle in radiants between two vectors
26684 * @param $x1 (int) X coordinate of first vector point
26685 * @param $y1 (int) Y coordinate of first vector point
26686 * @param $x2 (int) X coordinate of second vector point
26687 * @param $y2 (int) Y coordinate of second vector point
26688 * @author Nicola Asuni
26689 * @since 5.0.000 (2010-05-04)
26690 * @protected
26692 protected function getVectorsAngle($x1, $y1, $x2, $y2) {
26693 $dprod = ($x1 * $x2) + ($y1 * $y2);
26694 $dist1 = sqrt(($x1 * $x1) + ($y1 * $y1));
26695 $dist2 = sqrt(($x2 * $x2) + ($y2 * $y2));
26696 $angle = acos($dprod / ($dist1 * $dist2));
26697 if (is_nan($angle)) {
26698 $angle = M_PI;
26700 if ((($x1 * $y2) - ($x2 * $y1)) < 0) {
26701 $angle *= -1;
26703 return $angle;
26707 * Sets the opening SVG element handler function for the XML parser. (*** TO BE COMPLETED ***)
26708 * @param $parser (resource) The first parameter, parser, is a reference to the XML parser calling the handler.
26709 * @param $name (string) The second parameter, name, contains the name of the element for which this handler is called. If case-folding is in effect for this parser, the element name will be in uppercase letters.
26710 * @param $attribs (array) The third parameter, attribs, contains an associative array with the element's attributes (if any). The keys of this array are the attribute names, the values are the attribute values. Attribute names are case-folded on the same criteria as element names. Attribute values are not case-folded. The original order of the attributes can be retrieved by walking through attribs the normal way, using each(). The first key in the array was the first attribute, and so on.
26711 * @param $ctm (array) tranformation matrix for clipping mode (starting transformation matrix).
26712 * @author Nicola Asuni
26713 * @since 5.0.000 (2010-05-02)
26714 * @protected
26716 protected function startSVGElementHandler($parser, $name, $attribs, $ctm=array()) {
26717 // check if we are in clip mode
26718 if ($this->svgclipmode) {
26719 $this->svgclippaths[$this->svgclipid][] = array('name' => $name, 'attribs' => $attribs, 'tm' => $this->svgcliptm[$this->svgclipid]);
26720 return;
26722 if ($this->svgdefsmode AND !in_array($name, array('clipPath', 'linearGradient', 'radialGradient', 'stop'))) {
26723 if (!isset($attribs['id'])) {
26724 $attribs['id'] = 'DF_'.(count($this->svgdefs) + 1);
26726 $this->svgdefs[$attribs['id']] = array('name' => $name, 'attribs' => $attribs);
26727 return;
26729 $clipping = false;
26730 if ($parser == 'clip-path') {
26731 // set clipping mode
26732 $clipping = true;
26734 // get styling properties
26735 $prev_svgstyle = $this->svgstyles[(count($this->svgstyles) - 1)]; // previous style
26736 $svgstyle = $this->svgstyles[0]; // set default style
26737 if (isset($attribs['style']) AND !$this->empty_string($attribs['style'])) {
26738 // fix style for regular expression
26739 $attribs['style'] = ';'.$attribs['style'];
26741 foreach ($prev_svgstyle as $key => $val) {
26742 if (in_array($key, $this->svginheritprop)) {
26743 // inherit previous value
26744 $svgstyle[$key] = $val;
26746 if (isset($attribs[$key]) AND !$this->empty_string($attribs[$key])) {
26747 // specific attribute settings
26748 if ($attribs[$key] == 'inherit') {
26749 $svgstyle[$key] = $val;
26750 } else {
26751 $svgstyle[$key] = $attribs[$key];
26753 } elseif (isset($attribs['style']) AND !$this->empty_string($attribs['style'])) {
26754 // CSS style syntax
26755 $attrval = array();
26756 if (preg_match('/[;\"\s]{1}'.$key.'[\s]*:[\s]*([^;\"]*)/si', $attribs['style'], $attrval) AND isset($attrval[1])) {
26757 if ($attrval[1] == 'inherit') {
26758 $svgstyle[$key] = $val;
26759 } else {
26760 $svgstyle[$key] = $attrval[1];
26765 // transformation matrix
26766 if (!empty($ctm)) {
26767 $tm = $ctm;
26768 } else {
26769 $tm = $this->svgstyles[(count($this->svgstyles) - 1)]['transfmatrix'];
26771 if (isset($attribs['transform']) AND !empty($attribs['transform'])) {
26772 $tm = $this->getTransformationMatrixProduct($tm, $this->getSVGTransformMatrix($attribs['transform']));
26774 $svgstyle['transfmatrix'] = $tm;
26775 $invisible = false;
26776 if (($svgstyle['visibility'] == 'hidden') OR ($svgstyle['visibility'] == 'collapse') OR ($svgstyle['display'] == 'none')) {
26777 // the current graphics element is invisible (nothing is painted)
26778 $invisible = true;
26780 // process tag
26781 switch($name) {
26782 case 'defs': {
26783 $this->svgdefsmode = true;
26784 break;
26786 // clipPath
26787 case 'clipPath': {
26788 if ($invisible) {
26789 break;
26791 $this->svgclipmode = true;
26792 if (!isset($attribs['id'])) {
26793 $attribs['id'] = 'CP_'.(count($this->svgcliptm) + 1);
26795 $this->svgclipid = $attribs['id'];
26796 $this->svgclippaths[$this->svgclipid] = array();
26797 $this->svgcliptm[$this->svgclipid] = $tm;
26798 break;
26800 case 'svg': {
26801 // start of SVG object
26802 break;
26804 case 'g': {
26805 // group together related graphics elements
26806 array_push($this->svgstyles, $svgstyle);
26807 $this->StartTransform();
26808 $this->setSVGStyles($svgstyle, $prev_svgstyle);
26809 break;
26811 case 'linearGradient': {
26812 if (!isset($attribs['id'])) {
26813 $attribs['id'] = 'GR_'.(count($this->svggradients) + 1);
26815 $this->svggradientid = $attribs['id'];
26816 $this->svggradients[$this->svggradientid] = array();
26817 $this->svggradients[$this->svggradientid]['type'] = 2;
26818 $this->svggradients[$this->svggradientid]['stops'] = array();
26819 if (isset($attribs['gradientUnits'])) {
26820 $this->svggradients[$this->svggradientid]['gradientUnits'] = $attribs['gradientUnits'];
26821 } else {
26822 $this->svggradients[$this->svggradientid]['gradientUnits'] = 'objectBoundingBox';
26824 //$attribs['spreadMethod']
26825 $x1 = (isset($attribs['x1'])?$attribs['x1']:'0%');
26826 $y1 = (isset($attribs['y1'])?$attribs['y1']:'0%');
26827 $x2 = (isset($attribs['x2'])?$attribs['x2']:'100%');
26828 $y2 = (isset($attribs['y2'])?$attribs['y2']:'0%');
26829 if (substr($x1, -1) != '%') {
26830 $this->svggradients[$this->svggradientid]['mode'] = 'measure';
26831 } else {
26832 $this->svggradients[$this->svggradientid]['mode'] = 'percentage';
26834 if (isset($attribs['gradientTransform'])) {
26835 $this->svggradients[$this->svggradientid]['gradientTransform'] = $this->getSVGTransformMatrix($attribs['gradientTransform']);
26837 $this->svggradients[$this->svggradientid]['coords'] = array($x1, $y1, $x2, $y2);
26838 if (isset($attribs['xlink:href']) AND !empty($attribs['xlink:href'])) {
26839 // gradient is defined on another place
26840 $this->svggradients[$this->svggradientid]['xref'] = substr($attribs['xlink:href'], 1);
26842 break;
26844 case 'radialGradient': {
26845 if (!isset($attribs['id'])) {
26846 $attribs['id'] = 'GR_'.(count($this->svggradients) + 1);
26848 $this->svggradientid = $attribs['id'];
26849 $this->svggradients[$this->svggradientid] = array();
26850 $this->svggradients[$this->svggradientid]['type'] = 3;
26851 $this->svggradients[$this->svggradientid]['stops'] = array();
26852 if (isset($attribs['gradientUnits'])) {
26853 $this->svggradients[$this->svggradientid]['gradientUnits'] = $attribs['gradientUnits'];
26854 } else {
26855 $this->svggradients[$this->svggradientid]['gradientUnits'] = 'objectBoundingBox';
26857 //$attribs['spreadMethod']
26858 $cx = (isset($attribs['cx'])?$attribs['cx']:0.5);
26859 $cy = (isset($attribs['cy'])?$attribs['cy']:0.5);
26860 $fx = (isset($attribs['fx'])?$attribs['fx']:$cx);
26861 $fy = (isset($attribs['fy'])?$attribs['fy']:$cy);
26862 $r = (isset($attribs['r'])?$attribs['r']:0.5);
26863 if (isset($attribs['cx']) AND (substr($attribs['cx'], -1) != '%')) {
26864 $this->svggradients[$this->svggradientid]['mode'] = 'measure';
26865 } else {
26866 $this->svggradients[$this->svggradientid]['mode'] = 'percentage';
26868 if (isset($attribs['gradientTransform'])) {
26869 $this->svggradients[$this->svggradientid]['gradientTransform'] = $this->getSVGTransformMatrix($attribs['gradientTransform']);
26871 $this->svggradients[$this->svggradientid]['coords'] = array($cx, $cy, $fx, $fy, $r);
26872 if (isset($attribs['xlink:href']) AND !empty($attribs['xlink:href'])) {
26873 // gradient is defined on another place
26874 $this->svggradients[$this->svggradientid]['xref'] = substr($attribs['xlink:href'], 1);
26876 break;
26878 case 'stop': {
26879 // gradient stops
26880 if (substr($attribs['offset'], -1) == '%') {
26881 $offset = floatval(substr($attribs['offset'], -1)) / 100;
26882 } else {
26883 $offset = floatval($attribs['offset']);
26884 if ($offset > 1) {
26885 $offset /= 100;
26888 $stop_color = isset($svgstyle['stop-color'])?$this->convertHTMLColorToDec($svgstyle['stop-color']):'black';
26889 $opacity = isset($svgstyle['stop-opacity'])?$svgstyle['stop-opacity']:1;
26890 $this->svggradients[$this->svggradientid]['stops'][] = array('offset' => $offset, 'color' => $stop_color, 'opacity' => $opacity);
26891 break;
26893 // paths
26894 case 'path': {
26895 if ($invisible) {
26896 break;
26898 if (isset($attribs['d'])) {
26899 $d = trim($attribs['d']);
26900 if (!empty($d)) {
26901 if ($clipping) {
26902 $this->SVGTransform($tm);
26903 $this->SVGPath($d, 'CNZ');
26904 } else {
26905 $this->StartTransform();
26906 $this->SVGTransform($tm);
26907 $obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, 0, 0, 1, 1, 'SVGPath', array($d, 'CNZ'));
26908 if (!empty($obstyle)) {
26909 $this->SVGPath($d, $obstyle);
26911 $this->StopTransform();
26915 break;
26917 // shapes
26918 case 'rect': {
26919 if ($invisible) {
26920 break;
26922 $x = (isset($attribs['x'])?$this->getHTMLUnitToUnits($attribs['x'], 0, $this->svgunit, false):0);
26923 $y = (isset($attribs['y'])?$this->getHTMLUnitToUnits($attribs['y'], 0, $this->svgunit, false):0);
26924 $w = (isset($attribs['width'])?$this->getHTMLUnitToUnits($attribs['width'], 0, $this->svgunit, false):0);
26925 $h = (isset($attribs['height'])?$this->getHTMLUnitToUnits($attribs['height'], 0, $this->svgunit, false):0);
26926 $rx = (isset($attribs['rx'])?$this->getHTMLUnitToUnits($attribs['rx'], 0, $this->svgunit, false):0);
26927 $ry = (isset($attribs['ry'])?$this->getHTMLUnitToUnits($attribs['ry'], 0, $this->svgunit, false):$rx);
26928 if ($clipping) {
26929 $this->SVGTransform($tm);
26930 $this->RoundedRectXY($x, $y, $w, $h, $rx, $ry, '1111', 'CNZ', array(), array());
26931 } else {
26932 $this->StartTransform();
26933 $this->SVGTransform($tm);
26934 $obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h, 'RoundedRectXY', array($x, $y, $w, $h, $rx, $ry, '1111', 'CNZ'));
26935 if (!empty($obstyle)) {
26936 $this->RoundedRectXY($x, $y, $w, $h, $rx, $ry, '1111', $obstyle, array(), array());
26938 $this->StopTransform();
26940 break;
26942 case 'circle': {
26943 if ($invisible) {
26944 break;
26946 $cx = (isset($attribs['cx'])?$this->getHTMLUnitToUnits($attribs['cx'], 0, $this->svgunit, false):0);
26947 $cy = (isset($attribs['cy'])?$this->getHTMLUnitToUnits($attribs['cy'], 0, $this->svgunit, false):0);
26948 $r = (isset($attribs['r'])?$this->getHTMLUnitToUnits($attribs['r'], 0, $this->svgunit, false):0);
26949 $x = $cx - $r;
26950 $y = $cy - $r;
26951 $w = 2 * $r;
26952 $h = $w;
26953 if ($clipping) {
26954 $this->SVGTransform($tm);
26955 $this->Circle($cx, $cy, $r, 0, 360, 'CNZ', array(), array(), 8);
26956 } else {
26957 $this->StartTransform();
26958 $this->SVGTransform($tm);
26959 $obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h, 'Circle', array($cx, $cy, $r, 0, 360, 'CNZ'));
26960 if (!empty($obstyle)) {
26961 $this->Circle($cx, $cy, $r, 0, 360, $obstyle, array(), array(), 8);
26963 $this->StopTransform();
26965 break;
26967 case 'ellipse': {
26968 if ($invisible) {
26969 break;
26971 $cx = (isset($attribs['cx'])?$this->getHTMLUnitToUnits($attribs['cx'], 0, $this->svgunit, false):0);
26972 $cy = (isset($attribs['cy'])?$this->getHTMLUnitToUnits($attribs['cy'], 0, $this->svgunit, false):0);
26973 $rx = (isset($attribs['rx'])?$this->getHTMLUnitToUnits($attribs['rx'], 0, $this->svgunit, false):0);
26974 $ry = (isset($attribs['ry'])?$this->getHTMLUnitToUnits($attribs['ry'], 0, $this->svgunit, false):0);
26975 $x = $cx - $rx;
26976 $y = $cy - $ry;
26977 $w = 2 * $rx;
26978 $h = 2 * $ry;
26979 if ($clipping) {
26980 $this->SVGTransform($tm);
26981 $this->Ellipse($cx, $cy, $rx, $ry, 0, 0, 360, 'CNZ', array(), array(), 8);
26982 } else {
26983 $this->StartTransform();
26984 $this->SVGTransform($tm);
26985 $obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h, 'Ellipse', array($cx, $cy, $rx, $ry, 0, 0, 360, 'CNZ'));
26986 if (!empty($obstyle)) {
26987 $this->Ellipse($cx, $cy, $rx, $ry, 0, 0, 360, $obstyle, array(), array(), 8);
26989 $this->StopTransform();
26991 break;
26993 case 'line': {
26994 if ($invisible) {
26995 break;
26997 $x1 = (isset($attribs['x1'])?$this->getHTMLUnitToUnits($attribs['x1'], 0, $this->svgunit, false):0);
26998 $y1 = (isset($attribs['y1'])?$this->getHTMLUnitToUnits($attribs['y1'], 0, $this->svgunit, false):0);
26999 $x2 = (isset($attribs['x2'])?$this->getHTMLUnitToUnits($attribs['x2'], 0, $this->svgunit, false):0);
27000 $y2 = (isset($attribs['y2'])?$this->getHTMLUnitToUnits($attribs['y2'], 0, $this->svgunit, false):0);
27001 $x = $x1;
27002 $y = $y1;
27003 $w = abs($x2 - $x1);
27004 $h = abs($y2 - $y1);
27005 if (!$clipping) {
27006 $this->StartTransform();
27007 $this->SVGTransform($tm);
27008 $obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h, 'Line', array($x1, $y1, $x2, $y2));
27009 $this->Line($x1, $y1, $x2, $y2);
27010 $this->StopTransform();
27012 break;
27014 case 'polyline':
27015 case 'polygon': {
27016 if ($invisible) {
27017 break;
27019 $points = (isset($attribs['points'])?$attribs['points']:'0 0');
27020 $points = trim($points);
27021 // note that point may use a complex syntax not covered here
27022 $points = preg_split('/[\,\s]+/si', $points);
27023 if (count($points) < 4) {
27024 break;
27026 $p = array();
27027 $xmin = 2147483647;
27028 $xmax = 0;
27029 $ymin = 2147483647;
27030 $ymax = 0;
27031 foreach ($points as $key => $val) {
27032 $p[$key] = $this->getHTMLUnitToUnits($val, 0, $this->svgunit, false);
27033 if (($key % 2) == 0) {
27034 // X coordinate
27035 $xmin = min($xmin, $p[$key]);
27036 $xmax = max($xmax, $p[$key]);
27037 } else {
27038 // Y coordinate
27039 $ymin = min($ymin, $p[$key]);
27040 $ymax = max($ymax, $p[$key]);
27043 $x = $xmin;
27044 $y = $ymin;
27045 $w = ($xmax - $xmin);
27046 $h = ($ymax - $ymin);
27047 if ($name == 'polyline') {
27048 $this->StartTransform();
27049 $this->SVGTransform($tm);
27050 $obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h, 'PolyLine', array($p, 'CNZ'));
27051 $this->PolyLine($p, 'D', array(), array());
27052 $this->StopTransform();
27053 } else { // polygon
27054 if ($clipping) {
27055 $this->SVGTransform($tm);
27056 $this->Polygon($p, 'CNZ', array(), array(), true);
27057 } else {
27058 $this->StartTransform();
27059 $this->SVGTransform($tm);
27060 $obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h, 'Polygon', array($p, 'CNZ'));
27061 if (!empty($obstyle)) {
27062 $this->Polygon($p, $obstyle, array(), array(), true);
27064 $this->StopTransform();
27067 break;
27069 // image
27070 case 'image': {
27071 if ($invisible) {
27072 break;
27074 if (!isset($attribs['xlink:href']) OR empty($attribs['xlink:href'])) {
27075 break;
27077 $x = (isset($attribs['x'])?$this->getHTMLUnitToUnits($attribs['x'], 0, $this->svgunit, false):0);
27078 $y = (isset($attribs['y'])?$this->getHTMLUnitToUnits($attribs['y'], 0, $this->svgunit, false):0);
27079 $w = (isset($attribs['width'])?$this->getHTMLUnitToUnits($attribs['width'], 0, $this->svgunit, false):0);
27080 $h = (isset($attribs['height'])?$this->getHTMLUnitToUnits($attribs['height'], 0, $this->svgunit, false):0);
27081 $img = $attribs['xlink:href'];
27082 if (!$clipping) {
27083 $this->StartTransform();
27084 $this->SVGTransform($tm);
27085 $obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h);
27086 // fix image path
27087 if (!$this->empty_string($this->svgdir) AND (($img{0} == '.') OR (basename($img) == $img))) {
27088 // replace relative path with full server path
27089 $img = $this->svgdir.'/'.$img;
27091 if (($img[0] == '/') AND !empty($_SERVER['DOCUMENT_ROOT']) AND ($_SERVER['DOCUMENT_ROOT'] != '/')) {
27092 $findroot = strpos($img, $_SERVER['DOCUMENT_ROOT']);
27093 if (($findroot === false) OR ($findroot > 1)) {
27094 if (substr($_SERVER['DOCUMENT_ROOT'], -1) == '/') {
27095 $img = substr($_SERVER['DOCUMENT_ROOT'], 0, -1).$img;
27096 } else {
27097 $img = $_SERVER['DOCUMENT_ROOT'].$img;
27101 $img = urldecode($img);
27102 $testscrtype = @parse_url($img);
27103 if (!isset($testscrtype['query']) OR empty($testscrtype['query'])) {
27104 // convert URL to server path
27105 $img = str_replace(K_PATH_URL, K_PATH_MAIN, $img);
27107 $this->Image($img, $x, $y, $w, $h);
27108 $this->StopTransform();
27110 break;
27112 // text
27113 case 'text':
27114 case 'tspan': {
27115 $this->svgtextmode['invisible'] = $invisible;
27116 if ($invisible) {
27117 break;
27119 array_push($this->svgstyles, $svgstyle);
27120 // only basic support - advanced features must be implemented
27121 $x = (isset($attribs['x'])?$this->getHTMLUnitToUnits($attribs['x'], 0, $this->svgunit, false):$this->x);
27122 $y = (isset($attribs['y'])?$this->getHTMLUnitToUnits($attribs['y'], 0, $this->svgunit, false):$this->y);
27123 $svgstyle['text-color'] = $svgstyle['fill'];
27124 $this->svgtext = '';
27125 if (isset($svgstyle['text-anchor'])) {
27126 $this->svgtextmode['text-anchor'] = $svgstyle['text-anchor'];
27127 } else {
27128 $this->svgtextmode['text-anchor'] = 'start';
27130 if (isset($svgstyle['direction'])) {
27131 if ($svgstyle['direction'] == 'rtl') {
27132 $this->svgtextmode['rtl'] = true;
27133 } else {
27134 $this->svgtextmode['rtl'] = false;
27136 } else {
27137 $this->svgtextmode['rtl'] = false;
27139 if (isset($svgstyle['stroke']) AND ($svgstyle['stroke'] != 'none') AND isset($svgstyle['stroke-width']) AND ($svgstyle['stroke-width'] > 0)) {
27140 $this->svgtextmode['stroke'] = $this->getHTMLUnitToUnits($svgstyle['stroke-width'], 0, $this->svgunit, false);
27141 } else {
27142 $this->svgtextmode['stroke'] = false;
27144 $this->StartTransform();
27145 $this->SVGTransform($tm);
27146 $obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, 1, 1);
27147 $this->x = $x;
27148 $this->y = $y;
27149 break;
27151 // use
27152 case 'use': {
27153 if (isset($attribs['xlink:href'])) {
27154 $use = $this->svgdefs[substr($attribs['xlink:href'], 1)];
27155 if (isset($attribs['xlink:href'])) {
27156 unset($attribs['xlink:href']);
27158 if (isset($attribs['id'])) {
27159 unset($attribs['id']);
27161 $attribs = array_merge($use['attribs'], $attribs);
27162 $this->startSVGElementHandler($parser, $use['name'], $use['attribs']);
27164 break;
27166 default: {
27167 break;
27169 } // end of switch
27173 * Sets the closing SVG element handler function for the XML parser.
27174 * @param $parser (resource) The first parameter, parser, is a reference to the XML parser calling the handler.
27175 * @param $name (string) The second parameter, name, contains the name of the element for which this handler is called. If case-folding is in effect for this parser, the element name will be in uppercase letters.
27176 * @author Nicola Asuni
27177 * @since 5.0.000 (2010-05-02)
27178 * @protected
27180 protected function endSVGElementHandler($parser, $name) {
27181 switch($name) {
27182 case 'defs': {
27183 $this->svgdefsmode = false;
27184 break;
27186 // clipPath
27187 case 'clipPath': {
27188 $this->svgclipmode = false;
27189 break;
27191 case 'g': {
27192 // ungroup: remove last style from array
27193 array_pop($this->svgstyles);
27194 $this->StopTransform();
27195 break;
27197 case 'text':
27198 case 'tspan': {
27199 if ($this->svgtextmode['invisible']) {
27200 // This implementation must be fixed to following the rule:
27201 // 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.
27202 break;
27204 // print text
27205 $text = $this->stringTrim($this->svgtext);
27206 if ($this->svgtextmode['text-anchor'] != 'start') {
27207 $textlen = $this->GetStringWidth($text);
27208 // check if string is RTL text
27209 if ($this->svgtextmode['text-anchor'] == 'end') {
27210 if ($this->svgtextmode['rtl']) {
27211 $this->x += $textlen;
27212 } else {
27213 $this->x -= $textlen;
27215 } elseif ($this->svgtextmode['text-anchor'] == 'middle') {
27216 if ($this->svgtextmode['rtl']) {
27217 $this->x += ($textlen / 2);
27218 } else {
27219 $this->x -= ($textlen / 2);
27223 $textrendermode = $this->textrendermode;
27224 $textstrokewidth = $this->textstrokewidth;
27225 $this->setTextRenderingMode($this->svgtextmode['stroke'], true, false);
27226 $this->Cell(0, 0, $text, 0, 0, '', false, '', 0, false, 'L', 'T');
27227 // restore previous rendering mode
27228 $this->textrendermode = $textrendermode;
27229 $this->textstrokewidth = $textstrokewidth;
27230 $this->svgtext = '';
27231 $this->StopTransform();
27232 array_pop($this->svgstyles);
27233 break;
27235 default: {
27236 break;
27242 * Sets the character data handler function for the XML parser.
27243 * @param $parser (resource) The first parameter, parser, is a reference to the XML parser calling the handler.
27244 * @param $data (string) The second parameter, data, contains the character data as a string.
27245 * @author Nicola Asuni
27246 * @since 5.0.000 (2010-05-02)
27247 * @protected
27249 protected function segSVGContentHandler($parser, $data) {
27250 $this->svgtext .= $data;
27253 // --- END SVG METHODS -----------------------------------------------------
27255 } // END OF TCPDF CLASS
27257 //============================================================+
27258 // END OF FILE
27259 //============================================================+