Fork of FusionPBX but with LDAP kinda working
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

24569 lines
879 KiB

2 years ago
  1. <?php
  2. //============================================================+
  3. // File name : tcpdf.php
  4. // Version : 6.3.2
  5. // Begin : 2002-08-03
  6. // Last Update : 2019-09-20
  7. // Author : Nicola Asuni - Tecnick.com LTD - www.tecnick.com - info@tecnick.com
  8. // License : GNU-LGPL v3 (http://www.gnu.org/copyleft/lesser.html)
  9. // -------------------------------------------------------------------
  10. // Copyright (C) 2002-2019 Nicola Asuni - Tecnick.com LTD
  11. //
  12. // This file is part of TCPDF software library.
  13. //
  14. // TCPDF is free software: you can redistribute it and/or modify it
  15. // under the terms of the GNU Lesser General Public License as
  16. // published by the Free Software Foundation, either version 3 of the
  17. // License, or (at your option) any later version.
  18. //
  19. // TCPDF is distributed in the hope that it will be useful, but
  20. // WITHOUT ANY WARRANTY; without even the implied warranty of
  21. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  22. // See the GNU Lesser General Public License for more details.
  23. //
  24. // You should have received a copy of the License
  25. // along with TCPDF. If not, see
  26. // <http://www.tecnick.com/pagefiles/tcpdf/LICENSE.TXT>.
  27. //
  28. // See LICENSE.TXT file for more information.
  29. // -------------------------------------------------------------------
  30. //
  31. // Description :
  32. // This is a PHP class for generating PDF documents without requiring external extensions.
  33. //
  34. // NOTE:
  35. // This class was originally derived in 2002 from the Public
  36. // Domain FPDF class by Olivier Plathey (http://www.fpdf.org),
  37. // but now is almost entirely rewritten and contains thousands of
  38. // new lines of code and hundreds new features.
  39. //
  40. // Main features:
  41. // * no external libraries are required for the basic functions;
  42. // * all standard page formats, custom page formats, custom margins and units of measure;
  43. // * UTF-8 Unicode and Right-To-Left languages;
  44. // * TrueTypeUnicode, TrueType, Type1 and CID-0 fonts;
  45. // * font subsetting;
  46. // * methods to publish some XHTML + CSS code, Javascript and Forms;
  47. // * images, graphic (geometric figures) and transformation methods;
  48. // * supports JPEG, PNG and SVG images natively, all images supported by GD (GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM) and all images supported via ImageMagick (http://www.imagemagick.org/www/formats.html)
  49. // * 1D and 2D barcodes: CODE 39, ANSI MH10.8M-1983, USD-3, 3 of 9, CODE 93, USS-93, Standard 2 of 5, Interleaved 2 of 5, CODE 128 A/B/C, 2 and 5 Digits UPC-Based Extension, EAN 8, EAN 13, UPC-A, UPC-E, MSI, POSTNET, PLANET, RMS4CC (Royal Mail 4-state Customer Code), CBC (Customer Bar Code), KIX (Klant index - Customer index), Intelligent Mail Barcode, Onecode, USPS-B-3200, CODABAR, CODE 11, PHARMACODE, PHARMACODE TWO-TRACKS, Datamatrix, QR-Code, PDF417;
  50. // * JPEG and PNG ICC profiles, Grayscale, RGB, CMYK, Spot Colors and Transparencies;
  51. // * automatic page header and footer management;
  52. // * document encryption up to 256 bit and digital signature certifications;
  53. // * transactions to UNDO commands;
  54. // * PDF annotations, including links, text and file attachments;
  55. // * text rendering modes (fill, stroke and clipping);
  56. // * multiple columns mode;
  57. // * no-write page regions;
  58. // * bookmarks, named destinations and table of content;
  59. // * text hyphenation;
  60. // * text stretching and spacing (tracking);
  61. // * automatic page break, line break and text alignments including justification;
  62. // * automatic page numbering and page groups;
  63. // * move and delete pages;
  64. // * page compression (requires php-zlib extension);
  65. // * XOBject Templates;
  66. // * Layers and object visibility.
  67. // * PDF/A-1b support
  68. //============================================================+
  69. /**
  70. * @file
  71. * This is a PHP class for generating PDF documents without requiring external extensions.<br>
  72. * 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>
  73. * <h3>TCPDF main features are:</h3>
  74. * <ul>
  75. * <li>no external libraries are required for the basic functions;</li>
  76. * <li>all standard page formats, custom page formats, custom margins and units of measure;</li>
  77. * <li>UTF-8 Unicode and Right-To-Left languages;</li>
  78. * <li>TrueTypeUnicode, TrueType, Type1 and CID-0 fonts;</li>
  79. * <li>font subsetting;</li>
  80. * <li>methods to publish some XHTML + CSS code, Javascript and Forms;</li>
  81. * <li>images, graphic (geometric figures) and transformation methods;
  82. * <li>supports JPEG, PNG and SVG images natively, all images supported by GD (GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM) and all images supported via ImageMagick (http://www.imagemagick.org/www/formats.html)</li>
  83. * <li>1D and 2D barcodes: CODE 39, ANSI MH10.8M-1983, USD-3, 3 of 9, CODE 93, USS-93, Standard 2 of 5, Interleaved 2 of 5, CODE 128 A/B/C, 2 and 5 Digits UPC-Based Extension, EAN 8, EAN 13, UPC-A, UPC-E, MSI, POSTNET, PLANET, RMS4CC (Royal Mail 4-state Customer Code), CBC (Customer Bar Code), KIX (Klant index - Customer index), Intelligent Mail Barcode, Onecode, USPS-B-3200, CODABAR, CODE 11, PHARMACODE, PHARMACODE TWO-TRACKS, Datamatrix, QR-Code, PDF417;</li>
  84. * <li>JPEG and PNG ICC profiles, Grayscale, RGB, CMYK, Spot Colors and Transparencies;</li>
  85. * <li>automatic page header and footer management;</li>
  86. * <li>document encryption up to 256 bit and digital signature certifications;</li>
  87. * <li>transactions to UNDO commands;</li>
  88. * <li>PDF annotations, including links, text and file attachments;</li>
  89. * <li>text rendering modes (fill, stroke and clipping);</li>
  90. * <li>multiple columns mode;</li>
  91. * <li>no-write page regions;</li>
  92. * <li>bookmarks, named destinations and table of content;</li>
  93. * <li>text hyphenation;</li>
  94. * <li>text stretching and spacing (tracking);</li>
  95. * <li>automatic page break, line break and text alignments including justification;</li>
  96. * <li>automatic page numbering and page groups;</li>
  97. * <li>move and delete pages;</li>
  98. * <li>page compression (requires php-zlib extension);</li>
  99. * <li>XOBject Templates;</li>
  100. * <li>Layers and object visibility;</li>
  101. * <li>PDF/A-1b support.</li>
  102. * </ul>
  103. * Tools to encode your unicode fonts are on fonts/utils directory.</p>
  104. * @package com.tecnick.tcpdf
  105. * @author Nicola Asuni
  106. * @version 6.3.2
  107. */
  108. // TCPDF configuration
  109. require_once(dirname(__FILE__).'/tcpdf_autoconfig.php');
  110. // TCPDF static font methods and data
  111. require_once(dirname(__FILE__).'/include/tcpdf_font_data.php');
  112. // TCPDF static font methods and data
  113. require_once(dirname(__FILE__).'/include/tcpdf_fonts.php');
  114. // TCPDF static color methods and data
  115. require_once(dirname(__FILE__).'/include/tcpdf_colors.php');
  116. // TCPDF static image methods and data
  117. require_once(dirname(__FILE__).'/include/tcpdf_images.php');
  118. // TCPDF static methods and data
  119. require_once(dirname(__FILE__).'/include/tcpdf_static.php');
  120. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  121. /**
  122. * @class TCPDF
  123. * PHP class for generating PDF documents without requiring external extensions.
  124. * 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>
  125. * @package com.tecnick.tcpdf
  126. * @brief PHP class for generating PDF documents without requiring external extensions.
  127. * @version 6.3.2
  128. * @author Nicola Asuni - info@tecnick.com
  129. * @IgnoreAnnotation("protected")
  130. * @IgnoreAnnotation("public")
  131. * @IgnoreAnnotation("pre")
  132. */
  133. class TCPDF {
  134. // Protected properties
  135. /**
  136. * Current page number.
  137. * @protected
  138. */
  139. protected $page;
  140. /**
  141. * Current object number.
  142. * @protected
  143. */
  144. protected $n;
  145. /**
  146. * Array of object offsets.
  147. * @protected
  148. */
  149. protected $offsets = array();
  150. /**
  151. * Array of object IDs for each page.
  152. * @protected
  153. */
  154. protected $pageobjects = array();
  155. /**
  156. * Buffer holding in-memory PDF.
  157. * @protected
  158. */
  159. protected $buffer;
  160. /**
  161. * Array containing pages.
  162. * @protected
  163. */
  164. protected $pages = array();
  165. /**
  166. * Current document state.
  167. * @protected
  168. */
  169. protected $state;
  170. /**
  171. * Compression flag.
  172. * @protected
  173. */
  174. protected $compress;
  175. /**
  176. * Current page orientation (P = Portrait, L = Landscape).
  177. * @protected
  178. */
  179. protected $CurOrientation;
  180. /**
  181. * Page dimensions.
  182. * @protected
  183. */
  184. protected $pagedim = array();
  185. /**
  186. * Scale factor (number of points in user unit).
  187. * @protected
  188. */
  189. protected $k;
  190. /**
  191. * Width of page format in points.
  192. * @protected
  193. */
  194. protected $fwPt;
  195. /**
  196. * Height of page format in points.
  197. * @protected
  198. */
  199. protected $fhPt;
  200. /**
  201. * Current width of page in points.
  202. * @protected
  203. */
  204. protected $wPt;
  205. /**
  206. * Current height of page in points.
  207. * @protected
  208. */
  209. protected $hPt;
  210. /**
  211. * Current width of page in user unit.
  212. * @protected
  213. */
  214. protected $w;
  215. /**
  216. * Current height of page in user unit.
  217. * @protected
  218. */
  219. protected $h;
  220. /**
  221. * Left margin.
  222. * @protected
  223. */
  224. protected $lMargin;
  225. /**
  226. * Right margin.
  227. * @protected
  228. */
  229. protected $rMargin;
  230. /**
  231. * Cell left margin (used by regions).
  232. * @protected
  233. */
  234. protected $clMargin;
  235. /**
  236. * Cell right margin (used by regions).
  237. * @protected
  238. */
  239. protected $crMargin;
  240. /**
  241. * Top margin.
  242. * @protected
  243. */
  244. protected $tMargin;
  245. /**
  246. * Page break margin.
  247. * @protected
  248. */
  249. protected $bMargin;
  250. /**
  251. * Array of cell internal paddings ('T' => top, 'R' => right, 'B' => bottom, 'L' => left).
  252. * @since 5.9.000 (2010-10-03)
  253. * @protected
  254. */
  255. protected $cell_padding = array('T' => 0, 'R' => 0, 'B' => 0, 'L' => 0);
  256. /**
  257. * Array of cell margins ('T' => top, 'R' => right, 'B' => bottom, 'L' => left).
  258. * @since 5.9.000 (2010-10-04)
  259. * @protected
  260. */
  261. protected $cell_margin = array('T' => 0, 'R' => 0, 'B' => 0, 'L' => 0);
  262. /**
  263. * Current horizontal position in user unit for cell positioning.
  264. * @protected
  265. */
  266. protected $x;
  267. /**
  268. * Current vertical position in user unit for cell positioning.
  269. * @protected
  270. */
  271. protected $y;
  272. /**
  273. * Height of last cell printed.
  274. * @protected
  275. */
  276. protected $lasth;
  277. /**
  278. * Line width in user unit.
  279. * @protected
  280. */
  281. protected $LineWidth;
  282. /**
  283. * Array of standard font names.
  284. * @protected
  285. */
  286. protected $CoreFonts;
  287. /**
  288. * Array of used fonts.
  289. * @protected
  290. */
  291. protected $fonts = array();
  292. /**
  293. * Array of font files.
  294. * @protected
  295. */
  296. protected $FontFiles = array();
  297. /**
  298. * Array of encoding differences.
  299. * @protected
  300. */
  301. protected $diffs = array();
  302. /**
  303. * Array of used images.
  304. * @protected
  305. */
  306. protected $images = array();
  307. /**
  308. * Depth of the svg tag, to keep track if the svg tag is a subtag or the root tag.
  309. * @protected
  310. */
  311. protected $svg_tag_depth = 0;
  312. /**
  313. * Array of Annotations in pages.
  314. * @protected
  315. */
  316. protected $PageAnnots = array();
  317. /**
  318. * Array of internal links.
  319. * @protected
  320. */
  321. protected $links = array();
  322. /**
  323. * Current font family.
  324. * @protected
  325. */
  326. protected $FontFamily;
  327. /**
  328. * Current font style.
  329. * @protected
  330. */
  331. protected $FontStyle;
  332. /**
  333. * Current font ascent (distance between font top and baseline).
  334. * @protected
  335. * @since 2.8.000 (2007-03-29)
  336. */
  337. protected $FontAscent;
  338. /**
  339. * Current font descent (distance between font bottom and baseline).
  340. * @protected
  341. * @since 2.8.000 (2007-03-29)
  342. */
  343. protected $FontDescent;
  344. /**
  345. * Underlining flag.
  346. * @protected
  347. */
  348. protected $underline;
  349. /**
  350. * Overlining flag.
  351. * @protected
  352. */
  353. protected $overline;
  354. /**
  355. * Current font info.
  356. * @protected
  357. */
  358. protected $CurrentFont;
  359. /**
  360. * Current font size in points.
  361. * @protected
  362. */
  363. protected $FontSizePt;
  364. /**
  365. * Current font size in user unit.
  366. * @protected
  367. */
  368. protected $FontSize;
  369. /**
  370. * Commands for drawing color.
  371. * @protected
  372. */
  373. protected $DrawColor;
  374. /**
  375. * Commands for filling color.
  376. * @protected
  377. */
  378. protected $FillColor;
  379. /**
  380. * Commands for text color.
  381. * @protected
  382. */
  383. protected $TextColor;
  384. /**
  385. * Indicates whether fill and text colors are different.
  386. * @protected
  387. */
  388. protected $ColorFlag;
  389. /**
  390. * Automatic page breaking.
  391. * @protected
  392. */
  393. protected $AutoPageBreak;
  394. /**
  395. * Threshold used to trigger page breaks.
  396. * @protected
  397. */
  398. protected $PageBreakTrigger;
  399. /**
  400. * Flag set when processing page header.
  401. * @protected
  402. */
  403. protected $InHeader = false;
  404. /**
  405. * Flag set when processing page footer.
  406. * @protected
  407. */
  408. protected $InFooter = false;
  409. /**
  410. * Zoom display mode.
  411. * @protected
  412. */
  413. protected $ZoomMode;
  414. /**
  415. * Layout display mode.
  416. * @protected
  417. */
  418. protected $LayoutMode;
  419. /**
  420. * If true set the document information dictionary in Unicode.
  421. * @protected
  422. */
  423. protected $docinfounicode = true;
  424. /**
  425. * Document title.
  426. * @protected
  427. */
  428. protected $title = '';
  429. /**
  430. * Document subject.
  431. * @protected
  432. */
  433. protected $subject = '';
  434. /**
  435. * Document author.
  436. * @protected
  437. */
  438. protected $author = '';
  439. /**
  440. * Document keywords.
  441. * @protected
  442. */
  443. protected $keywords = '';
  444. /**
  445. * Document creator.
  446. * @protected
  447. */
  448. protected $creator = '';
  449. /**
  450. * Starting page number.
  451. * @protected
  452. */
  453. protected $starting_page_number = 1;
  454. /**
  455. * The right-bottom (or left-bottom for RTL) corner X coordinate of last inserted image.
  456. * @since 2002-07-31
  457. * @author Nicola Asuni
  458. * @protected
  459. */
  460. protected $img_rb_x;
  461. /**
  462. * The right-bottom corner Y coordinate of last inserted image.
  463. * @since 2002-07-31
  464. * @author Nicola Asuni
  465. * @protected
  466. */
  467. protected $img_rb_y;
  468. /**
  469. * Adjusting factor to convert pixels to user units.
  470. * @since 2004-06-14
  471. * @author Nicola Asuni
  472. * @protected
  473. */
  474. protected $imgscale = 1;
  475. /**
  476. * Boolean flag set to true when the input text is unicode (require unicode fonts).
  477. * @since 2005-01-02
  478. * @author Nicola Asuni
  479. * @protected
  480. */
  481. protected $isunicode = false;
  482. /**
  483. * PDF version.
  484. * @since 1.5.3
  485. * @protected
  486. */
  487. protected $PDFVersion = '1.7';
  488. /**
  489. * ID of the stored default header template (-1 = not set).
  490. * @protected
  491. */
  492. protected $header_xobjid = false;
  493. /**
  494. * If true reset the Header Xobject template at each page
  495. * @protected
  496. */
  497. protected $header_xobj_autoreset = false;
  498. /**
  499. * Minimum distance between header and top page margin.
  500. * @protected
  501. */
  502. protected $header_margin;
  503. /**
  504. * Minimum distance between footer and bottom page margin.
  505. * @protected
  506. */
  507. protected $footer_margin;
  508. /**
  509. * Original left margin value.
  510. * @protected
  511. * @since 1.53.0.TC013
  512. */
  513. protected $original_lMargin;
  514. /**
  515. * Original right margin value.
  516. * @protected
  517. * @since 1.53.0.TC013
  518. */
  519. protected $original_rMargin;
  520. /**
  521. * Default font used on page header.
  522. * @protected
  523. */
  524. protected $header_font;
  525. /**
  526. * Default font used on page footer.
  527. * @protected
  528. */
  529. protected $footer_font;
  530. /**
  531. * Language templates.
  532. * @protected
  533. */
  534. protected $l;
  535. /**
  536. * Barcode to print on page footer (only if set).
  537. * @protected
  538. */
  539. protected $barcode = false;
  540. /**
  541. * Boolean flag to print/hide page header.
  542. * @protected
  543. */
  544. protected $print_header = true;
  545. /**
  546. * Boolean flag to print/hide page footer.
  547. * @protected
  548. */
  549. protected $print_footer = true;
  550. /**
  551. * Header image logo.
  552. * @protected
  553. */
  554. protected $header_logo = '';
  555. /**
  556. * Width of header image logo in user units.
  557. * @protected
  558. */
  559. protected $header_logo_width = 30;
  560. /**
  561. * Title to be printed on default page header.
  562. * @protected
  563. */
  564. protected $header_title = '';
  565. /**
  566. * String to pring on page header after title.
  567. * @protected
  568. */
  569. protected $header_string = '';
  570. /**
  571. * Color for header text (RGB array).
  572. * @since 5.9.174 (2012-07-25)
  573. * @protected
  574. */
  575. protected $header_text_color = array(0,0,0);
  576. /**
  577. * Color for header line (RGB array).
  578. * @since 5.9.174 (2012-07-25)
  579. * @protected
  580. */
  581. protected $header_line_color = array(0,0,0);
  582. /**
  583. * Color for footer text (RGB array).
  584. * @since 5.9.174 (2012-07-25)
  585. * @protected
  586. */
  587. protected $footer_text_color = array(0,0,0);
  588. /**
  589. * Color for footer line (RGB array).
  590. * @since 5.9.174 (2012-07-25)
  591. * @protected
  592. */
  593. protected $footer_line_color = array(0,0,0);
  594. /**
  595. * Text shadow data array.
  596. * @since 5.9.174 (2012-07-25)
  597. * @protected
  598. */
  599. protected $txtshadow = array('enabled'=>false, 'depth_w'=>0, 'depth_h'=>0, 'color'=>false, 'opacity'=>1, 'blend_mode'=>'Normal');
  600. /**
  601. * Default number of columns for html table.
  602. * @protected
  603. */
  604. protected $default_table_columns = 4;
  605. // variables for html parser
  606. /**
  607. * HTML PARSER: array to store current link and rendering styles.
  608. * @protected
  609. */
  610. protected $HREF = array();
  611. /**
  612. * List of available fonts on filesystem.
  613. * @protected
  614. */
  615. protected $fontlist = array();
  616. /**
  617. * Current foreground color.
  618. * @protected
  619. */
  620. protected $fgcolor;
  621. /**
  622. * HTML PARSER: array of boolean values, true in case of ordered list (OL), false otherwise.
  623. * @protected
  624. */
  625. protected $listordered = array();
  626. /**
  627. * HTML PARSER: array count list items on nested lists.
  628. * @protected
  629. */
  630. protected $listcount = array();
  631. /**
  632. * HTML PARSER: current list nesting level.
  633. * @protected
  634. */
  635. protected $listnum = 0;
  636. /**
  637. * HTML PARSER: indent amount for lists.
  638. * @protected
  639. */
  640. protected $listindent = 0;
  641. /**
  642. * HTML PARSER: current list indententation level.
  643. * @protected
  644. */
  645. protected $listindentlevel = 0;
  646. /**
  647. * Current background color.
  648. * @protected
  649. */
  650. protected $bgcolor;
  651. /**
  652. * Temporary font size in points.
  653. * @protected
  654. */
  655. protected $tempfontsize = 10;
  656. /**
  657. * Spacer string for LI tags.
  658. * @protected
  659. */
  660. protected $lispacer = '';
  661. /**
  662. * Default encoding.
  663. * @protected
  664. * @since 1.53.0.TC010
  665. */
  666. protected $encoding = 'UTF-8';
  667. /**
  668. * PHP internal encoding.
  669. * @protected
  670. * @since 1.53.0.TC016
  671. */
  672. protected $internal_encoding;
  673. /**
  674. * Boolean flag to indicate if the document language is Right-To-Left.
  675. * @protected
  676. * @since 2.0.000
  677. */
  678. protected $rtl = false;
  679. /**
  680. * Boolean flag used to force RTL or LTR string direction.
  681. * @protected
  682. * @since 2.0.000
  683. */
  684. protected $tmprtl = false;
  685. // --- Variables used for document encryption:
  686. /**
  687. * IBoolean flag indicating whether document is protected.
  688. * @protected
  689. * @since 2.0.000 (2008-01-02)
  690. */
  691. protected $encrypted;
  692. /**
  693. * Array containing encryption settings.
  694. * @protected
  695. * @since 5.0.005 (2010-05-11)
  696. */
  697. protected $encryptdata = array();
  698. /**
  699. * Last RC4 key encrypted (cached for optimisation).
  700. * @protected
  701. * @since 2.0.000 (2008-01-02)
  702. */
  703. protected $last_enc_key;
  704. /**
  705. * Last RC4 computed key.
  706. * @protected
  707. * @since 2.0.000 (2008-01-02)
  708. */
  709. protected $last_enc_key_c;
  710. /**
  711. * File ID (used on document trailer).
  712. * @protected
  713. * @since 5.0.005 (2010-05-12)
  714. */
  715. protected $file_id;
  716. // --- bookmark ---
  717. /**
  718. * Outlines for bookmark.
  719. * @protected
  720. * @since 2.1.002 (2008-02-12)
  721. */
  722. protected $outlines = array();
  723. /**
  724. * Outline root for bookmark.
  725. * @protected
  726. * @since 2.1.002 (2008-02-12)
  727. */
  728. protected $OutlineRoot;
  729. // --- javascript and form ---
  730. /**
  731. * Javascript code.
  732. * @protected
  733. * @since 2.1.002 (2008-02-12)
  734. */
  735. protected $javascript = '';
  736. /**
  737. * Javascript counter.
  738. * @protected
  739. * @since 2.1.002 (2008-02-12)
  740. */
  741. protected $n_js;
  742. /**
  743. * line through state
  744. * @protected
  745. * @since 2.8.000 (2008-03-19)
  746. */
  747. protected $linethrough;
  748. /**
  749. * Array with additional document-wide usage rights for the document.
  750. * @protected
  751. * @since 5.8.014 (2010-08-23)
  752. */
  753. protected $ur = array();
  754. /**
  755. * DPI (Dot Per Inch) Document Resolution (do not change).
  756. * @protected
  757. * @since 3.0.000 (2008-03-27)
  758. */
  759. protected $dpi = 72;
  760. /**
  761. * Array of page numbers were a new page group was started (the page numbers are the keys of the array).
  762. * @protected
  763. * @since 3.0.000 (2008-03-27)
  764. */
  765. protected $newpagegroup = array();
  766. /**
  767. * Array that contains the number of pages in each page group.
  768. * @protected
  769. * @since 3.0.000 (2008-03-27)
  770. */
  771. protected $pagegroups = array();
  772. /**
  773. * Current page group number.
  774. * @protected
  775. * @since 3.0.000 (2008-03-27)
  776. */
  777. protected $currpagegroup = 0;
  778. /**
  779. * Array of transparency objects and parameters.
  780. * @protected
  781. * @since 3.0.000 (2008-03-27)
  782. */
  783. protected $extgstates;
  784. /**
  785. * Set the default JPEG compression quality (1-100).
  786. * @protected
  787. * @since 3.0.000 (2008-03-27)
  788. */
  789. protected $jpeg_quality;
  790. /**
  791. * Default cell height ratio.
  792. * @protected
  793. * @since 3.0.014 (2008-05-23)
  794. */
  795. protected $cell_height_ratio = K_CELL_HEIGHT_RATIO;
  796. /**
  797. * PDF viewer preferences.
  798. * @protected
  799. * @since 3.1.000 (2008-06-09)
  800. */
  801. protected $viewer_preferences;
  802. /**
  803. * A name object specifying how the document should be displayed when opened.
  804. * @protected
  805. * @since 3.1.000 (2008-06-09)
  806. */
  807. protected $PageMode;
  808. /**
  809. * Array for storing gradient information.
  810. * @protected
  811. * @since 3.1.000 (2008-06-09)
  812. */
  813. protected $gradients = array();
  814. /**
  815. * Array used to store positions inside the pages buffer (keys are the page numbers).
  816. * @protected
  817. * @since 3.2.000 (2008-06-26)
  818. */
  819. protected $intmrk = array();
  820. /**
  821. * Array used to store positions inside the pages buffer (keys are the page numbers).
  822. * @protected
  823. * @since 5.7.000 (2010-08-03)
  824. */
  825. protected $bordermrk = array();
  826. /**
  827. * Array used to store page positions to track empty pages (keys are the page numbers).
  828. * @protected
  829. * @since 5.8.007 (2010-08-18)
  830. */
  831. protected $emptypagemrk = array();
  832. /**
  833. * Array used to store content positions inside the pages buffer (keys are the page numbers).
  834. * @protected
  835. * @since 4.6.021 (2009-07-20)
  836. */
  837. protected $cntmrk = array();
  838. /**
  839. * Array used to store footer positions of each page.
  840. * @protected
  841. * @since 3.2.000 (2008-07-01)
  842. */
  843. protected $footerpos = array();
  844. /**
  845. * Array used to store footer length of each page.
  846. * @protected
  847. * @since 4.0.014 (2008-07-29)
  848. */
  849. protected $footerlen = array();
  850. /**
  851. * Boolean flag to indicate if a new line is created.
  852. * @protected
  853. * @since 3.2.000 (2008-07-01)
  854. */
  855. protected $newline = true;
  856. /**
  857. * End position of the latest inserted line.
  858. * @protected
  859. * @since 3.2.000 (2008-07-01)
  860. */
  861. protected $endlinex = 0;
  862. /**
  863. * PDF string for width value of the last line.
  864. * @protected
  865. * @since 4.0.006 (2008-07-16)
  866. */
  867. protected $linestyleWidth = '';
  868. /**
  869. * PDF string for CAP value of the last line.
  870. * @protected
  871. * @since 4.0.006 (2008-07-16)
  872. */
  873. protected $linestyleCap = '0 J';
  874. /**
  875. * PDF string for join value of the last line.
  876. * @protected
  877. * @since 4.0.006 (2008-07-16)
  878. */
  879. protected $linestyleJoin = '0 j';
  880. /**
  881. * PDF string for dash value of the last line.
  882. * @protected
  883. * @since 4.0.006 (2008-07-16)
  884. */
  885. protected $linestyleDash = '[] 0 d';
  886. /**
  887. * Boolean flag to indicate if marked-content sequence is open.
  888. * @protected
  889. * @since 4.0.013 (2008-07-28)
  890. */
  891. protected $openMarkedContent = false;
  892. /**
  893. * Count the latest inserted vertical spaces on HTML.
  894. * @protected
  895. * @since 4.0.021 (2008-08-24)
  896. */
  897. protected $htmlvspace = 0;
  898. /**
  899. * Array of Spot colors.
  900. * @protected
  901. * @since 4.0.024 (2008-09-12)
  902. */
  903. protected $spot_colors = array();
  904. /**
  905. * Symbol used for HTML unordered list items.
  906. * @protected
  907. * @since 4.0.028 (2008-09-26)
  908. */
  909. protected $lisymbol = '';
  910. /**
  911. * String used to mark the beginning and end of EPS image blocks.
  912. * @protected
  913. * @since 4.1.000 (2008-10-18)
  914. */
  915. protected $epsmarker = 'x#!#EPS#!#x';
  916. /**
  917. * Array of transformation matrix.
  918. * @protected
  919. * @since 4.2.000 (2008-10-29)
  920. */
  921. protected $transfmatrix = array();
  922. /**
  923. * Current key for transformation matrix.
  924. * @protected
  925. * @since 4.8.005 (2009-09-17)
  926. */
  927. protected $transfmatrix_key = 0;
  928. /**
  929. * Booklet mode for double-sided pages.
  930. * @protected
  931. * @since 4.2.000 (2008-10-29)
  932. */
  933. protected $booklet = false;
  934. /**
  935. * Epsilon value used for float calculations.
  936. * @protected
  937. * @since 4.2.000 (2008-10-29)
  938. */
  939. protected $feps = 0.005;
  940. /**
  941. * Array used for custom vertical spaces for HTML tags.
  942. * @protected
  943. * @since 4.2.001 (2008-10-30)
  944. */
  945. protected $tagvspaces = array();
  946. /**
  947. * HTML PARSER: custom indent amount for lists. Negative value means disabled.
  948. * @protected
  949. * @since 4.2.007 (2008-11-12)
  950. */
  951. protected $customlistindent = -1;
  952. /**
  953. * Boolean flag to indicate if the border of the cell sides that cross the page should be removed.
  954. * @protected
  955. * @since 4.2.010 (2008-11-14)
  956. */
  957. protected $opencell = true;
  958. /**
  959. * Array of files to embedd.
  960. * @protected
  961. * @since 4.4.000 (2008-12-07)
  962. */
  963. protected $embeddedfiles = array();
  964. /**
  965. * Boolean flag to indicate if we are inside a PRE tag.
  966. * @protected
  967. * @since 4.4.001 (2008-12-08)
  968. */
  969. protected $premode = false;
  970. /**
  971. * Array used to store positions of graphics transformation blocks inside the page buffer.
  972. * keys are the page numbers
  973. * @protected
  974. * @since 4.4.002 (2008-12-09)
  975. */
  976. protected $transfmrk = array();
  977. /**
  978. * Default color for html links.
  979. * @protected
  980. * @since 4.4.003 (2008-12-09)
  981. */
  982. protected $htmlLinkColorArray = array(0, 0, 255);
  983. /**
  984. * Default font style to add to html links.
  985. * @protected
  986. * @since 4.4.003 (2008-12-09)
  987. */
  988. protected $htmlLinkFontStyle = 'U';
  989. /**
  990. * Counts the number of pages.
  991. * @protected
  992. * @since 4.5.000 (2008-12-31)
  993. */
  994. protected $numpages = 0;
  995. /**
  996. * Array containing page lengths in bytes.
  997. * @protected
  998. * @since 4.5.000 (2008-12-31)
  999. */
  1000. protected $pagelen = array();
  1001. /**
  1002. * Counts the number of pages.
  1003. * @protected
  1004. * @since 4.5.000 (2008-12-31)
  1005. */
  1006. protected $numimages = 0;
  1007. /**
  1008. * Store the image keys.
  1009. * @protected
  1010. * @since 4.5.000 (2008-12-31)
  1011. */
  1012. protected $imagekeys = array();
  1013. /**
  1014. * Length of the buffer in bytes.
  1015. * @protected
  1016. * @since 4.5.000 (2008-12-31)
  1017. */
  1018. protected $bufferlen = 0;
  1019. /**
  1020. * Counts the number of fonts.
  1021. * @protected
  1022. * @since 4.5.000 (2009-01-02)
  1023. */
  1024. protected $numfonts = 0;
  1025. /**
  1026. * Store the font keys.
  1027. * @protected
  1028. * @since 4.5.000 (2009-01-02)
  1029. */
  1030. protected $fontkeys = array();
  1031. /**
  1032. * Store the font object IDs.
  1033. * @protected
  1034. * @since 4.8.001 (2009-09-09)
  1035. */
  1036. protected $font_obj_ids = array();
  1037. /**
  1038. * Store the fage status (true when opened, false when closed).
  1039. * @protected
  1040. * @since 4.5.000 (2009-01-02)
  1041. */
  1042. protected $pageopen = array();
  1043. /**
  1044. * Default monospace font.
  1045. * @protected
  1046. * @since 4.5.025 (2009-03-10)
  1047. */
  1048. protected $default_monospaced_font = 'courier';
  1049. /**
  1050. * Cloned copy of the current class object.
  1051. * @protected
  1052. * @since 4.5.029 (2009-03-19)
  1053. */
  1054. protected $objcopy;
  1055. /**
  1056. * Array used to store the lengths of cache files.
  1057. * @protected
  1058. * @since 4.5.029 (2009-03-19)
  1059. */
  1060. protected $cache_file_length = array();
  1061. /**
  1062. * Table header content to be repeated on each new page.
  1063. * @protected
  1064. * @since 4.5.030 (2009-03-20)
  1065. */
  1066. protected $thead = '';
  1067. /**
  1068. * Margins used for table header.
  1069. * @protected
  1070. * @since 4.5.030 (2009-03-20)
  1071. */
  1072. protected $theadMargins = array();
  1073. /**
  1074. * Boolean flag to enable document digital signature.
  1075. * @protected
  1076. * @since 4.6.005 (2009-04-24)
  1077. */
  1078. protected $sign = false;
  1079. /**
  1080. * Digital signature data.
  1081. * @protected
  1082. * @since 4.6.005 (2009-04-24)
  1083. */
  1084. protected $signature_data = array();
  1085. /**
  1086. * Digital signature max length.
  1087. * @protected
  1088. * @since 4.6.005 (2009-04-24)
  1089. */
  1090. protected $signature_max_length = 11742;
  1091. /**
  1092. * Data for digital signature appearance.
  1093. * @protected
  1094. * @since 5.3.011 (2010-06-16)
  1095. */
  1096. protected $signature_appearance = array('page' => 1, 'rect' => '0 0 0 0');
  1097. /**
  1098. * Array of empty digital signature appearances.
  1099. * @protected
  1100. * @since 5.9.101 (2011-07-06)
  1101. */
  1102. protected $empty_signature_appearance = array();
  1103. /**
  1104. * Boolean flag to enable document timestamping with TSA.
  1105. * @protected
  1106. * @since 6.0.085 (2014-06-19)
  1107. */
  1108. protected $tsa_timestamp = false;
  1109. /**
  1110. * Timestamping data.
  1111. * @protected
  1112. * @since 6.0.085 (2014-06-19)
  1113. */
  1114. protected $tsa_data = array();
  1115. /**
  1116. * Regular expression used to find blank characters (required for word-wrapping).
  1117. * @protected
  1118. * @since 4.6.006 (2009-04-28)
  1119. */
  1120. protected $re_spaces = '/[^\S\xa0]/';
  1121. /**
  1122. * Array of $re_spaces parts.
  1123. * @protected
  1124. * @since 5.5.011 (2010-07-09)
  1125. */
  1126. protected $re_space = array('p' => '[^\S\xa0]', 'm' => '');
  1127. /**
  1128. * Digital signature object ID.
  1129. * @protected
  1130. * @since 4.6.022 (2009-06-23)
  1131. */
  1132. protected $sig_obj_id = 0;
  1133. /**
  1134. * ID of page objects.
  1135. * @protected
  1136. * @since 4.7.000 (2009-08-29)
  1137. */
  1138. protected $page_obj_id = array();
  1139. /**
  1140. * List of form annotations IDs.
  1141. * @protected
  1142. * @since 4.8.000 (2009-09-07)
  1143. */
  1144. protected $form_obj_id = array();
  1145. /**
  1146. * 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.
  1147. * @protected
  1148. * @since 4.8.000 (2009-09-07)
  1149. */
  1150. protected $default_form_prop = array('lineWidth'=>1, 'borderStyle'=>'solid', 'fillColor'=>array(255, 255, 255), 'strokeColor'=>array(128, 128, 128));
  1151. /**
  1152. * Javascript objects array.
  1153. * @protected
  1154. * @since 4.8.000 (2009-09-07)
  1155. */
  1156. protected $js_objects = array();
  1157. /**
  1158. * Current form action (used during XHTML rendering).
  1159. * @protected
  1160. * @since 4.8.000 (2009-09-07)
  1161. */
  1162. protected $form_action = '';
  1163. /**
  1164. * Current form encryption type (used during XHTML rendering).
  1165. * @protected
  1166. * @since 4.8.000 (2009-09-07)
  1167. */
  1168. protected $form_enctype = 'application/x-www-form-urlencoded';
  1169. /**
  1170. * Current method to submit forms.
  1171. * @protected
  1172. * @since 4.8.000 (2009-09-07)
  1173. */
  1174. protected $form_mode = 'post';
  1175. /**
  1176. * List of fonts used on form fields (fontname => fontkey).
  1177. * @protected
  1178. * @since 4.8.001 (2009-09-09)
  1179. */
  1180. protected $annotation_fonts = array();
  1181. /**
  1182. * List of radio buttons parent objects.
  1183. * @protected
  1184. * @since 4.8.001 (2009-09-09)
  1185. */
  1186. protected $radiobutton_groups = array();
  1187. /**
  1188. * List of radio group objects IDs.
  1189. * @protected
  1190. * @since 4.8.001 (2009-09-09)
  1191. */
  1192. protected $radio_groups = array();
  1193. /**
  1194. * Text indentation value (used for text-indent CSS attribute).
  1195. * @protected
  1196. * @since 4.8.006 (2009-09-23)
  1197. */
  1198. protected $textindent = 0;
  1199. /**
  1200. * Store page number when startTransaction() is called.
  1201. * @protected
  1202. * @since 4.8.006 (2009-09-23)
  1203. */
  1204. protected $start_transaction_page = 0;
  1205. /**
  1206. * Store Y position when startTransaction() is called.
  1207. * @protected
  1208. * @since 4.9.001 (2010-03-28)
  1209. */
  1210. protected $start_transaction_y = 0;
  1211. /**
  1212. * True when we are printing the thead section on a new page.
  1213. * @protected
  1214. * @since 4.8.027 (2010-01-25)
  1215. */
  1216. protected $inthead = false;
  1217. /**
  1218. * Array of column measures (width, space, starting Y position).
  1219. * @protected
  1220. * @since 4.9.001 (2010-03-28)
  1221. */
  1222. protected $columns = array();
  1223. /**
  1224. * Number of colums.
  1225. * @protected
  1226. * @since 4.9.001 (2010-03-28)
  1227. */
  1228. protected $num_columns = 1;
  1229. /**
  1230. * Current column number.
  1231. * @protected
  1232. * @since 4.9.001 (2010-03-28)
  1233. */
  1234. protected $current_column = 0;
  1235. /**
  1236. * Starting page for columns.
  1237. * @protected
  1238. * @since 4.9.001 (2010-03-28)
  1239. */
  1240. protected $column_start_page = 0;
  1241. /**
  1242. * Maximum page and column selected.
  1243. * @protected
  1244. * @since 5.8.000 (2010-08-11)
  1245. */
  1246. protected $maxselcol = array('page' => 0, 'column' => 0);
  1247. /**
  1248. * Array of: X difference between table cell x start and starting page margin, cellspacing, cellpadding.
  1249. * @protected
  1250. * @since 5.8.000 (2010-08-11)
  1251. */
  1252. protected $colxshift = array('x' => 0, 's' => array('H' => 0, 'V' => 0), 'p' => array('L' => 0, 'T' => 0, 'R' => 0, 'B' => 0));
  1253. /**
  1254. * 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.
  1255. * @protected
  1256. * @since 4.9.008 (2010-04-03)
  1257. */
  1258. protected $textrendermode = 0;
  1259. /**
  1260. * Text stroke width in doc units.
  1261. * @protected
  1262. * @since 4.9.008 (2010-04-03)
  1263. */
  1264. protected $textstrokewidth = 0;
  1265. /**
  1266. * Current stroke color.
  1267. * @protected
  1268. * @since 4.9.008 (2010-04-03)
  1269. */
  1270. protected $strokecolor;
  1271. /**
  1272. * Default unit of measure for document.
  1273. * @protected
  1274. * @since 5.0.000 (2010-04-22)
  1275. */
  1276. protected $pdfunit = 'mm';
  1277. /**
  1278. * Boolean flag true when we are on TOC (Table Of Content) page.
  1279. * @protected
  1280. */
  1281. protected $tocpage = false;
  1282. /**
  1283. * Boolean flag: if true convert vector images (SVG, EPS) to raster image using GD or ImageMagick library.
  1284. * @protected
  1285. * @since 5.0.000 (2010-04-26)
  1286. */
  1287. protected $rasterize_vector_images = false;
  1288. /**
  1289. * Boolean flag: if true enables font subsetting by default.
  1290. * @protected
  1291. * @since 5.3.002 (2010-06-07)
  1292. */
  1293. protected $font_subsetting = true;
  1294. /**
  1295. * Array of default graphic settings.
  1296. * @protected
  1297. * @since 5.5.008 (2010-07-02)
  1298. */
  1299. protected $default_graphic_vars = array();
  1300. /**
  1301. * Array of XObjects.
  1302. * @protected
  1303. * @since 5.8.014 (2010-08-23)
  1304. */
  1305. protected $xobjects = array();
  1306. /**
  1307. * Boolean value true when we are inside an XObject.
  1308. * @protected
  1309. * @since 5.8.017 (2010-08-24)
  1310. */
  1311. protected $inxobj = false;
  1312. /**
  1313. * Current XObject ID.
  1314. * @protected
  1315. * @since 5.8.017 (2010-08-24)
  1316. */
  1317. protected $xobjid = '';
  1318. /**
  1319. * Percentage of character stretching.
  1320. * @protected
  1321. * @since 5.9.000 (2010-09-29)
  1322. */
  1323. protected $font_stretching = 100;
  1324. /**
  1325. * Increases or decreases the space between characters in a text by the specified amount (tracking).
  1326. * @protected
  1327. * @since 5.9.000 (2010-09-29)
  1328. */
  1329. protected $font_spacing = 0;
  1330. /**
  1331. * Array of no-write regions.
  1332. * ('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)
  1333. * @protected
  1334. * @since 5.9.003 (2010-10-14)
  1335. */
  1336. protected $page_regions = array();
  1337. /**
  1338. * Boolean value true when page region check is active.
  1339. * @protected
  1340. */
  1341. protected $check_page_regions = true;
  1342. /**
  1343. * Array of PDF layers data.
  1344. * @protected
  1345. * @since 5.9.102 (2011-07-13)
  1346. */
  1347. protected $pdflayers = array();
  1348. /**
  1349. * A dictionary of names and corresponding destinations (Dests key on document Catalog).
  1350. * @protected
  1351. * @since 5.9.097 (2011-06-23)
  1352. */
  1353. protected $dests = array();
  1354. /**
  1355. * Object ID for Named Destinations
  1356. * @protected
  1357. * @since 5.9.097 (2011-06-23)
  1358. */
  1359. protected $n_dests;
  1360. /**
  1361. * Embedded Files Names
  1362. * @protected
  1363. * @since 5.9.204 (2013-01-23)
  1364. */
  1365. protected $efnames = array();
  1366. /**
  1367. * Directory used for the last SVG image.
  1368. * @protected
  1369. * @since 5.0.000 (2010-05-05)
  1370. */
  1371. protected $svgdir = '';
  1372. /**
  1373. * Deafult unit of measure for SVG.
  1374. * @protected
  1375. * @since 5.0.000 (2010-05-02)
  1376. */
  1377. protected $svgunit = 'px';
  1378. /**
  1379. * Array of SVG gradients.
  1380. * @protected
  1381. * @since 5.0.000 (2010-05-02)
  1382. */
  1383. protected $svggradients = array();
  1384. /**
  1385. * ID of last SVG gradient.
  1386. * @protected
  1387. * @since 5.0.000 (2010-05-02)
  1388. */
  1389. protected $svggradientid = 0;
  1390. /**
  1391. * Boolean value true when in SVG defs group.
  1392. * @protected
  1393. * @since 5.0.000 (2010-05-02)
  1394. */
  1395. protected $svgdefsmode = false;
  1396. /**
  1397. * Array of SVG defs.
  1398. * @protected
  1399. * @since 5.0.000 (2010-05-02)
  1400. */
  1401. protected $svgdefs = array();
  1402. /**
  1403. * Boolean value true when in SVG clipPath tag.
  1404. * @protected
  1405. * @since 5.0.000 (2010-04-26)
  1406. */
  1407. protected $svgclipmode = false;
  1408. /**
  1409. * Array of SVG clipPath commands.
  1410. * @protected
  1411. * @since 5.0.000 (2010-05-02)
  1412. */
  1413. protected $svgclippaths = array();
  1414. /**
  1415. * Array of SVG clipPath tranformation matrix.
  1416. * @protected
  1417. * @since 5.8.022 (2010-08-31)
  1418. */
  1419. protected $svgcliptm = array();
  1420. /**
  1421. * ID of last SVG clipPath.
  1422. * @protected
  1423. * @since 5.0.000 (2010-05-02)
  1424. */
  1425. protected $svgclipid = 0;
  1426. /**
  1427. * SVG text.
  1428. * @protected
  1429. * @since 5.0.000 (2010-05-02)
  1430. */
  1431. protected $svgtext = '';
  1432. /**
  1433. * SVG text properties.
  1434. * @protected
  1435. * @since 5.8.013 (2010-08-23)
  1436. */
  1437. protected $svgtextmode = array();
  1438. /**
  1439. * Array of SVG properties.
  1440. * @protected
  1441. * @since 5.0.000 (2010-05-02)
  1442. */
  1443. protected $svgstyles = array(array(
  1444. 'alignment-baseline' => 'auto',
  1445. 'baseline-shift' => 'baseline',
  1446. 'clip' => 'auto',
  1447. 'clip-path' => 'none',
  1448. 'clip-rule' => 'nonzero',
  1449. 'color' => 'black',
  1450. 'color-interpolation' => 'sRGB',
  1451. 'color-interpolation-filters' => 'linearRGB',
  1452. 'color-profile' => 'auto',
  1453. 'color-rendering' => 'auto',
  1454. 'cursor' => 'auto',
  1455. 'direction' => 'ltr',
  1456. 'display' => 'inline',
  1457. 'dominant-baseline' => 'auto',
  1458. 'enable-background' => 'accumulate',
  1459. 'fill' => 'black',
  1460. 'fill-opacity' => 1,
  1461. 'fill-rule' => 'nonzero',
  1462. 'filter' => 'none',
  1463. 'flood-color' => 'black',
  1464. 'flood-opacity' => 1,
  1465. 'font' => '',
  1466. 'font-family' => 'helvetica',
  1467. 'font-size' => 'medium',
  1468. 'font-size-adjust' => 'none',
  1469. 'font-stretch' => 'normal',
  1470. 'font-style' => 'normal',
  1471. 'font-variant' => 'normal',
  1472. 'font-weight' => 'normal',
  1473. 'glyph-orientation-horizontal' => '0deg',
  1474. 'glyph-orientation-vertical' => 'auto',
  1475. 'image-rendering' => 'auto',
  1476. 'kerning' => 'auto',
  1477. 'letter-spacing' => 'normal',
  1478. 'lighting-color' => 'white',
  1479. 'marker' => '',
  1480. 'marker-end' => 'none',
  1481. 'marker-mid' => 'none',
  1482. 'marker-start' => 'none',
  1483. 'mask' => 'none',
  1484. 'opacity' => 1,
  1485. 'overflow' => 'auto',
  1486. 'pointer-events' => 'visiblePainted',
  1487. 'shape-rendering' => 'auto',
  1488. 'stop-color' => 'black',
  1489. 'stop-opacity' => 1,
  1490. 'stroke' => 'none',
  1491. 'stroke-dasharray' => 'none',
  1492. 'stroke-dashoffset' => 0,
  1493. 'stroke-linecap' => 'butt',
  1494. 'stroke-linejoin' => 'miter',
  1495. 'stroke-miterlimit' => 4,
  1496. 'stroke-opacity' => 1,
  1497. 'stroke-width' => 1,
  1498. 'text-anchor' => 'start',
  1499. 'text-decoration' => 'none',
  1500. 'text-rendering' => 'auto',
  1501. 'unicode-bidi' => 'normal',
  1502. 'visibility' => 'visible',
  1503. 'word-spacing' => 'normal',
  1504. 'writing-mode' => 'lr-tb',
  1505. 'text-color' => 'black',
  1506. 'transfmatrix' => array(1, 0, 0, 1, 0, 0)
  1507. ));
  1508. /**
  1509. * If true force sRGB color profile for all document.
  1510. * @protected
  1511. * @since 5.9.121 (2011-09-28)
  1512. */
  1513. protected $force_srgb = false;
  1514. /**
  1515. * If true set the document to PDF/A mode.
  1516. * @protected
  1517. * @since 5.9.121 (2011-09-27)
  1518. */
  1519. protected $pdfa_mode = false;
  1520. /**
  1521. * version of PDF/A mode (1 - 3).
  1522. * @protected
  1523. * @since 6.2.26 (2019-03-12)
  1524. */
  1525. protected $pdfa_version = 1;
  1526. /**
  1527. * Document creation date-time
  1528. * @protected
  1529. * @since 5.9.152 (2012-03-22)
  1530. */
  1531. protected $doc_creation_timestamp;
  1532. /**
  1533. * Document modification date-time
  1534. * @protected
  1535. * @since 5.9.152 (2012-03-22)
  1536. */
  1537. protected $doc_modification_timestamp;
  1538. /**
  1539. * Custom XMP data.
  1540. * @protected
  1541. * @since 5.9.128 (2011-10-06)
  1542. */
  1543. protected $custom_xmp = '';
  1544. /**
  1545. * Custom XMP RDF data.
  1546. * @protected
  1547. * @since 6.3.0 (2019-09-19)
  1548. */
  1549. protected $custom_xmp_rdf = '';
  1550. /**
  1551. * Overprint mode array.
  1552. * (Check the "Entries in a Graphics State Parameter Dictionary" on PDF 32000-1:2008).
  1553. * @protected
  1554. * @since 5.9.152 (2012-03-23)
  1555. */
  1556. protected $overprint = array('OP' => false, 'op' => false, 'OPM' => 0);
  1557. /**
  1558. * Alpha mode array.
  1559. * (Check the "Entries in a Graphics State Parameter Dictionary" on PDF 32000-1:2008).
  1560. * @protected
  1561. * @since 5.9.152 (2012-03-23)
  1562. */
  1563. protected $alpha = array('CA' => 1, 'ca' => 1, 'BM' => '/Normal', 'AIS' => false);
  1564. /**
  1565. * Define the page boundaries boxes to be set on document.
  1566. * @protected
  1567. * @since 5.9.152 (2012-03-23)
  1568. */
  1569. protected $page_boxes = array('MediaBox', 'CropBox', 'BleedBox', 'TrimBox', 'ArtBox');
  1570. /**
  1571. * If true print TCPDF meta link.
  1572. * @protected
  1573. * @since 5.9.152 (2012-03-23)
  1574. */
  1575. protected $tcpdflink = true;
  1576. /**
  1577. * Cache array for computed GD gamma values.
  1578. * @protected
  1579. * @since 5.9.1632 (2012-06-05)
  1580. */
  1581. protected $gdgammacache = array();
  1582. //------------------------------------------------------------
  1583. // METHODS
  1584. //------------------------------------------------------------
  1585. /**
  1586. * This is the class constructor.
  1587. * It allows to set up the page format, the orientation and the measure unit used in all the methods (except for the font sizes).
  1588. *
  1589. * IMPORTANT: Please note that this method sets the mb_internal_encoding to ASCII, so if you are using the mbstring module functions with TCPDF you need to correctly set/unset the mb_internal_encoding when needed.
  1590. *
  1591. * @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>
  1592. * @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.
  1593. * @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().
  1594. * @param $unicode (boolean) TRUE means that the input text is unicode (default = true)
  1595. * @param $encoding (string) Charset encoding (used only when converting back html entities); default is UTF-8.
  1596. * @param $diskcache (boolean) DEPRECATED FEATURE
  1597. * @param $pdfa (integer) If not false, set the document to PDF/A mode and the good version (1 or 3).
  1598. * @public
  1599. * @see getPageSizeFromFormat(), setPageFormat()
  1600. */
  1601. public function __construct($orientation='P', $unit='mm', $format='A4', $unicode=true, $encoding='UTF-8', $diskcache=false, $pdfa=false) {
  1602. /* Set internal character encoding to ASCII */
  1603. if (function_exists('mb_internal_encoding') AND mb_internal_encoding()) {
  1604. $this->internal_encoding = mb_internal_encoding();
  1605. mb_internal_encoding('ASCII');
  1606. }
  1607. // set file ID for trailer
  1608. $serformat = (is_array($format) ? json_encode($format) : $format);
  1609. $this->file_id = md5(TCPDF_STATIC::getRandomSeed('TCPDF'.$orientation.$unit.$serformat.$encoding));
  1610. $this->font_obj_ids = array();
  1611. $this->page_obj_id = array();
  1612. $this->form_obj_id = array();
  1613. // set pdf/a mode
  1614. if ($pdfa != false) {
  1615. $this->pdfa_mode = true;
  1616. $this->pdfa_version = $pdfa; // 1 or 3
  1617. } else
  1618. $this->pdfa_mode = false;
  1619. $this->force_srgb = false;
  1620. // set language direction
  1621. $this->rtl = false;
  1622. $this->tmprtl = false;
  1623. // some checks
  1624. $this->_dochecks();
  1625. // initialization of properties
  1626. $this->isunicode = $unicode;
  1627. $this->page = 0;
  1628. $this->transfmrk[0] = array();
  1629. $this->pagedim = array();
  1630. $this->n = 2;
  1631. $this->buffer = '';
  1632. $this->pages = array();
  1633. $this->state = 0;
  1634. $this->fonts = array();
  1635. $this->FontFiles = array();
  1636. $this->diffs = array();
  1637. $this->images = array();
  1638. $this->links = array();
  1639. $this->gradients = array();
  1640. $this->InFooter = false;
  1641. $this->lasth = 0;
  1642. $this->FontFamily = defined('PDF_FONT_NAME_MAIN')?PDF_FONT_NAME_MAIN:'helvetica';
  1643. $this->FontStyle = '';
  1644. $this->FontSizePt = 12;
  1645. $this->underline = false;
  1646. $this->overline = false;
  1647. $this->linethrough = false;
  1648. $this->DrawColor = '0 G';
  1649. $this->FillColor = '0 g';
  1650. $this->TextColor = '0 g';
  1651. $this->ColorFlag = false;
  1652. $this->pdflayers = array();
  1653. // encryption values
  1654. $this->encrypted = false;
  1655. $this->last_enc_key = '';
  1656. // standard Unicode fonts
  1657. $this->CoreFonts = array(
  1658. 'courier'=>'Courier',
  1659. 'courierB'=>'Courier-Bold',
  1660. 'courierI'=>'Courier-Oblique',
  1661. 'courierBI'=>'Courier-BoldOblique',
  1662. 'helvetica'=>'Helvetica',
  1663. 'helveticaB'=>'Helvetica-Bold',
  1664. 'helveticaI'=>'Helvetica-Oblique',
  1665. 'helveticaBI'=>'Helvetica-BoldOblique',
  1666. 'times'=>'Times-Roman',
  1667. 'timesB'=>'Times-Bold',
  1668. 'timesI'=>'Times-Italic',
  1669. 'timesBI'=>'Times-BoldItalic',
  1670. 'symbol'=>'Symbol',
  1671. 'zapfdingbats'=>'ZapfDingbats'
  1672. );
  1673. // set scale factor
  1674. $this->setPageUnit($unit);
  1675. // set page format and orientation
  1676. $this->setPageFormat($format, $orientation);
  1677. // page margins (1 cm)
  1678. $margin = 28.35 / $this->k;
  1679. $this->SetMargins($margin, $margin);
  1680. $this->clMargin = $this->lMargin;
  1681. $this->crMargin = $this->rMargin;
  1682. // internal cell padding
  1683. $cpadding = $margin / 10;
  1684. $this->setCellPaddings($cpadding, 0, $cpadding, 0);
  1685. // cell margins
  1686. $this->setCellMargins(0, 0, 0, 0);
  1687. // line width (0.2 mm)
  1688. $this->LineWidth = 0.57 / $this->k;
  1689. $this->linestyleWidth = sprintf('%F w', ($this->LineWidth * $this->k));
  1690. $this->linestyleCap = '0 J';
  1691. $this->linestyleJoin = '0 j';
  1692. $this->linestyleDash = '[] 0 d';
  1693. // automatic page break
  1694. $this->SetAutoPageBreak(true, (2 * $margin));
  1695. // full width display mode
  1696. $this->SetDisplayMode('fullwidth');
  1697. // compression
  1698. $this->SetCompression();
  1699. // set default PDF version number
  1700. $this->setPDFVersion();
  1701. $this->tcpdflink = true;
  1702. $this->encoding = $encoding;
  1703. $this->HREF = array();
  1704. $this->getFontsList();
  1705. $this->fgcolor = array('R' => 0, 'G' => 0, 'B' => 0);
  1706. $this->strokecolor = array('R' => 0, 'G' => 0, 'B' => 0);
  1707. $this->bgcolor = array('R' => 255, 'G' => 255, 'B' => 255);
  1708. $this->extgstates = array();
  1709. $this->setTextShadow();
  1710. // signature
  1711. $this->sign = false;
  1712. $this->tsa_timestamp = false;
  1713. $this->tsa_data = array();
  1714. $this->signature_appearance = array('page' => 1, 'rect' => '0 0 0 0', 'name' => 'Signature');
  1715. $this->empty_signature_appearance = array();
  1716. // user's rights
  1717. $this->ur['enabled'] = false;
  1718. $this->ur['document'] = '/FullSave';
  1719. $this->ur['annots'] = '/Create/Delete/Modify/Copy/Import/Export';
  1720. $this->ur['form'] = '/Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate';
  1721. $this->ur['signature'] = '/Modify';
  1722. $this->ur['ef'] = '/Create/Delete/Modify/Import';
  1723. $this->ur['formex'] = '';
  1724. // set default JPEG quality
  1725. $this->jpeg_quality = 75;
  1726. // initialize some settings
  1727. TCPDF_FONTS::utf8Bidi(array(), '', false, $this->isunicode, $this->CurrentFont);
  1728. // set default font
  1729. $this->SetFont($this->FontFamily, $this->FontStyle, $this->FontSizePt);
  1730. $this->setHeaderFont(array($this->FontFamily, $this->FontStyle, $this->FontSizePt));
  1731. $this->setFooterFont(array($this->FontFamily, $this->FontStyle, $this->FontSizePt));
  1732. // check if PCRE Unicode support is enabled
  1733. if ($this->isunicode AND (@preg_match('/\pL/u', 'a') == 1)) {
  1734. // PCRE unicode support is turned ON
  1735. // \s : any whitespace character
  1736. // \p{Z} : any separator
  1737. // \p{Lo} : Unicode letter or ideograph that does not have lowercase and uppercase variants. Is used to chunk chinese words.
  1738. // \xa0 : Unicode Character 'NO-BREAK SPACE' (U+00A0)
  1739. //$this->setSpacesRE('/(?!\xa0)[\s\p{Z}\p{Lo}]/u');
  1740. $this->setSpacesRE('/(?!\xa0)[\s\p{Z}]/u');
  1741. } else {
  1742. // PCRE unicode support is turned OFF
  1743. $this->setSpacesRE('/[^\S\xa0]/');
  1744. }
  1745. $this->default_form_prop = array('lineWidth'=>1, 'borderStyle'=>'solid', 'fillColor'=>array(255, 255, 255), 'strokeColor'=>array(128, 128, 128));
  1746. // set document creation and modification timestamp
  1747. $this->doc_creation_timestamp = time();
  1748. $this->doc_modification_timestamp = $this->doc_creation_timestamp;
  1749. // get default graphic vars
  1750. $this->default_graphic_vars = $this->getGraphicVars();
  1751. $this->header_xobj_autoreset = false;
  1752. $this->custom_xmp = '';
  1753. $this->custom_xmp_rdf = '';
  1754. // Call cleanup method after script execution finishes or exit() is called.
  1755. // NOTE: This will not be executed if the process is killed with a SIGTERM or SIGKILL signal.
  1756. register_shutdown_function(array($this, '_destroy'), true);
  1757. }
  1758. /**
  1759. * Default destructor.
  1760. * @public
  1761. * @since 1.53.0.TC016
  1762. */
  1763. public function __destruct() {
  1764. // cleanup
  1765. $this->_destroy(true);
  1766. }
  1767. /**
  1768. * Set the units of measure for the document.
  1769. * @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.
  1770. * @public
  1771. * @since 3.0.015 (2008-06-06)
  1772. */
  1773. public function setPageUnit($unit) {
  1774. $unit = strtolower($unit);
  1775. //Set scale factor
  1776. switch ($unit) {
  1777. // points
  1778. case 'px':
  1779. case 'pt': {
  1780. $this->k = 1;
  1781. break;
  1782. }
  1783. // millimeters
  1784. case 'mm': {
  1785. $this->k = $this->dpi / 25.4;
  1786. break;
  1787. }
  1788. // centimeters
  1789. case 'cm': {
  1790. $this->k = $this->dpi / 2.54;
  1791. break;
  1792. }
  1793. // inches
  1794. case 'in': {
  1795. $this->k = $this->dpi;
  1796. break;
  1797. }
  1798. // unsupported unit
  1799. default : {
  1800. $this->Error('Incorrect unit: '.$unit);
  1801. break;
  1802. }
  1803. }
  1804. $this->pdfunit = $unit;
  1805. if (isset($this->CurOrientation)) {
  1806. $this->setPageOrientation($this->CurOrientation);
  1807. }
  1808. }
  1809. /**
  1810. * Change the format of the current page
  1811. * @param $format (mixed) The format used for pages. It can be either: one of the string values specified at getPageSizeFromFormat() documentation or an array of two numbers (width, height) or an array containing the following measures and options:<ul>
  1812. * <li>['format'] = page format name (one of the above);</li>
  1813. * <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>
  1814. * <li>['PZ'] : The page's preferred zoom (magnification) factor.</li>
  1815. * <li>['MediaBox'] : the boundaries of the physical medium on which the page shall be displayed or printed:</li>
  1816. * <li>['MediaBox']['llx'] : lower-left x coordinate</li>
  1817. * <li>['MediaBox']['lly'] : lower-left y coordinate</li>
  1818. * <li>['MediaBox']['urx'] : upper-right x coordinate</li>
  1819. * <li>['MediaBox']['ury'] : upper-right y coordinate</li>
  1820. * <li>['CropBox'] : the visible region of default user space:</li>
  1821. * <li>['CropBox']['llx'] : lower-left x coordinate</li>
  1822. * <li>['CropBox']['lly'] : lower-left y coordinate</li>
  1823. * <li>['CropBox']['urx'] : upper-right x coordinate</li>
  1824. * <li>['CropBox']['ury'] : upper-right y coordinate</li>
  1825. * <li>['BleedBox'] : the region to which the contents of the page shall be clipped when output in a production environment:</li>
  1826. * <li>['BleedBox']['llx'] : lower-left x coordinate</li>
  1827. * <li>['BleedBox']['lly'] : lower-left y coordinate</li>
  1828. * <li>['BleedBox']['urx'] : upper-right x coordinate</li>
  1829. * <li>['BleedBox']['ury'] : upper-right y coordinate</li>
  1830. * <li>['TrimBox'] : the intended dimensions of the finished page after trimming:</li>
  1831. * <li>['TrimBox']['llx'] : lower-left x coordinate</li>
  1832. * <li>['TrimBox']['lly'] : lower-left y coordinate</li>
  1833. * <li>['TrimBox']['urx'] : upper-right x coordinate</li>
  1834. * <li>['TrimBox']['ury'] : upper-right y coordinate</li>
  1835. * <li>['ArtBox'] : the extent of the page's meaningful content:</li>
  1836. * <li>['ArtBox']['llx'] : lower-left x coordinate</li>
  1837. * <li>['ArtBox']['lly'] : lower-left y coordinate</li>
  1838. * <li>['ArtBox']['urx'] : upper-right x coordinate</li>
  1839. * <li>['ArtBox']['ury'] : upper-right y coordinate</li>
  1840. * <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>
  1841. * <li>['BoxColorInfo'][BOXTYPE]['C'] : an array of three numbers in the range 0-255, representing the components in the DeviceRGB colour space.</li>
  1842. * <li>['BoxColorInfo'][BOXTYPE]['W'] : the guideline width in default user units</li>
  1843. * <li>['BoxColorInfo'][BOXTYPE]['S'] : the guideline style: S = Solid; D = Dashed</li>
  1844. * <li>['BoxColorInfo'][BOXTYPE]['D'] : dash array defining a pattern of dashes and gaps to be used in drawing dashed guidelines</li>
  1845. * <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>
  1846. * <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>
  1847. * <li>['trans']['S'] : transition style : Split, Blinds, Box, Wipe, Dissolve, Glitter, R, Fly, Push, Cover, Uncover, Fade</li>
  1848. * <li>['trans']['D'] : The duration of the transition effect, in seconds.</li>
  1849. * <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>
  1850. * <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>
  1851. * <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>
  1852. * <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>
  1853. * <li>['trans']['B'] : (Fly transition style only) If true, the area that shall be flown in is rectangular and opaque. Default: false.</li>
  1854. * </ul>
  1855. * @param $orientation (string) page orientation. Possible values are (case insensitive):<ul>
  1856. * <li>P or Portrait (default)</li>
  1857. * <li>L or Landscape</li>
  1858. * <li>'' (empty string) for automatic orientation</li>
  1859. * </ul>
  1860. * @protected
  1861. * @since 3.0.015 (2008-06-06)
  1862. * @see getPageSizeFromFormat()
  1863. */
  1864. protected function setPageFormat($format, $orientation='P') {
  1865. if (!empty($format) AND isset($this->pagedim[$this->page])) {
  1866. // remove inherited values
  1867. unset($this->pagedim[$this->page]);
  1868. }
  1869. if (is_string($format)) {
  1870. // get page measures from format name
  1871. $pf = TCPDF_STATIC::getPageSizeFromFormat($format);
  1872. $this->fwPt = $pf[0];
  1873. $this->fhPt = $pf[1];
  1874. } else {
  1875. // the boundaries of the physical medium on which the page shall be displayed or printed
  1876. if (isset($format['MediaBox'])) {
  1877. $this->pagedim = TCPDF_STATIC::setPageBoxes($this->page, 'MediaBox', $format['MediaBox']['llx'], $format['MediaBox']['lly'], $format['MediaBox']['urx'], $format['MediaBox']['ury'], false, $this->k, $this->pagedim);
  1878. $this->fwPt = (($format['MediaBox']['urx'] - $format['MediaBox']['llx']) * $this->k);
  1879. $this->fhPt = (($format['MediaBox']['ury'] - $format['MediaBox']['lly']) * $this->k);
  1880. } else {
  1881. if (isset($format[0]) AND is_numeric($format[0]) AND isset($format[1]) AND is_numeric($format[1])) {
  1882. $pf = array(($format[0] * $this->k), ($format[1] * $this->k));
  1883. } else {
  1884. if (!isset($format['format'])) {
  1885. // default value
  1886. $format['format'] = 'A4';
  1887. }
  1888. $pf = TCPDF_STATIC::getPageSizeFromFormat($format['format']);
  1889. }
  1890. $this->fwPt = $pf[0];
  1891. $this->fhPt = $pf[1];
  1892. $this->pagedim = TCPDF_STATIC::setPageBoxes($this->page, 'MediaBox', 0, 0, $this->fwPt, $this->fhPt, true, $this->k, $this->pagedim);
  1893. }
  1894. // the visible region of default user space
  1895. if (isset($format['CropBox'])) {
  1896. $this->pagedim = TCPDF_STATIC::setPageBoxes($this->page, 'CropBox', $format['CropBox']['llx'], $format['CropBox']['lly'], $format['CropBox']['urx'], $format['CropBox']['ury'], false, $this->k, $this->pagedim);
  1897. }
  1898. // the region to which the contents of the page shall be clipped when output in a production environment
  1899. if (isset($format['BleedBox'])) {
  1900. $this->pagedim = TCPDF_STATIC::setPageBoxes($this->page, 'BleedBox', $format['BleedBox']['llx'], $format['BleedBox']['lly'], $format['BleedBox']['urx'], $format['BleedBox']['ury'], false, $this->k, $this->pagedim);
  1901. }
  1902. // the intended dimensions of the finished page after trimming
  1903. if (isset($format['TrimBox'])) {
  1904. $this->pagedim = TCPDF_STATIC::setPageBoxes($this->page, 'TrimBox', $format['TrimBox']['llx'], $format['TrimBox']['lly'], $format['TrimBox']['urx'], $format['TrimBox']['ury'], false, $this->k, $this->pagedim);
  1905. }
  1906. // the page's meaningful content (including potential white space)
  1907. if (isset($format['ArtBox'])) {
  1908. $this->pagedim = TCPDF_STATIC::setPageBoxes($this->page, 'ArtBox', $format['ArtBox']['llx'], $format['ArtBox']['lly'], $format['ArtBox']['urx'], $format['ArtBox']['ury'], false, $this->k, $this->pagedim);
  1909. }
  1910. // specify the colours and other visual characteristics that should be used in displaying guidelines on the screen for the various page boundaries
  1911. if (isset($format['BoxColorInfo'])) {
  1912. $this->pagedim[$this->page]['BoxColorInfo'] = $format['BoxColorInfo'];
  1913. }
  1914. if (isset($format['Rotate']) AND (($format['Rotate'] % 90) == 0)) {
  1915. // The number of degrees by which the page shall be rotated clockwise when displayed or printed. The value shall be a multiple of 90.
  1916. $this->pagedim[$this->page]['Rotate'] = intval($format['Rotate']);
  1917. }
  1918. if (isset($format['PZ'])) {
  1919. // The page's preferred zoom (magnification) factor
  1920. $this->pagedim[$this->page]['PZ'] = floatval($format['PZ']);
  1921. }
  1922. if (isset($format['trans'])) {
  1923. // The style and duration of the visual transition to use when moving from another page to the given page during a presentation
  1924. if (isset($format['trans']['Dur'])) {
  1925. // The page's display duration
  1926. $this->pagedim[$this->page]['trans']['Dur'] = floatval($format['trans']['Dur']);
  1927. }
  1928. $stansition_styles = array('Split', 'Blinds', 'Box', 'Wipe', 'Dissolve', 'Glitter', 'R', 'Fly', 'Push', 'Cover', 'Uncover', 'Fade');
  1929. if (isset($format['trans']['S']) AND in_array($format['trans']['S'], $stansition_styles)) {
  1930. // The transition style that shall be used when moving to this page from another during a presentation
  1931. $this->pagedim[$this->page]['trans']['S'] = $format['trans']['S'];
  1932. $valid_effect = array('Split', 'Blinds');
  1933. $valid_vals = array('H', 'V');
  1934. if (isset($format['trans']['Dm']) AND in_array($format['trans']['S'], $valid_effect) AND in_array($format['trans']['Dm'], $valid_vals)) {
  1935. $this->pagedim[$this->page]['trans']['Dm'] = $format['trans']['Dm'];
  1936. }
  1937. $valid_effect = array('Split', 'Box', 'Fly');
  1938. $valid_vals = array('I', 'O');
  1939. if (isset($format['trans']['M']) AND in_array($format['trans']['S'], $valid_effect) AND in_array($format['trans']['M'], $valid_vals)) {
  1940. $this->pagedim[$this->page]['trans']['M'] = $format['trans']['M'];
  1941. }
  1942. $valid_effect = array('Wipe', 'Glitter', 'Fly', 'Cover', 'Uncover', 'Push');
  1943. if (isset($format['trans']['Di']) AND in_array($format['trans']['S'], $valid_effect)) {
  1944. if (((($format['trans']['Di'] == 90) OR ($format['trans']['Di'] == 180)) AND ($format['trans']['S'] == 'Wipe'))
  1945. OR (($format['trans']['Di'] == 315) AND ($format['trans']['S'] == 'Glitter'))
  1946. OR (($format['trans']['Di'] == 0) OR ($format['trans']['Di'] == 270))) {
  1947. $this->pagedim[$this->page]['trans']['Di'] = intval($format['trans']['Di']);
  1948. }
  1949. }
  1950. if (isset($format['trans']['SS']) AND ($format['trans']['S'] == 'Fly')) {
  1951. $this->pagedim[$this->page]['trans']['SS'] = floatval($format['trans']['SS']);
  1952. }
  1953. if (isset($format['trans']['B']) AND ($format['trans']['B'] === true) AND ($format['trans']['S'] == 'Fly')) {
  1954. $this->pagedim[$this->page]['trans']['B'] = 'true';
  1955. }
  1956. } else {
  1957. $this->pagedim[$this->page]['trans']['S'] = 'R';
  1958. }
  1959. if (isset($format['trans']['D'])) {
  1960. // The duration of the transition effect, in seconds
  1961. $this->pagedim[$this->page]['trans']['D'] = floatval($format['trans']['D']);
  1962. } else {
  1963. $this->pagedim[$this->page]['trans']['D'] = 1;
  1964. }
  1965. }
  1966. }
  1967. $this->setPageOrientation($orientation);
  1968. }
  1969. /**
  1970. * Set page orientation.
  1971. * @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>
  1972. * @param $autopagebreak (boolean) Boolean indicating if auto-page-break mode should be on or off.
  1973. * @param $bottommargin (float) bottom margin of the page.
  1974. * @public
  1975. * @since 3.0.015 (2008-06-06)
  1976. */
  1977. public function setPageOrientation($orientation, $autopagebreak='', $bottommargin='') {
  1978. if (!isset($this->pagedim[$this->page]['MediaBox'])) {
  1979. // the boundaries of the physical medium on which the page shall be displayed or printed
  1980. $this->pagedim = TCPDF_STATIC::setPageBoxes($this->page, 'MediaBox', 0, 0, $this->fwPt, $this->fhPt, true, $this->k, $this->pagedim);
  1981. }
  1982. if (!isset($this->pagedim[$this->page]['CropBox'])) {
  1983. // the visible region of default user space
  1984. $this->pagedim = TCPDF_STATIC::setPageBoxes($this->page, 'CropBox', $this->pagedim[$this->page]['MediaBox']['llx'], $this->pagedim[$this->page]['MediaBox']['lly'], $this->pagedim[$this->page]['MediaBox']['urx'], $this->pagedim[$this->page]['MediaBox']['ury'], true, $this->k, $this->pagedim);
  1985. }
  1986. if (!isset($this->pagedim[$this->page]['BleedBox'])) {
  1987. // the region to which the contents of the page shall be clipped when output in a production environment
  1988. $this->pagedim = TCPDF_STATIC::setPageBoxes($this->page, 'BleedBox', $this->pagedim[$this->page]['CropBox']['llx'], $this->pagedim[$this->page]['CropBox']['lly'], $this->pagedim[$this->page]['CropBox']['urx'], $this->pagedim[$this->page]['CropBox']['ury'], true, $this->k, $this->pagedim);
  1989. }
  1990. if (!isset($this->pagedim[$this->page]['TrimBox'])) {
  1991. // the intended dimensions of the finished page after trimming
  1992. $this->pagedim = TCPDF_STATIC::setPageBoxes($this->page, 'TrimBox', $this->pagedim[$this->page]['CropBox']['llx'], $this->pagedim[$this->page]['CropBox']['lly'], $this->pagedim[$this->page]['CropBox']['urx'], $this->pagedim[$this->page]['CropBox']['ury'], true, $this->k, $this->pagedim);
  1993. }
  1994. if (!isset($this->pagedim[$this->page]['ArtBox'])) {
  1995. // the page's meaningful content (including potential white space)
  1996. $this->pagedim = TCPDF_STATIC::setPageBoxes($this->page, 'ArtBox', $this->pagedim[$this->page]['CropBox']['llx'], $this->pagedim[$this->page]['CropBox']['lly'], $this->pagedim[$this->page]['CropBox']['urx'], $this->pagedim[$this->page]['CropBox']['ury'], true, $this->k, $this->pagedim);
  1997. }
  1998. if (!isset($this->pagedim[$this->page]['Rotate'])) {
  1999. // The number of degrees by which the page shall be rotated clockwise when displayed or printed. The value shall be a multiple of 90.
  2000. $this->pagedim[$this->page]['Rotate'] = 0;
  2001. }
  2002. if (!isset($this->pagedim[$this->page]['PZ'])) {
  2003. // The page's preferred zoom (magnification) factor
  2004. $this->pagedim[$this->page]['PZ'] = 1;
  2005. }
  2006. if ($this->fwPt > $this->fhPt) {
  2007. // landscape
  2008. $default_orientation = 'L';
  2009. } else {
  2010. // portrait
  2011. $default_orientation = 'P';
  2012. }
  2013. $valid_orientations = array('P', 'L');
  2014. if (empty($orientation)) {
  2015. $orientation = $default_orientation;
  2016. } else {
  2017. $orientation = strtoupper($orientation[0]);
  2018. }
  2019. if (in_array($orientation, $valid_orientations) AND ($orientation != $default_orientation)) {
  2020. $this->CurOrientation = $orientation;
  2021. $this->wPt = $this->fhPt;
  2022. $this->hPt = $this->fwPt;
  2023. } else {
  2024. $this->CurOrientation = $default_orientation;
  2025. $this->wPt = $this->fwPt;
  2026. $this->hPt = $this->fhPt;
  2027. }
  2028. if ((abs($this->pagedim[$this->page]['MediaBox']['urx'] - $this->hPt) < $this->feps) AND (abs($this->pagedim[$this->page]['MediaBox']['ury'] - $this->wPt) < $this->feps)){
  2029. // swap X and Y coordinates (change page orientation)
  2030. $this->pagedim = TCPDF_STATIC::swapPageBoxCoordinates($this->page, $this->pagedim);
  2031. }
  2032. $this->w = ($this->wPt / $this->k);
  2033. $this->h = ($this->hPt / $this->k);
  2034. if (TCPDF_STATIC::empty_string($autopagebreak)) {
  2035. if (isset($this->AutoPageBreak)) {
  2036. $autopagebreak = $this->AutoPageBreak;
  2037. } else {
  2038. $autopagebreak = true;
  2039. }
  2040. }
  2041. if (TCPDF_STATIC::empty_string($bottommargin)) {
  2042. if (isset($this->bMargin)) {
  2043. $bottommargin = $this->bMargin;
  2044. } else {
  2045. // default value = 2 cm
  2046. $bottommargin = 2 * 28.35 / $this->k;
  2047. }
  2048. }
  2049. $this->SetAutoPageBreak($autopagebreak, $bottommargin);
  2050. // store page dimensions
  2051. $this->pagedim[$this->page]['w'] = $this->wPt;
  2052. $this->pagedim[$this->page]['h'] = $this->hPt;
  2053. $this->pagedim[$this->page]['wk'] = $this->w;
  2054. $this->pagedim[$this->page]['hk'] = $this->h;
  2055. $this->pagedim[$this->page]['tm'] = $this->tMargin;
  2056. $this->pagedim[$this->page]['bm'] = $bottommargin;
  2057. $this->pagedim[$this->page]['lm'] = $this->lMargin;
  2058. $this->pagedim[$this->page]['rm'] = $this->rMargin;
  2059. $this->pagedim[$this->page]['pb'] = $autopagebreak;
  2060. $this->pagedim[$this->page]['or'] = $this->CurOrientation;
  2061. $this->pagedim[$this->page]['olm'] = $this->original_lMargin;
  2062. $this->pagedim[$this->page]['orm'] = $this->original_rMargin;
  2063. }
  2064. /**
  2065. * Set regular expression to detect withespaces or word separators.
  2066. * The pattern delimiter must be the forward-slash character "/".
  2067. * Some example patterns are:
  2068. * <pre>
  2069. * Non-Unicode or missing PCRE unicode support: "/[^\S\xa0]/"
  2070. * Unicode and PCRE unicode support: "/(?!\xa0)[\s\p{Z}]/u"
  2071. * Unicode and PCRE unicode support in Chinese mode: "/(?!\xa0)[\s\p{Z}\p{Lo}]/u"
  2072. * if PCRE unicode support is turned ON ("\P" is the negate class of "\p"):
  2073. * \s : any whitespace character
  2074. * \p{Z} : any separator
  2075. * \p{Lo} : Unicode letter or ideograph that does not have lowercase and uppercase variants. Is used to chunk chinese words.
  2076. * \xa0 : Unicode Character 'NO-BREAK SPACE' (U+00A0)
  2077. * </pre>
  2078. * @param $re (string) regular expression (leave empty for default).
  2079. * @public
  2080. * @since 4.6.016 (2009-06-15)
  2081. */
  2082. public function setSpacesRE($re='/[^\S\xa0]/') {
  2083. $this->re_spaces = $re;
  2084. $re_parts = explode('/', $re);
  2085. // get pattern parts
  2086. $this->re_space = array();
  2087. if (isset($re_parts[1]) AND !empty($re_parts[1])) {
  2088. $this->re_space['p'] = $re_parts[1];
  2089. } else {
  2090. $this->re_space['p'] = '[\s]';
  2091. }
  2092. // set pattern modifiers
  2093. if (isset($re_parts[2]) AND !empty($re_parts[2])) {
  2094. $this->re_space['m'] = $re_parts[2];
  2095. } else {
  2096. $this->re_space['m'] = '';
  2097. }
  2098. }
  2099. /**
  2100. * Enable or disable Right-To-Left language mode
  2101. * @param $enable (Boolean) if true enable Right-To-Left language mode.
  2102. * @param $resetx (Boolean) if true reset the X position on direction change.
  2103. * @public
  2104. * @since 2.0.000 (2008-01-03)
  2105. */
  2106. public function setRTL($enable, $resetx=true) {
  2107. $enable = $enable ? true : false;
  2108. $resetx = ($resetx AND ($enable != $this->rtl));
  2109. $this->rtl = $enable;
  2110. $this->tmprtl = false;
  2111. if ($resetx) {
  2112. $this->Ln(0);
  2113. }
  2114. }
  2115. /**
  2116. * Return the RTL status
  2117. * @return boolean
  2118. * @public
  2119. * @since 4.0.012 (2008-07-24)
  2120. */
  2121. public function getRTL() {
  2122. return $this->rtl;
  2123. }
  2124. /**
  2125. * Force temporary RTL language direction
  2126. * @param $mode (mixed) can be false, 'L' for LTR or 'R' for RTL
  2127. * @public
  2128. * @since 2.1.000 (2008-01-09)
  2129. */
  2130. public function setTempRTL($mode) {
  2131. $newmode = false;
  2132. switch (strtoupper($mode)) {
  2133. case 'LTR':
  2134. case 'L': {
  2135. if ($this->rtl) {
  2136. $newmode = 'L';
  2137. }
  2138. break;
  2139. }
  2140. case 'RTL':
  2141. case 'R': {
  2142. if (!$this->rtl) {
  2143. $newmode = 'R';
  2144. }
  2145. break;
  2146. }
  2147. case false:
  2148. default: {
  2149. $newmode = false;
  2150. break;
  2151. }
  2152. }
  2153. $this->tmprtl = $newmode;
  2154. }
  2155. /**
  2156. * Return the current temporary RTL status
  2157. * @return boolean
  2158. * @public
  2159. * @since 4.8.014 (2009-11-04)
  2160. */
  2161. public function isRTLTextDir() {
  2162. return ($this->rtl OR ($this->tmprtl == 'R'));
  2163. }
  2164. /**
  2165. * Set the last cell height.
  2166. * @param $h (float) cell height.
  2167. * @author Nicola Asuni
  2168. * @public
  2169. * @since 1.53.0.TC034
  2170. */
  2171. public function setLastH($h) {
  2172. $this->lasth = $h;
  2173. }
  2174. /**
  2175. * Return the cell height
  2176. * @param $fontsize (int) Font size in internal units
  2177. * @param $padding (boolean) If true add cell padding
  2178. * @public
  2179. */
  2180. public function getCellHeight($fontsize, $padding=TRUE) {
  2181. $height = ($fontsize * $this->cell_height_ratio);
  2182. if ($padding) {
  2183. $height += ($this->cell_padding['T'] + $this->cell_padding['B']);
  2184. }
  2185. return round($height, 6);
  2186. }
  2187. /**
  2188. * Reset the last cell height.
  2189. * @public
  2190. * @since 5.9.000 (2010-10-03)
  2191. */
  2192. public function resetLastH() {
  2193. $this->lasth = $this->getCellHeight($this->FontSize);
  2194. }
  2195. /**
  2196. * Get the last cell height.
  2197. * @return last cell height
  2198. * @public
  2199. * @since 4.0.017 (2008-08-05)
  2200. */
  2201. public function getLastH() {
  2202. return $this->lasth;
  2203. }
  2204. /**
  2205. * Set the adjusting factor to convert pixels to user units.
  2206. * @param $scale (float) adjusting factor to convert pixels to user units.
  2207. * @author Nicola Asuni
  2208. * @public
  2209. * @since 1.5.2
  2210. */
  2211. public function setImageScale($scale) {
  2212. $this->imgscale = $scale;
  2213. }
  2214. /**
  2215. * Returns the adjusting factor to convert pixels to user units.
  2216. * @return float adjusting factor to convert pixels to user units.
  2217. * @author Nicola Asuni
  2218. * @public
  2219. * @since 1.5.2
  2220. */
  2221. public function getImageScale() {
  2222. return $this->imgscale;
  2223. }
  2224. /**
  2225. * Returns an array of page dimensions:
  2226. * <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</
  2227. * @param $pagenum (int) page number (empty = current page)
  2228. * @return array of page dimensions.
  2229. * @author Nicola Asuni
  2230. * @public
  2231. * @since 4.5.027 (2009-03-16)
  2232. */
  2233. public function getPageDimensions($pagenum='') {
  2234. if (empty($pagenum)) {
  2235. $pagenum = $this->page;
  2236. }
  2237. return $this->pagedim[$pagenum];
  2238. }
  2239. /**
  2240. * Returns the page width in units.
  2241. * @param $pagenum (int) page number (empty = current page)
  2242. * @return int page width.
  2243. * @author Nicola Asuni
  2244. * @public
  2245. * @since 1.5.2
  2246. * @see getPageDimensions()
  2247. */
  2248. public function getPageWidth($pagenum='') {
  2249. if (empty($pagenum)) {
  2250. return $this->w;
  2251. }
  2252. return $this->pagedim[$pagenum]['w'];
  2253. }
  2254. /**
  2255. * Returns the page height in units.
  2256. * @param $pagenum (int) page number (empty = current page)
  2257. * @return int page height.
  2258. * @author Nicola Asuni
  2259. * @public
  2260. * @since 1.5.2
  2261. * @see getPageDimensions()
  2262. */
  2263. public function getPageHeight($pagenum='') {
  2264. if (empty($pagenum)) {
  2265. return $this->h;
  2266. }
  2267. return $this->pagedim[$pagenum]['h'];
  2268. }
  2269. /**
  2270. * Returns the page break margin.
  2271. * @param $pagenum (int) page number (empty = current page)
  2272. * @return int page break margin.
  2273. * @author Nicola Asuni
  2274. * @public
  2275. * @since 1.5.2
  2276. * @see getPageDimensions()
  2277. */
  2278. public function getBreakMargin($pagenum='') {
  2279. if (empty($pagenum)) {
  2280. return $this->bMargin;
  2281. }
  2282. return $this->pagedim[$pagenum]['bm'];
  2283. }
  2284. /**
  2285. * Returns the scale factor (number of points in user unit).
  2286. * @return int scale factor.
  2287. * @author Nicola Asuni
  2288. * @public
  2289. * @since 1.5.2
  2290. */
  2291. public function getScaleFactor() {
  2292. return $this->k;
  2293. }
  2294. /**
  2295. * Defines the left, top and right margins.
  2296. * @param $left (float) Left margin.
  2297. * @param $top (float) Top margin.
  2298. * @param $right (float) Right margin. Default value is the left one.
  2299. * @param $keepmargins (boolean) if true overwrites the default page margins
  2300. * @public
  2301. * @since 1.0
  2302. * @see SetLeftMargin(), SetTopMargin(), SetRightMargin(), SetAutoPageBreak()
  2303. */
  2304. public function SetMargins($left, $top, $right=-1, $keepmargins=false) {
  2305. //Set left, top and right margins
  2306. $this->lMargin = $left;
  2307. $this->tMargin = $top;
  2308. if ($right == -1) {
  2309. $right = $left;
  2310. }
  2311. $this->rMargin = $right;
  2312. if ($keepmargins) {
  2313. // overwrite original values
  2314. $this->original_lMargin = $this->lMargin;
  2315. $this->original_rMargin = $this->rMargin;
  2316. }
  2317. }
  2318. /**
  2319. * 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.
  2320. * @param $margin (float) The margin.
  2321. * @public
  2322. * @since 1.4
  2323. * @see SetTopMargin(), SetRightMargin(), SetAutoPageBreak(), SetMargins()
  2324. */
  2325. public function SetLeftMargin($margin) {
  2326. //Set left margin
  2327. $this->lMargin = $margin;
  2328. if (($this->page > 0) AND ($this->x < $margin)) {
  2329. $this->x = $margin;
  2330. }
  2331. }
  2332. /**
  2333. * Defines the top margin. The method can be called before creating the first page.
  2334. * @param $margin (float) The margin.
  2335. * @public
  2336. * @since 1.5
  2337. * @see SetLeftMargin(), SetRightMargin(), SetAutoPageBreak(), SetMargins()
  2338. */
  2339. public function SetTopMargin($margin) {
  2340. //Set top margin
  2341. $this->tMargin = $margin;
  2342. if (($this->page > 0) AND ($this->y < $margin)) {
  2343. $this->y = $margin;
  2344. }
  2345. }
  2346. /**
  2347. * Defines the right margin. The method can be called before creating the first page.
  2348. * @param $margin (float) The margin.
  2349. * @public
  2350. * @since 1.5
  2351. * @see SetLeftMargin(), SetTopMargin(), SetAutoPageBreak(), SetMargins()
  2352. */
  2353. public function SetRightMargin($margin) {
  2354. $this->rMargin = $margin;
  2355. if (($this->page > 0) AND ($this->x > ($this->w - $margin))) {
  2356. $this->x = $this->w - $margin;
  2357. }
  2358. }
  2359. /**
  2360. * Set the same internal Cell padding for top, right, bottom, left-
  2361. * @param $pad (float) internal padding.
  2362. * @public
  2363. * @since 2.1.000 (2008-01-09)
  2364. * @see getCellPaddings(), setCellPaddings()
  2365. */
  2366. public function SetCellPadding($pad) {
  2367. if ($pad >= 0) {
  2368. $this->cell_padding['L'] = $pad;
  2369. $this->cell_padding['T'] = $pad;
  2370. $this->cell_padding['R'] = $pad;
  2371. $this->cell_padding['B'] = $pad;
  2372. }
  2373. }
  2374. /**
  2375. * Set the internal Cell paddings.
  2376. * @param $left (float) left padding
  2377. * @param $top (float) top padding
  2378. * @param $right (float) right padding
  2379. * @param $bottom (float) bottom padding
  2380. * @public
  2381. * @since 5.9.000 (2010-10-03)
  2382. * @see getCellPaddings(), SetCellPadding()
  2383. */
  2384. public function setCellPaddings($left='', $top='', $right='', $bottom='') {
  2385. if (($left !== '') AND ($left >= 0)) {
  2386. $this->cell_padding['L'] = $left;
  2387. }
  2388. if (($top !== '') AND ($top >= 0)) {
  2389. $this->cell_padding['T'] = $top;
  2390. }
  2391. if (($right !== '') AND ($right >= 0)) {
  2392. $this->cell_padding['R'] = $right;
  2393. }
  2394. if (($bottom !== '') AND ($bottom >= 0)) {
  2395. $this->cell_padding['B'] = $bottom;
  2396. }
  2397. }
  2398. /**
  2399. * Get the internal Cell padding array.
  2400. * @return array of padding values
  2401. * @public
  2402. * @since 5.9.000 (2010-10-03)
  2403. * @see setCellPaddings(), SetCellPadding()
  2404. */
  2405. public function getCellPaddings() {
  2406. return $this->cell_padding;
  2407. }
  2408. /**
  2409. * Set the internal Cell margins.
  2410. * @param $left (float) left margin
  2411. * @param $top (float) top margin
  2412. * @param $right (float) right margin
  2413. * @param $bottom (float) bottom margin
  2414. * @public
  2415. * @since 5.9.000 (2010-10-03)
  2416. * @see getCellMargins()
  2417. */
  2418. public function setCellMargins($left='', $top='', $right='', $bottom='') {
  2419. if (($left !== '') AND ($left >= 0)) {
  2420. $this->cell_margin['L'] = $left;
  2421. }
  2422. if (($top !== '') AND ($top >= 0)) {
  2423. $this->cell_margin['T'] = $top;
  2424. }
  2425. if (($right !== '') AND ($right >= 0)) {
  2426. $this->cell_margin['R'] = $right;
  2427. }
  2428. if (($bottom !== '') AND ($bottom >= 0)) {
  2429. $this->cell_margin['B'] = $bottom;
  2430. }
  2431. }
  2432. /**
  2433. * Get the internal Cell margin array.
  2434. * @return array of margin values
  2435. * @public
  2436. * @since 5.9.000 (2010-10-03)
  2437. * @see setCellMargins()
  2438. */
  2439. public function getCellMargins() {
  2440. return $this->cell_margin;
  2441. }
  2442. /**
  2443. * Adjust the internal Cell padding array to take account of the line width.
  2444. * @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)))
  2445. * @return array of adjustments
  2446. * @public
  2447. * @since 5.9.000 (2010-10-03)
  2448. */
  2449. protected function adjustCellPadding($brd=0) {
  2450. if (empty($brd)) {
  2451. return;
  2452. }
  2453. if (is_string($brd)) {
  2454. // convert string to array
  2455. $slen = strlen($brd);
  2456. $newbrd = array();
  2457. for ($i = 0; $i < $slen; ++$i) {
  2458. $newbrd[$brd[$i]] = true;
  2459. }
  2460. $brd = $newbrd;
  2461. } elseif (($brd === 1) OR ($brd === true) OR (is_numeric($brd) AND (intval($brd) > 0))) {
  2462. $brd = array('LRTB' => true);
  2463. }
  2464. if (!is_array($brd)) {
  2465. return;
  2466. }
  2467. // store current cell padding
  2468. $cp = $this->cell_padding;
  2469. // select border mode
  2470. if (isset($brd['mode'])) {
  2471. $mode = $brd['mode'];
  2472. unset($brd['mode']);
  2473. } else {
  2474. $mode = 'normal';
  2475. }
  2476. // process borders
  2477. foreach ($brd as $border => $style) {
  2478. $line_width = $this->LineWidth;
  2479. if (is_array($style) AND isset($style['width'])) {
  2480. // get border width
  2481. $line_width = $style['width'];
  2482. }
  2483. $adj = 0; // line width inside the cell
  2484. switch ($mode) {
  2485. case 'ext': {
  2486. $adj = 0;
  2487. break;
  2488. }
  2489. case 'int': {
  2490. $adj = $line_width;
  2491. break;
  2492. }
  2493. case 'normal':
  2494. default: {
  2495. $adj = ($line_width / 2);
  2496. break;
  2497. }
  2498. }
  2499. // correct internal cell padding if required to avoid overlap between text and lines
  2500. if ((strpos($border,'T') !== false) AND ($this->cell_padding['T'] < $adj)) {
  2501. $this->cell_padding['T'] = $adj;
  2502. }
  2503. if ((strpos($border,'R') !== false) AND ($this->cell_padding['R'] < $adj)) {
  2504. $this->cell_padding['R'] = $adj;
  2505. }
  2506. if ((strpos($border,'B') !== false) AND ($this->cell_padding['B'] < $adj)) {
  2507. $this->cell_padding['B'] = $adj;
  2508. }
  2509. if ((strpos($border,'L') !== false) AND ($this->cell_padding['L'] < $adj)) {
  2510. $this->cell_padding['L'] = $adj;
  2511. }
  2512. }
  2513. 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']));
  2514. }
  2515. /**
  2516. * 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.
  2517. * @param $auto (boolean) Boolean indicating if mode should be on or off.
  2518. * @param $margin (float) Distance from the bottom of the page.
  2519. * @public
  2520. * @since 1.0
  2521. * @see Cell(), MultiCell(), AcceptPageBreak()
  2522. */
  2523. public function SetAutoPageBreak($auto, $margin=0) {
  2524. $this->AutoPageBreak = $auto ? true : false;
  2525. $this->bMargin = $margin;
  2526. $this->PageBreakTrigger = $this->h - $margin;
  2527. }
  2528. /**
  2529. * Return the auto-page-break mode (true or false).
  2530. * @return boolean auto-page-break mode
  2531. * @public
  2532. * @since 5.9.088
  2533. */
  2534. public function getAutoPageBreak() {
  2535. return $this->AutoPageBreak;
  2536. }
  2537. /**
  2538. * Defines the way the document is to be displayed by the viewer.
  2539. * @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>
  2540. * @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>
  2541. * @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>
  2542. * @public
  2543. * @since 1.2
  2544. */
  2545. public function SetDisplayMode($zoom, $layout='SinglePage', $mode='UseNone') {
  2546. if (($zoom == 'fullpage') OR ($zoom == 'fullwidth') OR ($zoom == 'real') OR ($zoom == 'default') OR (!is_string($zoom))) {
  2547. $this->ZoomMode = $zoom;
  2548. } else {
  2549. $this->Error('Incorrect zoom display mode: '.$zoom);
  2550. }
  2551. $this->LayoutMode = TCPDF_STATIC::getPageLayoutMode($layout);
  2552. $this->PageMode = TCPDF_STATIC::getPageMode($mode);
  2553. }
  2554. /**
  2555. * 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.
  2556. * Note: the Zlib extension is required for this feature. If not present, compression will be turned off.
  2557. * @param $compress (boolean) Boolean indicating if compression must be enabled.
  2558. * @public
  2559. * @since 1.4
  2560. */
  2561. public function SetCompression($compress=true) {
  2562. $this->compress = false;
  2563. if (function_exists('gzcompress')) {
  2564. if ($compress) {
  2565. if ( !$this->pdfa_mode) {
  2566. $this->compress = true;
  2567. }
  2568. }
  2569. }
  2570. }
  2571. /**
  2572. * Set flag to force sRGB_IEC61966-2.1 black scaled ICC color profile for the whole document.
  2573. * @param $mode (boolean) If true force sRGB output intent.
  2574. * @public
  2575. * @since 5.9.121 (2011-09-28)
  2576. */
  2577. public function setSRGBmode($mode=false) {
  2578. $this->force_srgb = $mode ? true : false;
  2579. }
  2580. /**
  2581. * Turn on/off Unicode mode for document information dictionary (meta tags).
  2582. * This has effect only when unicode mode is set to false.
  2583. * @param $unicode (boolean) if true set the meta information in Unicode
  2584. * @since 5.9.027 (2010-12-01)
  2585. * @public
  2586. */
  2587. public function SetDocInfoUnicode($unicode=true) {
  2588. $this->docinfounicode = $unicode ? true : false;
  2589. }
  2590. /**
  2591. * Defines the title of the document.
  2592. * @param $title (string) The title.
  2593. * @public
  2594. * @since 1.2
  2595. * @see SetAuthor(), SetCreator(), SetKeywords(), SetSubject()
  2596. */
  2597. public function SetTitle($title) {
  2598. $this->title = $title;
  2599. }
  2600. /**
  2601. * Defines the subject of the document.
  2602. * @param $subject (string) The subject.
  2603. * @public
  2604. * @since 1.2
  2605. * @see SetAuthor(), SetCreator(), SetKeywords(), SetTitle()
  2606. */
  2607. public function SetSubject($subject) {
  2608. $this->subject = $subject;
  2609. }
  2610. /**
  2611. * Defines the author of the document.
  2612. * @param $author (string) The name of the author.
  2613. * @public
  2614. * @since 1.2
  2615. * @see SetCreator(), SetKeywords(), SetSubject(), SetTitle()
  2616. */
  2617. public function SetAuthor($author) {
  2618. $this->author = $author;
  2619. }
  2620. /**
  2621. * Associates keywords with the document, generally in the form 'keyword1 keyword2 ...'.
  2622. * @param $keywords (string) The list of keywords.
  2623. * @public
  2624. * @since 1.2
  2625. * @see SetAuthor(), SetCreator(), SetSubject(), SetTitle()
  2626. */
  2627. public function SetKeywords($keywords) {
  2628. $this->keywords = $keywords;
  2629. }
  2630. /**
  2631. * Defines the creator of the document. This is typically the name of the application that generates the PDF.
  2632. * @param $creator (string) The name of the creator.
  2633. * @public
  2634. * @since 1.2
  2635. * @see SetAuthor(), SetKeywords(), SetSubject(), SetTitle()
  2636. */
  2637. public function SetCreator($creator) {
  2638. $this->creator = $creator;
  2639. }
  2640. /**
  2641. * Throw an exception or print an error message and die if the K_TCPDF_PARSER_THROW_EXCEPTION_ERROR constant is set to true.
  2642. * @param $msg (string) The error message
  2643. * @public
  2644. * @since 1.0
  2645. */
  2646. public function Error($msg) {
  2647. // unset all class variables
  2648. $this->_destroy(true);
  2649. if (defined('K_TCPDF_THROW_EXCEPTION_ERROR') AND !K_TCPDF_THROW_EXCEPTION_ERROR) {
  2650. die('<strong>TCPDF ERROR: </strong>'.$msg);
  2651. } else {
  2652. throw new Exception('TCPDF ERROR: '.$msg);
  2653. }
  2654. }
  2655. /**
  2656. * This method begins the generation of the PDF document.
  2657. * It is not necessary to call it explicitly because AddPage() does it automatically.
  2658. * Note: no page is created by this method
  2659. * @public
  2660. * @since 1.0
  2661. * @see AddPage(), Close()
  2662. */
  2663. public function Open() {
  2664. $this->state = 1;
  2665. }
  2666. /**
  2667. * Terminates the PDF document.
  2668. * It is not necessary to call this method explicitly because Output() does it automatically.
  2669. * If the document contains no page, AddPage() is called to prevent from getting an invalid document.
  2670. * @public
  2671. * @since 1.0
  2672. * @see Open(), Output()
  2673. */
  2674. public function Close() {
  2675. if ($this->state == 3) {
  2676. return;
  2677. }
  2678. if ($this->page == 0) {
  2679. $this->AddPage();
  2680. }
  2681. $this->endLayer();
  2682. if ($this->tcpdflink) {
  2683. // save current graphic settings
  2684. $gvars = $this->getGraphicVars();
  2685. $this->setEqualColumns();
  2686. $this->lastpage(true);
  2687. $this->SetAutoPageBreak(false);
  2688. $this->x = 0;
  2689. $this->y = $this->h - (1 / $this->k);
  2690. $this->lMargin = 0;
  2691. $this->_outSaveGraphicsState();
  2692. $font = defined('PDF_FONT_NAME_MAIN')?PDF_FONT_NAME_MAIN:'helvetica';
  2693. $this->SetFont($font, '', 1);
  2694. $this->setTextRenderingMode(0, false, false);
  2695. $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";
  2696. $lnk = "\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x74\x63\x70\x64\x66\x2e\x6f\x72\x67";
  2697. $this->Cell(0, 0, $msg, 0, 0, 'L', 0, $lnk, 0, false, 'D', 'B');
  2698. $this->_outRestoreGraphicsState();
  2699. // restore graphic settings
  2700. $this->setGraphicVars($gvars);
  2701. }
  2702. // close page
  2703. $this->endPage();
  2704. // close document
  2705. $this->_enddoc();
  2706. // unset all class variables (except critical ones)
  2707. $this->_destroy(false);
  2708. }
  2709. /**
  2710. * Move pointer at the specified document page and update page dimensions.
  2711. * @param $pnum (int) page number (1 ... numpages)
  2712. * @param $resetmargins (boolean) if true reset left, right, top margins and Y position.
  2713. * @public
  2714. * @since 2.1.000 (2008-01-07)
  2715. * @see getPage(), lastpage(), getNumPages()
  2716. */
  2717. public function setPage($pnum, $resetmargins=false) {
  2718. if (($pnum == $this->page) AND ($this->state == 2)) {
  2719. return;
  2720. }
  2721. if (($pnum > 0) AND ($pnum <= $this->numpages)) {
  2722. $this->state = 2;
  2723. // save current graphic settings
  2724. //$gvars = $this->getGraphicVars();
  2725. $oldpage = $this->page;
  2726. $this->page = $pnum;
  2727. $this->wPt = $this->pagedim[$this->page]['w'];
  2728. $this->hPt = $this->pagedim[$this->page]['h'];
  2729. $this->w = $this->pagedim[$this->page]['wk'];
  2730. $this->h = $this->pagedim[$this->page]['hk'];
  2731. $this->tMargin = $this->pagedim[$this->page]['tm'];
  2732. $this->bMargin = $this->pagedim[$this->page]['bm'];
  2733. $this->original_lMargin = $this->pagedim[$this->page]['olm'];
  2734. $this->original_rMargin = $this->pagedim[$this->page]['orm'];
  2735. $this->AutoPageBreak = $this->pagedim[$this->page]['pb'];
  2736. $this->CurOrientation = $this->pagedim[$this->page]['or'];
  2737. $this->SetAutoPageBreak($this->AutoPageBreak, $this->bMargin);
  2738. // restore graphic settings
  2739. //$this->setGraphicVars($gvars);
  2740. if ($resetmargins) {
  2741. $this->lMargin = $this->pagedim[$this->page]['olm'];
  2742. $this->rMargin = $this->pagedim[$this->page]['orm'];
  2743. $this->SetY($this->tMargin);
  2744. } else {
  2745. // account for booklet mode
  2746. if ($this->pagedim[$this->page]['olm'] != $this->pagedim[$oldpage]['olm']) {
  2747. $deltam = $this->pagedim[$this->page]['olm'] - $this->pagedim[$this->page]['orm'];
  2748. $this->lMargin += $deltam;
  2749. $this->rMargin -= $deltam;
  2750. }
  2751. }
  2752. } else {
  2753. $this->Error('Wrong page number on setPage() function: '.$pnum);
  2754. }
  2755. }
  2756. /**
  2757. * Reset pointer to the last document page.
  2758. * @param $resetmargins (boolean) if true reset left, right, top margins and Y position.
  2759. * @public
  2760. * @since 2.0.000 (2008-01-04)
  2761. * @see setPage(), getPage(), getNumPages()
  2762. */
  2763. public function lastPage($resetmargins=false) {
  2764. $this->setPage($this->getNumPages(), $resetmargins);
  2765. }
  2766. /**
  2767. * Get current document page number.
  2768. * @return int page number
  2769. * @public
  2770. * @since 2.1.000 (2008-01-07)
  2771. * @see setPage(), lastpage(), getNumPages()
  2772. */
  2773. public function getPage() {
  2774. return $this->page;
  2775. }
  2776. /**
  2777. * Get the total number of insered pages.
  2778. * @return int number of pages
  2779. * @public
  2780. * @since 2.1.000 (2008-01-07)
  2781. * @see setPage(), getPage(), lastpage()
  2782. */
  2783. public function getNumPages() {
  2784. return $this->numpages;
  2785. }
  2786. /**
  2787. * Adds a new TOC (Table Of Content) page to the document.
  2788. * @param $orientation (string) page orientation.
  2789. * @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().
  2790. * @param $keepmargins (boolean) if true overwrites the default page margins with the current margins
  2791. * @public
  2792. * @since 5.0.001 (2010-05-06)
  2793. * @see AddPage(), startPage(), endPage(), endTOCPage()
  2794. */
  2795. public function addTOCPage($orientation='', $format='', $keepmargins=false) {
  2796. $this->AddPage($orientation, $format, $keepmargins, true);
  2797. }
  2798. /**
  2799. * Terminate the current TOC (Table Of Content) page
  2800. * @public
  2801. * @since 5.0.001 (2010-05-06)
  2802. * @see AddPage(), startPage(), endPage(), addTOCPage()
  2803. */
  2804. public function endTOCPage() {
  2805. $this->endPage(true);
  2806. }
  2807. /**
  2808. * 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).
  2809. * The origin of the coordinate system is at the top-left corner (or top-right for RTL) and increasing ordinates go downwards.
  2810. * @param $orientation (string) page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
  2811. * @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().
  2812. * @param $keepmargins (boolean) if true overwrites the default page margins with the current margins
  2813. * @param $tocpage (boolean) if true set the tocpage state to true (the added page will be used to display Table Of Content).
  2814. * @public
  2815. * @since 1.0
  2816. * @see startPage(), endPage(), addTOCPage(), endTOCPage(), getPageSizeFromFormat(), setPageFormat()
  2817. */
  2818. public function AddPage($orientation='', $format='', $keepmargins=false, $tocpage=false) {
  2819. if ($this->inxobj) {
  2820. // we are inside an XObject template
  2821. return;
  2822. }
  2823. if (!isset($this->original_lMargin) OR $keepmargins) {
  2824. $this->original_lMargin = $this->lMargin;
  2825. }
  2826. if (!isset($this->original_rMargin) OR $keepmargins) {
  2827. $this->original_rMargin = $this->rMargin;
  2828. }
  2829. // terminate previous page
  2830. $this->endPage();
  2831. // start new page
  2832. $this->startPage($orientation, $format, $tocpage);
  2833. }
  2834. /**
  2835. * Terminate the current page
  2836. * @param $tocpage (boolean) if true set the tocpage state to false (end the page used to display Table Of Content).
  2837. * @public
  2838. * @since 4.2.010 (2008-11-14)
  2839. * @see AddPage(), startPage(), addTOCPage(), endTOCPage()
  2840. */
  2841. public function endPage($tocpage=false) {
  2842. // check if page is already closed
  2843. if (($this->page == 0) OR ($this->numpages > $this->page) OR (!$this->pageopen[$this->page])) {
  2844. return;
  2845. }
  2846. // print page footer
  2847. $this->setFooter();
  2848. // close page
  2849. $this->_endpage();
  2850. // mark page as closed
  2851. $this->pageopen[$this->page] = false;
  2852. if ($tocpage) {
  2853. $this->tocpage = false;
  2854. }
  2855. }
  2856. /**
  2857. * Starts a new page to the document. The page must be closed using the endPage() function.
  2858. * The origin of the coordinate system is at the top-left corner and increasing ordinates go downwards.
  2859. * @param $orientation (string) page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
  2860. * @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().
  2861. * @param $tocpage (boolean) if true the page is designated to contain the Table-Of-Content.
  2862. * @since 4.2.010 (2008-11-14)
  2863. * @see AddPage(), endPage(), addTOCPage(), endTOCPage(), getPageSizeFromFormat(), setPageFormat()
  2864. * @public
  2865. */
  2866. public function startPage($orientation='', $format='', $tocpage=false) {
  2867. if ($tocpage) {
  2868. $this->tocpage = true;
  2869. }
  2870. // move page numbers of documents to be attached
  2871. if ($this->tocpage) {
  2872. // move reference to unexistent pages (used for page attachments)
  2873. // adjust outlines
  2874. $tmpoutlines = $this->outlines;
  2875. foreach ($tmpoutlines as $key => $outline) {
  2876. if (!$outline['f'] AND ($outline['p'] > $this->numpages)) {
  2877. $this->outlines[$key]['p'] = ($outline['p'] + 1);
  2878. }
  2879. }
  2880. // adjust dests
  2881. $tmpdests = $this->dests;
  2882. foreach ($tmpdests as $key => $dest) {
  2883. if (!$dest['f'] AND ($dest['p'] > $this->numpages)) {
  2884. $this->dests[$key]['p'] = ($dest['p'] + 1);
  2885. }
  2886. }
  2887. // adjust links
  2888. $tmplinks = $this->links;
  2889. foreach ($tmplinks as $key => $link) {
  2890. if (!$link['f'] AND ($link['p'] > $this->numpages)) {
  2891. $this->links[$key]['p'] = ($link['p'] + 1);
  2892. }
  2893. }
  2894. }
  2895. if ($this->numpages > $this->page) {
  2896. // this page has been already added
  2897. $this->setPage($this->page + 1);
  2898. $this->SetY($this->tMargin);
  2899. return;
  2900. }
  2901. // start a new page
  2902. if ($this->state == 0) {
  2903. $this->Open();
  2904. }
  2905. ++$this->numpages;
  2906. $this->swapMargins($this->booklet);
  2907. // save current graphic settings
  2908. $gvars = $this->getGraphicVars();
  2909. // start new page
  2910. $this->_beginpage($orientation, $format);
  2911. // mark page as open
  2912. $this->pageopen[$this->page] = true;
  2913. // restore graphic settings
  2914. $this->setGraphicVars($gvars);
  2915. // mark this point
  2916. $this->setPageMark();
  2917. // print page header
  2918. $this->setHeader();
  2919. // restore graphic settings
  2920. $this->setGraphicVars($gvars);
  2921. // mark this point
  2922. $this->setPageMark();
  2923. // print table header (if any)
  2924. $this->setTableHeader();
  2925. // set mark for empty page check
  2926. $this->emptypagemrk[$this->page]= $this->pagelen[$this->page];
  2927. }
  2928. /**
  2929. * Set start-writing mark on current page stream used to put borders and fills.
  2930. * Borders and fills are always created after content and inserted on the position marked by this method.
  2931. * This function must be called after calling Image() function for a background image.
  2932. * Background images must be always inserted before calling Multicell() or WriteHTMLCell() or WriteHTML() functions.
  2933. * @public
  2934. * @since 4.0.016 (2008-07-30)
  2935. */
  2936. public function setPageMark() {
  2937. $this->intmrk[$this->page] = $this->pagelen[$this->page];
  2938. $this->bordermrk[$this->page] = $this->intmrk[$this->page];
  2939. $this->setContentMark();
  2940. }
  2941. /**
  2942. * Set start-writing mark on selected page.
  2943. * Borders and fills are always created after content and inserted on the position marked by this method.
  2944. * @param $page (int) page number (default is the current page)
  2945. * @protected
  2946. * @since 4.6.021 (2009-07-20)
  2947. */
  2948. protected function setContentMark($page=0) {
  2949. if ($page <= 0) {
  2950. $page = $this->page;
  2951. }
  2952. if (isset($this->footerlen[$page])) {
  2953. $this->cntmrk[$page] = $this->pagelen[$page] - $this->footerlen[$page];
  2954. } else {
  2955. $this->cntmrk[$page] = $this->pagelen[$page];
  2956. }
  2957. }
  2958. /**
  2959. * Set header data.
  2960. * @param $ln (string) header image logo
  2961. * @param $lw (string) header image logo width in mm
  2962. * @param $ht (string) string to print as title on document header
  2963. * @param $hs (string) string to print on document header
  2964. * @param $tc (array) RGB array color for text.
  2965. * @param $lc (array) RGB array color for line.
  2966. * @public
  2967. */
  2968. public function setHeaderData($ln='', $lw=0, $ht='', $hs='', $tc=array(0,0,0), $lc=array(0,0,0)) {
  2969. $this->header_logo = $ln;
  2970. $this->header_logo_width = $lw;
  2971. $this->header_title = $ht;
  2972. $this->header_string = $hs;
  2973. $this->header_text_color = $tc;
  2974. $this->header_line_color = $lc;
  2975. }
  2976. /**
  2977. * Set footer data.
  2978. * @param $tc (array) RGB array color for text.
  2979. * @param $lc (array) RGB array color for line.
  2980. * @public
  2981. */
  2982. public function setFooterData($tc=array(0,0,0), $lc=array(0,0,0)) {
  2983. $this->footer_text_color = $tc;
  2984. $this->footer_line_color = $lc;
  2985. }
  2986. /**
  2987. * Returns header data:
  2988. * <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>
  2989. * @return array()
  2990. * @public
  2991. * @since 4.0.012 (2008-07-24)
  2992. */
  2993. public function getHeaderData() {
  2994. $ret = array();
  2995. $ret['logo'] = $this->header_logo;
  2996. $ret['logo_width'] = $this->header_logo_width;
  2997. $ret['title'] = $this->header_title;
  2998. $ret['string'] = $this->header_string;
  2999. $ret['text_color'] = $this->header_text_color;
  3000. $ret['line_color'] = $this->header_line_color;
  3001. return $ret;
  3002. }
  3003. /**
  3004. * Set header margin.
  3005. * (minimum distance between header and top page margin)
  3006. * @param $hm (int) distance in user units
  3007. * @public
  3008. */
  3009. public function setHeaderMargin($hm=10) {
  3010. $this->header_margin = $hm;
  3011. }
  3012. /**
  3013. * Returns header margin in user units.
  3014. * @return float
  3015. * @since 4.0.012 (2008-07-24)
  3016. * @public
  3017. */
  3018. public function getHeaderMargin() {
  3019. return $this->header_margin;
  3020. }
  3021. /**
  3022. * Set footer margin.
  3023. * (minimum distance between footer and bottom page margin)
  3024. * @param $fm (int) distance in user units
  3025. * @public
  3026. */
  3027. public function setFooterMargin($fm=10) {
  3028. $this->footer_margin = $fm;
  3029. }
  3030. /**
  3031. * Returns footer margin in user units.
  3032. * @return float
  3033. * @since 4.0.012 (2008-07-24)
  3034. * @public
  3035. */
  3036. public function getFooterMargin() {
  3037. return $this->footer_margin;
  3038. }
  3039. /**
  3040. * Set a flag to print page header.
  3041. * @param $val (boolean) set to true to print the page header (default), false otherwise.
  3042. * @public
  3043. */
  3044. public function setPrintHeader($val=true) {
  3045. $this->print_header = $val ? true : false;
  3046. }
  3047. /**
  3048. * Set a flag to print page footer.
  3049. * @param $val (boolean) set to true to print the page footer (default), false otherwise.
  3050. * @public
  3051. */
  3052. public function setPrintFooter($val=true) {
  3053. $this->print_footer = $val ? true : false;
  3054. }
  3055. /**
  3056. * Return the right-bottom (or left-bottom for RTL) corner X coordinate of last inserted image
  3057. * @return float
  3058. * @public
  3059. */
  3060. public function getImageRBX() {
  3061. return $this->img_rb_x;
  3062. }
  3063. /**
  3064. * Return the right-bottom (or left-bottom for RTL) corner Y coordinate of last inserted image
  3065. * @return float
  3066. * @public
  3067. */
  3068. public function getImageRBY() {
  3069. return $this->img_rb_y;
  3070. }
  3071. /**
  3072. * Reset the xobject template used by Header() method.
  3073. * @public
  3074. */
  3075. public function resetHeaderTemplate() {
  3076. $this->header_xobjid = false;
  3077. }
  3078. /**
  3079. * Set a flag to automatically reset the xobject template used by Header() method at each page.
  3080. * @param $val (boolean) set to true to reset Header xobject template at each page, false otherwise.
  3081. * @public
  3082. */
  3083. public function setHeaderTemplateAutoreset($val=true) {
  3084. $this->header_xobj_autoreset = $val ? true : false;
  3085. }
  3086. /**
  3087. * This method is used to render the page header.
  3088. * It is automatically called by AddPage() and could be overwritten in your own inherited class.
  3089. * @public
  3090. */
  3091. public function Header() {
  3092. if ($this->header_xobjid === false) {
  3093. // start a new XObject Template
  3094. $this->header_xobjid = $this->startTemplate($this->w, $this->tMargin);
  3095. $headerfont = $this->getHeaderFont();
  3096. $headerdata = $this->getHeaderData();
  3097. $this->y = $this->header_margin;
  3098. if ($this->rtl) {
  3099. $this->x = $this->w - $this->original_rMargin;
  3100. } else {
  3101. $this->x = $this->original_lMargin;
  3102. }
  3103. if (($headerdata['logo']) AND ($headerdata['logo'] != K_BLANK_IMAGE)) {
  3104. $imgtype = TCPDF_IMAGES::getImageFileType(K_PATH_IMAGES.$headerdata['logo']);
  3105. if (($imgtype == 'eps') OR ($imgtype == 'ai')) {
  3106. $this->ImageEps(K_PATH_IMAGES.$headerdata['logo'], '', '', $headerdata['logo_width']);
  3107. } elseif ($imgtype == 'svg') {
  3108. $this->ImageSVG(K_PATH_IMAGES.$headerdata['logo'], '', '', $headerdata['logo_width']);
  3109. } else {
  3110. $this->Image(K_PATH_IMAGES.$headerdata['logo'], '', '', $headerdata['logo_width']);
  3111. }
  3112. $imgy = $this->getImageRBY();
  3113. } else {
  3114. $imgy = $this->y;
  3115. }
  3116. $cell_height = $this->getCellHeight($headerfont[2] / $this->k);
  3117. // set starting margin for text data cell
  3118. if ($this->getRTL()) {
  3119. $header_x = $this->original_rMargin + ($headerdata['logo_width'] * 1.1);
  3120. } else {
  3121. $header_x = $this->original_lMargin + ($headerdata['logo_width'] * 1.1);
  3122. }
  3123. $cw = $this->w - $this->original_lMargin - $this->original_rMargin - ($headerdata['logo_width'] * 1.1);
  3124. $this->SetTextColorArray($this->header_text_color);
  3125. // header title
  3126. $this->SetFont($headerfont[0], 'B', $headerfont[2] + 1);
  3127. $this->SetX($header_x);
  3128. $this->Cell($cw, $cell_height, $headerdata['title'], 0, 1, '', 0, '', 0);
  3129. // header string
  3130. $this->SetFont($headerfont[0], $headerfont[1], $headerfont[2]);
  3131. $this->SetX($header_x);
  3132. $this->MultiCell($cw, $cell_height, $headerdata['string'], 0, '', 0, 1, '', '', true, 0, false, true, 0, 'T', false);
  3133. // print an ending header line
  3134. $this->SetLineStyle(array('width' => 0.85 / $this->k, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => $headerdata['line_color']));
  3135. $this->SetY((2.835 / $this->k) + max($imgy, $this->y));
  3136. if ($this->rtl) {
  3137. $this->SetX($this->original_rMargin);
  3138. } else {
  3139. $this->SetX($this->original_lMargin);
  3140. }
  3141. $this->Cell(($this->w - $this->original_lMargin - $this->original_rMargin), 0, '', 'T', 0, 'C');
  3142. $this->endTemplate();
  3143. }
  3144. // print header template
  3145. $x = 0;
  3146. $dx = 0;
  3147. if (!$this->header_xobj_autoreset AND $this->booklet AND (($this->page % 2) == 0)) {
  3148. // adjust margins for booklet mode
  3149. $dx = ($this->original_lMargin - $this->original_rMargin);
  3150. }
  3151. if ($this->rtl) {
  3152. $x = $this->w + $dx;
  3153. } else {
  3154. $x = 0 + $dx;
  3155. }
  3156. $this->printTemplate($this->header_xobjid, $x, 0, 0, 0, '', '', false);
  3157. if ($this->header_xobj_autoreset) {
  3158. // reset header xobject template at each page
  3159. $this->header_xobjid = false;
  3160. }
  3161. }
  3162. /**
  3163. * This method is used to render the page footer.
  3164. * It is automatically called by AddPage() and could be overwritten in your own inherited class.
  3165. * @public
  3166. */
  3167. public function Footer() {
  3168. $cur_y = $this->y;
  3169. $this->SetTextColorArray($this->footer_text_color);
  3170. //set style for cell border
  3171. $line_width = (0.85 / $this->k);
  3172. $this->SetLineStyle(array('width' => $line_width, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => $this->footer_line_color));
  3173. //print document barcode
  3174. $barcode = $this->getBarcode();
  3175. if (!empty($barcode)) {
  3176. $this->Ln($line_width);
  3177. $barcode_width = round(($this->w - $this->original_lMargin - $this->original_rMargin) / 3);
  3178. $style = array(
  3179. 'position' => $this->rtl?'R':'L',
  3180. 'align' => $this->rtl?'R':'L',
  3181. 'stretch' => false,
  3182. 'fitwidth' => true,
  3183. 'cellfitalign' => '',
  3184. 'border' => false,
  3185. 'padding' => 0,
  3186. 'fgcolor' => array(0,0,0),
  3187. 'bgcolor' => false,
  3188. 'text' => false
  3189. );
  3190. $this->write1DBarcode($barcode, 'C128', '', $cur_y + $line_width, '', (($this->footer_margin / 3) - $line_width), 0.3, $style, '');
  3191. }
  3192. $w_page = isset($this->l['w_page']) ? $this->l['w_page'].' ' : '';
  3193. if (empty($this->pagegroups)) {
  3194. $pagenumtxt = $w_page.$this->getAliasNumPage().' / '.$this->getAliasNbPages();
  3195. } else {
  3196. $pagenumtxt = $w_page.$this->getPageNumGroupAlias().' / '.$this->getPageGroupAlias();
  3197. }
  3198. $this->SetY($cur_y);
  3199. //Print page number
  3200. if ($this->getRTL()) {
  3201. $this->SetX($this->original_rMargin);
  3202. $this->Cell(0, 0, $pagenumtxt, 'T', 0, 'L');
  3203. } else {
  3204. $this->SetX($this->original_lMargin);
  3205. $this->Cell(0, 0, $this->getAliasRightShift().$pagenumtxt, 'T', 0, 'R');
  3206. }
  3207. }
  3208. /**
  3209. * This method is used to render the page header.
  3210. * @protected
  3211. * @since 4.0.012 (2008-07-24)
  3212. */
  3213. protected function setHeader() {
  3214. if (!$this->print_header OR ($this->state != 2)) {
  3215. return;
  3216. }
  3217. $this->InHeader = true;
  3218. $this->setGraphicVars($this->default_graphic_vars);
  3219. $temp_thead = $this->thead;
  3220. $temp_theadMargins = $this->theadMargins;
  3221. $lasth = $this->lasth;
  3222. $newline = $this->newline;
  3223. $this->_outSaveGraphicsState();
  3224. $this->rMargin = $this->original_rMargin;
  3225. $this->lMargin = $this->original_lMargin;
  3226. $this->SetCellPadding(0);
  3227. //set current position
  3228. if ($this->rtl) {
  3229. $this->SetXY($this->original_rMargin, $this->header_margin);
  3230. } else {
  3231. $this->SetXY($this->original_lMargin, $this->header_margin);
  3232. }
  3233. $this->SetFont($this->header_font[0], $this->header_font[1], $this->header_font[2]);
  3234. $this->Header();
  3235. //restore position
  3236. if ($this->rtl) {
  3237. $this->SetXY($this->original_rMargin, $this->tMargin);
  3238. } else {
  3239. $this->SetXY($this->original_lMargin, $this->tMargin);
  3240. }
  3241. $this->_outRestoreGraphicsState();
  3242. $this->lasth = $lasth;
  3243. $this->thead = $temp_thead;
  3244. $this->theadMargins = $temp_theadMargins;
  3245. $this->newline = $newline;
  3246. $this->InHeader = false;
  3247. }
  3248. /**
  3249. * This method is used to render the page footer.
  3250. * @protected
  3251. * @since 4.0.012 (2008-07-24)
  3252. */
  3253. protected function setFooter() {
  3254. if ($this->state != 2) {
  3255. return;
  3256. }
  3257. $this->InFooter = true;
  3258. // save current graphic settings
  3259. $gvars = $this->getGraphicVars();
  3260. // mark this point
  3261. $this->footerpos[$this->page] = $this->pagelen[$this->page];
  3262. $this->_out("\n");
  3263. if ($this->print_footer) {
  3264. $this->setGraphicVars($this->default_graphic_vars);
  3265. $this->current_column = 0;
  3266. $this->num_columns = 1;
  3267. $temp_thead = $this->thead;
  3268. $temp_theadMargins = $this->theadMargins;
  3269. $lasth = $this->lasth;
  3270. $this->_outSaveGraphicsState();
  3271. $this->rMargin = $this->original_rMargin;
  3272. $this->lMargin = $this->original_lMargin;
  3273. $this->SetCellPadding(0);
  3274. //set current position
  3275. $footer_y = $this->h - $this->footer_margin;
  3276. if ($this->rtl) {
  3277. $this->SetXY($this->original_rMargin, $footer_y);
  3278. } else {
  3279. $this->SetXY($this->original_lMargin, $footer_y);
  3280. }
  3281. $this->SetFont($this->footer_font[0], $this->footer_font[1], $this->footer_font[2]);
  3282. $this->Footer();
  3283. //restore position
  3284. if ($this->rtl) {
  3285. $this->SetXY($this->original_rMargin, $this->tMargin);
  3286. } else {
  3287. $this->SetXY($this->original_lMargin, $this->tMargin);
  3288. }
  3289. $this->_outRestoreGraphicsState();
  3290. $this->lasth = $lasth;
  3291. $this->thead = $temp_thead;
  3292. $this->theadMargins = $temp_theadMargins;
  3293. }
  3294. // restore graphic settings
  3295. $this->setGraphicVars($gvars);
  3296. $this->current_column = $gvars['current_column'];
  3297. $this->num_columns = $gvars['num_columns'];
  3298. // calculate footer length
  3299. $this->footerlen[$this->page] = $this->pagelen[$this->page] - $this->footerpos[$this->page] + 1;
  3300. $this->InFooter = false;
  3301. }
  3302. /**
  3303. * Check if we are on the page body (excluding page header and footer).
  3304. * @return true if we are not in page header nor in page footer, false otherwise.
  3305. * @protected
  3306. * @since 5.9.091 (2011-06-15)
  3307. */
  3308. protected function inPageBody() {
  3309. return (($this->InHeader === false) AND ($this->InFooter === false));
  3310. }
  3311. /**
  3312. * This method is used to render the table header on new page (if any).
  3313. * @protected
  3314. * @since 4.5.030 (2009-03-25)
  3315. */
  3316. protected function setTableHeader() {
  3317. if ($this->num_columns > 1) {
  3318. // multi column mode
  3319. return;
  3320. }
  3321. if (isset($this->theadMargins['top'])) {
  3322. // restore the original top-margin
  3323. $this->tMargin = $this->theadMargins['top'];
  3324. $this->pagedim[$this->page]['tm'] = $this->tMargin;
  3325. $this->y = $this->tMargin;
  3326. }
  3327. if (!TCPDF_STATIC::empty_string($this->thead) AND (!$this->inthead)) {
  3328. // set margins
  3329. $prev_lMargin = $this->lMargin;
  3330. $prev_rMargin = $this->rMargin;
  3331. $prev_cell_padding = $this->cell_padding;
  3332. $this->lMargin = $this->theadMargins['lmargin'] + ($this->pagedim[$this->page]['olm'] - $this->pagedim[$this->theadMargins['page']]['olm']);
  3333. $this->rMargin = $this->theadMargins['rmargin'] + ($this->pagedim[$this->page]['orm'] - $this->pagedim[$this->theadMargins['page']]['orm']);
  3334. $this->cell_padding = $this->theadMargins['cell_padding'];
  3335. if ($this->rtl) {
  3336. $this->x = $this->w - $this->rMargin;
  3337. } else {
  3338. $this->x = $this->lMargin;
  3339. }
  3340. // account for special "cell" mode
  3341. if ($this->theadMargins['cell']) {
  3342. if ($this->rtl) {
  3343. $this->x -= $this->cell_padding['R'];
  3344. } else {
  3345. $this->x += $this->cell_padding['L'];
  3346. }
  3347. }
  3348. $gvars = $this->getGraphicVars();
  3349. if (!empty($this->theadMargins['gvars'])) {
  3350. // set the correct graphic style
  3351. $this->setGraphicVars($this->theadMargins['gvars']);
  3352. $this->rMargin = $gvars['rMargin'];
  3353. $this->lMargin = $gvars['lMargin'];
  3354. }
  3355. // print table header
  3356. $this->writeHTML($this->thead, false, false, false, false, '');
  3357. $this->setGraphicVars($gvars);
  3358. // set new top margin to skip the table headers
  3359. if (!isset($this->theadMargins['top'])) {
  3360. $this->theadMargins['top'] = $this->tMargin;
  3361. }
  3362. // store end of header position
  3363. if (!isset($this->columns[0]['th'])) {
  3364. $this->columns[0]['th'] = array();
  3365. }
  3366. $this->columns[0]['th']['\''.$this->page.'\''] = $this->y;
  3367. $this->tMargin = $this->y;
  3368. $this->pagedim[$this->page]['tm'] = $this->tMargin;
  3369. $this->lasth = 0;
  3370. $this->lMargin = $prev_lMargin;
  3371. $this->rMargin = $prev_rMargin;
  3372. $this->cell_padding = $prev_cell_padding;
  3373. }
  3374. }
  3375. /**
  3376. * Returns the current page number.
  3377. * @return int page number
  3378. * @public
  3379. * @since 1.0
  3380. * @see getAliasNbPages()
  3381. */
  3382. public function PageNo() {
  3383. return $this->page;
  3384. }
  3385. /**
  3386. * Returns the array of spot colors.
  3387. * @return (array) Spot colors array.
  3388. * @public
  3389. * @since 6.0.038 (2013-09-30)
  3390. */
  3391. public function getAllSpotColors() {
  3392. return $this->spot_colors;
  3393. }
  3394. /**
  3395. * Defines a new spot color.
  3396. * It can be expressed in RGB components or gray scale.
  3397. * The method can be called before the first page is created and the value is retained from page to page.
  3398. * @param $name (string) Full name of the spot color.
  3399. * @param $c (float) Cyan color for CMYK. Value between 0 and 100.
  3400. * @param $m (float) Magenta color for CMYK. Value between 0 and 100.
  3401. * @param $y (float) Yellow color for CMYK. Value between 0 and 100.
  3402. * @param $k (float) Key (Black) color for CMYK. Value between 0 and 100.
  3403. * @public
  3404. * @since 4.0.024 (2008-09-12)
  3405. * @see SetDrawSpotColor(), SetFillSpotColor(), SetTextSpotColor()
  3406. */
  3407. public function AddSpotColor($name, $c, $m, $y, $k) {
  3408. if (!isset($this->spot_colors[$name])) {
  3409. $i = (1 + count($this->spot_colors));
  3410. $this->spot_colors[$name] = array('C' => $c, 'M' => $m, 'Y' => $y, 'K' => $k, 'name' => $name, 'i' => $i);
  3411. }
  3412. }
  3413. /**
  3414. * Set the spot color for the specified type ('draw', 'fill', 'text').
  3415. * @param $type (string) Type of object affected by this color: ('draw', 'fill', 'text').
  3416. * @param $name (string) Name of the spot color.
  3417. * @param $tint (float) Intensity of the color (from 0 to 100 ; 100 = full intensity by default).
  3418. * @return (string) PDF color command.
  3419. * @public
  3420. * @since 5.9.125 (2011-10-03)
  3421. */
  3422. public function setSpotColor($type, $name, $tint=100) {
  3423. $spotcolor = TCPDF_COLORS::getSpotColor($name, $this->spot_colors);
  3424. if ($spotcolor === false) {
  3425. $this->Error('Undefined spot color: '.$name.', you must add it using the AddSpotColor() method.');
  3426. }
  3427. $tint = (max(0, min(100, $tint)) / 100);
  3428. $pdfcolor = sprintf('/CS%d ', $this->spot_colors[$name]['i']);
  3429. switch ($type) {
  3430. case 'draw': {
  3431. $pdfcolor .= sprintf('CS %F SCN', $tint);
  3432. $this->DrawColor = $pdfcolor;
  3433. $this->strokecolor = $spotcolor;
  3434. break;
  3435. }
  3436. case 'fill': {
  3437. $pdfcolor .= sprintf('cs %F scn', $tint);
  3438. $this->FillColor = $pdfcolor;
  3439. $this->bgcolor = $spotcolor;
  3440. break;
  3441. }
  3442. case 'text': {
  3443. $pdfcolor .= sprintf('cs %F scn', $tint);
  3444. $this->TextColor = $pdfcolor;
  3445. $this->fgcolor = $spotcolor;
  3446. break;
  3447. }
  3448. }
  3449. $this->ColorFlag = ($this->FillColor != $this->TextColor);
  3450. if ($this->state == 2) {
  3451. $this->_out($pdfcolor);
  3452. }
  3453. if ($this->inxobj) {
  3454. // we are inside an XObject template
  3455. $this->xobjects[$this->xobjid]['spot_colors'][$name] = $this->spot_colors[$name];
  3456. }
  3457. return $pdfcolor;
  3458. }
  3459. /**
  3460. * Defines the spot color used for all drawing operations (lines, rectangles and cell borders).
  3461. * @param $name (string) Name of the spot color.
  3462. * @param $tint (float) Intensity of the color (from 0 to 100 ; 100 = full intensity by default).
  3463. * @public
  3464. * @since 4.0.024 (2008-09-12)
  3465. * @see AddSpotColor(), SetFillSpotColor(), SetTextSpotColor()
  3466. */
  3467. public function SetDrawSpotColor($name, $tint=100) {
  3468. $this->setSpotColor('draw', $name, $tint);
  3469. }
  3470. /**
  3471. * Defines the spot color used for all filling operations (filled rectangles and cell backgrounds).
  3472. * @param $name (string) Name of the spot color.
  3473. * @param $tint (float) Intensity of the color (from 0 to 100 ; 100 = full intensity by default).
  3474. * @public
  3475. * @since 4.0.024 (2008-09-12)
  3476. * @see AddSpotColor(), SetDrawSpotColor(), SetTextSpotColor()
  3477. */
  3478. public function SetFillSpotColor($name, $tint=100) {
  3479. $this->setSpotColor('fill', $name, $tint);
  3480. }
  3481. /**
  3482. * Defines the spot color used for text.
  3483. * @param $name (string) Name of the spot color.
  3484. * @param $tint (int) Intensity of the color (from 0 to 100 ; 100 = full intensity by default).
  3485. * @public
  3486. * @since 4.0.024 (2008-09-12)
  3487. * @see AddSpotColor(), SetDrawSpotColor(), SetFillSpotColor()
  3488. */
  3489. public function SetTextSpotColor($name, $tint=100) {
  3490. $this->setSpotColor('text', $name, $tint);
  3491. }
  3492. /**
  3493. * Set the color array for the specified type ('draw', 'fill', 'text').
  3494. * It can be expressed in RGB, CMYK or GRAY SCALE components.
  3495. * The method can be called before the first page is created and the value is retained from page to page.
  3496. * @param $type (string) Type of object affected by this color: ('draw', 'fill', 'text').
  3497. * @param $color (array) Array of colors (1=gray, 3=RGB, 4=CMYK or 5=spotcolor=CMYK+name values).
  3498. * @param $ret (boolean) If true do not send the PDF command.
  3499. * @return (string) The PDF command or empty string.
  3500. * @public
  3501. * @since 3.1.000 (2008-06-11)
  3502. */
  3503. public function setColorArray($type, $color, $ret=false) {
  3504. if (is_array($color)) {
  3505. $color = array_values($color);
  3506. // component: grey, RGB red or CMYK cyan
  3507. $c = isset($color[0]) ? $color[0] : -1;
  3508. // component: RGB green or CMYK magenta
  3509. $m = isset($color[1]) ? $color[1] : -1;
  3510. // component: RGB blue or CMYK yellow
  3511. $y = isset($color[2]) ? $color[2] : -1;
  3512. // component: CMYK black
  3513. $k = isset($color[3]) ? $color[3] : -1;
  3514. // color name
  3515. $name = isset($color[4]) ? $color[4] : '';
  3516. if ($c >= 0) {
  3517. return $this->setColor($type, $c, $m, $y, $k, $ret, $name);
  3518. }
  3519. }
  3520. return '';
  3521. }
  3522. /**
  3523. * Defines the color used for all drawing operations (lines, rectangles and cell borders).
  3524. * It can be expressed in RGB, CMYK or GRAY SCALE components.
  3525. * The method can be called before the first page is created and the value is retained from page to page.
  3526. * @param $color (array) Array of colors (1, 3 or 4 values).
  3527. * @param $ret (boolean) If true do not send the PDF command.
  3528. * @return string the PDF command
  3529. * @public
  3530. * @since 3.1.000 (2008-06-11)
  3531. * @see SetDrawColor()
  3532. */
  3533. public function SetDrawColorArray($color, $ret=false) {
  3534. return $this->setColorArray('draw', $color, $ret);
  3535. }
  3536. /**
  3537. * Defines the color used for all filling operations (filled rectangles and cell backgrounds).
  3538. * It can be expressed in RGB, CMYK or GRAY SCALE components.
  3539. * The method can be called before the first page is created and the value is retained from page to page.
  3540. * @param $color (array) Array of colors (1, 3 or 4 values).
  3541. * @param $ret (boolean) If true do not send the PDF command.
  3542. * @public
  3543. * @since 3.1.000 (2008-6-11)
  3544. * @see SetFillColor()
  3545. */
  3546. public function SetFillColorArray($color, $ret=false) {
  3547. return $this->setColorArray('fill', $color, $ret);
  3548. }
  3549. /**
  3550. * Defines the color used for text. It can be expressed in RGB components or gray scale.
  3551. * The method can be called before the first page is created and the value is retained from page to page.
  3552. * @param $color (array) Array of colors (1, 3 or 4 values).
  3553. * @param $ret (boolean) If true do not send the PDF command.
  3554. * @public
  3555. * @since 3.1.000 (2008-6-11)
  3556. * @see SetFillColor()
  3557. */
  3558. public function SetTextColorArray($color, $ret=false) {
  3559. return $this->setColorArray('text', $color, $ret);
  3560. }
  3561. /**
  3562. * Defines the color used by the specified type ('draw', 'fill', 'text').
  3563. * @param $type (string) Type of object affected by this color: ('draw', 'fill', 'text').
  3564. * @param $col1 (float) GRAY level for single color, or Red color for RGB (0-255), or CYAN color for CMYK (0-100).
  3565. * @param $col2 (float) GREEN color for RGB (0-255), or MAGENTA color for CMYK (0-100).
  3566. * @param $col3 (float) BLUE color for RGB (0-255), or YELLOW color for CMYK (0-100).
  3567. * @param $col4 (float) KEY (BLACK) color for CMYK (0-100).
  3568. * @param $ret (boolean) If true do not send the command.
  3569. * @param $name (string) spot color name (if any)
  3570. * @return (string) The PDF command or empty string.
  3571. * @public
  3572. * @since 5.9.125 (2011-10-03)
  3573. */
  3574. public function setColor($type, $col1=0, $col2=-1, $col3=-1, $col4=-1, $ret=false, $name='') {
  3575. // set default values
  3576. if (!is_numeric($col1)) {
  3577. $col1 = 0;
  3578. }
  3579. if (!is_numeric($col2)) {
  3580. $col2 = -1;
  3581. }
  3582. if (!is_numeric($col3)) {
  3583. $col3 = -1;
  3584. }
  3585. if (!is_numeric($col4)) {
  3586. $col4 = -1;
  3587. }
  3588. // set color by case
  3589. $suffix = '';
  3590. if (($col2 == -1) AND ($col3 == -1) AND ($col4 == -1)) {
  3591. // Grey scale
  3592. $col1 = max(0, min(255, $col1));
  3593. $intcolor = array('G' => $col1);
  3594. $pdfcolor = sprintf('%F ', ($col1 / 255));
  3595. $suffix = 'g';
  3596. } elseif ($col4 == -1) {
  3597. // RGB
  3598. $col1 = max(0, min(255, $col1));
  3599. $col2 = max(0, min(255, $col2));
  3600. $col3 = max(0, min(255, $col3));
  3601. $intcolor = array('R' => $col1, 'G' => $col2, 'B' => $col3);
  3602. $pdfcolor = sprintf('%F %F %F ', ($col1 / 255), ($col2 / 255), ($col3 / 255));
  3603. $suffix = 'rg';
  3604. } else {
  3605. $col1 = max(0, min(100, $col1));
  3606. $col2 = max(0, min(100, $col2));
  3607. $col3 = max(0, min(100, $col3));
  3608. $col4 = max(0, min(100, $col4));
  3609. if (empty($name)) {
  3610. // CMYK
  3611. $intcolor = array('C' => $col1, 'M' => $col2, 'Y' => $col3, 'K' => $col4);
  3612. $pdfcolor = sprintf('%F %F %F %F ', ($col1 / 100), ($col2 / 100), ($col3 / 100), ($col4 / 100));
  3613. $suffix = 'k';
  3614. } else {
  3615. // SPOT COLOR
  3616. $intcolor = array('C' => $col1, 'M' => $col2, 'Y' => $col3, 'K' => $col4, 'name' => $name);
  3617. $this->AddSpotColor($name, $col1, $col2, $col3, $col4);
  3618. $pdfcolor = $this->setSpotColor($type, $name, 100);
  3619. }
  3620. }
  3621. switch ($type) {
  3622. case 'draw': {
  3623. $pdfcolor .= strtoupper($suffix);
  3624. $this->DrawColor = $pdfcolor;
  3625. $this->strokecolor = $intcolor;
  3626. break;
  3627. }
  3628. case 'fill': {
  3629. $pdfcolor .= $suffix;
  3630. $this->FillColor = $pdfcolor;
  3631. $this->bgcolor = $intcolor;
  3632. break;
  3633. }
  3634. case 'text': {
  3635. $pdfcolor .= $suffix;
  3636. $this->TextColor = $pdfcolor;
  3637. $this->fgcolor = $intcolor;
  3638. break;
  3639. }
  3640. }
  3641. $this->ColorFlag = ($this->FillColor != $this->TextColor);
  3642. if (($type != 'text') AND ($this->state == 2)) {
  3643. if (!$ret) {
  3644. $this->_out($pdfcolor);
  3645. }
  3646. return $pdfcolor;
  3647. }
  3648. return '';
  3649. }
  3650. /**
  3651. * 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.
  3652. * @param $col1 (float) GRAY level for single color, or Red color for RGB (0-255), or CYAN color for CMYK (0-100).
  3653. * @param $col2 (float) GREEN color for RGB (0-255), or MAGENTA color for CMYK (0-100).
  3654. * @param $col3 (float) BLUE color for RGB (0-255), or YELLOW color for CMYK (0-100).
  3655. * @param $col4 (float) KEY (BLACK) color for CMYK (0-100).
  3656. * @param $ret (boolean) If true do not send the command.
  3657. * @param $name (string) spot color name (if any)
  3658. * @return string the PDF command
  3659. * @public
  3660. * @since 1.3
  3661. * @see SetDrawColorArray(), SetFillColor(), SetTextColor(), Line(), Rect(), Cell(), MultiCell()
  3662. */
  3663. public function SetDrawColor($col1=0, $col2=-1, $col3=-1, $col4=-1, $ret=false, $name='') {
  3664. return $this->setColor('draw', $col1, $col2, $col3, $col4, $ret, $name);
  3665. }
  3666. /**
  3667. * 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.
  3668. * @param $col1 (float) GRAY level for single color, or Red color for RGB (0-255), or CYAN color for CMYK (0-100).
  3669. * @param $col2 (float) GREEN color for RGB (0-255), or MAGENTA color for CMYK (0-100).
  3670. * @param $col3 (float) BLUE color for RGB (0-255), or YELLOW color for CMYK (0-100).
  3671. * @param $col4 (float) KEY (BLACK) color for CMYK (0-100).
  3672. * @param $ret (boolean) If true do not send the command.
  3673. * @param $name (string) Spot color name (if any).
  3674. * @return (string) The PDF command.
  3675. * @public
  3676. * @since 1.3
  3677. * @see SetFillColorArray(), SetDrawColor(), SetTextColor(), Rect(), Cell(), MultiCell()
  3678. */
  3679. public function SetFillColor($col1=0, $col2=-1, $col3=-1, $col4=-1, $ret=false, $name='') {
  3680. return $this->setColor('fill', $col1, $col2, $col3, $col4, $ret, $name);
  3681. }
  3682. /**
  3683. * 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.
  3684. * @param $col1 (float) GRAY level for single color, or Red color for RGB (0-255), or CYAN color for CMYK (0-100).
  3685. * @param $col2 (float) GREEN color for RGB (0-255), or MAGENTA color for CMYK (0-100).
  3686. * @param $col3 (float) BLUE color for RGB (0-255), or YELLOW color for CMYK (0-100).
  3687. * @param $col4 (float) KEY (BLACK) color for CMYK (0-100).
  3688. * @param $ret (boolean) If true do not send the command.
  3689. * @param $name (string) Spot color name (if any).
  3690. * @return (string) Empty string.
  3691. * @public
  3692. * @since 1.3
  3693. * @see SetTextColorArray(), SetDrawColor(), SetFillColor(), Text(), Cell(), MultiCell()
  3694. */
  3695. public function SetTextColor($col1=0, $col2=-1, $col3=-1, $col4=-1, $ret=false, $name='') {
  3696. return $this->setColor('text', $col1, $col2, $col3, $col4, $ret, $name);
  3697. }
  3698. /**
  3699. * Returns the length of a string in user unit. A font must be selected.<br>
  3700. * @param $s (string) The string whose length is to be computed
  3701. * @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.
  3702. * @param $fontstyle (string) Font style. Possible values are (case insensitive):<ul><li>empty string: regular</li><li>B: bold</li><li>I: italic</li><li>U: underline</li><li>D: line-through</li><li>O: overline</li></ul> or any combination. The default value is regular.
  3703. * @param $fontsize (float) Font size in points. The default value is the current size.
  3704. * @param $getarray (boolean) if true returns an array of characters widths, if false returns the total length.
  3705. * @return mixed int total string length or array of characted widths
  3706. * @author Nicola Asuni
  3707. * @public
  3708. * @since 1.2
  3709. */
  3710. public function GetStringWidth($s, $fontname='', $fontstyle='', $fontsize=0, $getarray=false) {
  3711. return $this->GetArrStringWidth(TCPDF_FONTS::utf8Bidi(TCPDF_FONTS::UTF8StringToArray($s, $this->isunicode, $this->CurrentFont), $s, $this->tmprtl, $this->isunicode, $this->CurrentFont), $fontname, $fontstyle, $fontsize, $getarray);
  3712. }
  3713. /**
  3714. * Returns the string length of an array of chars in user unit or an array of characters widths. A font must be selected.<br>
  3715. * @param $sa (string) The array of chars whose total length is to be computed
  3716. * @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.
  3717. * @param $fontstyle (string) Font style. Possible values are (case insensitive):<ul><li>empty string: regular</li><li>B: bold</li><li>I: italic</li><li>U: underline</li><li>D: line through</li><li>O: overline</li></ul> or any combination. The default value is regular.
  3718. * @param $fontsize (float) Font size in points. The default value is the current size.
  3719. * @param $getarray (boolean) if true returns an array of characters widths, if false returns the total length.
  3720. * @return mixed int total string length or array of characted widths
  3721. * @author Nicola Asuni
  3722. * @public
  3723. * @since 2.4.000 (2008-03-06)
  3724. */
  3725. public function GetArrStringWidth($sa, $fontname='', $fontstyle='', $fontsize=0, $getarray=false) {
  3726. // store current values
  3727. if (!TCPDF_STATIC::empty_string($fontname)) {
  3728. $prev_FontFamily = $this->FontFamily;
  3729. $prev_FontStyle = $this->FontStyle;
  3730. $prev_FontSizePt = $this->FontSizePt;
  3731. $this->SetFont($fontname, $fontstyle, $fontsize, '', 'default', false);
  3732. }
  3733. // convert UTF-8 array to Latin1 if required
  3734. if ($this->isunicode AND (!$this->isUnicodeFont())) {
  3735. $sa = TCPDF_FONTS::UTF8ArrToLatin1Arr($sa);
  3736. }
  3737. $w = 0; // total width
  3738. $wa = array(); // array of characters widths
  3739. foreach ($sa as $ck => $char) {
  3740. // character width
  3741. $cw = $this->GetCharWidth($char, isset($sa[($ck + 1)]));
  3742. $wa[] = $cw;
  3743. $w += $cw;
  3744. }
  3745. // restore previous values
  3746. if (!TCPDF_STATIC::empty_string($fontname)) {
  3747. $this->SetFont($prev_FontFamily, $prev_FontStyle, $prev_FontSizePt, '', 'default', false);
  3748. }
  3749. if ($getarray) {
  3750. return $wa;
  3751. }
  3752. return $w;
  3753. }
  3754. /**
  3755. * Returns the length of the char in user unit for the current font considering current stretching and spacing (tracking).
  3756. * @param $char (int) The char code whose length is to be returned
  3757. * @param $notlast (boolean) If false ignore the font-spacing.
  3758. * @return float char width
  3759. * @author Nicola Asuni
  3760. * @public
  3761. * @since 2.4.000 (2008-03-06)
  3762. */
  3763. public function GetCharWidth($char, $notlast=true) {
  3764. // get raw width
  3765. $chw = $this->getRawCharWidth($char);
  3766. if (($this->font_spacing < 0) OR (($this->font_spacing > 0) AND $notlast)) {
  3767. // increase/decrease font spacing
  3768. $chw += $this->font_spacing;
  3769. }
  3770. if ($this->font_stretching != 100) {
  3771. // fixed stretching mode
  3772. $chw *= ($this->font_stretching / 100);
  3773. }
  3774. return $chw;
  3775. }
  3776. /**
  3777. * Returns the length of the char in user unit for the current font.
  3778. * @param $char (int) The char code whose length is to be returned
  3779. * @return float char width
  3780. * @author Nicola Asuni
  3781. * @public
  3782. * @since 5.9.000 (2010-09-28)
  3783. */
  3784. public function getRawCharWidth($char) {
  3785. if ($char == 173) {
  3786. // SHY character will not be printed
  3787. return (0);
  3788. }
  3789. if (isset($this->CurrentFont['cw'][$char])) {
  3790. $w = $this->CurrentFont['cw'][$char];
  3791. } elseif (isset($this->CurrentFont['dw'])) {
  3792. // default width
  3793. $w = $this->CurrentFont['dw'];
  3794. } elseif (isset($this->CurrentFont['cw'][32])) {
  3795. // default width
  3796. $w = $this->CurrentFont['cw'][32];
  3797. } else {
  3798. $w = 600;
  3799. }
  3800. return $this->getAbsFontMeasure($w);
  3801. }
  3802. /**
  3803. * Returns the numbero of characters in a string.
  3804. * @param $s (string) The input string.
  3805. * @return int number of characters
  3806. * @public
  3807. * @since 2.0.0001 (2008-01-07)
  3808. */
  3809. public function GetNumChars($s) {
  3810. if ($this->isUnicodeFont()) {
  3811. return count(TCPDF_FONTS::UTF8StringToArray($s, $this->isunicode, $this->CurrentFont));
  3812. }
  3813. return strlen($s);
  3814. }
  3815. /**
  3816. * Fill the list of available fonts ($this->fontlist).
  3817. * @protected
  3818. * @since 4.0.013 (2008-07-28)
  3819. */
  3820. protected function getFontsList() {
  3821. if (($fontsdir = opendir(TCPDF_FONTS::_getfontpath())) !== false) {
  3822. while (($file = readdir($fontsdir)) !== false) {
  3823. if (substr($file, -4) == '.php') {
  3824. array_push($this->fontlist, strtolower(basename($file, '.php')));
  3825. }
  3826. }
  3827. closedir($fontsdir);
  3828. }
  3829. }
  3830. /**
  3831. * Imports a TrueType, Type1, core, or CID0 font and makes it available.
  3832. * It is necessary to generate a font definition file first (read /fonts/utils/README.TXT).
  3833. * 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.
  3834. * @param $family (string) Font family. The name can be chosen arbitrarily. If it is a standard family name, it will override the corresponding font.
  3835. * @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>
  3836. * @param $fontfile (string) The font definition file. By default, the name is built from the family and style, in lower case with no spaces.
  3837. * @return array containing the font data, or false in case of error.
  3838. * @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.
  3839. * @public
  3840. * @since 1.5
  3841. * @see SetFont(), setFontSubsetting()
  3842. */
  3843. public function AddFont($family, $style='', $fontfile='', $subset='default') {
  3844. if ($subset === 'default') {
  3845. $subset = $this->font_subsetting;
  3846. }
  3847. if ($this->pdfa_mode) {
  3848. $subset = false;
  3849. }
  3850. if (TCPDF_STATIC::empty_string($family)) {
  3851. if (!TCPDF_STATIC::empty_string($this->FontFamily)) {
  3852. $family = $this->FontFamily;
  3853. } else {
  3854. $this->Error('Empty font family');
  3855. }
  3856. }
  3857. // move embedded styles on $style
  3858. if (substr($family, -1) == 'I') {
  3859. $style .= 'I';
  3860. $family = substr($family, 0, -1);
  3861. }
  3862. if (substr($family, -1) == 'B') {
  3863. $style .= 'B';
  3864. $family = substr($family, 0, -1);
  3865. }
  3866. // normalize family name
  3867. $family = strtolower($family);
  3868. if ((!$this->isunicode) AND ($family == 'arial')) {
  3869. $family = 'helvetica';
  3870. }
  3871. if (($family == 'symbol') OR ($family == 'zapfdingbats')) {
  3872. $style = '';
  3873. }
  3874. if ($this->pdfa_mode AND (isset($this->CoreFonts[$family]))) {
  3875. // all fonts must be embedded
  3876. $family = 'pdfa'.$family;
  3877. }
  3878. $tempstyle = strtoupper($style);
  3879. $style = '';
  3880. // underline
  3881. if (strpos($tempstyle, 'U') !== false) {
  3882. $this->underline = true;
  3883. } else {
  3884. $this->underline = false;
  3885. }
  3886. // line-through (deleted)
  3887. if (strpos($tempstyle, 'D') !== false) {
  3888. $this->linethrough = true;
  3889. } else {
  3890. $this->linethrough = false;
  3891. }
  3892. // overline
  3893. if (strpos($tempstyle, 'O') !== false) {
  3894. $this->overline = true;
  3895. } else {
  3896. $this->overline = false;
  3897. }
  3898. // bold
  3899. if (strpos($tempstyle, 'B') !== false) {
  3900. $style .= 'B';
  3901. }
  3902. // oblique
  3903. if (strpos($tempstyle, 'I') !== false) {
  3904. $style .= 'I';
  3905. }
  3906. $bistyle = $style;
  3907. $fontkey = $family.$style;
  3908. $font_style = $style.($this->underline ? 'U' : '').($this->linethrough ? 'D' : '').($this->overline ? 'O' : '');
  3909. $fontdata = array('fontkey' => $fontkey, 'family' => $family, 'style' => $font_style);
  3910. // check if the font has been already added
  3911. $fb = $this->getFontBuffer($fontkey);
  3912. if ($fb !== false) {
  3913. if ($this->inxobj) {
  3914. // we are inside an XObject template
  3915. $this->xobjects[$this->xobjid]['fonts'][$fontkey] = $fb['i'];
  3916. }
  3917. return $fontdata;
  3918. }
  3919. // get specified font directory (if any)
  3920. $fontdir = false;
  3921. if (!TCPDF_STATIC::empty_string($fontfile)) {
  3922. $fontdir = dirname($fontfile);
  3923. if (TCPDF_STATIC::empty_string($fontdir) OR ($fontdir == '.')) {
  3924. $fontdir = '';
  3925. } else {
  3926. $fontdir .= '/';
  3927. }
  3928. }
  3929. // true when the font style variation is missing
  3930. $missing_style = false;
  3931. // search and include font file
  3932. if (TCPDF_STATIC::empty_string($fontfile) OR (!@TCPDF_STATIC::file_exists($fontfile))) {
  3933. // build a standard filenames for specified font
  3934. $tmp_fontfile = str_replace(' ', '', $family).strtolower($style).'.php';
  3935. $fontfile = TCPDF_FONTS::getFontFullPath($tmp_fontfile, $fontdir);
  3936. if (TCPDF_STATIC::empty_string($fontfile)) {
  3937. $missing_style = true;
  3938. // try to remove the style part
  3939. $tmp_fontfile = str_replace(' ', '', $family).'.php';
  3940. $fontfile = TCPDF_FONTS::getFontFullPath($tmp_fontfile, $fontdir);
  3941. }
  3942. }
  3943. // include font file
  3944. if (!TCPDF_STATIC::empty_string($fontfile) AND (@TCPDF_STATIC::file_exists($fontfile))) {
  3945. include($fontfile);
  3946. } else {
  3947. $this->Error('Could not include font definition file: '.$family.'');
  3948. }
  3949. // check font parameters
  3950. if ((!isset($type)) OR (!isset($cw))) {
  3951. $this->Error('The font definition file has a bad format: '.$fontfile.'');
  3952. }
  3953. // SET default parameters
  3954. if (!isset($file) OR TCPDF_STATIC::empty_string($file)) {
  3955. $file = '';
  3956. }
  3957. if (!isset($enc) OR TCPDF_STATIC::empty_string($enc)) {
  3958. $enc = '';
  3959. }
  3960. if (!isset($cidinfo) OR TCPDF_STATIC::empty_string($cidinfo)) {
  3961. $cidinfo = array('Registry'=>'Adobe', 'Ordering'=>'Identity', 'Supplement'=>0);
  3962. $cidinfo['uni2cid'] = array();
  3963. }
  3964. if (!isset($ctg) OR TCPDF_STATIC::empty_string($ctg)) {
  3965. $ctg = '';
  3966. }
  3967. if (!isset($desc) OR TCPDF_STATIC::empty_string($desc)) {
  3968. $desc = array();
  3969. }
  3970. if (!isset($up) OR TCPDF_STATIC::empty_string($up)) {
  3971. $up = -100;
  3972. }
  3973. if (!isset($ut) OR TCPDF_STATIC::empty_string($ut)) {
  3974. $ut = 50;
  3975. }
  3976. if (!isset($cw) OR TCPDF_STATIC::empty_string($cw)) {
  3977. $cw = array();
  3978. }
  3979. if (!isset($dw) OR TCPDF_STATIC::empty_string($dw)) {
  3980. // set default width
  3981. if (isset($desc['MissingWidth']) AND ($desc['MissingWidth'] > 0)) {
  3982. $dw = $desc['MissingWidth'];
  3983. } elseif (isset($cw[32])) {
  3984. $dw = $cw[32];
  3985. } else {
  3986. $dw = 600;
  3987. }
  3988. }
  3989. ++$this->numfonts;
  3990. if ($type == 'core') {
  3991. $name = $this->CoreFonts[$fontkey];
  3992. $subset = false;
  3993. } elseif (($type == 'TrueType') OR ($type == 'Type1')) {
  3994. $subset = false;
  3995. } elseif ($type == 'TrueTypeUnicode') {
  3996. $enc = 'Identity-H';
  3997. } elseif ($type == 'cidfont0') {
  3998. if ($this->pdfa_mode) {
  3999. $this->Error('All fonts must be embedded in PDF/A mode!');
  4000. }
  4001. } else {
  4002. $this->Error('Unknow font type: '.$type.'');
  4003. }
  4004. // set name if unset
  4005. if (!isset($name) OR empty($name)) {
  4006. $name = $fontkey;
  4007. }
  4008. // create artificial font style variations if missing (only works with non-embedded fonts)
  4009. if (($type != 'core') AND $missing_style) {
  4010. // style variations
  4011. $styles = array('' => '', 'B' => ',Bold', 'I' => ',Italic', 'BI' => ',BoldItalic');
  4012. $name .= $styles[$bistyle];
  4013. // artificial bold
  4014. if (strpos($bistyle, 'B') !== false) {
  4015. if (isset($desc['StemV'])) {
  4016. // from normal to bold
  4017. $desc['StemV'] = round($desc['StemV'] * 1.75);
  4018. } else {
  4019. // bold
  4020. $desc['StemV'] = 123;
  4021. }
  4022. }
  4023. // artificial italic
  4024. if (strpos($bistyle, 'I') !== false) {
  4025. if (isset($desc['ItalicAngle'])) {
  4026. $desc['ItalicAngle'] -= 11;
  4027. } else {
  4028. $desc['ItalicAngle'] = -11;
  4029. }
  4030. if (isset($desc['Flags'])) {
  4031. $desc['Flags'] |= 64; //bit 7
  4032. } else {
  4033. $desc['Flags'] = 64;
  4034. }
  4035. }
  4036. }
  4037. // check if the array of characters bounding boxes is defined
  4038. if (!isset($cbbox)) {
  4039. $cbbox = array();
  4040. }
  4041. // initialize subsetchars
  4042. $subsetchars = array_fill(0, 255, true);
  4043. $this->setFontBuffer($fontkey, array('fontkey' => $fontkey, 'i' => $this->numfonts, 'type' => $type, 'name' => $name, 'desc' => $desc, 'up' => $up, 'ut' => $ut, 'cw' => $cw, 'cbbox' => $cbbox, 'dw' => $dw, 'enc' => $enc, 'cidinfo' => $cidinfo, 'file' => $file, 'ctg' => $ctg, 'subset' => $subset, 'subsetchars' => $subsetchars));
  4044. if ($this->inxobj) {
  4045. // we are inside an XObject template
  4046. $this->xobjects[$this->xobjid]['fonts'][$fontkey] = $this->numfonts;
  4047. }
  4048. if (isset($diff) AND (!empty($diff))) {
  4049. //Search existing encodings
  4050. $d = 0;
  4051. $nb = count($this->diffs);
  4052. for ($i=1; $i <= $nb; ++$i) {
  4053. if ($this->diffs[$i] == $diff) {
  4054. $d = $i;
  4055. break;
  4056. }
  4057. }
  4058. if ($d == 0) {
  4059. $d = $nb + 1;
  4060. $this->diffs[$d] = $diff;
  4061. }
  4062. $this->setFontSubBuffer($fontkey, 'diff', $d);
  4063. }
  4064. if (!TCPDF_STATIC::empty_string($file)) {
  4065. if (!isset($this->FontFiles[$file])) {
  4066. if ((strcasecmp($type,'TrueType') == 0) OR (strcasecmp($type, 'TrueTypeUnicode') == 0)) {
  4067. $this->FontFiles[$file] = array('length1' => $originalsize, 'fontdir' => $fontdir, 'subset' => $subset, 'fontkeys' => array($fontkey));
  4068. } elseif ($type != 'core') {
  4069. $this->FontFiles[$file] = array('length1' => $size1, 'length2' => $size2, 'fontdir' => $fontdir, 'subset' => $subset, 'fontkeys' => array($fontkey));
  4070. }
  4071. } else {
  4072. // update fontkeys that are sharing this font file
  4073. $this->FontFiles[$file]['subset'] = ($this->FontFiles[$file]['subset'] AND $subset);
  4074. if (!in_array($fontkey, $this->FontFiles[$file]['fontkeys'])) {
  4075. $this->FontFiles[$file]['fontkeys'][] = $fontkey;
  4076. }
  4077. }
  4078. }
  4079. return $fontdata;
  4080. }
  4081. /**
  4082. * Sets the font used to print character strings.
  4083. * The font can be either a standard one or a font added via the AddFont() method. Standard fonts use Windows encoding cp1252 (Western Europe).
  4084. * The method can be called before the first page is created and the font is retained from page to page.
  4085. * If you just wish to change the current font size, it is simpler to call SetFontSize().
  4086. * 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 />
  4087. * @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.
  4088. * @param $style (string) Font style. Possible values are (case insensitive):<ul><li>empty string: regular</li><li>B: bold</li><li>I: italic</li><li>U: underline</li><li>D: line through</li><li>O: overline</li></ul> or any combination. The default value is regular. Bold and italic styles do not apply to Symbol and ZapfDingbats basic fonts or other fonts when not defined.
  4089. * @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
  4090. * @param $fontfile (string) The font definition file. By default, the name is built from the family and style, in lower case with no spaces.
  4091. * @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.
  4092. * @param $out (boolean) if true output the font size command, otherwise only set the font properties.
  4093. * @author Nicola Asuni
  4094. * @public
  4095. * @since 1.0
  4096. * @see AddFont(), SetFontSize()
  4097. */
  4098. public function SetFont($family, $style='', $size=null, $fontfile='', $subset='default', $out=true) {
  4099. //Select a font; size given in points
  4100. if ($size === null) {
  4101. $size = $this->FontSizePt;
  4102. }
  4103. if ($size < 0) {
  4104. $size = 0;
  4105. }
  4106. // try to add font (if not already added)
  4107. $fontdata = $this->AddFont($family, $style, $fontfile, $subset);
  4108. $this->FontFamily = $fontdata['family'];
  4109. $this->FontStyle = $fontdata['style'];
  4110. if (isset($this->CurrentFont['fontkey']) AND isset($this->CurrentFont['subsetchars'])) {
  4111. // save subset chars of the previous font
  4112. $this->setFontSubBuffer($this->CurrentFont['fontkey'], 'subsetchars', $this->CurrentFont['subsetchars']);
  4113. }
  4114. $this->CurrentFont = $this->getFontBuffer($fontdata['fontkey']);
  4115. $this->SetFontSize($size, $out);
  4116. }
  4117. /**
  4118. * Defines the size of the current font.
  4119. * @param $size (float) The font size in points.
  4120. * @param $out (boolean) if true output the font size command, otherwise only set the font properties.
  4121. * @public
  4122. * @since 1.0
  4123. * @see SetFont()
  4124. */
  4125. public function SetFontSize($size, $out=true) {
  4126. $size = (float)$size;
  4127. // font size in points
  4128. $this->FontSizePt = $size;
  4129. // font size in user units
  4130. $this->FontSize = $size / $this->k;
  4131. // calculate some font metrics
  4132. if (isset($this->CurrentFont['desc']['FontBBox'])) {
  4133. $bbox = explode(' ', substr($this->CurrentFont['desc']['FontBBox'], 1, -1));
  4134. $font_height = ((intval($bbox[3]) - intval($bbox[1])) * $size / 1000);
  4135. } else {
  4136. $font_height = $size * 1.219;
  4137. }
  4138. if (isset($this->CurrentFont['desc']['Ascent']) AND ($this->CurrentFont['desc']['Ascent'] > 0)) {
  4139. $font_ascent = ($this->CurrentFont['desc']['Ascent'] * $size / 1000);
  4140. }
  4141. if (isset($this->CurrentFont['desc']['Descent']) AND ($this->CurrentFont['desc']['Descent'] <= 0)) {
  4142. $font_descent = (- $this->CurrentFont['desc']['Descent'] * $size / 1000);
  4143. }
  4144. if (!isset($font_ascent) AND !isset($font_descent)) {
  4145. // core font
  4146. $font_ascent = 0.76 * $font_height;
  4147. $font_descent = $font_height - $font_ascent;
  4148. } elseif (!isset($font_descent)) {
  4149. $font_descent = $font_height - $font_ascent;
  4150. } elseif (!isset($font_ascent)) {
  4151. $font_ascent = $font_height - $font_descent;
  4152. }
  4153. $this->FontAscent = ($font_ascent / $this->k);
  4154. $this->FontDescent = ($font_descent / $this->k);
  4155. if ($out AND ($this->page > 0) AND (isset($this->CurrentFont['i'])) AND ($this->state == 2)) {
  4156. $this->_out(sprintf('BT /F%d %F Tf ET', $this->CurrentFont['i'], $this->FontSizePt));
  4157. }
  4158. }
  4159. /**
  4160. * Returns the bounding box of the current font in user units.
  4161. * @return array
  4162. * @public
  4163. * @since 5.9.152 (2012-03-23)
  4164. */
  4165. public function getFontBBox() {
  4166. $fbbox = array();
  4167. if (isset($this->CurrentFont['desc']['FontBBox'])) {
  4168. $tmpbbox = explode(' ', substr($this->CurrentFont['desc']['FontBBox'], 1, -1));
  4169. $fbbox = array_map(array($this,'getAbsFontMeasure'), $tmpbbox);
  4170. } else {
  4171. // Find max width
  4172. if (isset($this->CurrentFont['desc']['MaxWidth'])) {
  4173. $maxw = $this->getAbsFontMeasure(intval($this->CurrentFont['desc']['MaxWidth']));
  4174. } else {
  4175. $maxw = 0;
  4176. if (isset($this->CurrentFont['desc']['MissingWidth'])) {
  4177. $maxw = max($maxw, $this->CurrentFont['desc']['MissingWidth']);
  4178. }
  4179. if (isset($this->CurrentFont['desc']['AvgWidth'])) {
  4180. $maxw = max($maxw, $this->CurrentFont['desc']['AvgWidth']);
  4181. }
  4182. if (isset($this->CurrentFont['dw'])) {
  4183. $maxw = max($maxw, $this->CurrentFont['dw']);
  4184. }
  4185. foreach ($this->CurrentFont['cw'] as $char => $w) {
  4186. $maxw = max($maxw, $w);
  4187. }
  4188. if ($maxw == 0) {
  4189. $maxw = 600;
  4190. }
  4191. $maxw = $this->getAbsFontMeasure($maxw);
  4192. }
  4193. $fbbox = array(0, (0 - $this->FontDescent), $maxw, $this->FontAscent);
  4194. }
  4195. return $fbbox;
  4196. }
  4197. /**
  4198. * Convert a relative font measure into absolute value.
  4199. * @param $s (int) Font measure.
  4200. * @return float Absolute measure.
  4201. * @since 5.9.186 (2012-09-13)
  4202. */
  4203. public function getAbsFontMeasure($s) {
  4204. return ($s * $this->FontSize / 1000);
  4205. }
  4206. /**
  4207. * Returns the glyph bounding box of the specified character in the current font in user units.
  4208. * @param $char (int) Input character code.
  4209. * @return mixed array(xMin, yMin, xMax, yMax) or FALSE if not defined.
  4210. * @since 5.9.186 (2012-09-13)
  4211. */
  4212. public function getCharBBox($char) {
  4213. $c = intval($char);
  4214. if (isset($this->CurrentFont['cw'][$c])) {
  4215. // glyph is defined ... use zero width & height for glyphs without outlines
  4216. $result = array(0,0,0,0);
  4217. if (isset($this->CurrentFont['cbbox'][$c])) {
  4218. $result = $this->CurrentFont['cbbox'][$c];
  4219. }
  4220. return array_map(array($this,'getAbsFontMeasure'), $result);
  4221. }
  4222. return false;
  4223. }
  4224. /**
  4225. * Return the font descent value
  4226. * @param $font (string) font name
  4227. * @param $style (string) font style
  4228. * @param $size (float) The size (in points)
  4229. * @return int font descent
  4230. * @public
  4231. * @author Nicola Asuni
  4232. * @since 4.9.003 (2010-03-30)
  4233. */
  4234. public function getFontDescent($font, $style='', $size=0) {
  4235. $fontdata = $this->AddFont($font, $style);
  4236. $fontinfo = $this->getFontBuffer($fontdata['fontkey']);
  4237. if (isset($fontinfo['desc']['Descent']) AND ($fontinfo['desc']['Descent'] <= 0)) {
  4238. $descent = (- $fontinfo['desc']['Descent'] * $size / 1000);
  4239. } else {
  4240. $descent = (1.219 * 0.24 * $size);
  4241. }
  4242. return ($descent / $this->k);
  4243. }
  4244. /**
  4245. * Return the font ascent value.
  4246. * @param $font (string) font name
  4247. * @param $style (string) font style
  4248. * @param $size (float) The size (in points)
  4249. * @return int font ascent
  4250. * @public
  4251. * @author Nicola Asuni
  4252. * @since 4.9.003 (2010-03-30)
  4253. */
  4254. public function getFontAscent($font, $style='', $size=0) {
  4255. $fontdata = $this->AddFont($font, $style);
  4256. $fontinfo = $this->getFontBuffer($fontdata['fontkey']);
  4257. if (isset($fontinfo['desc']['Ascent']) AND ($fontinfo['desc']['Ascent'] > 0)) {
  4258. $ascent = ($fontinfo['desc']['Ascent'] * $size / 1000);
  4259. } else {
  4260. $ascent = 1.219 * 0.76 * $size;
  4261. }
  4262. return ($ascent / $this->k);
  4263. }
  4264. /**
  4265. * Return true in the character is present in the specified font.
  4266. * @param $char (mixed) Character to check (integer value or string)
  4267. * @param $font (string) Font name (family name).
  4268. * @param $style (string) Font style.
  4269. * @return (boolean) true if the char is defined, false otherwise.
  4270. * @public
  4271. * @since 5.9.153 (2012-03-28)
  4272. */
  4273. public function isCharDefined($char, $font='', $style='') {
  4274. if (is_string($char)) {
  4275. // get character code
  4276. $char = TCPDF_FONTS::UTF8StringToArray($char, $this->isunicode, $this->CurrentFont);
  4277. $char = $char[0];
  4278. }
  4279. if (TCPDF_STATIC::empty_string($font)) {
  4280. if (TCPDF_STATIC::empty_string($style)) {
  4281. return (isset($this->CurrentFont['cw'][intval($char)]));
  4282. }
  4283. $font = $this->FontFamily;
  4284. }
  4285. $fontdata = $this->AddFont($font, $style);
  4286. $fontinfo = $this->getFontBuffer($fontdata['fontkey']);
  4287. return (isset($fontinfo['cw'][intval($char)]));
  4288. }
  4289. /**
  4290. * Replace missing font characters on selected font with specified substitutions.
  4291. * @param $text (string) Text to process.
  4292. * @param $font (string) Font name (family name).
  4293. * @param $style (string) Font style.
  4294. * @param $subs (array) Array of possible character substitutions. The key is the character to check (integer value) and the value is a single intege value or an array of possible substitutes.
  4295. * @return (string) Processed text.
  4296. * @public
  4297. * @since 5.9.153 (2012-03-28)
  4298. */
  4299. public function replaceMissingChars($text, $font='', $style='', $subs=array()) {
  4300. if (empty($subs)) {
  4301. return $text;
  4302. }
  4303. if (TCPDF_STATIC::empty_string($font)) {
  4304. $font = $this->FontFamily;
  4305. }
  4306. $fontdata = $this->AddFont($font, $style);
  4307. $fontinfo = $this->getFontBuffer($fontdata['fontkey']);
  4308. $uniarr = TCPDF_FONTS::UTF8StringToArray($text, $this->isunicode, $this->CurrentFont);
  4309. foreach ($uniarr as $k => $chr) {
  4310. if (!isset($fontinfo['cw'][$chr])) {
  4311. // this character is missing on the selected font
  4312. if (isset($subs[$chr])) {
  4313. // we have available substitutions
  4314. if (is_array($subs[$chr])) {
  4315. foreach($subs[$chr] as $s) {
  4316. if (isset($fontinfo['cw'][$s])) {
  4317. $uniarr[$k] = $s;
  4318. break;
  4319. }
  4320. }
  4321. } elseif (isset($fontinfo['cw'][$subs[$chr]])) {
  4322. $uniarr[$k] = $subs[$chr];
  4323. }
  4324. }
  4325. }
  4326. }
  4327. return TCPDF_FONTS::UniArrSubString(TCPDF_FONTS::UTF8ArrayToUniArray($uniarr, $this->isunicode));
  4328. }
  4329. /**
  4330. * Defines the default monospaced font.
  4331. * @param $font (string) Font name.
  4332. * @public
  4333. * @since 4.5.025
  4334. */
  4335. public function SetDefaultMonospacedFont($font) {
  4336. $this->default_monospaced_font = $font;
  4337. }
  4338. /**
  4339. * 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 />
  4340. * The identifier can then be passed to Cell(), Write(), Image() or Link(). The destination is defined with SetLink().
  4341. * @public
  4342. * @since 1.5
  4343. * @see Cell(), Write(), Image(), Link(), SetLink()
  4344. */
  4345. public function AddLink() {
  4346. // create a new internal link
  4347. $n = count($this->links) + 1;
  4348. $this->links[$n] = array('p' => 0, 'y' => 0, 'f' => false);
  4349. return $n;
  4350. }
  4351. /**
  4352. * Defines the page and position a link points to.
  4353. * @param $link (int) The link identifier returned by AddLink()
  4354. * @param $y (float) Ordinate of target position; -1 indicates the current position. The default value is 0 (top of page)
  4355. * @param $page (int) Number of target page; -1 indicates the current page (default value). If you prefix a page number with the * character, then this page will not be changed when adding/deleting/moving pages.
  4356. * @public
  4357. * @since 1.5
  4358. * @see AddLink()
  4359. */
  4360. public function SetLink($link, $y=0, $page=-1) {
  4361. $fixed = false;
  4362. if (!empty($page) AND ($page[0] == '*')) {
  4363. $page = intval(substr($page, 1));
  4364. // this page number will not be changed when moving/add/deleting pages
  4365. $fixed = true;
  4366. }
  4367. if ($page < 0) {
  4368. $page = $this->page;
  4369. }
  4370. if ($y == -1) {
  4371. $y = $this->y;
  4372. }
  4373. $this->links[$link] = array('p' => $page, 'y' => $y, 'f' => $fixed);
  4374. }
  4375. /**
  4376. * Puts a link on a rectangular area of the page.
  4377. * 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.
  4378. * @param $x (float) Abscissa of the upper-left corner of the rectangle
  4379. * @param $y (float) Ordinate of the upper-left corner of the rectangle
  4380. * @param $w (float) Width of the rectangle
  4381. * @param $h (float) Height of the rectangle
  4382. * @param $link (mixed) URL or identifier returned by AddLink()
  4383. * @param $spaces (int) number of spaces on the text to link
  4384. * @public
  4385. * @since 1.5
  4386. * @see AddLink(), Annotation(), Cell(), Write(), Image()
  4387. */
  4388. public function Link($x, $y, $w, $h, $link, $spaces=0) {
  4389. $this->Annotation($x, $y, $w, $h, $link, array('Subtype'=>'Link'), $spaces);
  4390. }
  4391. /**
  4392. * Puts a markup annotation on a rectangular area of the page.
  4393. * !!!!THE ANNOTATION SUPPORT IS NOT YET FULLY IMPLEMENTED !!!!
  4394. * @param $x (float) Abscissa of the upper-left corner of the rectangle
  4395. * @param $y (float) Ordinate of the upper-left corner of the rectangle
  4396. * @param $w (float) Width of the rectangle
  4397. * @param $h (float) Height of the rectangle
  4398. * @param $text (string) annotation text or alternate content
  4399. * @param $opt (array) array of options (see section 8.4 of PDF reference 1.7).
  4400. * @param $spaces (int) number of spaces on the text to link
  4401. * @public
  4402. * @since 4.0.018 (2008-08-06)
  4403. */
  4404. public function Annotation($x, $y, $w, $h, $text, $opt=array('Subtype'=>'Text'), $spaces=0) {
  4405. if ($this->inxobj) {
  4406. // store parameters for later use on template
  4407. $this->xobjects[$this->xobjid]['annotations'][] = array('x' => $x, 'y' => $y, 'w' => $w, 'h' => $h, 'text' => $text, 'opt' => $opt, 'spaces' => $spaces);
  4408. return;
  4409. }
  4410. if ($x === '') {
  4411. $x = $this->x;
  4412. }
  4413. if ($y === '') {
  4414. $y = $this->y;
  4415. }
  4416. // check page for no-write regions and adapt page margins if necessary
  4417. list($x, $y) = $this->checkPageRegions($h, $x, $y);
  4418. // recalculate coordinates to account for graphic transformations
  4419. if (isset($this->transfmatrix) AND !empty($this->transfmatrix)) {
  4420. for ($i=$this->transfmatrix_key; $i > 0; --$i) {
  4421. $maxid = count($this->transfmatrix[$i]) - 1;
  4422. for ($j=$maxid; $j >= 0; --$j) {
  4423. $ctm = $this->transfmatrix[$i][$j];
  4424. if (isset($ctm['a'])) {
  4425. $x = $x * $this->k;
  4426. $y = ($this->h - $y) * $this->k;
  4427. $w = $w * $this->k;
  4428. $h = $h * $this->k;
  4429. // top left
  4430. $xt = $x;
  4431. $yt = $y;
  4432. $x1 = ($ctm['a'] * $xt) + ($ctm['c'] * $yt) + $ctm['e'];
  4433. $y1 = ($ctm['b'] * $xt) + ($ctm['d'] * $yt) + $ctm['f'];
  4434. // top right
  4435. $xt = $x + $w;
  4436. $yt = $y;
  4437. $x2 = ($ctm['a'] * $xt) + ($ctm['c'] * $yt) + $ctm['e'];
  4438. $y2 = ($ctm['b'] * $xt) + ($ctm['d'] * $yt) + $ctm['f'];
  4439. // bottom left
  4440. $xt = $x;
  4441. $yt = $y - $h;
  4442. $x3 = ($ctm['a'] * $xt) + ($ctm['c'] * $yt) + $ctm['e'];
  4443. $y3 = ($ctm['b'] * $xt) + ($ctm['d'] * $yt) + $ctm['f'];
  4444. // bottom right
  4445. $xt = $x + $w;
  4446. $yt = $y - $h;
  4447. $x4 = ($ctm['a'] * $xt) + ($ctm['c'] * $yt) + $ctm['e'];
  4448. $y4 = ($ctm['b'] * $xt) + ($ctm['d'] * $yt) + $ctm['f'];
  4449. // new coordinates (rectangle area)
  4450. $x = min($x1, $x2, $x3, $x4);
  4451. $y = max($y1, $y2, $y3, $y4);
  4452. $w = (max($x1, $x2, $x3, $x4) - $x) / $this->k;
  4453. $h = ($y - min($y1, $y2, $y3, $y4)) / $this->k;
  4454. $x = $x / $this->k;
  4455. $y = $this->h - ($y / $this->k);
  4456. }
  4457. }
  4458. }
  4459. }
  4460. if ($this->page <= 0) {
  4461. $page = 1;
  4462. } else {
  4463. $page = $this->page;
  4464. }
  4465. if (!isset($this->PageAnnots[$page])) {
  4466. $this->PageAnnots[$page] = array();
  4467. }
  4468. $this->PageAnnots[$page][] = array('n' => ++$this->n, 'x' => $x, 'y' => $y, 'w' => $w, 'h' => $h, 'txt' => $text, 'opt' => $opt, 'numspaces' => $spaces);
  4469. if (!$this->pdfa_mode || ($this->pdfa_mode && $this->pdfa_version == 3)) {
  4470. if ((($opt['Subtype'] == 'FileAttachment') OR ($opt['Subtype'] == 'Sound')) AND (!TCPDF_STATIC::empty_string($opt['FS']))
  4471. AND (@TCPDF_STATIC::file_exists($opt['FS']) OR TCPDF_STATIC::isValidURL($opt['FS']))
  4472. AND (!isset($this->embeddedfiles[basename($opt['FS'])]))) {
  4473. $this->embeddedfiles[basename($opt['FS'])] = array('f' => ++$this->n, 'n' => ++$this->n, 'file' => $opt['FS']);
  4474. }
  4475. }
  4476. // Add widgets annotation's icons
  4477. if (isset($opt['mk']['i']) AND @TCPDF_STATIC::file_exists($opt['mk']['i'])) {
  4478. $this->Image($opt['mk']['i'], '', '', 10, 10, '', '', '', false, 300, '', false, false, 0, false, true);
  4479. }
  4480. if (isset($opt['mk']['ri']) AND @TCPDF_STATIC::file_exists($opt['mk']['ri'])) {
  4481. $this->Image($opt['mk']['ri'], '', '', 0, 0, '', '', '', false, 300, '', false, false, 0, false, true);
  4482. }
  4483. if (isset($opt['mk']['ix']) AND @TCPDF_STATIC::file_exists($opt['mk']['ix'])) {
  4484. $this->Image($opt['mk']['ix'], '', '', 0, 0, '', '', '', false, 300, '', false, false, 0, false, true);
  4485. }
  4486. }
  4487. /**
  4488. * Embedd the attached files.
  4489. * @since 4.4.000 (2008-12-07)
  4490. * @protected
  4491. * @see Annotation()
  4492. */
  4493. protected function _putEmbeddedFiles() {
  4494. if ($this->pdfa_mode && $this->pdfa_version != 3) {
  4495. // embedded files are not allowed in PDF/A mode version 1 and 2
  4496. return;
  4497. }
  4498. reset($this->embeddedfiles);
  4499. foreach ($this->embeddedfiles as $filename => $filedata) {
  4500. $data = TCPDF_STATIC::fileGetContents($filedata['file']);
  4501. if ($data !== FALSE) {
  4502. $rawsize = strlen($data);
  4503. if ($rawsize > 0) {
  4504. // update name tree
  4505. $this->efnames[$filename] = $filedata['f'].' 0 R';
  4506. // embedded file specification object
  4507. $out = $this->_getobj($filedata['f'])."\n";
  4508. $out .= '<</Type /Filespec /F '.$this->_datastring($filename, $filedata['f']);
  4509. $out .= ' /UF '.$this->_datastring($filename, $filedata['f']);
  4510. $out .= ' /AFRelationship /Source';
  4511. $out .= ' /EF <</F '.$filedata['n'].' 0 R>> >>';
  4512. $out .= "\n".'endobj';
  4513. $this->_out($out);
  4514. // embedded file object
  4515. $filter = '';
  4516. if ($this->compress) {
  4517. $data = gzcompress($data);
  4518. $filter = ' /Filter /FlateDecode';
  4519. }
  4520. if ($this->pdfa_version == 3) {
  4521. $filter = ' /Subtype /text#2Fxml';
  4522. }
  4523. $stream = $this->_getrawstream($data, $filedata['n']);
  4524. $out = $this->_getobj($filedata['n'])."\n";
  4525. $out .= '<< /Type /EmbeddedFile'.$filter.' /Length '.strlen($stream).' /Params <</Size '.$rawsize.'>> >>';
  4526. $out .= ' stream'."\n".$stream."\n".'endstream';
  4527. $out .= "\n".'endobj';
  4528. $this->_out($out);
  4529. }
  4530. }
  4531. }
  4532. }
  4533. /**
  4534. * Prints a text cell at the specified position.
  4535. * This method allows to place a string precisely on the page.
  4536. * @param $x (float) Abscissa of the cell origin
  4537. * @param $y (float) Ordinate of the cell origin
  4538. * @param $txt (string) String to print
  4539. * @param $fstroke (int) outline size in user units (false = disable)
  4540. * @param $fclip (boolean) if true activate clipping mode (you must call StartTransform() before this function and StopTransform() to stop the clipping tranformation).
  4541. * @param $ffill (boolean) if true fills the text
  4542. * @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)))
  4543. * @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.
  4544. * @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>
  4545. * @param $fill (boolean) Indicates if the cell background must be painted (true) or transparent (false).
  4546. * @param $link (mixed) URL or identifier returned by AddLink().
  4547. * @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.
  4548. * @param $ignore_min_height (boolean) if true ignore automatic minimum height value.
  4549. * @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>
  4550. * @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>
  4551. * @param $rtloff (boolean) if true uses the page top-left corner as origin of axis for $x and $y initial position.
  4552. * @public
  4553. * @since 1.0
  4554. * @see Cell(), Write(), MultiCell(), WriteHTML(), WriteHTMLCell()
  4555. */
  4556. 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) {
  4557. $textrendermode = $this->textrendermode;
  4558. $textstrokewidth = $this->textstrokewidth;
  4559. $this->setTextRenderingMode($fstroke, $ffill, $fclip);
  4560. $this->SetXY($x, $y, $rtloff);
  4561. $this->Cell(0, 0, $txt, $border, $ln, $align, $fill, $link, $stretch, $ignore_min_height, $calign, $valign);
  4562. // restore previous rendering mode
  4563. $this->textrendermode = $textrendermode;
  4564. $this->textstrokewidth = $textstrokewidth;
  4565. }
  4566. /**
  4567. * Whenever a page break condition is met, the method is called, and the break is issued or not depending on the returned value.
  4568. * The default implementation returns a value according to the mode selected by SetAutoPageBreak().<br />
  4569. * This method is called automatically and should not be called directly by the application.
  4570. * @return boolean
  4571. * @public
  4572. * @since 1.4
  4573. * @see SetAutoPageBreak()
  4574. */
  4575. public function AcceptPageBreak() {
  4576. if ($this->num_columns > 1) {
  4577. // multi column mode
  4578. if ($this->current_column < ($this->num_columns - 1)) {
  4579. // go to next column
  4580. $this->selectColumn($this->current_column + 1);
  4581. } elseif ($this->AutoPageBreak) {
  4582. // add a new page
  4583. $this->AddPage();
  4584. // set first column
  4585. $this->selectColumn(0);
  4586. }
  4587. // avoid page breaking from checkPageBreak()
  4588. return false;
  4589. }
  4590. return $this->AutoPageBreak;
  4591. }
  4592. /**
  4593. * Add page if needed.
  4594. * @param $h (float) Cell height. Default value: 0.
  4595. * @param $y (mixed) starting y position, leave empty for current position.
  4596. * @param $addpage (boolean) if true add a page, otherwise only return the true/false state
  4597. * @return boolean true in case of page break, false otherwise.
  4598. * @since 3.2.000 (2008-07-01)
  4599. * @protected
  4600. */
  4601. protected function checkPageBreak($h=0, $y='', $addpage=true) {
  4602. if (TCPDF_STATIC::empty_string($y)) {
  4603. $y = $this->y;
  4604. }
  4605. $current_page = $this->page;
  4606. if ((($y + $h) > $this->PageBreakTrigger) AND ($this->inPageBody()) AND ($this->AcceptPageBreak())) {
  4607. if ($addpage) {
  4608. //Automatic page break
  4609. $x = $this->x;
  4610. $this->AddPage($this->CurOrientation);
  4611. $this->y = $this->tMargin;
  4612. $oldpage = $this->page - 1;
  4613. if ($this->rtl) {
  4614. if ($this->pagedim[$this->page]['orm'] != $this->pagedim[$oldpage]['orm']) {
  4615. $this->x = $x - ($this->pagedim[$this->page]['orm'] - $this->pagedim[$oldpage]['orm']);
  4616. } else {
  4617. $this->x = $x;
  4618. }
  4619. } else {
  4620. if ($this->pagedim[$this->page]['olm'] != $this->pagedim[$oldpage]['olm']) {
  4621. $this->x = $x + ($this->pagedim[$this->page]['olm'] - $this->pagedim[$oldpage]['olm']);
  4622. } else {
  4623. $this->x = $x;
  4624. }
  4625. }
  4626. }
  4627. return true;
  4628. }
  4629. if ($current_page != $this->page) {
  4630. // account for columns mode
  4631. return true;
  4632. }
  4633. return false;
  4634. }
  4635. /**
  4636. * 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 />
  4637. * If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting.
  4638. * @param $w (float) Cell width. If 0, the cell extends up to the right margin.
  4639. * @param $h (float) Cell height. Default value: 0.
  4640. * @param $txt (string) String to print. Default value: empty string.
  4641. * @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)))
  4642. * @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.
  4643. * @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>
  4644. * @param $fill (boolean) Indicates if the cell background must be painted (true) or transparent (false).
  4645. * @param $link (mixed) URL or identifier returned by AddLink().
  4646. * @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.
  4647. * @param $ignore_min_height (boolean) if true ignore automatic minimum height value.
  4648. * @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>
  4649. * @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>
  4650. * @public
  4651. * @since 1.0
  4652. * @see SetFont(), SetDrawColor(), SetFillColor(), SetTextColor(), SetLineWidth(), AddLink(), Ln(), MultiCell(), Write(), SetAutoPageBreak()
  4653. */
  4654. 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') {
  4655. $prev_cell_margin = $this->cell_margin;
  4656. $prev_cell_padding = $this->cell_padding;
  4657. $this->adjustCellPadding($border);
  4658. if (!$ignore_min_height) {
  4659. $min_cell_height = $this->getCellHeight($this->FontSize);
  4660. if ($h < $min_cell_height) {
  4661. $h = $min_cell_height;
  4662. }
  4663. }
  4664. $this->checkPageBreak($h + $this->cell_margin['T'] + $this->cell_margin['B']);
  4665. // apply text shadow if enabled
  4666. if ($this->txtshadow['enabled']) {
  4667. // save data
  4668. $x = $this->x;
  4669. $y = $this->y;
  4670. $bc = $this->bgcolor;
  4671. $fc = $this->fgcolor;
  4672. $sc = $this->strokecolor;
  4673. $alpha = $this->alpha;
  4674. // print shadow
  4675. $this->x += $this->txtshadow['depth_w'];
  4676. $this->y += $this->txtshadow['depth_h'];
  4677. $this->SetFillColorArray($this->txtshadow['color']);
  4678. $this->SetTextColorArray($this->txtshadow['color']);
  4679. $this->SetDrawColorArray($this->txtshadow['color']);
  4680. if ($this->txtshadow['opacity'] != $alpha['CA']) {
  4681. $this->setAlpha($this->txtshadow['opacity'], $this->txtshadow['blend_mode']);
  4682. }
  4683. if ($this->state == 2) {
  4684. $this->_out($this->getCellCode($w, $h, $txt, $border, $ln, $align, $fill, $link, $stretch, true, $calign, $valign));
  4685. }
  4686. //restore data
  4687. $this->x = $x;
  4688. $this->y = $y;
  4689. $this->SetFillColorArray($bc);
  4690. $this->SetTextColorArray($fc);
  4691. $this->SetDrawColorArray($sc);
  4692. if ($this->txtshadow['opacity'] != $alpha['CA']) {
  4693. $this->setAlpha($alpha['CA'], $alpha['BM'], $alpha['ca'], $alpha['AIS']);
  4694. }
  4695. }
  4696. if ($this->state == 2) {
  4697. $this->_out($this->getCellCode($w, $h, $txt, $border, $ln, $align, $fill, $link, $stretch, true, $calign, $valign));
  4698. }
  4699. $this->cell_padding = $prev_cell_padding;
  4700. $this->cell_margin = $prev_cell_margin;
  4701. }
  4702. /**
  4703. * 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 />
  4704. * If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting.
  4705. * @param $w (float) Cell width. If 0, the cell extends up to the right margin.
  4706. * @param $h (float) Cell height. Default value: 0.
  4707. * @param $txt (string) String to print. Default value: empty string.
  4708. * @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)))
  4709. * @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.
  4710. * @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>
  4711. * @param $fill (boolean) Indicates if the cell background must be painted (true) or transparent (false).
  4712. * @param $link (mixed) URL or identifier returned by AddLink().
  4713. * @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.
  4714. * @param $ignore_min_height (boolean) if true ignore automatic minimum height value.
  4715. * @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>
  4716. * @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>
  4717. * @return string containing cell code
  4718. * @protected
  4719. * @since 1.0
  4720. * @see Cell()
  4721. */
  4722. 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') {
  4723. // replace 'NO-BREAK SPACE' (U+00A0) character with a simple space
  4724. $txt = str_replace(TCPDF_FONTS::unichr(160, $this->isunicode), ' ', $txt);
  4725. $prev_cell_margin = $this->cell_margin;
  4726. $prev_cell_padding = $this->cell_padding;
  4727. $txt = TCPDF_STATIC::removeSHY($txt, $this->isunicode);
  4728. $rs = ''; //string to be returned
  4729. $this->adjustCellPadding($border);
  4730. if (!$ignore_min_height) {
  4731. $min_cell_height = $this->getCellHeight($this->FontSize);
  4732. if ($h < $min_cell_height) {
  4733. $h = $min_cell_height;
  4734. }
  4735. }
  4736. $k = $this->k;
  4737. // check page for no-write regions and adapt page margins if necessary
  4738. list($this->x, $this->y) = $this->checkPageRegions($h, $this->x, $this->y);
  4739. if ($this->rtl) {
  4740. $x = $this->x - $this->cell_margin['R'];
  4741. } else {
  4742. $x = $this->x + $this->cell_margin['L'];
  4743. }
  4744. $y = $this->y + $this->cell_margin['T'];
  4745. $prev_font_stretching = $this->font_stretching;
  4746. $prev_font_spacing = $this->font_spacing;
  4747. // cell vertical alignment
  4748. switch ($calign) {
  4749. case 'A': {
  4750. // font top
  4751. switch ($valign) {
  4752. case 'T': {
  4753. // top
  4754. $y -= $this->cell_padding['T'];
  4755. break;
  4756. }
  4757. case 'B': {
  4758. // bottom
  4759. $y -= ($h - $this->cell_padding['B'] - $this->FontAscent - $this->FontDescent);
  4760. break;
  4761. }
  4762. default:
  4763. case 'C':
  4764. case 'M': {
  4765. // center
  4766. $y -= (($h - $this->FontAscent - $this->FontDescent) / 2);
  4767. break;
  4768. }
  4769. }
  4770. break;
  4771. }
  4772. case 'L': {
  4773. // font baseline
  4774. switch ($valign) {
  4775. case 'T': {
  4776. // top
  4777. $y -= ($this->cell_padding['T'] + $this->FontAscent);
  4778. break;
  4779. }
  4780. case 'B': {
  4781. // bottom
  4782. $y -= ($h - $this->cell_padding['B'] - $this->FontDescent);
  4783. break;
  4784. }
  4785. default:
  4786. case 'C':
  4787. case 'M': {
  4788. // center
  4789. $y -= (($h + $this->FontAscent - $this->FontDescent) / 2);
  4790. break;
  4791. }
  4792. }
  4793. break;
  4794. }
  4795. case 'D': {
  4796. // font bottom
  4797. switch ($valign) {
  4798. case 'T': {
  4799. // top
  4800. $y -= ($this->cell_padding['T'] + $this->FontAscent + $this->FontDescent);
  4801. break;
  4802. }
  4803. case 'B': {
  4804. // bottom
  4805. $y -= ($h - $this->cell_padding['B']);
  4806. break;
  4807. }
  4808. default:
  4809. case 'C':
  4810. case 'M': {
  4811. // center
  4812. $y -= (($h + $this->FontAscent + $this->FontDescent) / 2);
  4813. break;
  4814. }
  4815. }
  4816. break;
  4817. }
  4818. case 'B': {
  4819. // cell bottom
  4820. $y -= $h;
  4821. break;
  4822. }
  4823. case 'C':
  4824. case 'M': {
  4825. // cell center
  4826. $y -= ($h / 2);
  4827. break;
  4828. }
  4829. default:
  4830. case 'T': {
  4831. // cell top
  4832. break;
  4833. }
  4834. }
  4835. // text vertical alignment
  4836. switch ($valign) {
  4837. case 'T': {
  4838. // top
  4839. $yt = $y + $this->cell_padding['T'];
  4840. break;
  4841. }
  4842. case 'B': {
  4843. // bottom
  4844. $yt = $y + $h - $this->cell_padding['B'] - $this->FontAscent - $this->FontDescent;
  4845. break;
  4846. }
  4847. default:
  4848. case 'C':
  4849. case 'M': {
  4850. // center
  4851. $yt = $y + (($h - $this->FontAscent - $this->FontDescent) / 2);
  4852. break;
  4853. }
  4854. }
  4855. $basefonty = $yt + $this->FontAscent;
  4856. if (TCPDF_STATIC::empty_string($w) OR ($w <= 0)) {
  4857. if ($this->rtl) {
  4858. $w = $x - $this->lMargin;
  4859. } else {
  4860. $w = $this->w - $this->rMargin - $x;
  4861. }
  4862. }
  4863. $s = '';
  4864. // fill and borders
  4865. if (is_string($border) AND (strlen($border) == 4)) {
  4866. // full border
  4867. $border = 1;
  4868. }
  4869. if ($fill OR ($border == 1)) {
  4870. if ($fill) {
  4871. $op = ($border == 1) ? 'B' : 'f';
  4872. } else {
  4873. $op = 'S';
  4874. }
  4875. if ($this->rtl) {
  4876. $xk = (($x - $w) * $k);
  4877. } else {
  4878. $xk = ($x * $k);
  4879. }
  4880. $s .= sprintf('%F %F %F %F re %s ', $xk, (($this->h - $y) * $k), ($w * $k), (-$h * $k), $op);
  4881. }
  4882. // draw borders
  4883. $s .= $this->getCellBorder($x, $y, $w, $h, $border);
  4884. if ($txt != '') {
  4885. $txt2 = $txt;
  4886. if ($this->isunicode) {
  4887. if (($this->CurrentFont['type'] == 'core') OR ($this->CurrentFont['type'] == 'TrueType') OR ($this->CurrentFont['type'] == 'Type1')) {
  4888. $txt2 = TCPDF_FONTS::UTF8ToLatin1($txt2, $this->isunicode, $this->CurrentFont);
  4889. } else {
  4890. $unicode = TCPDF_FONTS::UTF8StringToArray($txt, $this->isunicode, $this->CurrentFont); // array of UTF-8 unicode values
  4891. $unicode = TCPDF_FONTS::utf8Bidi($unicode, '', $this->tmprtl, $this->isunicode, $this->CurrentFont);
  4892. // replace thai chars (if any)
  4893. if (defined('K_THAI_TOPCHARS') AND (K_THAI_TOPCHARS == true)) {
  4894. // number of chars
  4895. $numchars = count($unicode);
  4896. // po pla, for far, for fan
  4897. $longtail = array(0x0e1b, 0x0e1d, 0x0e1f);
  4898. // do chada, to patak
  4899. $lowtail = array(0x0e0e, 0x0e0f);
  4900. // mai hun arkad, sara i, sara ii, sara ue, sara uee
  4901. $upvowel = array(0x0e31, 0x0e34, 0x0e35, 0x0e36, 0x0e37);
  4902. // mai ek, mai tho, mai tri, mai chattawa, karan
  4903. $tonemark = array(0x0e48, 0x0e49, 0x0e4a, 0x0e4b, 0x0e4c);
  4904. // sara u, sara uu, pinthu
  4905. $lowvowel = array(0x0e38, 0x0e39, 0x0e3a);
  4906. $output = array();
  4907. for ($i = 0; $i < $numchars; $i++) {
  4908. if (($unicode[$i] >= 0x0e00) && ($unicode[$i] <= 0x0e5b)) {
  4909. $ch0 = $unicode[$i];
  4910. $ch1 = ($i > 0) ? $unicode[($i - 1)] : 0;
  4911. $ch2 = ($i > 1) ? $unicode[($i - 2)] : 0;
  4912. $chn = ($i < ($numchars - 1)) ? $unicode[($i + 1)] : 0;
  4913. if (in_array($ch0, $tonemark)) {
  4914. if ($chn == 0x0e33) {
  4915. // sara um
  4916. if (in_array($ch1, $longtail)) {
  4917. // tonemark at upper left
  4918. $output[] = $this->replaceChar($ch0, (0xf713 + $ch0 - 0x0e48));
  4919. } else {
  4920. // tonemark at upper right (normal position)
  4921. $output[] = $ch0;
  4922. }
  4923. } elseif (in_array($ch1, $longtail) OR (in_array($ch2, $longtail) AND in_array($ch1, $lowvowel))) {
  4924. // tonemark at lower left
  4925. $output[] = $this->replaceChar($ch0, (0xf705 + $ch0 - 0x0e48));
  4926. } elseif (in_array($ch1, $upvowel)) {
  4927. if (in_array($ch2, $longtail)) {
  4928. // tonemark at upper left
  4929. $output[] = $this->replaceChar($ch0, (0xf713 + $ch0 - 0x0e48));
  4930. } else {
  4931. // tonemark at upper right (normal position)
  4932. $output[] = $ch0;
  4933. }
  4934. } else {
  4935. // tonemark at lower right
  4936. $output[] = $this->replaceChar($ch0, (0xf70a + $ch0 - 0x0e48));
  4937. }
  4938. } elseif (($ch0 == 0x0e33) AND (in_array($ch1, $longtail) OR (in_array($ch2, $longtail) AND in_array($ch1, $tonemark)))) {
  4939. // add lower left nikhahit and sara aa
  4940. if ($this->isCharDefined(0xf711) AND $this->isCharDefined(0x0e32)) {
  4941. $output[] = 0xf711;
  4942. $this->CurrentFont['subsetchars'][0xf711] = true;
  4943. $output[] = 0x0e32;
  4944. $this->CurrentFont['subsetchars'][0x0e32] = true;
  4945. } else {
  4946. $output[] = $ch0;
  4947. }
  4948. } elseif (in_array($ch1, $longtail)) {
  4949. if ($ch0 == 0x0e31) {
  4950. // lower left mai hun arkad
  4951. $output[] = $this->replaceChar($ch0, 0xf710);
  4952. } elseif (in_array($ch0, $upvowel)) {
  4953. // lower left
  4954. $output[] = $this->replaceChar($ch0, (0xf701 + $ch0 - 0x0e34));
  4955. } elseif ($ch0 == 0x0e47) {
  4956. // lower left mai tai koo
  4957. $output[] = $this->replaceChar($ch0, 0xf712);
  4958. } else {
  4959. // normal character
  4960. $output[] = $ch0;
  4961. }
  4962. } elseif (in_array($ch1, $lowtail) AND in_array($ch0, $lowvowel)) {
  4963. // lower vowel
  4964. $output[] = $this->replaceChar($ch0, (0xf718 + $ch0 - 0x0e38));
  4965. } elseif (($ch0 == 0x0e0d) AND in_array($chn, $lowvowel)) {
  4966. // yo ying without lower part
  4967. $output[] = $this->replaceChar($ch0, 0xf70f);
  4968. } elseif (($ch0 == 0x0e10) AND in_array($chn, $lowvowel)) {
  4969. // tho santan without lower part
  4970. $output[] = $this->replaceChar($ch0, 0xf700);
  4971. } else {
  4972. $output[] = $ch0;
  4973. }
  4974. } else {
  4975. // non-thai character
  4976. $output[] = $unicode[$i];
  4977. }
  4978. }
  4979. $unicode = $output;
  4980. // update font subsetchars
  4981. $this->setFontSubBuffer($this->CurrentFont['fontkey'], 'subsetchars', $this->CurrentFont['subsetchars']);
  4982. } // end of K_THAI_TOPCHARS
  4983. $txt2 = TCPDF_FONTS::arrUTF8ToUTF16BE($unicode, false);
  4984. }
  4985. }
  4986. $txt2 = TCPDF_STATIC::_escape($txt2);
  4987. // get current text width (considering general font stretching and spacing)
  4988. $txwidth = $this->GetStringWidth($txt);
  4989. $width = $txwidth;
  4990. // check for stretch mode
  4991. if ($stretch > 0) {
  4992. // calculate ratio between cell width and text width
  4993. if ($width <= 0) {
  4994. $ratio = 1;
  4995. } else {
  4996. $ratio = (($w - $this->cell_padding['L'] - $this->cell_padding['R']) / $width);
  4997. }
  4998. // check if stretching is required
  4999. if (($ratio < 1) OR (($ratio > 1) AND (($stretch % 2) == 0))) {
  5000. // the text will be stretched to fit cell width
  5001. if ($stretch > 2) {
  5002. // set new character spacing
  5003. $this->font_spacing += ($w - $this->cell_padding['L'] - $this->cell_padding['R'] - $width) / (max(($this->GetNumChars($txt) - 1), 1) * ($this->font_stretching / 100));
  5004. } else {
  5005. // set new horizontal stretching
  5006. $this->font_stretching *= $ratio;
  5007. }
  5008. // recalculate text width (the text fills the entire cell)
  5009. $width = $w - $this->cell_padding['L'] - $this->cell_padding['R'];
  5010. // reset alignment
  5011. $align = '';
  5012. }
  5013. }
  5014. if ($this->font_stretching != 100) {
  5015. // apply font stretching
  5016. $rs .= sprintf('BT %F Tz ET ', $this->font_stretching);
  5017. }
  5018. if ($this->font_spacing != 0) {
  5019. // increase/decrease font spacing
  5020. $rs .= sprintf('BT %F Tc ET ', ($this->font_spacing * $this->k));
  5021. }
  5022. if ($this->ColorFlag AND ($this->textrendermode < 4)) {
  5023. $s .= 'q '.$this->TextColor.' ';
  5024. }
  5025. // rendering mode
  5026. $s .= sprintf('BT %d Tr %F w ET ', $this->textrendermode, ($this->textstrokewidth * $this->k));
  5027. // count number of spaces
  5028. $ns = substr_count($txt, chr(32));
  5029. // Justification
  5030. $spacewidth = 0;
  5031. if (($align == 'J') AND ($ns > 0)) {
  5032. if ($this->isUnicodeFont()) {
  5033. // get string width without spaces
  5034. $width = $this->GetStringWidth(str_replace(' ', '', $txt));
  5035. // calculate average space width
  5036. $spacewidth = -1000 * ($w - $width - $this->cell_padding['L'] - $this->cell_padding['R']) / ($ns?$ns:1) / ($this->FontSize?$this->FontSize:1);
  5037. if ($this->font_stretching != 100) {
  5038. // word spacing is affected by stretching
  5039. $spacewidth /= ($this->font_stretching / 100);
  5040. }
  5041. // set word position to be used with TJ operator
  5042. $txt2 = str_replace(chr(0).chr(32), ') '.sprintf('%F', $spacewidth).' (', $txt2);
  5043. $unicode_justification = true;
  5044. } else {
  5045. // get string width
  5046. $width = $txwidth;
  5047. // new space width
  5048. $spacewidth = (($w - $width - $this->cell_padding['L'] - $this->cell_padding['R']) / ($ns?$ns:1)) * $this->k;
  5049. if ($this->font_stretching != 100) {
  5050. // word spacing (Tw) is affected by stretching
  5051. $spacewidth /= ($this->font_stretching / 100);
  5052. }
  5053. // set word spacing
  5054. $rs .= sprintf('BT %F Tw ET ', $spacewidth);
  5055. }
  5056. $width = $w - $this->cell_padding['L'] - $this->cell_padding['R'];
  5057. }
  5058. // replace carriage return characters
  5059. $txt2 = str_replace("\r", ' ', $txt2);
  5060. switch ($align) {
  5061. case 'C': {
  5062. $dx = ($w - $width) / 2;
  5063. break;
  5064. }
  5065. case 'R': {
  5066. if ($this->rtl) {
  5067. $dx = $this->cell_padding['R'];
  5068. } else {
  5069. $dx = $w - $width - $this->cell_padding['R'];
  5070. }
  5071. break;
  5072. }
  5073. case 'L': {
  5074. if ($this->rtl) {
  5075. $dx = $w - $width - $this->cell_padding['L'];
  5076. } else {
  5077. $dx = $this->cell_padding['L'];
  5078. }
  5079. break;
  5080. }
  5081. case 'J':
  5082. default: {
  5083. if ($this->rtl) {
  5084. $dx = $this->cell_padding['R'];
  5085. } else {
  5086. $dx = $this->cell_padding['L'];
  5087. }
  5088. break;
  5089. }
  5090. }
  5091. if ($this->rtl) {
  5092. $xdx = $x - $dx - $width;
  5093. } else {
  5094. $xdx = $x + $dx;
  5095. }
  5096. $xdk = $xdx * $k;
  5097. // print text
  5098. $s .= sprintf('BT %F %F Td [(%s)] TJ ET', $xdk, (($this->h - $basefonty) * $k), $txt2);
  5099. if (isset($uniblock)) {
  5100. // print overlapping characters as separate string
  5101. $xshift = 0; // horizontal shift
  5102. $ty = (($this->h - $basefonty + (0.2 * $this->FontSize)) * $k);
  5103. $spw = (($w - $txwidth - $this->cell_padding['L'] - $this->cell_padding['R']) / ($ns?$ns:1));
  5104. foreach ($uniblock as $uk => $uniarr) {
  5105. if (($uk % 2) == 0) {
  5106. // x space to skip
  5107. if ($spacewidth != 0) {
  5108. // justification shift
  5109. $xshift += (count(array_keys($uniarr, 32)) * $spw);
  5110. }
  5111. $xshift += $this->GetArrStringWidth($uniarr); // + shift justification
  5112. } else {
  5113. // character to print
  5114. $topchr = TCPDF_FONTS::arrUTF8ToUTF16BE($uniarr, false);
  5115. $topchr = TCPDF_STATIC::_escape($topchr);
  5116. $s .= sprintf(' BT %F %F Td [(%s)] TJ ET', ($xdk + ($xshift * $k)), $ty, $topchr);
  5117. }
  5118. }
  5119. }
  5120. if ($this->underline) {
  5121. $s .= ' '.$this->_dounderlinew($xdx, $basefonty, $width);
  5122. }
  5123. if ($this->linethrough) {
  5124. $s .= ' '.$this->_dolinethroughw($xdx, $basefonty, $width);
  5125. }
  5126. if ($this->overline) {
  5127. $s .= ' '.$this->_dooverlinew($xdx, $basefonty, $width);
  5128. }
  5129. if ($this->ColorFlag AND ($this->textrendermode < 4)) {
  5130. $s .= ' Q';
  5131. }
  5132. if ($link) {
  5133. $this->Link($xdx, $yt, $width, ($this->FontAscent + $this->FontDescent), $link, $ns);
  5134. }
  5135. }
  5136. // output cell
  5137. if ($s) {
  5138. // output cell
  5139. $rs .= $s;
  5140. if ($this->font_spacing != 0) {
  5141. // reset font spacing mode
  5142. $rs .= ' BT 0 Tc ET';
  5143. }
  5144. if ($this->font_stretching != 100) {
  5145. // reset font stretching mode
  5146. $rs .= ' BT 100 Tz ET';
  5147. }
  5148. }
  5149. // reset word spacing
  5150. if (!$this->isUnicodeFont() AND ($align == 'J')) {
  5151. $rs .= ' BT 0 Tw ET';
  5152. }
  5153. // reset stretching and spacing
  5154. $this->font_stretching = $prev_font_stretching;
  5155. $this->font_spacing = $prev_font_spacing;
  5156. $this->lasth = $h;
  5157. if ($ln > 0) {
  5158. //Go to the beginning of the next line
  5159. $this->y = $y + $h + $this->cell_margin['B'];
  5160. if ($ln == 1) {
  5161. if ($this->rtl) {
  5162. $this->x = $this->w - $this->rMargin;
  5163. } else {
  5164. $this->x = $this->lMargin;
  5165. }
  5166. }
  5167. } else {
  5168. // go left or right by case
  5169. if ($this->rtl) {
  5170. $this->x = $x - $w - $this->cell_margin['L'];
  5171. } else {
  5172. $this->x = $x + $w + $this->cell_margin['R'];
  5173. }
  5174. }
  5175. $gstyles = ''.$this->linestyleWidth.' '.$this->linestyleCap.' '.$this->linestyleJoin.' '.$this->linestyleDash.' '.$this->DrawColor.' '.$this->FillColor."\n";
  5176. $rs = $gstyles.$rs;
  5177. $this->cell_padding = $prev_cell_padding;
  5178. $this->cell_margin = $prev_cell_margin;
  5179. return $rs;
  5180. }
  5181. /**
  5182. * Replace a char if is defined on the current font.
  5183. * @param $oldchar (int) Integer code (unicode) of the character to replace.
  5184. * @param $newchar (int) Integer code (unicode) of the new character.
  5185. * @return int the replaced char or the old char in case the new char i not defined
  5186. * @protected
  5187. * @since 5.9.167 (2012-06-22)
  5188. */
  5189. protected function replaceChar($oldchar, $newchar) {
  5190. if ($this->isCharDefined($newchar)) {
  5191. // add the new char on the subset list
  5192. $this->CurrentFont['subsetchars'][$newchar] = true;
  5193. // return the new character
  5194. return $newchar;
  5195. }
  5196. // return the old char
  5197. return $oldchar;
  5198. }
  5199. /**
  5200. * Returns the code to draw the cell border
  5201. * @param $x (float) X coordinate.
  5202. * @param $y (float) Y coordinate.
  5203. * @param $w (float) Cell width.
  5204. * @param $h (float) Cell height.
  5205. * @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)))
  5206. * @return string containing cell border code
  5207. * @protected
  5208. * @see SetLineStyle()
  5209. * @since 5.7.000 (2010-08-02)
  5210. */
  5211. protected function getCellBorder($x, $y, $w, $h, $brd) {
  5212. $s = ''; // string to be returned
  5213. if (empty($brd)) {
  5214. return $s;
  5215. }
  5216. if ($brd == 1) {
  5217. $brd = array('LRTB' => true);
  5218. }
  5219. // calculate coordinates for border
  5220. $k = $this->k;
  5221. if ($this->rtl) {
  5222. $xeL = ($x - $w) * $k;
  5223. $xeR = $x * $k;
  5224. } else {
  5225. $xeL = $x * $k;
  5226. $xeR = ($x + $w) * $k;
  5227. }
  5228. $yeL = (($this->h - ($y + $h)) * $k);
  5229. $yeT = (($this->h - $y) * $k);
  5230. $xeT = $xeL;
  5231. $xeB = $xeR;
  5232. $yeR = $yeT;
  5233. $yeB = $yeL;
  5234. if (is_string($brd)) {
  5235. // convert string to array
  5236. $slen = strlen($brd);
  5237. $newbrd = array();
  5238. for ($i = 0; $i < $slen; ++$i) {
  5239. $newbrd[$brd[$i]] = array('cap' => 'square', 'join' => 'miter');
  5240. }
  5241. $brd = $newbrd;
  5242. }
  5243. if (isset($brd['mode'])) {
  5244. $mode = $brd['mode'];
  5245. unset($brd['mode']);
  5246. } else {
  5247. $mode = 'normal';
  5248. }
  5249. foreach ($brd as $border => $style) {
  5250. if (is_array($style) AND !empty($style)) {
  5251. // apply border style
  5252. $prev_style = $this->linestyleWidth.' '.$this->linestyleCap.' '.$this->linestyleJoin.' '.$this->linestyleDash.' '.$this->DrawColor.' ';
  5253. $s .= $this->SetLineStyle($style, true)."\n";
  5254. }
  5255. switch ($mode) {
  5256. case 'ext': {
  5257. $off = (($this->LineWidth / 2) * $k);
  5258. $xL = $xeL - $off;
  5259. $xR = $xeR + $off;
  5260. $yT = $yeT + $off;
  5261. $yL = $yeL - $off;
  5262. $xT = $xL;
  5263. $xB = $xR;
  5264. $yR = $yT;
  5265. $yB = $yL;
  5266. $w += $this->LineWidth;
  5267. $h += $this->LineWidth;
  5268. break;
  5269. }
  5270. case 'int': {
  5271. $off = ($this->LineWidth / 2) * $k;
  5272. $xL = $xeL + $off;
  5273. $xR = $xeR - $off;
  5274. $yT = $yeT - $off;
  5275. $yL = $yeL + $off;
  5276. $xT = $xL;
  5277. $xB = $xR;
  5278. $yR = $yT;
  5279. $yB = $yL;
  5280. $w -= $this->LineWidth;
  5281. $h -= $this->LineWidth;
  5282. break;
  5283. }
  5284. case 'normal':
  5285. default: {
  5286. $xL = $xeL;
  5287. $xT = $xeT;
  5288. $xB = $xeB;
  5289. $xR = $xeR;
  5290. $yL = $yeL;
  5291. $yT = $yeT;
  5292. $yB = $yeB;
  5293. $yR = $yeR;
  5294. break;
  5295. }
  5296. }
  5297. // draw borders by case
  5298. if (strlen($border) == 4) {
  5299. $s .= sprintf('%F %F %F %F re S ', $xT, $yT, ($w * $k), (-$h * $k));
  5300. } elseif (strlen($border) == 3) {
  5301. if (strpos($border,'B') === false) { // LTR
  5302. $s .= sprintf('%F %F m ', $xL, $yL);
  5303. $s .= sprintf('%F %F l ', $xT, $yT);
  5304. $s .= sprintf('%F %F l ', $xR, $yR);
  5305. $s .= sprintf('%F %F l ', $xB, $yB);
  5306. $s .= 'S ';
  5307. } elseif (strpos($border,'L') === false) { // TRB
  5308. $s .= sprintf('%F %F m ', $xT, $yT);
  5309. $s .= sprintf('%F %F l ', $xR, $yR);
  5310. $s .= sprintf('%F %F l ', $xB, $yB);
  5311. $s .= sprintf('%F %F l ', $xL, $yL);
  5312. $s .= 'S ';
  5313. } elseif (strpos($border,'T') === false) { // RBL
  5314. $s .= sprintf('%F %F m ', $xR, $yR);
  5315. $s .= sprintf('%F %F l ', $xB, $yB);
  5316. $s .= sprintf('%F %F l ', $xL, $yL);
  5317. $s .= sprintf('%F %F l ', $xT, $yT);
  5318. $s .= 'S ';
  5319. } elseif (strpos($border,'R') === false) { // BLT
  5320. $s .= sprintf('%F %F m ', $xB, $yB);
  5321. $s .= sprintf('%F %F l ', $xL, $yL);
  5322. $s .= sprintf('%F %F l ', $xT, $yT);
  5323. $s .= sprintf('%F %F l ', $xR, $yR);
  5324. $s .= 'S ';
  5325. }
  5326. } elseif (strlen($border) == 2) {
  5327. if ((strpos($border,'L') !== false) AND (strpos($border,'T') !== false)) { // LT
  5328. $s .= sprintf('%F %F m ', $xL, $yL);
  5329. $s .= sprintf('%F %F l ', $xT, $yT);
  5330. $s .= sprintf('%F %F l ', $xR, $yR);
  5331. $s .= 'S ';
  5332. } elseif ((strpos($border,'T') !== false) AND (strpos($border,'R') !== false)) { // TR
  5333. $s .= sprintf('%F %F m ', $xT, $yT);
  5334. $s .= sprintf('%F %F l ', $xR, $yR);
  5335. $s .= sprintf('%F %F l ', $xB, $yB);
  5336. $s .= 'S ';
  5337. } elseif ((strpos($border,'R') !== false) AND (strpos($border,'B') !== false)) { // RB
  5338. $s .= sprintf('%F %F m ', $xR, $yR);
  5339. $s .= sprintf('%F %F l ', $xB, $yB);
  5340. $s .= sprintf('%F %F l ', $xL, $yL);
  5341. $s .= 'S ';
  5342. } elseif ((strpos($border,'B') !== false) AND (strpos($border,'L') !== false)) { // BL
  5343. $s .= sprintf('%F %F m ', $xB, $yB);
  5344. $s .= sprintf('%F %F l ', $xL, $yL);
  5345. $s .= sprintf('%F %F l ', $xT, $yT);
  5346. $s .= 'S ';
  5347. } elseif ((strpos($border,'L') !== false) AND (strpos($border,'R') !== false)) { // LR
  5348. $s .= sprintf('%F %F m ', $xL, $yL);
  5349. $s .= sprintf('%F %F l ', $xT, $yT);
  5350. $s .= 'S ';
  5351. $s .= sprintf('%F %F m ', $xR, $yR);
  5352. $s .= sprintf('%F %F l ', $xB, $yB);
  5353. $s .= 'S ';
  5354. } elseif ((strpos($border,'T') !== false) AND (strpos($border,'B') !== false)) { // TB
  5355. $s .= sprintf('%F %F m ', $xT, $yT);
  5356. $s .= sprintf('%F %F l ', $xR, $yR);
  5357. $s .= 'S ';
  5358. $s .= sprintf('%F %F m ', $xB, $yB);
  5359. $s .= sprintf('%F %F l ', $xL, $yL);
  5360. $s .= 'S ';
  5361. }
  5362. } else { // strlen($border) == 1
  5363. if (strpos($border,'L') !== false) { // L
  5364. $s .= sprintf('%F %F m ', $xL, $yL);
  5365. $s .= sprintf('%F %F l ', $xT, $yT);
  5366. $s .= 'S ';
  5367. } elseif (strpos($border,'T') !== false) { // T
  5368. $s .= sprintf('%F %F m ', $xT, $yT);
  5369. $s .= sprintf('%F %F l ', $xR, $yR);
  5370. $s .= 'S ';
  5371. } elseif (strpos($border,'R') !== false) { // R
  5372. $s .= sprintf('%F %F m ', $xR, $yR);
  5373. $s .= sprintf('%F %F l ', $xB, $yB);
  5374. $s .= 'S ';
  5375. } elseif (strpos($border,'B') !== false) { // B
  5376. $s .= sprintf('%F %F m ', $xB, $yB);
  5377. $s .= sprintf('%F %F l ', $xL, $yL);
  5378. $s .= 'S ';
  5379. }
  5380. }
  5381. if (is_array($style) AND !empty($style)) {
  5382. // reset border style to previous value
  5383. $s .= "\n".$this->linestyleWidth.' '.$this->linestyleCap.' '.$this->linestyleJoin.' '.$this->linestyleDash.' '.$this->DrawColor."\n";
  5384. }
  5385. }
  5386. return $s;
  5387. }
  5388. /**
  5389. * This method allows printing text with line breaks.
  5390. * 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 />
  5391. * Text can be aligned, centered or justified. The cell block can be framed and the background painted.
  5392. * @param $w (float) Width of cells. If 0, they extend up to the right margin of the page.
  5393. * @param $h (float) Cell minimum height. The cell extends automatically if needed.
  5394. * @param $txt (string) String to print
  5395. * @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)))
  5396. * @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>
  5397. * @param $fill (boolean) Indicates if the cell background must be painted (true) or transparent (false).
  5398. * @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>
  5399. * @param $x (float) x position in user units
  5400. * @param $y (float) y position in user units
  5401. * @param $reseth (boolean) if true reset the last cell height (default true).
  5402. * @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.
  5403. * @param $ishtml (boolean) INTERNAL USE ONLY -- set to true if $txt is HTML content (default = false). Never set this parameter to true, use instead writeHTMLCell() or writeHTML() methods.
  5404. * @param $autopadding (boolean) if true, uses internal padding and automatically adjust it to account for line width.
  5405. * @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.
  5406. * @param $valign (string) Vertical alignment of text (requires $maxh = $h > 0). Possible values are:<ul><li>T: TOP</li><li>M: middle</li><li>B: bottom</li></ul>. This feature works only when $ishtml=false and the cell must fit in a single page.
  5407. * @param $fitcell (boolean) if true attempt to fit all the text within the cell by reducing the font size (do not work in HTML mode). $maxh must be greater than 0 and equal to $h.
  5408. * @return int Return the number of cells or 1 for html mode.
  5409. * @public
  5410. * @since 1.3
  5411. * @see SetFont(), SetDrawColor(), SetFillColor(), SetTextColor(), SetLineWidth(), Cell(), Write(), SetAutoPageBreak()
  5412. */
  5413. 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) {
  5414. $prev_cell_margin = $this->cell_margin;
  5415. $prev_cell_padding = $this->cell_padding;
  5416. // adjust internal padding
  5417. $this->adjustCellPadding($border);
  5418. $mc_padding = $this->cell_padding;
  5419. $mc_margin = $this->cell_margin;
  5420. $this->cell_padding['T'] = 0;
  5421. $this->cell_padding['B'] = 0;
  5422. $this->setCellMargins(0, 0, 0, 0);
  5423. if (TCPDF_STATIC::empty_string($this->lasth) OR $reseth) {
  5424. // reset row height
  5425. $this->resetLastH();
  5426. }
  5427. if (!TCPDF_STATIC::empty_string($y)) {
  5428. $this->SetY($y); // set y in order to convert negative y values to positive ones
  5429. }
  5430. $y = $this->GetY();
  5431. $resth = 0;
  5432. if (($h > 0) AND $this->inPageBody() AND (($y + $h + $mc_margin['T'] + $mc_margin['B']) > $this->PageBreakTrigger)) {
  5433. // spit cell in more pages/columns
  5434. $newh = ($this->PageBreakTrigger - $y);
  5435. $resth = ($h - $newh); // cell to be printed on the next page/column
  5436. $h = $newh;
  5437. }
  5438. // get current page number
  5439. $startpage = $this->page;
  5440. // get current column
  5441. $startcolumn = $this->current_column;
  5442. if (!TCPDF_STATIC::empty_string($x)) {
  5443. $this->SetX($x);
  5444. } else {
  5445. $x = $this->GetX();
  5446. }
  5447. // check page for no-write regions and adapt page margins if necessary
  5448. list($x, $y) = $this->checkPageRegions(0, $x, $y);
  5449. // apply margins
  5450. $oy = $y + $mc_margin['T'];
  5451. if ($this->rtl) {
  5452. $ox = ($this->w - $x - $mc_margin['R']);
  5453. } else {
  5454. $ox = ($x + $mc_margin['L']);
  5455. }
  5456. $this->x = $ox;
  5457. $this->y = $oy;
  5458. // set width
  5459. if (TCPDF_STATIC::empty_string($w) OR ($w <= 0)) {
  5460. if ($this->rtl) {
  5461. $w = ($this->x - $this->lMargin - $mc_margin['L']);
  5462. } else {
  5463. $w = ($this->w - $this->x - $this->rMargin - $mc_margin['R']);
  5464. }
  5465. }
  5466. // store original margin values
  5467. $lMargin = $this->lMargin;
  5468. $rMargin = $this->rMargin;
  5469. if ($this->rtl) {
  5470. $this->rMargin = ($this->w - $this->x);
  5471. $this->lMargin = ($this->x - $w);
  5472. } else {
  5473. $this->lMargin = ($this->x);
  5474. $this->rMargin = ($this->w - $this->x - $w);
  5475. }
  5476. $this->clMargin = $this->lMargin;
  5477. $this->crMargin = $this->rMargin;
  5478. if ($autopadding) {
  5479. // add top padding
  5480. $this->y += $mc_padding['T'];
  5481. }
  5482. if ($ishtml) { // ******* Write HTML text
  5483. $this->writeHTML($txt, true, false, $reseth, true, $align);
  5484. $nl = 1;
  5485. } else { // ******* Write simple text
  5486. $prev_FontSizePt = $this->FontSizePt;
  5487. if ($fitcell) {
  5488. // ajust height values
  5489. $tobottom = ($this->h - $this->y - $this->bMargin - $this->cell_padding['T'] - $this->cell_padding['B']);
  5490. $h = $maxh = max(min($h, $tobottom), min($maxh, $tobottom));
  5491. }
  5492. // vertical alignment
  5493. if ($maxh > 0) {
  5494. // get text height
  5495. $text_height = $this->getStringHeight($w, $txt, $reseth, $autopadding, $mc_padding, $border);
  5496. if ($fitcell AND ($text_height > $maxh) AND ($this->FontSizePt > 1)) {
  5497. // try to reduce font size to fit text on cell (use a quick search algorithm)
  5498. $fmin = 1;
  5499. $fmax = $this->FontSizePt;
  5500. $diff_epsilon = (1 / $this->k); // one point (min resolution)
  5501. $maxit = (2 * min(100, max(10, intval($fmax)))); // max number of iterations
  5502. while ($maxit >= 0) {
  5503. $fmid = (($fmax + $fmin) / 2);
  5504. $this->SetFontSize($fmid, false);
  5505. $this->resetLastH();
  5506. $text_height = $this->getStringHeight($w, $txt, $reseth, $autopadding, $mc_padding, $border);
  5507. $diff = ($maxh - $text_height);
  5508. if ($diff >= 0) {
  5509. if ($diff <= $diff_epsilon) {
  5510. break;
  5511. }
  5512. $fmin = $fmid;
  5513. } else {
  5514. $fmax = $fmid;
  5515. }
  5516. --$maxit;
  5517. }
  5518. if ($maxit < 0) {
  5519. // premature exit, we get the minimum font value to fit the cell
  5520. $this->SetFontSize($fmin);
  5521. $this->resetLastH();
  5522. $text_height = $this->getStringHeight($w, $txt, $reseth, $autopadding, $mc_padding, $border);
  5523. } else {
  5524. $this->SetFontSize($fmid);
  5525. $this->resetLastH();
  5526. }
  5527. }
  5528. if ($text_height < $maxh) {
  5529. if ($valign == 'M') {
  5530. // text vertically centered
  5531. $this->y += (($maxh - $text_height) / 2);
  5532. } elseif ($valign == 'B') {
  5533. // text vertically aligned on bottom
  5534. $this->y += ($maxh - $text_height);
  5535. }
  5536. }
  5537. }
  5538. $nl = $this->Write($this->lasth, $txt, '', 0, $align, true, $stretch, false, true, $maxh, 0, $mc_margin);
  5539. if ($fitcell) {
  5540. // restore font size
  5541. $this->SetFontSize($prev_FontSizePt);
  5542. }
  5543. }
  5544. if ($autopadding) {
  5545. // add bottom padding
  5546. $this->y += $mc_padding['B'];
  5547. }
  5548. // Get end-of-text Y position
  5549. $currentY = $this->y;
  5550. // get latest page number
  5551. $endpage = $this->page;
  5552. if ($resth > 0) {
  5553. $skip = ($endpage - $startpage);
  5554. $tmpresth = $resth;
  5555. while ($tmpresth > 0) {
  5556. if ($skip <= 0) {
  5557. // add a page (or trig AcceptPageBreak() for multicolumn mode)
  5558. $this->checkPageBreak($this->PageBreakTrigger + 1);
  5559. }
  5560. if ($this->num_columns > 1) {
  5561. $tmpresth -= ($this->h - $this->y - $this->bMargin);
  5562. } else {
  5563. $tmpresth -= ($this->h - $this->tMargin - $this->bMargin);
  5564. }
  5565. --$skip;
  5566. }
  5567. $currentY = $this->y;
  5568. $endpage = $this->page;
  5569. }
  5570. // get latest column
  5571. $endcolumn = $this->current_column;
  5572. if ($this->num_columns == 0) {
  5573. $this->num_columns = 1;
  5574. }
  5575. // disable page regions check
  5576. $check_page_regions = $this->check_page_regions;
  5577. $this->check_page_regions = false;
  5578. // get border modes
  5579. $border_start = TCPDF_STATIC::getBorderMode($border, $position='start', $this->opencell);
  5580. $border_end = TCPDF_STATIC::getBorderMode($border, $position='end', $this->opencell);
  5581. $border_middle = TCPDF_STATIC::getBorderMode($border, $position='middle', $this->opencell);
  5582. // design borders around HTML cells.
  5583. for ($page = $startpage; $page <= $endpage; ++$page) { // for each page
  5584. $ccode = '';
  5585. $this->setPage($page);
  5586. if ($this->num_columns < 2) {
  5587. // single-column mode
  5588. $this->SetX($x);
  5589. $this->y = $this->tMargin;
  5590. }
  5591. // account for margin changes
  5592. if ($page > $startpage) {
  5593. if (($this->rtl) AND ($this->pagedim[$page]['orm'] != $this->pagedim[$startpage]['orm'])) {
  5594. $this->x -= ($this->pagedim[$page]['orm'] - $this->pagedim[$startpage]['orm']);
  5595. } elseif ((!$this->rtl) AND ($this->pagedim[$page]['olm'] != $this->pagedim[$startpage]['olm'])) {
  5596. $this->x += ($this->pagedim[$page]['olm'] - $this->pagedim[$startpage]['olm']);
  5597. }
  5598. }
  5599. if ($startpage == $endpage) {
  5600. // single page
  5601. for ($column = $startcolumn; $column <= $endcolumn; ++$column) { // for each column
  5602. if ($column != $this->current_column) {
  5603. $this->selectColumn($column);
  5604. }
  5605. if ($this->rtl) {
  5606. $this->x -= $mc_margin['R'];
  5607. } else {
  5608. $this->x += $mc_margin['L'];
  5609. }
  5610. if ($startcolumn == $endcolumn) { // single column
  5611. $cborder = $border;
  5612. $h = max($h, ($currentY - $oy));
  5613. $this->y = $oy;
  5614. } elseif ($column == $startcolumn) { // first column
  5615. $cborder = $border_start;
  5616. $this->y = $oy;
  5617. $h = $this->h - $this->y - $this->bMargin;
  5618. } elseif ($column == $endcolumn) { // end column
  5619. $cborder = $border_end;
  5620. $h = $currentY - $this->y;
  5621. if ($resth > $h) {
  5622. $h = $resth;
  5623. }
  5624. } else { // middle column
  5625. $cborder = $border_middle;
  5626. $h = $this->h - $this->y - $this->bMargin;
  5627. $resth -= $h;
  5628. }
  5629. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  5630. } // end for each column
  5631. } elseif ($page == $startpage) { // first page
  5632. for ($column = $startcolumn; $column < $this->num_columns; ++$column) { // for each column
  5633. if ($column != $this->current_column) {
  5634. $this->selectColumn($column);
  5635. }
  5636. if ($this->rtl) {
  5637. $this->x -= $mc_margin['R'];
  5638. } else {
  5639. $this->x += $mc_margin['L'];
  5640. }
  5641. if ($column == $startcolumn) { // first column
  5642. $cborder = $border_start;
  5643. $this->y = $oy;
  5644. $h = $this->h - $this->y - $this->bMargin;
  5645. } else { // middle column
  5646. $cborder = $border_middle;
  5647. $h = $this->h - $this->y - $this->bMargin;
  5648. $resth -= $h;
  5649. }
  5650. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  5651. } // end for each column
  5652. } elseif ($page == $endpage) { // last page
  5653. for ($column = 0; $column <= $endcolumn; ++$column) { // for each column
  5654. if ($column != $this->current_column) {
  5655. $this->selectColumn($column);
  5656. }
  5657. if ($this->rtl) {
  5658. $this->x -= $mc_margin['R'];
  5659. } else {
  5660. $this->x += $mc_margin['L'];
  5661. }
  5662. if ($column == $endcolumn) {
  5663. // end column
  5664. $cborder = $border_end;
  5665. $h = $currentY - $this->y;
  5666. if ($resth > $h) {
  5667. $h = $resth;
  5668. }
  5669. } else {
  5670. // middle column
  5671. $cborder = $border_middle;
  5672. $h = $this->h - $this->y - $this->bMargin;
  5673. $resth -= $h;
  5674. }
  5675. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  5676. } // end for each column
  5677. } else { // middle page
  5678. for ($column = 0; $column < $this->num_columns; ++$column) { // for each column
  5679. $this->selectColumn($column);
  5680. if ($this->rtl) {
  5681. $this->x -= $mc_margin['R'];
  5682. } else {
  5683. $this->x += $mc_margin['L'];
  5684. }
  5685. $cborder = $border_middle;
  5686. $h = $this->h - $this->y - $this->bMargin;
  5687. $resth -= $h;
  5688. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  5689. } // end for each column
  5690. }
  5691. if ($cborder OR $fill) {
  5692. $offsetlen = strlen($ccode);
  5693. // draw border and fill
  5694. if ($this->inxobj) {
  5695. // we are inside an XObject template
  5696. if (end($this->xobjects[$this->xobjid]['transfmrk']) !== false) {
  5697. $pagemarkkey = key($this->xobjects[$this->xobjid]['transfmrk']);
  5698. $pagemark = $this->xobjects[$this->xobjid]['transfmrk'][$pagemarkkey];
  5699. $this->xobjects[$this->xobjid]['transfmrk'][$pagemarkkey] += $offsetlen;
  5700. } else {
  5701. $pagemark = $this->xobjects[$this->xobjid]['intmrk'];
  5702. $this->xobjects[$this->xobjid]['intmrk'] += $offsetlen;
  5703. }
  5704. $pagebuff = $this->xobjects[$this->xobjid]['outdata'];
  5705. $pstart = substr($pagebuff, 0, $pagemark);
  5706. $pend = substr($pagebuff, $pagemark);
  5707. $this->xobjects[$this->xobjid]['outdata'] = $pstart.$ccode.$pend;
  5708. } else {
  5709. if (end($this->transfmrk[$this->page]) !== false) {
  5710. $pagemarkkey = key($this->transfmrk[$this->page]);
  5711. $pagemark = $this->transfmrk[$this->page][$pagemarkkey];
  5712. $this->transfmrk[$this->page][$pagemarkkey] += $offsetlen;
  5713. } elseif ($this->InFooter) {
  5714. $pagemark = $this->footerpos[$this->page];
  5715. $this->footerpos[$this->page] += $offsetlen;
  5716. } else {
  5717. $pagemark = $this->intmrk[$this->page];
  5718. $this->intmrk[$this->page] += $offsetlen;
  5719. }
  5720. $pagebuff = $this->getPageBuffer($this->page);
  5721. $pstart = substr($pagebuff, 0, $pagemark);
  5722. $pend = substr($pagebuff, $pagemark);
  5723. $this->setPageBuffer($this->page, $pstart.$ccode.$pend);
  5724. }
  5725. }
  5726. } // end for each page
  5727. // restore page regions check
  5728. $this->check_page_regions = $check_page_regions;
  5729. // Get end-of-cell Y position
  5730. $currentY = $this->GetY();
  5731. // restore previous values
  5732. if ($this->num_columns > 1) {
  5733. $this->selectColumn();
  5734. } else {
  5735. // restore original margins
  5736. $this->lMargin = $lMargin;
  5737. $this->rMargin = $rMargin;
  5738. if ($this->page > $startpage) {
  5739. // check for margin variations between pages (i.e. booklet mode)
  5740. $dl = ($this->pagedim[$this->page]['olm'] - $this->pagedim[$startpage]['olm']);
  5741. $dr = ($this->pagedim[$this->page]['orm'] - $this->pagedim[$startpage]['orm']);
  5742. if (($dl != 0) OR ($dr != 0)) {
  5743. $this->lMargin += $dl;
  5744. $this->rMargin += $dr;
  5745. }
  5746. }
  5747. }
  5748. if ($ln > 0) {
  5749. //Go to the beginning of the next line
  5750. $this->SetY($currentY + $mc_margin['B']);
  5751. if ($ln == 2) {
  5752. $this->SetX($x + $w + $mc_margin['L'] + $mc_margin['R']);
  5753. }
  5754. } else {
  5755. // go left or right by case
  5756. $this->setPage($startpage);
  5757. $this->y = $y;
  5758. $this->SetX($x + $w + $mc_margin['L'] + $mc_margin['R']);
  5759. }
  5760. $this->setContentMark();
  5761. $this->cell_padding = $prev_cell_padding;
  5762. $this->cell_margin = $prev_cell_margin;
  5763. $this->clMargin = $this->lMargin;
  5764. $this->crMargin = $this->rMargin;
  5765. return $nl;
  5766. }
  5767. /**
  5768. * This method return the estimated number of lines for print a simple text string using Multicell() method.
  5769. * @param $txt (string) String for calculating his height
  5770. * @param $w (float) Width of cells. If 0, they extend up to the right margin of the page.
  5771. * @param $reseth (boolean) if true reset the last cell height (default false).
  5772. * @param $autopadding (boolean) if true, uses internal padding and automatically adjust it to account for line width (default true).
  5773. * @param $cellpadding (float) Internal cell padding, if empty uses default cell padding.
  5774. * @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)))
  5775. * @return float Return the minimal height needed for multicell method for printing the $txt param.
  5776. * @author Alexander Escalona Fern\E1ndez, Nicola Asuni
  5777. * @public
  5778. * @since 4.5.011
  5779. */
  5780. public function getNumLines($txt, $w=0, $reseth=false, $autopadding=true, $cellpadding='', $border=0) {
  5781. if ($txt === NULL) {
  5782. return 0;
  5783. }
  5784. if ($txt === '') {
  5785. // empty string
  5786. return 1;
  5787. }
  5788. // adjust internal padding
  5789. $prev_cell_padding = $this->cell_padding;
  5790. $prev_lasth = $this->lasth;
  5791. if (is_array($cellpadding)) {
  5792. $this->cell_padding = $cellpadding;
  5793. }
  5794. $this->adjustCellPadding($border);
  5795. if (TCPDF_STATIC::empty_string($w) OR ($w <= 0)) {
  5796. if ($this->rtl) {
  5797. $w = $this->x - $this->lMargin;
  5798. } else {
  5799. $w = $this->w - $this->rMargin - $this->x;
  5800. }
  5801. }
  5802. $wmax = $w - $this->cell_padding['L'] - $this->cell_padding['R'];
  5803. if ($reseth) {
  5804. // reset row height
  5805. $this->resetLastH();
  5806. }
  5807. $lines = 1;
  5808. $sum = 0;
  5809. $chars = TCPDF_FONTS::utf8Bidi(TCPDF_FONTS::UTF8StringToArray($txt, $this->isunicode, $this->CurrentFont), $txt, $this->tmprtl, $this->isunicode, $this->CurrentFont);
  5810. $charsWidth = $this->GetArrStringWidth($chars, '', '', 0, true);
  5811. $length = count($chars);
  5812. $lastSeparator = -1;
  5813. for ($i = 0; $i < $length; ++$i) {
  5814. $c = $chars[$i];
  5815. $charWidth = $charsWidth[$i];
  5816. if (($c != 160)
  5817. AND (($c == 173)
  5818. OR preg_match($this->re_spaces, TCPDF_FONTS::unichr($c, $this->isunicode))
  5819. OR (($c == 45)
  5820. AND ($i > 0) AND ($i < ($length - 1))
  5821. AND @preg_match('/[\p{L}]/'.$this->re_space['m'], TCPDF_FONTS::unichr($chars[($i - 1)], $this->isunicode))
  5822. AND @preg_match('/[\p{L}]/'.$this->re_space['m'], TCPDF_FONTS::unichr($chars[($i + 1)], $this->isunicode))
  5823. )
  5824. )
  5825. ) {
  5826. $lastSeparator = $i;
  5827. }
  5828. if ((($sum + $charWidth) > $wmax) OR ($c == 10)) {
  5829. ++$lines;
  5830. if ($c == 10) {
  5831. $lastSeparator = -1;
  5832. $sum = 0;
  5833. } elseif ($lastSeparator != -1) {
  5834. $i = $lastSeparator;
  5835. $lastSeparator = -1;
  5836. $sum = 0;
  5837. } else {
  5838. $sum = $charWidth;
  5839. }
  5840. } else {
  5841. $sum += $charWidth;
  5842. }
  5843. }
  5844. if ($chars[($length - 1)] == 10) {
  5845. --$lines;
  5846. }
  5847. $this->cell_padding = $prev_cell_padding;
  5848. $this->lasth = $prev_lasth;
  5849. return $lines;
  5850. }
  5851. /**
  5852. * This method return the estimated height needed for printing a simple text string using the Multicell() method.
  5853. * Generally, if you want to know the exact height for a block of content you can use the following alternative technique:
  5854. * @pre
  5855. * // store current object
  5856. * $pdf->startTransaction();
  5857. * // store starting values
  5858. * $start_y = $pdf->GetY();
  5859. * $start_page = $pdf->getPage();
  5860. * // call your printing functions with your parameters
  5861. * // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  5862. * $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);
  5863. * // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  5864. * // get the new Y
  5865. * $end_y = $pdf->GetY();
  5866. * $end_page = $pdf->getPage();
  5867. * // calculate height
  5868. * $height = 0;
  5869. * if ($end_page == $start_page) {
  5870. * $height = $end_y - $start_y;
  5871. * } else {
  5872. * for ($page=$start_page; $page <= $end_page; ++$page) {
  5873. * $this->setPage($page);
  5874. * if ($page == $start_page) {
  5875. * // first page
  5876. * $height += $this->h - $start_y - $this->bMargin;
  5877. * } elseif ($page == $end_page) {
  5878. * // last page
  5879. * $height += $end_y - $this->tMargin;
  5880. * } else {
  5881. * $height += $this->h - $this->tMargin - $this->bMargin;
  5882. * }
  5883. * }
  5884. * }
  5885. * // restore previous object
  5886. * $pdf = $pdf->rollbackTransaction();
  5887. *
  5888. * @param $w (float) Width of cells. If 0, they extend up to the right margin of the page.
  5889. * @param $txt (string) String for calculating his height
  5890. * @param $reseth (boolean) if true reset the last cell height (default false).
  5891. * @param $autopadding (boolean) if true, uses internal padding and automatically adjust it to account for line width (default true).
  5892. * @param $cellpadding (float) Internal cell padding, if empty uses default cell padding.
  5893. * @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)))
  5894. * @return float Return the minimal height needed for multicell method for printing the $txt param.
  5895. * @author Nicola Asuni, Alexander Escalona Fern\E1ndez
  5896. * @public
  5897. */
  5898. public function getStringHeight($w, $txt, $reseth=false, $autopadding=true, $cellpadding='', $border=0) {
  5899. // adjust internal padding
  5900. $prev_cell_padding = $this->cell_padding;
  5901. $prev_lasth = $this->lasth;
  5902. if (is_array($cellpadding)) {
  5903. $this->cell_padding = $cellpadding;
  5904. }
  5905. $this->adjustCellPadding($border);
  5906. $lines = $this->getNumLines($txt, $w, $reseth, $autopadding, $cellpadding, $border);
  5907. $height = $this->getCellHeight(($lines * $this->FontSize), $autopadding);
  5908. $this->cell_padding = $prev_cell_padding;
  5909. $this->lasth = $prev_lasth;
  5910. return $height;
  5911. }
  5912. /**
  5913. * This method prints text from the current position.<br />
  5914. * @param $h (float) Line height
  5915. * @param $txt (string) String to print
  5916. * @param $link (mixed) URL or identifier returned by AddLink()
  5917. * @param $fill (boolean) Indicates if the cell background must be painted (true) or transparent (false).
  5918. * @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>
  5919. * @param $ln (boolean) if true set cursor at the bottom of the line, otherwise set cursor at the top of the line.
  5920. * @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.
  5921. * @param $firstline (boolean) if true prints only the first line and return the remaining string.
  5922. * @param $firstblock (boolean) if true the string is the starting of a line.
  5923. * @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.
  5924. * @param $wadj (float) first line width will be reduced by this amount (used in HTML mode).
  5925. * @param $margin (array) margin array of the parent container
  5926. * @return mixed Return the number of cells or the remaining string if $firstline = true.
  5927. * @public
  5928. * @since 1.5
  5929. */
  5930. public function Write($h, $txt, $link='', $fill=false, $align='', $ln=false, $stretch=0, $firstline=false, $firstblock=false, $maxh=0, $wadj=0, $margin='') {
  5931. // check page for no-write regions and adapt page margins if necessary
  5932. list($this->x, $this->y) = $this->checkPageRegions($h, $this->x, $this->y);
  5933. if (strlen($txt) == 0) {
  5934. // fix empty text
  5935. $txt = ' ';
  5936. }
  5937. if ($margin === '') {
  5938. // set default margins
  5939. $margin = $this->cell_margin;
  5940. }
  5941. // remove carriage returns
  5942. $s = str_replace("\r", '', $txt);
  5943. // check if string contains arabic text
  5944. if (preg_match(TCPDF_FONT_DATA::$uni_RE_PATTERN_ARABIC, $s)) {
  5945. $arabic = true;
  5946. } else {
  5947. $arabic = false;
  5948. }
  5949. // check if string contains RTL text
  5950. if ($arabic OR ($this->tmprtl == 'R') OR preg_match(TCPDF_FONT_DATA::$uni_RE_PATTERN_RTL, $s)) {
  5951. $rtlmode = true;
  5952. } else {
  5953. $rtlmode = false;
  5954. }
  5955. // get a char width
  5956. $chrwidth = $this->GetCharWidth(46); // dot character
  5957. // get array of unicode values
  5958. $chars = TCPDF_FONTS::UTF8StringToArray($s, $this->isunicode, $this->CurrentFont);
  5959. // calculate maximum width for a single character on string
  5960. $chrw = $this->GetArrStringWidth($chars, '', '', 0, true);
  5961. array_walk($chrw, array($this, 'getRawCharWidth'));
  5962. $maxchwidth = max($chrw);
  5963. // get array of chars
  5964. $uchars = TCPDF_FONTS::UTF8ArrayToUniArray($chars, $this->isunicode);
  5965. // get the number of characters
  5966. $nb = count($chars);
  5967. // replacement for SHY character (minus symbol)
  5968. $shy_replacement = 45;
  5969. $shy_replacement_char = TCPDF_FONTS::unichr($shy_replacement, $this->isunicode);
  5970. // widht for SHY replacement
  5971. $shy_replacement_width = $this->GetCharWidth($shy_replacement);
  5972. // page width
  5973. $pw = $w = $this->w - $this->lMargin - $this->rMargin;
  5974. // calculate remaining line width ($w)
  5975. if ($this->rtl) {
  5976. $w = $this->x - $this->lMargin;
  5977. } else {
  5978. $w = $this->w - $this->rMargin - $this->x;
  5979. }
  5980. // max column width
  5981. $wmax = ($w - $wadj);
  5982. if (!$firstline) {
  5983. $wmax -= ($this->cell_padding['L'] + $this->cell_padding['R']);
  5984. }
  5985. if ((!$firstline) AND (($chrwidth > $wmax) OR ($maxchwidth > $wmax))) {
  5986. // the maximum width character do not fit on column
  5987. return '';
  5988. }
  5989. // minimum row height
  5990. $row_height = max($h, $this->getCellHeight($this->FontSize));
  5991. // max Y
  5992. $maxy = $this->y + $maxh - max($row_height, $h);
  5993. $start_page = $this->page;
  5994. $i = 0; // character position
  5995. $j = 0; // current starting position
  5996. $sep = -1; // position of the last blank space
  5997. $prevsep = $sep; // previous separator
  5998. $shy = false; // true if the last blank is a soft hypen (SHY)
  5999. $prevshy = $shy; // previous shy mode
  6000. $l = 0; // current string length
  6001. $nl = 0; //number of lines
  6002. $linebreak = false;
  6003. $pc = 0; // previous character
  6004. // for each character
  6005. while ($i < $nb) {
  6006. if (($maxh > 0) AND ($this->y > $maxy) ) {
  6007. break;
  6008. }
  6009. //Get the current character
  6010. $c = $chars[$i];
  6011. if ($c == 10) { // 10 = "\n" = new line
  6012. //Explicit line break
  6013. if ($align == 'J') {
  6014. if ($this->rtl) {
  6015. $talign = 'R';
  6016. } else {
  6017. $talign = 'L';
  6018. }
  6019. } else {
  6020. $talign = $align;
  6021. }
  6022. $tmpstr = TCPDF_FONTS::UniArrSubString($uchars, $j, $i);
  6023. if ($firstline) {
  6024. $startx = $this->x;
  6025. $tmparr = array_slice($chars, $j, ($i - $j));
  6026. if ($rtlmode) {
  6027. $tmparr = TCPDF_FONTS::utf8Bidi($tmparr, $tmpstr, $this->tmprtl, $this->isunicode, $this->CurrentFont);
  6028. }
  6029. $linew = $this->GetArrStringWidth($tmparr);
  6030. unset($tmparr);
  6031. if ($this->rtl) {
  6032. $this->endlinex = $startx - $linew;
  6033. } else {
  6034. $this->endlinex = $startx + $linew;
  6035. }
  6036. $w = $linew;
  6037. $tmpcellpadding = $this->cell_padding;
  6038. if ($maxh == 0) {
  6039. $this->SetCellPadding(0);
  6040. }
  6041. }
  6042. if ($firstblock AND $this->isRTLTextDir()) {
  6043. $tmpstr = $this->stringRightTrim($tmpstr);
  6044. }
  6045. // Skip newlines at the beginning of a page or column
  6046. if (!empty($tmpstr) OR ($this->y < ($this->PageBreakTrigger - $row_height))) {
  6047. $this->Cell($w, $h, $tmpstr, 0, 1, $talign, $fill, $link, $stretch);
  6048. }
  6049. unset($tmpstr);
  6050. if ($firstline) {
  6051. $this->cell_padding = $tmpcellpadding;
  6052. return (TCPDF_FONTS::UniArrSubString($uchars, $i));
  6053. }
  6054. ++$nl;
  6055. $j = $i + 1;
  6056. $l = 0;
  6057. $sep = -1;
  6058. $prevsep = $sep;
  6059. $shy = false;
  6060. // account for margin changes
  6061. if ((($this->y + $this->lasth) > $this->PageBreakTrigger) AND ($this->inPageBody())) {
  6062. $this->AcceptPageBreak();
  6063. if ($this->rtl) {
  6064. $this->x -= $margin['R'];
  6065. } else {
  6066. $this->x += $margin['L'];
  6067. }
  6068. $this->lMargin += $margin['L'];
  6069. $this->rMargin += $margin['R'];
  6070. }
  6071. $w = $this->getRemainingWidth();
  6072. $wmax = ($w - $this->cell_padding['L'] - $this->cell_padding['R']);
  6073. } else {
  6074. // 160 is the non-breaking space.
  6075. // 173 is SHY (Soft Hypen).
  6076. // \p{Z} or \p{Separator}: any kind of Unicode whitespace or invisible separator.
  6077. // \p{Lo} or \p{Other_Letter}: a Unicode letter or ideograph that does not have lowercase and uppercase variants.
  6078. // \p{Lo} is needed because Chinese characters are packed next to each other without spaces in between.
  6079. if (($c != 160)
  6080. AND (($c == 173)
  6081. OR preg_match($this->re_spaces, TCPDF_FONTS::unichr($c, $this->isunicode))
  6082. OR (($c == 45)
  6083. AND ($i < ($nb - 1))
  6084. AND @preg_match('/[\p{L}]/'.$this->re_space['m'], TCPDF_FONTS::unichr($pc, $this->isunicode))
  6085. AND @preg_match('/[\p{L}]/'.$this->re_space['m'], TCPDF_FONTS::unichr($chars[($i + 1)], $this->isunicode))
  6086. )
  6087. )
  6088. ) {
  6089. // update last blank space position
  6090. $prevsep = $sep;
  6091. $sep = $i;
  6092. // check if is a SHY
  6093. if (($c == 173) OR ($c == 45)) {
  6094. $prevshy = $shy;
  6095. $shy = true;
  6096. if ($pc == 45) {
  6097. $tmp_shy_replacement_width = 0;
  6098. $tmp_shy_replacement_char = '';
  6099. } else {
  6100. $tmp_shy_replacement_width = $shy_replacement_width;
  6101. $tmp_shy_replacement_char = $shy_replacement_char;
  6102. }
  6103. } else {
  6104. $shy = false;
  6105. }
  6106. }
  6107. // update string length
  6108. if ($this->isUnicodeFont() AND ($arabic)) {
  6109. // with bidirectional algorithm some chars may be changed affecting the line length
  6110. // *** very slow ***
  6111. $l = $this->GetArrStringWidth(TCPDF_FONTS::utf8Bidi(array_slice($chars, $j, ($i - $j)), '', $this->tmprtl, $this->isunicode, $this->CurrentFont));
  6112. } else {
  6113. $l += $this->GetCharWidth($c);
  6114. }
  6115. if (($l > $wmax) OR (($c == 173) AND (($l + $tmp_shy_replacement_width) >= $wmax))) {
  6116. if (($c == 173) AND (($l + $tmp_shy_replacement_width) > $wmax)) {
  6117. $sep = $prevsep;
  6118. $shy = $prevshy;
  6119. }
  6120. // we have reached the end of column
  6121. if ($sep == -1) {
  6122. // check if the line was already started
  6123. if (($this->rtl AND ($this->x <= ($this->w - $this->rMargin - $this->cell_padding['R'] - $margin['R'] - $chrwidth)))
  6124. OR ((!$this->rtl) AND ($this->x >= ($this->lMargin + $this->cell_padding['L'] + $margin['L'] + $chrwidth)))) {
  6125. // print a void cell and go to next line
  6126. $this->Cell($w, $h, '', 0, 1);
  6127. $linebreak = true;
  6128. if ($firstline) {
  6129. return (TCPDF_FONTS::UniArrSubString($uchars, $j));
  6130. }
  6131. } else {
  6132. // truncate the word because do not fit on column
  6133. $tmpstr = TCPDF_FONTS::UniArrSubString($uchars, $j, $i);
  6134. if ($firstline) {
  6135. $startx = $this->x;
  6136. $tmparr = array_slice($chars, $j, ($i - $j));
  6137. if ($rtlmode) {
  6138. $tmparr = TCPDF_FONTS::utf8Bidi($tmparr, $tmpstr, $this->tmprtl, $this->isunicode, $this->CurrentFont);
  6139. }
  6140. $linew = $this->GetArrStringWidth($tmparr);
  6141. unset($tmparr);
  6142. if ($this->rtl) {
  6143. $this->endlinex = $startx - $linew;
  6144. } else {
  6145. $this->endlinex = $startx + $linew;
  6146. }
  6147. $w = $linew;
  6148. $tmpcellpadding = $this->cell_padding;
  6149. if ($maxh == 0) {
  6150. $this->SetCellPadding(0);
  6151. }
  6152. }
  6153. if ($firstblock AND $this->isRTLTextDir()) {
  6154. $tmpstr = $this->stringRightTrim($tmpstr);
  6155. }
  6156. $this->Cell($w, $h, $tmpstr, 0, 1, $align, $fill, $link, $stretch);
  6157. unset($tmpstr);
  6158. if ($firstline) {
  6159. $this->cell_padding = $tmpcellpadding;
  6160. return (TCPDF_FONTS::UniArrSubString($uchars, $i));
  6161. }
  6162. $j = $i;
  6163. --$i;
  6164. }
  6165. } else {
  6166. // word wrapping
  6167. if ($this->rtl AND (!$firstblock) AND ($sep < $i)) {
  6168. $endspace = 1;
  6169. } else {
  6170. $endspace = 0;
  6171. }
  6172. // check the length of the next string
  6173. $strrest = TCPDF_FONTS::UniArrSubString($uchars, ($sep + $endspace));
  6174. $nextstr = TCPDF_STATIC::pregSplit('/'.$this->re_space['p'].'/', $this->re_space['m'], $this->stringTrim($strrest));
  6175. if (isset($nextstr[0]) AND ($this->GetStringWidth($nextstr[0]) > $pw)) {
  6176. // truncate the word because do not fit on a full page width
  6177. $tmpstr = TCPDF_FONTS::UniArrSubString($uchars, $j, $i);
  6178. if ($firstline) {
  6179. $startx = $this->x;
  6180. $tmparr = array_slice($chars, $j, ($i - $j));
  6181. if ($rtlmode) {
  6182. $tmparr = TCPDF_FONTS::utf8Bidi($tmparr, $tmpstr, $this->tmprtl, $this->isunicode, $this->CurrentFont);
  6183. }
  6184. $linew = $this->GetArrStringWidth($tmparr);
  6185. unset($tmparr);
  6186. if ($this->rtl) {
  6187. $this->endlinex = ($startx - $linew);
  6188. } else {
  6189. $this->endlinex = ($startx + $linew);
  6190. }
  6191. $w = $linew;
  6192. $tmpcellpadding = $this->cell_padding;
  6193. if ($maxh == 0) {
  6194. $this->SetCellPadding(0);
  6195. }
  6196. }
  6197. if ($firstblock AND $this->isRTLTextDir()) {
  6198. $tmpstr = $this->stringRightTrim($tmpstr);
  6199. }
  6200. $this->Cell($w, $h, $tmpstr, 0, 1, $align, $fill, $link, $stretch);
  6201. unset($tmpstr);
  6202. if ($firstline) {
  6203. $this->cell_padding = $tmpcellpadding;
  6204. return (TCPDF_FONTS::UniArrSubString($uchars, $i));
  6205. }
  6206. $j = $i;
  6207. --$i;
  6208. } else {
  6209. // word wrapping
  6210. if ($shy) {
  6211. // add hypen (minus symbol) at the end of the line
  6212. $shy_width = $tmp_shy_replacement_width;
  6213. if ($this->rtl) {
  6214. $shy_char_left = $tmp_shy_replacement_char;
  6215. $shy_char_right = '';
  6216. } else {
  6217. $shy_char_left = '';
  6218. $shy_char_right = $tmp_shy_replacement_char;
  6219. }
  6220. } else {
  6221. $shy_width = 0;
  6222. $shy_char_left = '';
  6223. $shy_char_right = '';
  6224. }
  6225. $tmpstr = TCPDF_FONTS::UniArrSubString($uchars, $j, ($sep + $endspace));
  6226. if ($firstline) {
  6227. $startx = $this->x;
  6228. $tmparr = array_slice($chars, $j, (($sep + $endspace) - $j));
  6229. if ($rtlmode) {
  6230. $tmparr = TCPDF_FONTS::utf8Bidi($tmparr, $tmpstr, $this->tmprtl, $this->isunicode, $this->CurrentFont);
  6231. }
  6232. $linew = $this->GetArrStringWidth($tmparr);
  6233. unset($tmparr);
  6234. if ($this->rtl) {
  6235. $this->endlinex = $startx - $linew - $shy_width;
  6236. } else {
  6237. $this->endlinex = $startx + $linew + $shy_width;
  6238. }
  6239. $w = $linew;
  6240. $tmpcellpadding = $this->cell_padding;
  6241. if ($maxh == 0) {
  6242. $this->SetCellPadding(0);
  6243. }
  6244. }
  6245. // print the line
  6246. if ($firstblock AND $this->isRTLTextDir()) {
  6247. $tmpstr = $this->stringRightTrim($tmpstr);
  6248. }
  6249. $this->Cell($w, $h, $shy_char_left.$tmpstr.$shy_char_right, 0, 1, $align, $fill, $link, $stretch);
  6250. unset($tmpstr);
  6251. if ($firstline) {
  6252. if ($chars[$sep] == 45) {
  6253. $endspace += 1;
  6254. }
  6255. // return the remaining text
  6256. $this->cell_padding = $tmpcellpadding;
  6257. return (TCPDF_FONTS::UniArrSubString($uchars, ($sep + $endspace)));
  6258. }
  6259. $i = $sep;
  6260. $sep = -1;
  6261. $shy = false;
  6262. $j = ($i + 1);
  6263. }
  6264. }
  6265. // account for margin changes
  6266. if ((($this->y + $this->lasth) > $this->PageBreakTrigger) AND ($this->inPageBody())) {
  6267. $this->AcceptPageBreak();
  6268. if ($this->rtl) {
  6269. $this->x -= $margin['R'];
  6270. } else {
  6271. $this->x += $margin['L'];
  6272. }
  6273. $this->lMargin += $margin['L'];
  6274. $this->rMargin += $margin['R'];
  6275. }
  6276. $w = $this->getRemainingWidth();
  6277. $wmax = $w - $this->cell_padding['L'] - $this->cell_padding['R'];
  6278. if ($linebreak) {
  6279. $linebreak = false;
  6280. } else {
  6281. ++$nl;
  6282. $l = 0;
  6283. }
  6284. }
  6285. }
  6286. // save last character
  6287. $pc = $c;
  6288. ++$i;
  6289. } // end while i < nb
  6290. // print last substring (if any)
  6291. if ($l > 0) {
  6292. switch ($align) {
  6293. case 'J':
  6294. case 'C': {
  6295. $w = $w;
  6296. break;
  6297. }
  6298. case 'L': {
  6299. if ($this->rtl) {
  6300. $w = $w;
  6301. } else {
  6302. $w = $l;
  6303. }
  6304. break;
  6305. }
  6306. case 'R': {
  6307. if ($this->rtl) {
  6308. $w = $l;
  6309. } else {
  6310. $w = $w;
  6311. }
  6312. break;
  6313. }
  6314. default: {
  6315. $w = $l;
  6316. break;
  6317. }
  6318. }
  6319. $tmpstr = TCPDF_FONTS::UniArrSubString($uchars, $j, $nb);
  6320. if ($firstline) {
  6321. $startx = $this->x;
  6322. $tmparr = array_slice($chars, $j, ($nb - $j));
  6323. if ($rtlmode) {
  6324. $tmparr = TCPDF_FONTS::utf8Bidi($tmparr, $tmpstr, $this->tmprtl, $this->isunicode, $this->CurrentFont);
  6325. }
  6326. $linew = $this->GetArrStringWidth($tmparr);
  6327. unset($tmparr);
  6328. if ($this->rtl) {
  6329. $this->endlinex = $startx - $linew;
  6330. } else {
  6331. $this->endlinex = $startx + $linew;
  6332. }
  6333. $w = $linew;
  6334. $tmpcellpadding = $this->cell_padding;
  6335. if ($maxh == 0) {
  6336. $this->SetCellPadding(0);
  6337. }
  6338. }
  6339. if ($firstblock AND $this->isRTLTextDir()) {
  6340. $tmpstr = $this->stringRightTrim($tmpstr);
  6341. }
  6342. $this->Cell($w, $h, $tmpstr, 0, $ln, $align, $fill, $link, $stretch);
  6343. unset($tmpstr);
  6344. if ($firstline) {
  6345. $this->cell_padding = $tmpcellpadding;
  6346. return (TCPDF_FONTS::UniArrSubString($uchars, $nb));
  6347. }
  6348. ++$nl;
  6349. }
  6350. if ($firstline) {
  6351. return '';
  6352. }
  6353. return $nl;
  6354. }
  6355. /**
  6356. * Returns the remaining width between the current position and margins.
  6357. * @return int Return the remaining width
  6358. * @protected
  6359. */
  6360. protected function getRemainingWidth() {
  6361. list($this->x, $this->y) = $this->checkPageRegions(0, $this->x, $this->y);
  6362. if ($this->rtl) {
  6363. return ($this->x - $this->lMargin);
  6364. } else {
  6365. return ($this->w - $this->rMargin - $this->x);
  6366. }
  6367. }
  6368. /**
  6369. * Set the block dimensions accounting for page breaks and page/column fitting
  6370. * @param $w (float) width
  6371. * @param $h (float) height
  6372. * @param $x (float) X coordinate
  6373. * @param $y (float) Y coodiante
  6374. * @param $fitonpage (boolean) if true the block is resized to not exceed page dimensions.
  6375. * @return array($w, $h, $x, $y)
  6376. * @protected
  6377. * @since 5.5.009 (2010-07-05)
  6378. */
  6379. protected function fitBlock($w, $h, $x, $y, $fitonpage=false) {
  6380. if ($w <= 0) {
  6381. // set maximum width
  6382. $w = ($this->w - $this->lMargin - $this->rMargin);
  6383. if ($w <= 0) {
  6384. $w = 1;
  6385. }
  6386. }
  6387. if ($h <= 0) {
  6388. // set maximum height
  6389. $h = ($this->PageBreakTrigger - $this->tMargin);
  6390. if ($h <= 0) {
  6391. $h = 1;
  6392. }
  6393. }
  6394. // resize the block to be vertically contained on a single page or single column
  6395. if ($fitonpage OR $this->AutoPageBreak) {
  6396. $ratio_wh = ($w / $h);
  6397. if ($h > ($this->PageBreakTrigger - $this->tMargin)) {
  6398. $h = $this->PageBreakTrigger - $this->tMargin;
  6399. $w = ($h * $ratio_wh);
  6400. }
  6401. // resize the block to be horizontally contained on a single page or single column
  6402. if ($fitonpage) {
  6403. $maxw = ($this->w - $this->lMargin - $this->rMargin);
  6404. if ($w > $maxw) {
  6405. $w = $maxw;
  6406. $h = ($w / $ratio_wh);
  6407. }
  6408. }
  6409. }
  6410. // Check whether we need a new page or new column first as this does not fit
  6411. $prev_x = $this->x;
  6412. $prev_y = $this->y;
  6413. if ($this->checkPageBreak($h, $y) OR ($this->y < $prev_y)) {
  6414. $y = $this->y;
  6415. if ($this->rtl) {
  6416. $x += ($prev_x - $this->x);
  6417. } else {
  6418. $x += ($this->x - $prev_x);
  6419. }
  6420. $this->newline = true;
  6421. }
  6422. // resize the block to be contained on the remaining available page or column space
  6423. if ($fitonpage) {
  6424. $ratio_wh = ($w / $h);
  6425. if (($y + $h) > $this->PageBreakTrigger) {
  6426. $h = $this->PageBreakTrigger - $y;
  6427. $w = ($h * $ratio_wh);
  6428. }
  6429. if ((!$this->rtl) AND (($x + $w) > ($this->w - $this->rMargin))) {
  6430. $w = $this->w - $this->rMargin - $x;
  6431. $h = ($w / $ratio_wh);
  6432. } elseif (($this->rtl) AND (($x - $w) < ($this->lMargin))) {
  6433. $w = $x - $this->lMargin;
  6434. $h = ($w / $ratio_wh);
  6435. }
  6436. }
  6437. return array($w, $h, $x, $y);
  6438. }
  6439. /**
  6440. * Puts an image in the page.
  6441. * The upper-left corner must be given.
  6442. * The dimensions can be specified in different ways:<ul>
  6443. * <li>explicit width and height (expressed in user unit)</li>
  6444. * <li>one explicit dimension, the other being calculated automatically in order to keep the original proportions</li>
  6445. * <li>no explicit dimension, in which case the image is put at 72 dpi</li></ul>
  6446. * 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;
  6447. * The format can be specified explicitly or inferred from the file extension.<br />
  6448. * It is possible to put a link on the image.<br />
  6449. * Remark: if an image is used several times, only one copy will be embedded in the file.<br />
  6450. * @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').
  6451. * @param $x (float) Abscissa of the upper-left corner (LTR) or upper-right corner (RTL).
  6452. * @param $y (float) Ordinate of the upper-left corner (LTR) or upper-right corner (RTL).
  6453. * @param $w (float) Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
  6454. * @param $h (float) Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
  6455. * @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.
  6456. * @param $link (mixed) URL or identifier returned by AddLink().
  6457. * @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>
  6458. * @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).
  6459. * @param $dpi (int) dot-per-inch resolution used on resize
  6460. * @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>
  6461. * @param $ismask (boolean) true if this image is a mask, false otherwise
  6462. * @param $imgmask (mixed) image object returned by this function or false
  6463. * @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)))
  6464. * @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).
  6465. * @param $hidden (boolean) If true do not display the image.
  6466. * @param $fitonpage (boolean) If true the image is resized to not exceed page dimensions.
  6467. * @param $alt (boolean) If true the image will be added as alternative and not directly printed (the ID of the image will be returned).
  6468. * @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.
  6469. * @return image information
  6470. * @public
  6471. * @since 1.1
  6472. */
  6473. 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()) {
  6474. if ($this->state != 2) {
  6475. return;
  6476. }
  6477. if (strcmp($x, '') === 0) {
  6478. $x = $this->x;
  6479. }
  6480. if (strcmp($y, '') === 0) {
  6481. $y = $this->y;
  6482. }
  6483. // check page for no-write regions and adapt page margins if necessary
  6484. list($x, $y) = $this->checkPageRegions($h, $x, $y);
  6485. $exurl = ''; // external streams
  6486. $imsize = FALSE;
  6487. // check if we are passing an image as file or string
  6488. if ($file[0] === '@') {
  6489. // image from string
  6490. $imgdata = substr($file, 1);
  6491. } else { // image file
  6492. if ($file[0] === '*') {
  6493. // image as external stream
  6494. $file = substr($file, 1);
  6495. $exurl = $file;
  6496. }
  6497. // check if file exist and it is valid
  6498. if (!@TCPDF_STATIC::file_exists($file)) {
  6499. return false;
  6500. }
  6501. if (($imsize = @getimagesize($file)) === FALSE) {
  6502. if (in_array($file, $this->imagekeys)) {
  6503. // get existing image data
  6504. $info = $this->getImageBuffer($file);
  6505. $imsize = array($info['w'], $info['h']);
  6506. } elseif (strpos($file, '__tcpdf_'.$this->file_id.'_img') === FALSE) {
  6507. $imgdata = TCPDF_STATIC::fileGetContents($file);
  6508. }
  6509. }
  6510. }
  6511. if (!empty($imgdata)) {
  6512. // copy image to cache
  6513. $original_file = $file;
  6514. $file = TCPDF_STATIC::getObjFilename('img', $this->file_id);
  6515. $fp = TCPDF_STATIC::fopenLocal($file, 'w');
  6516. if (!$fp) {
  6517. $this->Error('Unable to write file: '.$file);
  6518. }
  6519. fwrite($fp, $imgdata);
  6520. fclose($fp);
  6521. unset($imgdata);
  6522. $imsize = @getimagesize($file);
  6523. if ($imsize === FALSE) {
  6524. unlink($file);
  6525. $file = $original_file;
  6526. }
  6527. }
  6528. if ($imsize === FALSE) {
  6529. if (($w > 0) AND ($h > 0)) {
  6530. // get measures from specified data
  6531. $pw = $this->getHTMLUnitToUnits($w, 0, $this->pdfunit, true) * $this->imgscale * $this->k;
  6532. $ph = $this->getHTMLUnitToUnits($h, 0, $this->pdfunit, true) * $this->imgscale * $this->k;
  6533. $imsize = array($pw, $ph);
  6534. } else {
  6535. $this->Error('[Image] Unable to get the size of the image: '.$file);
  6536. }
  6537. }
  6538. // file hash
  6539. $filehash = md5($file);
  6540. // get original image width and height in pixels
  6541. list($pixw, $pixh) = $imsize;
  6542. // calculate image width and height on document
  6543. if (($w <= 0) AND ($h <= 0)) {
  6544. // convert image size to document unit
  6545. $w = $this->pixelsToUnits($pixw);
  6546. $h = $this->pixelsToUnits($pixh);
  6547. } elseif ($w <= 0) {
  6548. $w = $h * $pixw / $pixh;
  6549. } elseif ($h <= 0) {
  6550. $h = $w * $pixh / $pixw;
  6551. } elseif (($fitbox !== false) AND ($w > 0) AND ($h > 0)) {
  6552. if (strlen($fitbox) !== 2) {
  6553. // set default alignment
  6554. $fitbox = '--';
  6555. }
  6556. // scale image dimensions proportionally to fit within the ($w, $h) box
  6557. if ((($w * $pixh) / ($h * $pixw)) < 1) {
  6558. // store current height
  6559. $oldh = $h;
  6560. // calculate new height
  6561. $h = $w * $pixh / $pixw;
  6562. // height difference
  6563. $hdiff = ($oldh - $h);
  6564. // vertical alignment
  6565. switch (strtoupper($fitbox[1])) {
  6566. case 'T': {
  6567. break;
  6568. }
  6569. case 'M': {
  6570. $y += ($hdiff / 2);
  6571. break;
  6572. }
  6573. case 'B': {
  6574. $y += $hdiff;
  6575. break;
  6576. }
  6577. }
  6578. } else {
  6579. // store current width
  6580. $oldw = $w;
  6581. // calculate new width
  6582. $w = $h * $pixw / $pixh;
  6583. // width difference
  6584. $wdiff = ($oldw - $w);
  6585. // horizontal alignment
  6586. switch (strtoupper($fitbox[0])) {
  6587. case 'L': {
  6588. if ($this->rtl) {
  6589. $x -= $wdiff;
  6590. }
  6591. break;
  6592. }
  6593. case 'C': {
  6594. if ($this->rtl) {
  6595. $x -= ($wdiff / 2);
  6596. } else {
  6597. $x += ($wdiff / 2);
  6598. }
  6599. break;
  6600. }
  6601. case 'R': {
  6602. if (!$this->rtl) {
  6603. $x += $wdiff;
  6604. }
  6605. break;
  6606. }
  6607. }
  6608. }
  6609. }
  6610. // fit the image on available space
  6611. list($w, $h, $x, $y) = $this->fitBlock($w, $h, $x, $y, $fitonpage);
  6612. // calculate new minimum dimensions in pixels
  6613. $neww = round($w * $this->k * $dpi / $this->dpi);
  6614. $newh = round($h * $this->k * $dpi / $this->dpi);
  6615. // check if resize is necessary (resize is used only to reduce the image)
  6616. $newsize = ($neww * $newh);
  6617. $pixsize = ($pixw * $pixh);
  6618. if (intval($resize) == 2) {
  6619. $resize = true;
  6620. } elseif ($newsize >= $pixsize) {
  6621. $resize = false;
  6622. }
  6623. // check if image has been already added on document
  6624. $newimage = true;
  6625. if (in_array($file, $this->imagekeys)) {
  6626. $newimage = false;
  6627. // get existing image data
  6628. $info = $this->getImageBuffer($file);
  6629. if (strpos($file, '__tcpdf_'.$this->file_id.'_imgmask_') === FALSE) {
  6630. // check if the newer image is larger
  6631. $oldsize = ($info['w'] * $info['h']);
  6632. if ((($oldsize < $newsize) AND ($resize)) OR (($oldsize < $pixsize) AND (!$resize))) {
  6633. $newimage = true;
  6634. }
  6635. }
  6636. } elseif (($ismask === false) AND ($imgmask === false) AND (strpos($file, '__tcpdf_'.$this->file_id.'_imgmask_') === FALSE)) {
  6637. // create temp image file (without alpha channel)
  6638. $tempfile_plain = K_PATH_CACHE.'__tcpdf_'.$this->file_id.'_imgmask_plain_'.$filehash;
  6639. // create temp alpha file
  6640. $tempfile_alpha = K_PATH_CACHE.'__tcpdf_'.$this->file_id.'_imgmask_alpha_'.$filehash;
  6641. // check for cached images
  6642. if (in_array($tempfile_plain, $this->imagekeys)) {
  6643. // get existing image data
  6644. $info = $this->getImageBuffer($tempfile_plain);
  6645. // check if the newer image is larger
  6646. $oldsize = ($info['w'] * $info['h']);
  6647. if ((($oldsize < $newsize) AND ($resize)) OR (($oldsize < $pixsize) AND (!$resize))) {
  6648. $newimage = true;
  6649. } else {
  6650. $newimage = false;
  6651. // embed mask image
  6652. $imgmask = $this->Image($tempfile_alpha, $x, $y, $w, $h, 'PNG', '', '', $resize, $dpi, '', true, false);
  6653. // embed image, masked with previously embedded mask
  6654. return $this->Image($tempfile_plain, $x, $y, $w, $h, $type, $link, $align, $resize, $dpi, $palign, false, $imgmask);
  6655. }
  6656. }
  6657. }
  6658. if ($newimage) {
  6659. //First use of image, get info
  6660. $type = strtolower($type);
  6661. if ($type == '') {
  6662. $type = TCPDF_IMAGES::getImageFileType($file, $imsize);
  6663. } elseif ($type == 'jpg') {
  6664. $type = 'jpeg';
  6665. }
  6666. $mqr = TCPDF_STATIC::get_mqr();
  6667. TCPDF_STATIC::set_mqr(false);
  6668. // Specific image handlers (defined on TCPDF_IMAGES CLASS)
  6669. $mtd = '_parse'.$type;
  6670. // GD image handler function
  6671. $gdfunction = 'imagecreatefrom'.$type;
  6672. $info = false;
  6673. if ((method_exists('TCPDF_IMAGES', $mtd)) AND (!($resize AND (function_exists($gdfunction) OR extension_loaded('imagick'))))) {
  6674. // TCPDF image functions
  6675. $info = TCPDF_IMAGES::$mtd($file);
  6676. if (($ismask === false) AND ($imgmask === false) AND (strpos($file, '__tcpdf_'.$this->file_id.'_imgmask_') === FALSE)
  6677. AND (($info === 'pngalpha') OR (isset($info['trns']) AND !empty($info['trns'])))) {
  6678. return $this->ImagePngAlpha($file, $x, $y, $pixw, $pixh, $w, $h, 'PNG', $link, $align, $resize, $dpi, $palign, $filehash);
  6679. }
  6680. }
  6681. if (($info === false) AND function_exists($gdfunction)) {
  6682. try {
  6683. // GD library
  6684. $img = $gdfunction($file);
  6685. if ($img !== false) {
  6686. if ($resize) {
  6687. $imgr = imagecreatetruecolor($neww, $newh);
  6688. if (($type == 'gif') OR ($type == 'png')) {
  6689. $imgr = TCPDF_IMAGES::setGDImageTransparency($imgr, $img);
  6690. }
  6691. imagecopyresampled($imgr, $img, 0, 0, 0, 0, $neww, $newh, $pixw, $pixh);
  6692. $img = $imgr;
  6693. }
  6694. if (($type == 'gif') OR ($type == 'png')) {
  6695. $info = TCPDF_IMAGES::_toPNG($img, TCPDF_STATIC::getObjFilename('img', $this->file_id));
  6696. } else {
  6697. $info = TCPDF_IMAGES::_toJPEG($img, $this->jpeg_quality, TCPDF_STATIC::getObjFilename('img', $this->file_id));
  6698. }
  6699. }
  6700. } catch(Exception $e) {
  6701. $info = false;
  6702. }
  6703. }
  6704. if (($info === false) AND extension_loaded('imagick')) {
  6705. try {
  6706. // ImageMagick library
  6707. $img = new Imagick();
  6708. if ($type == 'svg') {
  6709. if ($file[0] === '@') {
  6710. // image from string
  6711. $svgimg = substr($file, 1);
  6712. } else {
  6713. // get SVG file content
  6714. $svgimg = TCPDF_STATIC::fileGetContents($file);
  6715. }
  6716. if ($svgimg !== FALSE) {
  6717. // get width and height
  6718. $regs = array();
  6719. if (preg_match('/<svg([^\>]*)>/si', $svgimg, $regs)) {
  6720. $svgtag = $regs[1];
  6721. $tmp = array();
  6722. if (preg_match('/[\s]+width[\s]*=[\s]*"([^"]*)"/si', $svgtag, $tmp)) {
  6723. $ow = $this->getHTMLUnitToUnits($tmp[1], 1, $this->svgunit, false);
  6724. $owu = sprintf('%F', ($ow * $dpi / 72)).$this->pdfunit;
  6725. $svgtag = preg_replace('/[\s]+width[\s]*=[\s]*"[^"]*"/si', ' width="'.$owu.'"', $svgtag, 1);
  6726. } else {
  6727. $ow = $w;
  6728. }
  6729. $tmp = array();
  6730. if (preg_match('/[\s]+height[\s]*=[\s]*"([^"]*)"/si', $svgtag, $tmp)) {
  6731. $oh = $this->getHTMLUnitToUnits($tmp[1], 1, $this->svgunit, false);
  6732. $ohu = sprintf('%F', ($oh * $dpi / 72)).$this->pdfunit;
  6733. $svgtag = preg_replace('/[\s]+height[\s]*=[\s]*"[^"]*"/si', ' height="'.$ohu.'"', $svgtag, 1);
  6734. } else {
  6735. $oh = $h;
  6736. }
  6737. $tmp = array();
  6738. if (!preg_match('/[\s]+viewBox[\s]*=[\s]*"[\s]*([0-9\.]+)[\s]+([0-9\.]+)[\s]+([0-9\.]+)[\s]+([0-9\.]+)[\s]*"/si', $svgtag, $tmp)) {
  6739. $vbw = ($ow * $this->imgscale * $this->k);
  6740. $vbh = ($oh * $this->imgscale * $this->k);
  6741. $vbox = sprintf(' viewBox="0 0 %F %F" ', $vbw, $vbh);
  6742. $svgtag = $vbox.$svgtag;
  6743. }
  6744. $svgimg = preg_replace('/<svg([^\>]*)>/si', '<svg'.$svgtag.'>', $svgimg, 1);
  6745. }
  6746. $img->readImageBlob($svgimg);
  6747. }
  6748. } else {
  6749. $img->readImage($file);
  6750. }
  6751. if ($resize) {
  6752. $img->resizeImage($neww, $newh, 10, 1, false);
  6753. }
  6754. $img->setCompressionQuality($this->jpeg_quality);
  6755. $img->setImageFormat('jpeg');
  6756. $tempname = TCPDF_STATIC::getObjFilename('img', $this->file_id);
  6757. $img->writeImage($tempname);
  6758. $info = TCPDF_IMAGES::_parsejpeg($tempname);
  6759. unlink($tempname);
  6760. $img->destroy();
  6761. } catch(Exception $e) {
  6762. $info = false;
  6763. }
  6764. }
  6765. if ($info === false) {
  6766. // unable to process image
  6767. return;
  6768. }
  6769. TCPDF_STATIC::set_mqr($mqr);
  6770. if ($ismask) {
  6771. // force grayscale
  6772. $info['cs'] = 'DeviceGray';
  6773. }
  6774. if ($imgmask !== false) {
  6775. $info['masked'] = $imgmask;
  6776. }
  6777. if (!empty($exurl)) {
  6778. $info['exurl'] = $exurl;
  6779. }
  6780. // array of alternative images
  6781. $info['altimgs'] = $altimgs;
  6782. // add image to document
  6783. $info['i'] = $this->setImageBuffer($file, $info);
  6784. }
  6785. // set alignment
  6786. $this->img_rb_y = $y + $h;
  6787. // set alignment
  6788. if ($this->rtl) {
  6789. if ($palign == 'L') {
  6790. $ximg = $this->lMargin;
  6791. } elseif ($palign == 'C') {
  6792. $ximg = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
  6793. } elseif ($palign == 'R') {
  6794. $ximg = $this->w - $this->rMargin - $w;
  6795. } else {
  6796. $ximg = $x - $w;
  6797. }
  6798. $this->img_rb_x = $ximg;
  6799. } else {
  6800. if ($palign == 'L') {
  6801. $ximg = $this->lMargin;
  6802. } elseif ($palign == 'C') {
  6803. $ximg = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
  6804. } elseif ($palign == 'R') {
  6805. $ximg = $this->w - $this->rMargin - $w;
  6806. } else {
  6807. $ximg = $x;
  6808. }
  6809. $this->img_rb_x = $ximg + $w;
  6810. }
  6811. if ($ismask OR $hidden) {
  6812. // image is not displayed
  6813. return $info['i'];
  6814. }
  6815. $xkimg = $ximg * $this->k;
  6816. if (!$alt) {
  6817. // only non-alternative immages will be set
  6818. $this->_out(sprintf('q %F 0 0 %F %F %F cm /I%u Do Q', ($w * $this->k), ($h * $this->k), $xkimg, (($this->h - ($y + $h)) * $this->k), $info['i']));
  6819. }
  6820. if (!empty($border)) {
  6821. $bx = $this->x;
  6822. $by = $this->y;
  6823. $this->x = $ximg;
  6824. if ($this->rtl) {
  6825. $this->x += $w;
  6826. }
  6827. $this->y = $y;
  6828. $this->Cell($w, $h, '', $border, 0, '', 0, '', 0, true);
  6829. $this->x = $bx;
  6830. $this->y = $by;
  6831. }
  6832. if ($link) {
  6833. $this->Link($ximg, $y, $w, $h, $link, 0);
  6834. }
  6835. // set pointer to align the next text/objects
  6836. switch($align) {
  6837. case 'T': {
  6838. $this->y = $y;
  6839. $this->x = $this->img_rb_x;
  6840. break;
  6841. }
  6842. case 'M': {
  6843. $this->y = $y + round($h/2);
  6844. $this->x = $this->img_rb_x;
  6845. break;
  6846. }
  6847. case 'B': {
  6848. $this->y = $this->img_rb_y;
  6849. $this->x = $this->img_rb_x;
  6850. break;
  6851. }
  6852. case 'N': {
  6853. $this->SetY($this->img_rb_y);
  6854. break;
  6855. }
  6856. default:{
  6857. break;
  6858. }
  6859. }
  6860. $this->endlinex = $this->img_rb_x;
  6861. if ($this->inxobj) {
  6862. // we are inside an XObject template
  6863. $this->xobjects[$this->xobjid]['images'][] = $info['i'];
  6864. }
  6865. return $info['i'];
  6866. }
  6867. /**
  6868. * Extract info from a PNG image with alpha channel using the Imagick or GD library.
  6869. * @param $file (string) Name of the file containing the image.
  6870. * @param $x (float) Abscissa of the upper-left corner.
  6871. * @param $y (float) Ordinate of the upper-left corner.
  6872. * @param $wpx (float) Original width of the image in pixels.
  6873. * @param $hpx (float) original height of the image in pixels.
  6874. * @param $w (float) Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
  6875. * @param $h (float) Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
  6876. * @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.
  6877. * @param $link (mixed) URL or identifier returned by AddLink().
  6878. * @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>
  6879. * @param $resize (boolean) If true resize (reduce) the image to fit $w and $h (requires GD library).
  6880. * @param $dpi (int) dot-per-inch resolution used on resize
  6881. * @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>
  6882. * @param $filehash (string) File hash used to build unique file names.
  6883. * @author Nicola Asuni
  6884. * @protected
  6885. * @since 4.3.007 (2008-12-04)
  6886. * @see Image()
  6887. */
  6888. protected function ImagePngAlpha($file, $x, $y, $wpx, $hpx, $w, $h, $type, $link, $align, $resize, $dpi, $palign, $filehash='') {
  6889. // create temp images
  6890. if (empty($filehash)) {
  6891. $filehash = md5($file);
  6892. }
  6893. // create temp image file (without alpha channel)
  6894. $tempfile_plain = K_PATH_CACHE.'__tcpdf_'.$this->file_id.'_imgmask_plain_'.$filehash;
  6895. // create temp alpha file
  6896. $tempfile_alpha = K_PATH_CACHE.'__tcpdf_'.$this->file_id.'_imgmask_alpha_'.$filehash;
  6897. $parsed = false;
  6898. $parse_error = '';
  6899. // ImageMagick extension
  6900. if (($parsed === false) AND extension_loaded('imagick')) {
  6901. try {
  6902. // ImageMagick library
  6903. $img = new Imagick();
  6904. $img->readImage($file);
  6905. // clone image object
  6906. $imga = TCPDF_STATIC::objclone($img);
  6907. // extract alpha channel
  6908. if (method_exists($img, 'setImageAlphaChannel') AND defined('Imagick::ALPHACHANNEL_EXTRACT')) {
  6909. $img->setImageAlphaChannel(Imagick::ALPHACHANNEL_EXTRACT);
  6910. } else {
  6911. $img->separateImageChannel(8); // 8 = (imagick::CHANNEL_ALPHA | imagick::CHANNEL_OPACITY | imagick::CHANNEL_MATTE);
  6912. $img->negateImage(true);
  6913. }
  6914. $img->setImageFormat('png');
  6915. $img->writeImage($tempfile_alpha);
  6916. // remove alpha channel
  6917. if (method_exists($imga, 'setImageMatte')) {
  6918. $imga->setImageMatte(false);
  6919. } else {
  6920. $imga->separateImageChannel(39); // 39 = (imagick::CHANNEL_ALL & ~(imagick::CHANNEL_ALPHA | imagick::CHANNEL_OPACITY | imagick::CHANNEL_MATTE));
  6921. }
  6922. $imga->setImageFormat('png');
  6923. $imga->writeImage($tempfile_plain);
  6924. $parsed = true;
  6925. } catch (Exception $e) {
  6926. // Imagemagick fails, try with GD
  6927. $parse_error = 'Imagick library error: '.$e->getMessage();
  6928. }
  6929. }
  6930. // GD extension
  6931. if (($parsed === false) AND function_exists('imagecreatefrompng')) {
  6932. try {
  6933. // generate images
  6934. $img = imagecreatefrompng($file);
  6935. $imgalpha = imagecreate($wpx, $hpx);
  6936. // generate gray scale palette (0 -> 255)
  6937. for ($c = 0; $c < 256; ++$c) {
  6938. ImageColorAllocate($imgalpha, $c, $c, $c);
  6939. }
  6940. // extract alpha channel
  6941. for ($xpx = 0; $xpx < $wpx; ++$xpx) {
  6942. for ($ypx = 0; $ypx < $hpx; ++$ypx) {
  6943. $color = imagecolorat($img, $xpx, $ypx);
  6944. // get and correct gamma color
  6945. $alpha = $this->getGDgamma($img, $color);
  6946. imagesetpixel($imgalpha, $xpx, $ypx, $alpha);
  6947. }
  6948. }
  6949. imagepng($imgalpha, $tempfile_alpha);
  6950. imagedestroy($imgalpha);
  6951. // extract image without alpha channel
  6952. $imgplain = imagecreatetruecolor($wpx, $hpx);
  6953. imagecopy($imgplain, $img, 0, 0, 0, 0, $wpx, $hpx);
  6954. imagepng($imgplain, $tempfile_plain);
  6955. imagedestroy($imgplain);
  6956. $parsed = true;
  6957. } catch (Exception $e) {
  6958. // GD fails
  6959. $parse_error = 'GD library error: '.$e->getMessage();
  6960. }
  6961. }
  6962. if ($parsed === false) {
  6963. if (empty($parse_error)) {
  6964. $this->Error('TCPDF requires the Imagick or GD extension to handle PNG images with alpha channel.');
  6965. } else {
  6966. $this->Error($parse_error);
  6967. }
  6968. }
  6969. // embed mask image
  6970. $imgmask = $this->Image($tempfile_alpha, $x, $y, $w, $h, 'PNG', '', '', $resize, $dpi, '', true, false);
  6971. // embed image, masked with previously embedded mask
  6972. $this->Image($tempfile_plain, $x, $y, $w, $h, $type, $link, $align, $resize, $dpi, $palign, false, $imgmask);
  6973. }
  6974. /**
  6975. * Get the GD-corrected PNG gamma value from alpha color
  6976. * @param $img (int) GD image Resource ID.
  6977. * @param $c (int) alpha color
  6978. * @protected
  6979. * @since 4.3.007 (2008-12-04)
  6980. */
  6981. protected function getGDgamma($img, $c) {
  6982. if (!isset($this->gdgammacache['#'.$c])) {
  6983. $colors = imagecolorsforindex($img, $c);
  6984. // GD alpha is only 7 bit (0 -> 127)
  6985. $this->gdgammacache['#'.$c] = (((127 - $colors['alpha']) / 127) * 255);
  6986. // correct gamma
  6987. $this->gdgammacache['#'.$c] = (pow(($this->gdgammacache['#'.$c] / 255), 2.2) * 255);
  6988. // store the latest values on cache to improve performances
  6989. if (count($this->gdgammacache) > 8) {
  6990. // remove one element from the cache array
  6991. array_shift($this->gdgammacache);
  6992. }
  6993. }
  6994. return $this->gdgammacache['#'.$c];
  6995. }
  6996. /**
  6997. * Performs a line break.
  6998. * The current abscissa goes back to the left margin and the ordinate increases by the amount passed in parameter.
  6999. * @param $h (float) The height of the break. By default, the value equals the height of the last printed cell.
  7000. * @param $cell (boolean) if true add the current left (or right o for RTL) padding to the X coordinate
  7001. * @public
  7002. * @since 1.0
  7003. * @see Cell()
  7004. */
  7005. public function Ln($h='', $cell=false) {
  7006. 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'])) {
  7007. // revove vertical space from the top of the column
  7008. return;
  7009. }
  7010. if ($cell) {
  7011. if ($this->rtl) {
  7012. $cellpadding = $this->cell_padding['R'];
  7013. } else {
  7014. $cellpadding = $this->cell_padding['L'];
  7015. }
  7016. } else {
  7017. $cellpadding = 0;
  7018. }
  7019. if ($this->rtl) {
  7020. $this->x = $this->w - $this->rMargin - $cellpadding;
  7021. } else {
  7022. $this->x = $this->lMargin + $cellpadding;
  7023. }
  7024. if (is_string($h)) {
  7025. $h = $this->lasth;
  7026. }
  7027. $this->y += $h;
  7028. $this->newline = true;
  7029. }
  7030. /**
  7031. * Returns the relative X value of current position.
  7032. * The value is relative to the left border for LTR languages and to the right border for RTL languages.
  7033. * @return float
  7034. * @public
  7035. * @since 1.2
  7036. * @see SetX(), GetY(), SetY()
  7037. */
  7038. public function GetX() {
  7039. //Get x position
  7040. if ($this->rtl) {
  7041. return ($this->w - $this->x);
  7042. } else {
  7043. return $this->x;
  7044. }
  7045. }
  7046. /**
  7047. * Returns the absolute X value of current position.
  7048. * @return float
  7049. * @public
  7050. * @since 1.2
  7051. * @see SetX(), GetY(), SetY()
  7052. */
  7053. public function GetAbsX() {
  7054. return $this->x;
  7055. }
  7056. /**
  7057. * Returns the ordinate of the current position.
  7058. * @return float
  7059. * @public
  7060. * @since 1.0
  7061. * @see SetY(), GetX(), SetX()
  7062. */
  7063. public function GetY() {
  7064. return $this->y;
  7065. }
  7066. /**
  7067. * Defines the abscissa of the current position.
  7068. * If the passed value is negative, it is relative to the right of the page (or left if language is RTL).
  7069. * @param $x (float) The value of the abscissa in user units.
  7070. * @param $rtloff (boolean) if true always uses the page top-left corner as origin of axis.
  7071. * @public
  7072. * @since 1.2
  7073. * @see GetX(), GetY(), SetY(), SetXY()
  7074. */
  7075. public function SetX($x, $rtloff=false) {
  7076. $x = floatval($x);
  7077. if (!$rtloff AND $this->rtl) {
  7078. if ($x >= 0) {
  7079. $this->x = $this->w - $x;
  7080. } else {
  7081. $this->x = abs($x);
  7082. }
  7083. } else {
  7084. if ($x >= 0) {
  7085. $this->x = $x;
  7086. } else {
  7087. $this->x = $this->w + $x;
  7088. }
  7089. }
  7090. if ($this->x < 0) {
  7091. $this->x = 0;
  7092. }
  7093. if ($this->x > $this->w) {
  7094. $this->x = $this->w;
  7095. }
  7096. }
  7097. /**
  7098. * Moves the current abscissa back to the left margin and sets the ordinate.
  7099. * If the passed value is negative, it is relative to the bottom of the page.
  7100. * @param $y (float) The value of the ordinate in user units.
  7101. * @param $resetx (bool) if true (default) reset the X position.
  7102. * @param $rtloff (boolean) if true always uses the page top-left corner as origin of axis.
  7103. * @public
  7104. * @since 1.0
  7105. * @see GetX(), GetY(), SetY(), SetXY()
  7106. */
  7107. public function SetY($y, $resetx=true, $rtloff=false) {
  7108. $y = floatval($y);
  7109. if ($resetx) {
  7110. //reset x
  7111. if (!$rtloff AND $this->rtl) {
  7112. $this->x = $this->w - $this->rMargin;
  7113. } else {
  7114. $this->x = $this->lMargin;
  7115. }
  7116. }
  7117. if ($y >= 0) {
  7118. $this->y = $y;
  7119. } else {
  7120. $this->y = $this->h + $y;
  7121. }
  7122. if ($this->y < 0) {
  7123. $this->y = 0;
  7124. }
  7125. if ($this->y > $this->h) {
  7126. $this->y = $this->h;
  7127. }
  7128. }
  7129. /**
  7130. * Defines the abscissa and ordinate of the current position.
  7131. * If the passed values are negative, they are relative respectively to the right and bottom of the page.
  7132. * @param $x (float) The value of the abscissa.
  7133. * @param $y (float) The value of the ordinate.
  7134. * @param $rtloff (boolean) if true always uses the page top-left corner as origin of axis.
  7135. * @public
  7136. * @since 1.2
  7137. * @see SetX(), SetY()
  7138. */
  7139. public function SetXY($x, $y, $rtloff=false) {
  7140. $this->SetY($y, false, $rtloff);
  7141. $this->SetX($x, $rtloff);
  7142. }
  7143. /**
  7144. * Set the absolute X coordinate of the current pointer.
  7145. * @param $x (float) The value of the abscissa in user units.
  7146. * @public
  7147. * @since 5.9.186 (2012-09-13)
  7148. * @see setAbsX(), setAbsY(), SetAbsXY()
  7149. */
  7150. public function SetAbsX($x) {
  7151. $this->x = floatval($x);
  7152. }
  7153. /**
  7154. * Set the absolute Y coordinate of the current pointer.
  7155. * @param $y (float) (float) The value of the ordinate in user units.
  7156. * @public
  7157. * @since 5.9.186 (2012-09-13)
  7158. * @see setAbsX(), setAbsY(), SetAbsXY()
  7159. */
  7160. public function SetAbsY($y) {
  7161. $this->y = floatval($y);
  7162. }
  7163. /**
  7164. * Set the absolute X and Y coordinates of the current pointer.
  7165. * @param $x (float) The value of the abscissa in user units.
  7166. * @param $y (float) (float) The value of the ordinate in user units.
  7167. * @public
  7168. * @since 5.9.186 (2012-09-13)
  7169. * @see setAbsX(), setAbsY(), SetAbsXY()
  7170. */
  7171. public function SetAbsXY($x, $y) {
  7172. $this->SetAbsX($x);
  7173. $this->SetAbsY($y);
  7174. }
  7175. /**
  7176. * Send the document to a given destination: string, local file or browser.
  7177. * In the last case, the plug-in may be used (if present) or a download ("Save as" dialog box) may be forced.<br />
  7178. * The method first calls Close() if necessary to terminate the document.
  7179. * @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.
  7180. * @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>
  7181. * @return string
  7182. * @public
  7183. * @since 1.0
  7184. * @see Close()
  7185. */
  7186. public function Output($name='doc.pdf', $dest='I') {
  7187. //Output PDF to some destination
  7188. //Finish document if necessary
  7189. if ($this->state < 3) {
  7190. $this->Close();
  7191. }
  7192. //Normalize parameters
  7193. if (is_bool($dest)) {
  7194. $dest = $dest ? 'D' : 'F';
  7195. }
  7196. $dest = strtoupper($dest);
  7197. if ($dest[0] != 'F') {
  7198. $name = preg_replace('/[\s]+/', '_', $name);
  7199. $name = preg_replace('/[^a-zA-Z0-9_\.-]/', '', $name);
  7200. }
  7201. if ($this->sign) {
  7202. // *** apply digital signature to the document ***
  7203. // get the document content
  7204. $pdfdoc = $this->getBuffer();
  7205. // remove last newline
  7206. $pdfdoc = substr($pdfdoc, 0, -1);
  7207. // remove filler space
  7208. $byterange_string_len = strlen(TCPDF_STATIC::$byterange_string);
  7209. // define the ByteRange
  7210. $byte_range = array();
  7211. $byte_range[0] = 0;
  7212. $byte_range[1] = strpos($pdfdoc, TCPDF_STATIC::$byterange_string) + $byterange_string_len + 10;
  7213. $byte_range[2] = $byte_range[1] + $this->signature_max_length + 2;
  7214. $byte_range[3] = strlen($pdfdoc) - $byte_range[2];
  7215. $pdfdoc = substr($pdfdoc, 0, $byte_range[1]).substr($pdfdoc, $byte_range[2]);
  7216. // replace the ByteRange
  7217. $byterange = sprintf('/ByteRange[0 %u %u %u]', $byte_range[1], $byte_range[2], $byte_range[3]);
  7218. $byterange .= str_repeat(' ', ($byterange_string_len - strlen($byterange)));
  7219. $pdfdoc = str_replace(TCPDF_STATIC::$byterange_string, $byterange, $pdfdoc);
  7220. // write the document to a temporary folder
  7221. $tempdoc = TCPDF_STATIC::getObjFilename('doc', $this->file_id);
  7222. $f = TCPDF_STATIC::fopenLocal($tempdoc, 'wb');
  7223. if (!$f) {
  7224. $this->Error('Unable to create temporary file: '.$tempdoc);
  7225. }
  7226. $pdfdoc_length = strlen($pdfdoc);
  7227. fwrite($f, $pdfdoc, $pdfdoc_length);
  7228. fclose($f);
  7229. // get digital signature via openssl library
  7230. $tempsign = TCPDF_STATIC::getObjFilename('sig', $this->file_id);
  7231. if (empty($this->signature_data['extracerts'])) {
  7232. openssl_pkcs7_sign($tempdoc, $tempsign, $this->signature_data['signcert'], array($this->signature_data['privkey'], $this->signature_data['password']), array(), PKCS7_BINARY | PKCS7_DETACHED);
  7233. } else {
  7234. 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']);
  7235. }
  7236. // read signature
  7237. $signature = file_get_contents($tempsign);
  7238. // extract signature
  7239. $signature = substr($signature, $pdfdoc_length);
  7240. $signature = substr($signature, (strpos($signature, "%%EOF\n\n------") + 13));
  7241. $tmparr = explode("\n\n", $signature);
  7242. $signature = $tmparr[1];
  7243. // decode signature
  7244. $signature = base64_decode(trim($signature));
  7245. // add TSA timestamp to signature
  7246. $signature = $this->applyTSA($signature);
  7247. // convert signature to hex
  7248. $signature = current(unpack('H*', $signature));
  7249. $signature = str_pad($signature, $this->signature_max_length, '0');
  7250. // Add signature to the document
  7251. $this->buffer = substr($pdfdoc, 0, $byte_range[1]).'<'.$signature.'>'.substr($pdfdoc, $byte_range[1]);
  7252. $this->bufferlen = strlen($this->buffer);
  7253. }
  7254. switch($dest) {
  7255. case 'I': {
  7256. // Send PDF to the standard output
  7257. if (ob_get_contents()) {
  7258. $this->Error('Some data has already been output, can\'t send PDF file');
  7259. }
  7260. if (php_sapi_name() != 'cli') {
  7261. // send output to a browser
  7262. header('Content-Type: application/pdf');
  7263. if (headers_sent()) {
  7264. $this->Error('Some data has already been output to browser, can\'t send PDF file');
  7265. }
  7266. header('Cache-Control: private, must-revalidate, post-check=0, pre-check=0, max-age=1');
  7267. //header('Cache-Control: public, must-revalidate, max-age=0'); // HTTP/1.1
  7268. header('Pragma: public');
  7269. header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
  7270. header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
  7271. header('Content-Disposition: inline; filename="'.basename($name).'"');
  7272. TCPDF_STATIC::sendOutputData($this->getBuffer(), $this->bufferlen);
  7273. } else {
  7274. echo $this->getBuffer();
  7275. }
  7276. break;
  7277. }
  7278. case 'D': {
  7279. // download PDF as file
  7280. if (ob_get_contents()) {
  7281. $this->Error('Some data has already been output, can\'t send PDF file');
  7282. }
  7283. header('Content-Description: File Transfer');
  7284. if (headers_sent()) {
  7285. $this->Error('Some data has already been output to browser, can\'t send PDF file');
  7286. }
  7287. header('Cache-Control: private, must-revalidate, post-check=0, pre-check=0, max-age=1');
  7288. //header('Cache-Control: public, must-revalidate, max-age=0'); // HTTP/1.1
  7289. header('Pragma: public');
  7290. header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
  7291. header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
  7292. // force download dialog
  7293. if (strpos(php_sapi_name(), 'cgi') === false) {
  7294. header('Content-Type: application/force-download');
  7295. header('Content-Type: application/octet-stream', false);
  7296. header('Content-Type: application/download', false);
  7297. header('Content-Type: application/pdf', false);
  7298. } else {
  7299. header('Content-Type: application/pdf');
  7300. }
  7301. // use the Content-Disposition header to supply a recommended filename
  7302. header('Content-Disposition: attachment; filename="'.basename($name).'"');
  7303. header('Content-Transfer-Encoding: binary');
  7304. TCPDF_STATIC::sendOutputData($this->getBuffer(), $this->bufferlen);
  7305. break;
  7306. }
  7307. case 'F':
  7308. case 'FI':
  7309. case 'FD': {
  7310. // save PDF to a local file
  7311. $f = TCPDF_STATIC::fopenLocal($name, 'wb');
  7312. if (!$f) {
  7313. $this->Error('Unable to create output file: '.$name);
  7314. }
  7315. fwrite($f, $this->getBuffer(), $this->bufferlen);
  7316. fclose($f);
  7317. if ($dest == 'FI') {
  7318. // send headers to browser
  7319. header('Content-Type: application/pdf');
  7320. header('Cache-Control: private, must-revalidate, post-check=0, pre-check=0, max-age=1');
  7321. //header('Cache-Control: public, must-revalidate, max-age=0'); // HTTP/1.1
  7322. header('Pragma: public');
  7323. header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
  7324. header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
  7325. header('Content-Disposition: inline; filename="'.basename($name).'"');
  7326. TCPDF_STATIC::sendOutputData(file_get_contents($name), filesize($name));
  7327. } elseif ($dest == 'FD') {
  7328. // send headers to browser
  7329. if (ob_get_contents()) {
  7330. $this->Error('Some data has already been output, can\'t send PDF file');
  7331. }
  7332. header('Content-Description: File Transfer');
  7333. if (headers_sent()) {
  7334. $this->Error('Some data has already been output to browser, can\'t send PDF file');
  7335. }
  7336. header('Cache-Control: private, must-revalidate, post-check=0, pre-check=0, max-age=1');
  7337. header('Pragma: public');
  7338. header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
  7339. header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
  7340. // force download dialog
  7341. if (strpos(php_sapi_name(), 'cgi') === false) {
  7342. header('Content-Type: application/force-download');
  7343. header('Content-Type: application/octet-stream', false);
  7344. header('Content-Type: application/download', false);
  7345. header('Content-Type: application/pdf', false);
  7346. } else {
  7347. header('Content-Type: application/pdf');
  7348. }
  7349. // use the Content-Disposition header to supply a recommended filename
  7350. header('Content-Disposition: attachment; filename="'.basename($name).'"');
  7351. header('Content-Transfer-Encoding: binary');
  7352. TCPDF_STATIC::sendOutputData(file_get_contents($name), filesize($name));
  7353. }
  7354. break;
  7355. }
  7356. case 'E': {
  7357. // return PDF as base64 mime multi-part email attachment (RFC 2045)
  7358. $retval = 'Content-Type: application/pdf;'."\r\n";
  7359. $retval .= ' name="'.$name.'"'."\r\n";
  7360. $retval .= 'Content-Transfer-Encoding: base64'."\r\n";
  7361. $retval .= 'Content-Disposition: attachment;'."\r\n";
  7362. $retval .= ' filename="'.$name.'"'."\r\n\r\n";
  7363. $retval .= chunk_split(base64_encode($this->getBuffer()), 76, "\r\n");
  7364. return $retval;
  7365. }
  7366. case 'S': {
  7367. // returns PDF as a string
  7368. return $this->getBuffer();
  7369. }
  7370. default: {
  7371. $this->Error('Incorrect output destination: '.$dest);
  7372. }
  7373. }
  7374. return '';
  7375. }
  7376. protected static $cleaned_ids = array();
  7377. /**
  7378. * Unset all class variables except the following critical variables.
  7379. * @param $destroyall (boolean) if true destroys all class variables, otherwise preserves critical variables.
  7380. * @param $preserve_objcopy (boolean) if true preserves the objcopy variable
  7381. * @public
  7382. * @since 4.5.016 (2009-02-24)
  7383. */
  7384. public function _destroy($destroyall=false, $preserve_objcopy=false) {
  7385. // restore internal encoding
  7386. if (isset($this->internal_encoding) AND !empty($this->internal_encoding)) {
  7387. mb_internal_encoding($this->internal_encoding);
  7388. }
  7389. if (isset(self::$cleaned_ids[$this->file_id])) {
  7390. $destroyall = false;
  7391. }
  7392. if ($destroyall AND !$preserve_objcopy) {
  7393. self::$cleaned_ids[$this->file_id] = true;
  7394. // remove all temporary files
  7395. if ($handle = opendir(K_PATH_CACHE)) {
  7396. while ( false !== ( $file_name = readdir( $handle ) ) ) {
  7397. if (strpos($file_name, '__tcpdf_'.$this->file_id.'_') === 0) {
  7398. unlink(K_PATH_CACHE.$file_name);
  7399. }
  7400. }
  7401. closedir($handle);
  7402. }
  7403. if (isset($this->imagekeys)) {
  7404. foreach($this->imagekeys as $file) {
  7405. unlink($file);
  7406. }
  7407. }
  7408. }
  7409. $preserve = array(
  7410. 'file_id',
  7411. 'internal_encoding',
  7412. 'state',
  7413. 'bufferlen',
  7414. 'buffer',
  7415. 'cached_files',
  7416. 'sign',
  7417. 'signature_data',
  7418. 'signature_max_length',
  7419. 'byterange_string',
  7420. 'tsa_timestamp',
  7421. 'tsa_data'
  7422. );
  7423. foreach (array_keys(get_object_vars($this)) as $val) {
  7424. if ($destroyall OR !in_array($val, $preserve)) {
  7425. if ((!$preserve_objcopy OR ($val != 'objcopy')) AND ($val != 'file_id') AND isset($this->$val)) {
  7426. unset($this->$val);
  7427. }
  7428. }
  7429. }
  7430. }
  7431. /**
  7432. * Check for locale-related bug
  7433. * @protected
  7434. */
  7435. protected function _dochecks() {
  7436. //Check for locale-related bug
  7437. if (1.1 == 1) {
  7438. $this->Error('Don\'t alter the locale before including class file');
  7439. }
  7440. //Check for decimal separator
  7441. if (sprintf('%.1F', 1.0) != '1.0') {
  7442. setlocale(LC_NUMERIC, 'C');
  7443. }
  7444. }
  7445. /**
  7446. * Return an array containing variations for the basic page number alias.
  7447. * @param $a (string) Base alias.
  7448. * @return array of page number aliases
  7449. * @protected
  7450. */
  7451. protected function getInternalPageNumberAliases($a= '') {
  7452. $alias = array();
  7453. // build array of Unicode + ASCII variants (the order is important)
  7454. $alias = array('u' => array(), 'a' => array());
  7455. $u = '{'.$a.'}';
  7456. $alias['u'][] = TCPDF_STATIC::_escape($u);
  7457. if ($this->isunicode) {
  7458. $alias['u'][] = TCPDF_STATIC::_escape(TCPDF_FONTS::UTF8ToLatin1($u, $this->isunicode, $this->CurrentFont));
  7459. $alias['u'][] = TCPDF_STATIC::_escape(TCPDF_FONTS::utf8StrRev($u, false, $this->tmprtl, $this->isunicode, $this->CurrentFont));
  7460. $alias['a'][] = TCPDF_STATIC::_escape(TCPDF_FONTS::UTF8ToLatin1($a, $this->isunicode, $this->CurrentFont));
  7461. $alias['a'][] = TCPDF_STATIC::_escape(TCPDF_FONTS::utf8StrRev($a, false, $this->tmprtl, $this->isunicode, $this->CurrentFont));
  7462. }
  7463. $alias['a'][] = TCPDF_STATIC::_escape($a);
  7464. return $alias;
  7465. }
  7466. /**
  7467. * Return an array containing all internal page aliases.
  7468. * @return array of page number aliases
  7469. * @protected
  7470. */
  7471. protected function getAllInternalPageNumberAliases() {
  7472. $basic_alias = array(TCPDF_STATIC::$alias_tot_pages, TCPDF_STATIC::$alias_num_page, TCPDF_STATIC::$alias_group_tot_pages, TCPDF_STATIC::$alias_group_num_page, TCPDF_STATIC::$alias_right_shift);
  7473. $pnalias = array();
  7474. foreach($basic_alias as $k => $a) {
  7475. $pnalias[$k] = $this->getInternalPageNumberAliases($a);
  7476. }
  7477. return $pnalias;
  7478. }
  7479. /**
  7480. * Replace right shift page number aliases with spaces to correct right alignment.
  7481. * This works perfectly only when using monospaced fonts.
  7482. * @param $page (string) Page content.
  7483. * @param $aliases (array) Array of page aliases.
  7484. * @param $diff (int) initial difference to add.
  7485. * @return replaced page content.
  7486. * @protected
  7487. */
  7488. protected function replaceRightShiftPageNumAliases($page, $aliases, $diff) {
  7489. foreach ($aliases as $type => $alias) {
  7490. foreach ($alias as $a) {
  7491. // find position of compensation factor
  7492. $startnum = (strpos($a, ':') + 1);
  7493. $a = substr($a, 0, $startnum);
  7494. if (($pos = strpos($page, $a)) !== false) {
  7495. // end of alias
  7496. $endnum = strpos($page, '}', $pos);
  7497. // string to be replaced
  7498. $aa = substr($page, $pos, ($endnum - $pos + 1));
  7499. // get compensation factor
  7500. $ratio = substr($page, ($pos + $startnum), ($endnum - $pos - $startnum));
  7501. $ratio = preg_replace('/[^0-9\.]/', '', $ratio);
  7502. $ratio = floatval($ratio);
  7503. if ($type == 'u') {
  7504. $chrdiff = floor(($diff + 12) * $ratio);
  7505. $shift = str_repeat(' ', $chrdiff);
  7506. $shift = TCPDF_FONTS::UTF8ToUTF16BE($shift, false, $this->isunicode, $this->CurrentFont);
  7507. } else {
  7508. $chrdiff = floor(($diff + 11) * $ratio);
  7509. $shift = str_repeat(' ', $chrdiff);
  7510. }
  7511. $page = str_replace($aa, $shift, $page);
  7512. }
  7513. }
  7514. }
  7515. return $page;
  7516. }
  7517. /**
  7518. * Set page boxes to be included on page descriptions.
  7519. * @param $boxes (array) Array of page boxes to set on document: ('MediaBox', 'CropBox', 'BleedBox', 'TrimBox', 'ArtBox').
  7520. * @protected
  7521. */
  7522. protected function setPageBoxTypes($boxes) {
  7523. $this->page_boxes = array();
  7524. foreach ($boxes as $box) {
  7525. if (in_array($box, TCPDF_STATIC::$pageboxes)) {
  7526. $this->page_boxes[] = $box;
  7527. }
  7528. }
  7529. }
  7530. /**
  7531. * Output pages (and replace page number aliases).
  7532. * @protected
  7533. */
  7534. protected function _putpages() {
  7535. $filter = ($this->compress) ? '/Filter /FlateDecode ' : '';
  7536. // get internal aliases for page numbers
  7537. $pnalias = $this->getAllInternalPageNumberAliases();
  7538. $num_pages = $this->numpages;
  7539. $ptpa = TCPDF_STATIC::formatPageNumber(($this->starting_page_number + $num_pages - 1));
  7540. $ptpu = TCPDF_FONTS::UTF8ToUTF16BE($ptpa, false, $this->isunicode, $this->CurrentFont);
  7541. $ptp_num_chars = $this->GetNumChars($ptpa);
  7542. $pagegroupnum = 0;
  7543. $groupnum = 0;
  7544. $ptgu = 1;
  7545. $ptga = 1;
  7546. $ptg_num_chars = 1;
  7547. for ($n = 1; $n <= $num_pages; ++$n) {
  7548. // get current page
  7549. $temppage = $this->getPageBuffer($n);
  7550. $pagelen = strlen($temppage);
  7551. // set replacements for total pages number
  7552. $pnpa = TCPDF_STATIC::formatPageNumber(($this->starting_page_number + $n - 1));
  7553. $pnpu = TCPDF_FONTS::UTF8ToUTF16BE($pnpa, false, $this->isunicode, $this->CurrentFont);
  7554. $pnp_num_chars = $this->GetNumChars($pnpa);
  7555. $pdiff = 0; // difference used for right shift alignment of page numbers
  7556. $gdiff = 0; // difference used for right shift alignment of page group numbers
  7557. if (!empty($this->pagegroups)) {
  7558. if (isset($this->newpagegroup[$n])) {
  7559. $pagegroupnum = 0;
  7560. ++$groupnum;
  7561. $ptga = TCPDF_STATIC::formatPageNumber($this->pagegroups[$groupnum]);
  7562. $ptgu = TCPDF_FONTS::UTF8ToUTF16BE($ptga, false, $this->isunicode, $this->CurrentFont);
  7563. $ptg_num_chars = $this->GetNumChars($ptga);
  7564. }
  7565. ++$pagegroupnum;
  7566. $pnga = TCPDF_STATIC::formatPageNumber($pagegroupnum);
  7567. $pngu = TCPDF_FONTS::UTF8ToUTF16BE($pnga, false, $this->isunicode, $this->CurrentFont);
  7568. $png_num_chars = $this->GetNumChars($pnga);
  7569. // replace page numbers
  7570. $replace = array();
  7571. $replace[] = array($ptgu, $ptg_num_chars, 9, $pnalias[2]['u']);
  7572. $replace[] = array($ptga, $ptg_num_chars, 7, $pnalias[2]['a']);
  7573. $replace[] = array($pngu, $png_num_chars, 9, $pnalias[3]['u']);
  7574. $replace[] = array($pnga, $png_num_chars, 7, $pnalias[3]['a']);
  7575. list($temppage, $gdiff) = TCPDF_STATIC::replacePageNumAliases($temppage, $replace, $gdiff);
  7576. }
  7577. // replace page numbers
  7578. $replace = array();
  7579. $replace[] = array($ptpu, $ptp_num_chars, 9, $pnalias[0]['u']);
  7580. $replace[] = array($ptpa, $ptp_num_chars, 7, $pnalias[0]['a']);
  7581. $replace[] = array($pnpu, $pnp_num_chars, 9, $pnalias[1]['u']);
  7582. $replace[] = array($pnpa, $pnp_num_chars, 7, $pnalias[1]['a']);
  7583. list($temppage, $pdiff) = TCPDF_STATIC::replacePageNumAliases($temppage, $replace, $pdiff);
  7584. // replace right shift alias
  7585. $temppage = $this->replaceRightShiftPageNumAliases($temppage, $pnalias[4], max($pdiff, $gdiff));
  7586. // replace EPS marker
  7587. $temppage = str_replace($this->epsmarker, '', $temppage);
  7588. //Page
  7589. $this->page_obj_id[$n] = $this->_newobj();
  7590. $out = '<<';
  7591. $out .= ' /Type /Page';
  7592. $out .= ' /Parent 1 0 R';
  7593. if (empty($this->signature_data['approval']) OR ($this->signature_data['approval'] != 'A')) {
  7594. $out .= ' /LastModified '.$this->_datestring(0, $this->doc_modification_timestamp);
  7595. }
  7596. $out .= ' /Resources 2 0 R';
  7597. foreach ($this->page_boxes as $box) {
  7598. $out .= ' /'.$box;
  7599. $out .= sprintf(' [%F %F %F %F]', $this->pagedim[$n][$box]['llx'], $this->pagedim[$n][$box]['lly'], $this->pagedim[$n][$box]['urx'], $this->pagedim[$n][$box]['ury']);
  7600. }
  7601. if (isset($this->pagedim[$n]['BoxColorInfo']) AND !empty($this->pagedim[$n]['BoxColorInfo'])) {
  7602. $out .= ' /BoxColorInfo <<';
  7603. foreach ($this->page_boxes as $box) {
  7604. if (isset($this->pagedim[$n]['BoxColorInfo'][$box])) {
  7605. $out .= ' /'.$box.' <<';
  7606. if (isset($this->pagedim[$n]['BoxColorInfo'][$box]['C'])) {
  7607. $color = $this->pagedim[$n]['BoxColorInfo'][$box]['C'];
  7608. $out .= ' /C [';
  7609. $out .= sprintf(' %F %F %F', ($color[0] / 255), ($color[1] / 255), ($color[2] / 255));
  7610. $out .= ' ]';
  7611. }
  7612. if (isset($this->pagedim[$n]['BoxColorInfo'][$box]['W'])) {
  7613. $out .= ' /W '.($this->pagedim[$n]['BoxColorInfo'][$box]['W'] * $this->k);
  7614. }
  7615. if (isset($this->pagedim[$n]['BoxColorInfo'][$box]['S'])) {
  7616. $out .= ' /S /'.$this->pagedim[$n]['BoxColorInfo'][$box]['S'];
  7617. }
  7618. if (isset($this->pagedim[$n]['BoxColorInfo'][$box]['D'])) {
  7619. $dashes = $this->pagedim[$n]['BoxColorInfo'][$box]['D'];
  7620. $out .= ' /D [';
  7621. foreach ($dashes as $dash) {
  7622. $out .= sprintf(' %F', ($dash * $this->k));
  7623. }
  7624. $out .= ' ]';
  7625. }
  7626. $out .= ' >>';
  7627. }
  7628. }
  7629. $out .= ' >>';
  7630. }
  7631. $out .= ' /Contents '.($this->n + 1).' 0 R';
  7632. $out .= ' /Rotate '.$this->pagedim[$n]['Rotate'];
  7633. if (!$this->pdfa_mode) {
  7634. $out .= ' /Group << /Type /Group /S /Transparency /CS /DeviceRGB >>';
  7635. }
  7636. if (isset($this->pagedim[$n]['trans']) AND !empty($this->pagedim[$n]['trans'])) {
  7637. // page transitions
  7638. if (isset($this->pagedim[$n]['trans']['Dur'])) {
  7639. $out .= ' /Dur '.$this->pagedim[$n]['trans']['Dur'];
  7640. }
  7641. $out .= ' /Trans <<';
  7642. $out .= ' /Type /Trans';
  7643. if (isset($this->pagedim[$n]['trans']['S'])) {
  7644. $out .= ' /S /'.$this->pagedim[$n]['trans']['S'];
  7645. }
  7646. if (isset($this->pagedim[$n]['trans']['D'])) {
  7647. $out .= ' /D '.$this->pagedim[$n]['trans']['D'];
  7648. }
  7649. if (isset($this->pagedim[$n]['trans']['Dm'])) {
  7650. $out .= ' /Dm /'.$this->pagedim[$n]['trans']['Dm'];
  7651. }
  7652. if (isset($this->pagedim[$n]['trans']['M'])) {
  7653. $out .= ' /M /'.$this->pagedim[$n]['trans']['M'];
  7654. }
  7655. if (isset($this->pagedim[$n]['trans']['Di'])) {
  7656. $out .= ' /Di '.$this->pagedim[$n]['trans']['Di'];
  7657. }
  7658. if (isset($this->pagedim[$n]['trans']['SS'])) {
  7659. $out .= ' /SS '.$this->pagedim[$n]['trans']['SS'];
  7660. }
  7661. if (isset($this->pagedim[$n]['trans']['B'])) {
  7662. $out .= ' /B '.$this->pagedim[$n]['trans']['B'];
  7663. }
  7664. $out .= ' >>';
  7665. }
  7666. $out .= $this->_getannotsrefs($n);
  7667. $out .= ' /PZ '.$this->pagedim[$n]['PZ'];
  7668. $out .= ' >>';
  7669. $out .= "\n".'endobj';
  7670. $this->_out($out);
  7671. //Page content
  7672. $p = ($this->compress) ? gzcompress($temppage) : $temppage;
  7673. $this->_newobj();
  7674. $p = $this->_getrawstream($p);
  7675. $this->_out('<<'.$filter.'/Length '.strlen($p).'>> stream'."\n".$p."\n".'endstream'."\n".'endobj');
  7676. }
  7677. //Pages root
  7678. $out = $this->_getobj(1)."\n";
  7679. $out .= '<< /Type /Pages /Kids [';
  7680. foreach($this->page_obj_id as $page_obj) {
  7681. $out .= ' '.$page_obj.' 0 R';
  7682. }
  7683. $out .= ' ] /Count '.$num_pages.' >>';
  7684. $out .= "\n".'endobj';
  7685. $this->_out($out);
  7686. }
  7687. /**
  7688. * Get references to page annotations.
  7689. * @param $n (int) page number
  7690. * @return string
  7691. * @protected
  7692. * @author Nicola Asuni
  7693. * @since 5.0.010 (2010-05-17)
  7694. */
  7695. protected function _getannotsrefs($n) {
  7696. if (!(isset($this->PageAnnots[$n]) OR ($this->sign AND isset($this->signature_data['cert_type'])))) {
  7697. return '';
  7698. }
  7699. $out = ' /Annots [';
  7700. if (isset($this->PageAnnots[$n])) {
  7701. foreach ($this->PageAnnots[$n] as $key => $val) {
  7702. if (!in_array($val['n'], $this->radio_groups)) {
  7703. $out .= ' '.$val['n'].' 0 R';
  7704. }
  7705. }
  7706. // add radiobutton groups
  7707. if (isset($this->radiobutton_groups[$n])) {
  7708. foreach ($this->radiobutton_groups[$n] as $key => $data) {
  7709. if (isset($data['n'])) {
  7710. $out .= ' '.$data['n'].' 0 R';
  7711. }
  7712. }
  7713. }
  7714. }
  7715. if ($this->sign AND ($n == $this->signature_appearance['page']) AND isset($this->signature_data['cert_type'])) {
  7716. // set reference for signature object
  7717. $out .= ' '.$this->sig_obj_id.' 0 R';
  7718. }
  7719. if (!empty($this->empty_signature_appearance)) {
  7720. foreach ($this->empty_signature_appearance as $esa) {
  7721. if ($esa['page'] == $n) {
  7722. // set reference for empty signature objects
  7723. $out .= ' '.$esa['objid'].' 0 R';
  7724. }
  7725. }
  7726. }
  7727. $out .= ' ]';
  7728. return $out;
  7729. }
  7730. /**
  7731. * Output annotations objects for all pages.
  7732. * !!! THIS METHOD IS NOT YET COMPLETED !!!
  7733. * See section 12.5 of PDF 32000_2008 reference.
  7734. * @protected
  7735. * @author Nicola Asuni
  7736. * @since 4.0.018 (2008-08-06)
  7737. */
  7738. protected function _putannotsobjs() {
  7739. // reset object counter
  7740. for ($n=1; $n <= $this->numpages; ++$n) {
  7741. if (isset($this->PageAnnots[$n])) {
  7742. // set page annotations
  7743. foreach ($this->PageAnnots[$n] as $key => $pl) {
  7744. $annot_obj_id = $this->PageAnnots[$n][$key]['n'];
  7745. // create annotation object for grouping radiobuttons
  7746. if (isset($this->radiobutton_groups[$n][$pl['txt']]) AND is_array($this->radiobutton_groups[$n][$pl['txt']])) {
  7747. $radio_button_obj_id = $this->radiobutton_groups[$n][$pl['txt']]['n'];
  7748. $annots = '<<';
  7749. $annots .= ' /Type /Annot';
  7750. $annots .= ' /Subtype /Widget';
  7751. $annots .= ' /Rect [0 0 0 0]';
  7752. if ($this->radiobutton_groups[$n][$pl['txt']]['#readonly#']) {
  7753. // read only
  7754. $annots .= ' /F 68';
  7755. $annots .= ' /Ff 49153';
  7756. } else {
  7757. $annots .= ' /F 4'; // default print for PDF/A
  7758. $annots .= ' /Ff 49152';
  7759. }
  7760. $annots .= ' /T '.$this->_datastring($pl['txt'], $radio_button_obj_id);
  7761. if (isset($pl['opt']['tu']) AND is_string($pl['opt']['tu'])) {
  7762. $annots .= ' /TU '.$this->_datastring($pl['opt']['tu'], $radio_button_obj_id);
  7763. }
  7764. $annots .= ' /FT /Btn';
  7765. $annots .= ' /Kids [';
  7766. $defval = '';
  7767. foreach ($this->radiobutton_groups[$n][$pl['txt']] as $key => $data) {
  7768. if (isset($data['kid'])) {
  7769. $annots .= ' '.$data['kid'].' 0 R';
  7770. if ($data['def'] !== 'Off') {
  7771. $defval = $data['def'];
  7772. }
  7773. }
  7774. }
  7775. $annots .= ' ]';
  7776. if (!empty($defval)) {
  7777. $annots .= ' /V /'.$defval;
  7778. }
  7779. $annots .= ' >>';
  7780. $this->_out($this->_getobj($radio_button_obj_id)."\n".$annots."\n".'endobj');
  7781. $this->form_obj_id[] = $radio_button_obj_id;
  7782. // store object id to be used on Parent entry of Kids
  7783. $this->radiobutton_groups[$n][$pl['txt']] = $radio_button_obj_id;
  7784. }
  7785. $formfield = false;
  7786. $pl['opt'] = array_change_key_case($pl['opt'], CASE_LOWER);
  7787. $a = $pl['x'] * $this->k;
  7788. $b = $this->pagedim[$n]['h'] - (($pl['y'] + $pl['h']) * $this->k);
  7789. $c = $pl['w'] * $this->k;
  7790. $d = $pl['h'] * $this->k;
  7791. $rect = sprintf('%F %F %F %F', $a, $b, $a+$c, $b+$d);
  7792. // create new annotation object
  7793. $annots = '<</Type /Annot';
  7794. $annots .= ' /Subtype /'.$pl['opt']['subtype'];
  7795. $annots .= ' /Rect ['.$rect.']';
  7796. $ft = array('Btn', 'Tx', 'Ch', 'Sig');
  7797. if (isset($pl['opt']['ft']) AND in_array($pl['opt']['ft'], $ft)) {
  7798. $annots .= ' /FT /'.$pl['opt']['ft'];
  7799. $formfield = true;
  7800. }
  7801. if ($pl['opt']['subtype'] !== 'Link') {
  7802. $annots .= ' /Contents '.$this->_textstring($pl['txt'], $annot_obj_id);
  7803. }
  7804. $annots .= ' /P '.$this->page_obj_id[$n].' 0 R';
  7805. $annots .= ' /NM '.$this->_datastring(sprintf('%04u-%04u', $n, $key), $annot_obj_id);
  7806. $annots .= ' /M '.$this->_datestring($annot_obj_id, $this->doc_modification_timestamp);
  7807. if (isset($pl['opt']['f'])) {
  7808. $fval = 0;
  7809. if (is_array($pl['opt']['f'])) {
  7810. foreach ($pl['opt']['f'] as $f) {
  7811. switch (strtolower($f)) {
  7812. case 'invisible': {
  7813. $fval += 1 << 0;
  7814. break;
  7815. }
  7816. case 'hidden': {
  7817. $fval += 1 << 1;
  7818. break;
  7819. }
  7820. case 'print': {
  7821. $fval += 1 << 2;
  7822. break;
  7823. }
  7824. case 'nozoom': {
  7825. $fval += 1 << 3;
  7826. break;
  7827. }
  7828. case 'norotate': {
  7829. $fval += 1 << 4;
  7830. break;
  7831. }
  7832. case 'noview': {
  7833. $fval += 1 << 5;
  7834. break;
  7835. }
  7836. case 'readonly': {
  7837. $fval += 1 << 6;
  7838. break;
  7839. }
  7840. case 'locked': {
  7841. $fval += 1 << 8;
  7842. break;
  7843. }
  7844. case 'togglenoview': {
  7845. $fval += 1 << 9;
  7846. break;
  7847. }
  7848. case 'lockedcontents': {
  7849. $fval += 1 << 10;
  7850. break;
  7851. }
  7852. default: {
  7853. break;
  7854. }
  7855. }
  7856. }
  7857. } else {
  7858. $fval = intval($pl['opt']['f']);
  7859. }
  7860. } else {
  7861. $fval = 4;
  7862. }
  7863. if ($this->pdfa_mode) {
  7864. // force print flag for PDF/A mode
  7865. $fval |= 4;
  7866. }
  7867. $annots .= ' /F '.intval($fval);
  7868. if (isset($pl['opt']['as']) AND is_string($pl['opt']['as'])) {
  7869. $annots .= ' /AS /'.$pl['opt']['as'];
  7870. }
  7871. if (isset($pl['opt']['ap'])) {
  7872. // appearance stream
  7873. $annots .= ' /AP <<';
  7874. if (is_array($pl['opt']['ap'])) {
  7875. foreach ($pl['opt']['ap'] as $apmode => $apdef) {
  7876. // $apmode can be: n = normal; r = rollover; d = down;
  7877. $annots .= ' /'.strtoupper($apmode);
  7878. if (is_array($apdef)) {
  7879. $annots .= ' <<';
  7880. foreach ($apdef as $apstate => $stream) {
  7881. // reference to XObject that define the appearance for this mode-state
  7882. $apsobjid = $this->_putAPXObject($c, $d, $stream);
  7883. $annots .= ' /'.$apstate.' '.$apsobjid.' 0 R';
  7884. }
  7885. $annots .= ' >>';
  7886. } else {
  7887. // reference to XObject that define the appearance for this mode
  7888. $apsobjid = $this->_putAPXObject($c, $d, $apdef);
  7889. $annots .= ' '.$apsobjid.' 0 R';
  7890. }
  7891. }
  7892. } else {
  7893. $annots .= $pl['opt']['ap'];
  7894. }
  7895. $annots .= ' >>';
  7896. }
  7897. if (isset($pl['opt']['bs']) AND (is_array($pl['opt']['bs']))) {
  7898. $annots .= ' /BS <<';
  7899. $annots .= ' /Type /Border';
  7900. if (isset($pl['opt']['bs']['w'])) {
  7901. $annots .= ' /W '.intval($pl['opt']['bs']['w']);
  7902. }
  7903. $bstyles = array('S', 'D', 'B', 'I', 'U');
  7904. if (isset($pl['opt']['bs']['s']) AND in_array($pl['opt']['bs']['s'], $bstyles)) {
  7905. $annots .= ' /S /'.$pl['opt']['bs']['s'];
  7906. }
  7907. if (isset($pl['opt']['bs']['d']) AND (is_array($pl['opt']['bs']['d']))) {
  7908. $annots .= ' /D [';
  7909. foreach ($pl['opt']['bs']['d'] as $cord) {
  7910. $annots .= ' '.intval($cord);
  7911. }
  7912. $annots .= ']';
  7913. }
  7914. $annots .= ' >>';
  7915. } else {
  7916. $annots .= ' /Border [';
  7917. if (isset($pl['opt']['border']) AND (count($pl['opt']['border']) >= 3)) {
  7918. $annots .= intval($pl['opt']['border'][0]).' ';
  7919. $annots .= intval($pl['opt']['border'][1]).' ';
  7920. $annots .= intval($pl['opt']['border'][2]);
  7921. if (isset($pl['opt']['border'][3]) AND is_array($pl['opt']['border'][3])) {
  7922. $annots .= ' [';
  7923. foreach ($pl['opt']['border'][3] as $dash) {
  7924. $annots .= intval($dash).' ';
  7925. }
  7926. $annots .= ']';
  7927. }
  7928. } else {
  7929. $annots .= '0 0 0';
  7930. }
  7931. $annots .= ']';
  7932. }
  7933. if (isset($pl['opt']['be']) AND (is_array($pl['opt']['be']))) {
  7934. $annots .= ' /BE <<';
  7935. $bstyles = array('S', 'C');
  7936. if (isset($pl['opt']['be']['s']) AND in_array($pl['opt']['be']['s'], $bstyles)) {
  7937. $annots .= ' /S /'.$pl['opt']['bs']['s'];
  7938. } else {
  7939. $annots .= ' /S /S';
  7940. }
  7941. if (isset($pl['opt']['be']['i']) AND ($pl['opt']['be']['i'] >= 0) AND ($pl['opt']['be']['i'] <= 2)) {
  7942. $annots .= ' /I '.sprintf(' %F', $pl['opt']['be']['i']);
  7943. }
  7944. $annots .= '>>';
  7945. }
  7946. if (isset($pl['opt']['c']) AND (is_array($pl['opt']['c'])) AND !empty($pl['opt']['c'])) {
  7947. $annots .= ' /C '.TCPDF_COLORS::getColorStringFromArray($pl['opt']['c']);
  7948. }
  7949. //$annots .= ' /StructParent ';
  7950. //$annots .= ' /OC ';
  7951. $markups = array('text', 'freetext', 'line', 'square', 'circle', 'polygon', 'polyline', 'highlight', 'underline', 'squiggly', 'strikeout', 'stamp', 'caret', 'ink', 'fileattachment', 'sound');
  7952. if (in_array(strtolower($pl['opt']['subtype']), $markups)) {
  7953. // this is a markup type
  7954. if (isset($pl['opt']['t']) AND is_string($pl['opt']['t'])) {
  7955. $annots .= ' /T '.$this->_textstring($pl['opt']['t'], $annot_obj_id);
  7956. }
  7957. //$annots .= ' /Popup ';
  7958. if (isset($pl['opt']['ca'])) {
  7959. $annots .= ' /CA '.sprintf('%F', floatval($pl['opt']['ca']));
  7960. }
  7961. if (isset($pl['opt']['rc'])) {
  7962. $annots .= ' /RC '.$this->_textstring($pl['opt']['rc'], $annot_obj_id);
  7963. }
  7964. $annots .= ' /CreationDate '.$this->_datestring($annot_obj_id, $this->doc_creation_timestamp);
  7965. //$annots .= ' /IRT ';
  7966. if (isset($pl['opt']['subj'])) {
  7967. $annots .= ' /Subj '.$this->_textstring($pl['opt']['subj'], $annot_obj_id);
  7968. }
  7969. //$annots .= ' /RT ';
  7970. //$annots .= ' /IT ';
  7971. //$annots .= ' /ExData ';
  7972. }
  7973. $lineendings = array('Square', 'Circle', 'Diamond', 'OpenArrow', 'ClosedArrow', 'None', 'Butt', 'ROpenArrow', 'RClosedArrow', 'Slash');
  7974. // Annotation types
  7975. switch (strtolower($pl['opt']['subtype'])) {
  7976. case 'text': {
  7977. if (isset($pl['opt']['open'])) {
  7978. $annots .= ' /Open '. (strtolower($pl['opt']['open']) == 'true' ? 'true' : 'false');
  7979. }
  7980. $iconsapp = array('Comment', 'Help', 'Insert', 'Key', 'NewParagraph', 'Note', 'Paragraph');
  7981. if (isset($pl['opt']['name']) AND in_array($pl['opt']['name'], $iconsapp)) {
  7982. $annots .= ' /Name /'.$pl['opt']['name'];
  7983. } else {
  7984. $annots .= ' /Name /Note';
  7985. }
  7986. $statemodels = array('Marked', 'Review');
  7987. if (isset($pl['opt']['statemodel']) AND in_array($pl['opt']['statemodel'], $statemodels)) {
  7988. $annots .= ' /StateModel /'.$pl['opt']['statemodel'];
  7989. } else {
  7990. $pl['opt']['statemodel'] = 'Marked';
  7991. $annots .= ' /StateModel /'.$pl['opt']['statemodel'];
  7992. }
  7993. if ($pl['opt']['statemodel'] == 'Marked') {
  7994. $states = array('Accepted', 'Unmarked');
  7995. } else {
  7996. $states = array('Accepted', 'Rejected', 'Cancelled', 'Completed', 'None');
  7997. }
  7998. if (isset($pl['opt']['state']) AND in_array($pl['opt']['state'], $states)) {
  7999. $annots .= ' /State /'.$pl['opt']['state'];
  8000. } else {
  8001. if ($pl['opt']['statemodel'] == 'Marked') {
  8002. $annots .= ' /State /Unmarked';
  8003. } else {
  8004. $annots .= ' /State /None';
  8005. }
  8006. }
  8007. break;
  8008. }
  8009. case 'link': {
  8010. if (is_string($pl['txt']) && !empty($pl['txt'])) {
  8011. if ($pl['txt'][0] == '#') {
  8012. // internal destination
  8013. $annots .= ' /A <</S /GoTo /D '.TCPDF_STATIC::encodeNameObject(substr($pl['txt'], 1)).'>>';
  8014. } elseif ($pl['txt'][0] == '%') {
  8015. // embedded PDF file
  8016. $filename = basename(substr($pl['txt'], 1));
  8017. $annots .= ' /A << /S /GoToE /D [0 /Fit] /NewWindow true /T << /R /C /P '.($n - 1).' /A '.$this->embeddedfiles[$filename]['a'].' >> >>';
  8018. } elseif ($pl['txt'][0] == '*') {
  8019. // embedded generic file
  8020. $filename = basename(substr($pl['txt'], 1));
  8021. $jsa = 'var D=event.target.doc;var MyData=D.dataObjects;for (var i in MyData) if (MyData[i].path=="'.$filename.'") D.exportDataObject( { cName : MyData[i].name, nLaunch : 2});';
  8022. $annots .= ' /A << /S /JavaScript /JS '.$this->_textstring($jsa, $annot_obj_id).'>>';
  8023. } else {
  8024. $parsedUrl = parse_url($pl['txt']);
  8025. if (empty($parsedUrl['scheme']) AND (!empty($parsedUrl['path']) && strtolower(substr($parsedUrl['path'], -4)) == '.pdf')) {
  8026. // relative link to a PDF file
  8027. $dest = '[0 /Fit]'; // default page 0
  8028. if (!empty($parsedUrl['fragment'])) {
  8029. // check for named destination
  8030. $tmp = explode('=', $parsedUrl['fragment']);
  8031. $dest = '('.((count($tmp) == 2) ? $tmp[1] : $tmp[0]).')';
  8032. }
  8033. $annots .= ' /A <</S /GoToR /D '.$dest.' /F '.$this->_datastring($this->unhtmlentities($parsedUrl['path']), $annot_obj_id).' /NewWindow true>>';
  8034. } else {
  8035. // external URI link
  8036. $annots .= ' /A <</S /URI /URI '.$this->_datastring($this->unhtmlentities($pl['txt']), $annot_obj_id).'>>';
  8037. }
  8038. }
  8039. } elseif (isset($this->links[$pl['txt']])) {
  8040. // internal link ID
  8041. $l = $this->links[$pl['txt']];
  8042. if (isset($this->page_obj_id[($l['p'])])) {
  8043. $annots .= sprintf(' /Dest [%u 0 R /XYZ 0 %F null]', $this->page_obj_id[($l['p'])], ($this->pagedim[$l['p']]['h'] - ($l['y'] * $this->k)));
  8044. }
  8045. }
  8046. $hmodes = array('N', 'I', 'O', 'P');
  8047. if (isset($pl['opt']['h']) AND in_array($pl['opt']['h'], $hmodes)) {
  8048. $annots .= ' /H /'.$pl['opt']['h'];
  8049. } else {
  8050. $annots .= ' /H /I';
  8051. }
  8052. //$annots .= ' /PA ';
  8053. //$annots .= ' /Quadpoints ';
  8054. break;
  8055. }
  8056. case 'freetext': {
  8057. if (isset($pl['opt']['da']) AND !empty($pl['opt']['da'])) {
  8058. $annots .= ' /DA ('.$pl['opt']['da'].')';
  8059. }
  8060. if (isset($pl['opt']['q']) AND ($pl['opt']['q'] >= 0) AND ($pl['opt']['q'] <= 2)) {
  8061. $annots .= ' /Q '.intval($pl['opt']['q']);
  8062. }
  8063. if (isset($pl['opt']['rc'])) {
  8064. $annots .= ' /RC '.$this->_textstring($pl['opt']['rc'], $annot_obj_id);
  8065. }
  8066. if (isset($pl['opt']['ds'])) {
  8067. $annots .= ' /DS '.$this->_textstring($pl['opt']['ds'], $annot_obj_id);
  8068. }
  8069. if (isset($pl['opt']['cl']) AND is_array($pl['opt']['cl'])) {
  8070. $annots .= ' /CL [';
  8071. foreach ($pl['opt']['cl'] as $cl) {
  8072. $annots .= sprintf('%F ', $cl * $this->k);
  8073. }
  8074. $annots .= ']';
  8075. }
  8076. $tfit = array('FreeText', 'FreeTextCallout', 'FreeTextTypeWriter');
  8077. if (isset($pl['opt']['it']) AND in_array($pl['opt']['it'], $tfit)) {
  8078. $annots .= ' /IT /'.$pl['opt']['it'];
  8079. }
  8080. if (isset($pl['opt']['rd']) AND is_array($pl['opt']['rd'])) {
  8081. $l = $pl['opt']['rd'][0] * $this->k;
  8082. $r = $pl['opt']['rd'][1] * $this->k;
  8083. $t = $pl['opt']['rd'][2] * $this->k;
  8084. $b = $pl['opt']['rd'][3] * $this->k;
  8085. $annots .= ' /RD ['.sprintf('%F %F %F %F', $l, $r, $t, $b).']';
  8086. }
  8087. if (isset($pl['opt']['le']) AND in_array($pl['opt']['le'], $lineendings)) {
  8088. $annots .= ' /LE /'.$pl['opt']['le'];
  8089. }
  8090. break;
  8091. }
  8092. case 'line': {
  8093. break;
  8094. }
  8095. case 'square': {
  8096. break;
  8097. }
  8098. case 'circle': {
  8099. break;
  8100. }
  8101. case 'polygon': {
  8102. break;
  8103. }
  8104. case 'polyline': {
  8105. break;
  8106. }
  8107. case 'highlight': {
  8108. break;
  8109. }
  8110. case 'underline': {
  8111. break;
  8112. }
  8113. case 'squiggly': {
  8114. break;
  8115. }
  8116. case 'strikeout': {
  8117. break;
  8118. }
  8119. case 'stamp': {
  8120. break;
  8121. }
  8122. case 'caret': {
  8123. break;
  8124. }
  8125. case 'ink': {
  8126. break;
  8127. }
  8128. case 'popup': {
  8129. break;
  8130. }
  8131. case 'fileattachment': {
  8132. if ($this->pdfa_mode && $this->pdfa_version != 3) {
  8133. // embedded files are not allowed in PDF/A mode version 1 and 2
  8134. break;
  8135. }
  8136. if (!isset($pl['opt']['fs'])) {
  8137. break;
  8138. }
  8139. $filename = basename($pl['opt']['fs']);
  8140. if (isset($this->embeddedfiles[$filename]['f'])) {
  8141. $annots .= ' /FS '.$this->embeddedfiles[$filename]['f'].' 0 R';
  8142. $iconsapp = array('Graph', 'Paperclip', 'PushPin', 'Tag');
  8143. if (isset($pl['opt']['name']) AND in_array($pl['opt']['name'], $iconsapp)) {
  8144. $annots .= ' /Name /'.$pl['opt']['name'];
  8145. } else {
  8146. $annots .= ' /Name /PushPin';
  8147. }
  8148. // index (zero-based) of the annotation in the Annots array of this page
  8149. $this->embeddedfiles[$filename]['a'] = $key;
  8150. }
  8151. break;
  8152. }
  8153. case 'sound': {
  8154. if (!isset($pl['opt']['fs'])) {
  8155. break;
  8156. }
  8157. $filename = basename($pl['opt']['fs']);
  8158. if (isset($this->embeddedfiles[$filename]['f'])) {
  8159. // ... TO BE COMPLETED ...
  8160. // /R /C /B /E /CO /CP
  8161. $annots .= ' /Sound '.$this->embeddedfiles[$filename]['f'].' 0 R';
  8162. $iconsapp = array('Speaker', 'Mic');
  8163. if (isset($pl['opt']['name']) AND in_array($pl['opt']['name'], $iconsapp)) {
  8164. $annots .= ' /Name /'.$pl['opt']['name'];
  8165. } else {
  8166. $annots .= ' /Name /Speaker';
  8167. }
  8168. }
  8169. break;
  8170. }
  8171. case 'movie': {
  8172. break;
  8173. }
  8174. case 'widget': {
  8175. $hmode = array('N', 'I', 'O', 'P', 'T');
  8176. if (isset($pl['opt']['h']) AND in_array($pl['opt']['h'], $hmode)) {
  8177. $annots .= ' /H /'.$pl['opt']['h'];
  8178. }
  8179. if (isset($pl['opt']['mk']) AND (is_array($pl['opt']['mk'])) AND !empty($pl['opt']['mk'])) {
  8180. $annots .= ' /MK <<';
  8181. if (isset($pl['opt']['mk']['r'])) {
  8182. $annots .= ' /R '.$pl['opt']['mk']['r'];
  8183. }
  8184. if (isset($pl['opt']['mk']['bc']) AND (is_array($pl['opt']['mk']['bc']))) {
  8185. $annots .= ' /BC '.TCPDF_COLORS::getColorStringFromArray($pl['opt']['mk']['bc']);
  8186. }
  8187. if (isset($pl['opt']['mk']['bg']) AND (is_array($pl['opt']['mk']['bg']))) {
  8188. $annots .= ' /BG '.TCPDF_COLORS::getColorStringFromArray($pl['opt']['mk']['bg']);
  8189. }
  8190. if (isset($pl['opt']['mk']['ca'])) {
  8191. $annots .= ' /CA '.$pl['opt']['mk']['ca'];
  8192. }
  8193. if (isset($pl['opt']['mk']['rc'])) {
  8194. $annots .= ' /RC '.$pl['opt']['mk']['rc'];
  8195. }
  8196. if (isset($pl['opt']['mk']['ac'])) {
  8197. $annots .= ' /AC '.$pl['opt']['mk']['ac'];
  8198. }
  8199. if (isset($pl['opt']['mk']['i'])) {
  8200. $info = $this->getImageBuffer($pl['opt']['mk']['i']);
  8201. if ($info !== false) {
  8202. $annots .= ' /I '.$info['n'].' 0 R';
  8203. }
  8204. }
  8205. if (isset($pl['opt']['mk']['ri'])) {
  8206. $info = $this->getImageBuffer($pl['opt']['mk']['ri']);
  8207. if ($info !== false) {
  8208. $annots .= ' /RI '.$info['n'].' 0 R';
  8209. }
  8210. }
  8211. if (isset($pl['opt']['mk']['ix'])) {
  8212. $info = $this->getImageBuffer($pl['opt']['mk']['ix']);
  8213. if ($info !== false) {
  8214. $annots .= ' /IX '.$info['n'].' 0 R';
  8215. }
  8216. }
  8217. if (isset($pl['opt']['mk']['if']) AND (is_array($pl['opt']['mk']['if'])) AND !empty($pl['opt']['mk']['if'])) {
  8218. $annots .= ' /IF <<';
  8219. $if_sw = array('A', 'B', 'S', 'N');
  8220. if (isset($pl['opt']['mk']['if']['sw']) AND in_array($pl['opt']['mk']['if']['sw'], $if_sw)) {
  8221. $annots .= ' /SW /'.$pl['opt']['mk']['if']['sw'];
  8222. }
  8223. $if_s = array('A', 'P');
  8224. if (isset($pl['opt']['mk']['if']['s']) AND in_array($pl['opt']['mk']['if']['s'], $if_s)) {
  8225. $annots .= ' /S /'.$pl['opt']['mk']['if']['s'];
  8226. }
  8227. if (isset($pl['opt']['mk']['if']['a']) AND (is_array($pl['opt']['mk']['if']['a'])) AND !empty($pl['opt']['mk']['if']['a'])) {
  8228. $annots .= sprintf(' /A [%F %F]', $pl['opt']['mk']['if']['a'][0], $pl['opt']['mk']['if']['a'][1]);
  8229. }
  8230. if (isset($pl['opt']['mk']['if']['fb']) AND ($pl['opt']['mk']['if']['fb'])) {
  8231. $annots .= ' /FB true';
  8232. }
  8233. $annots .= '>>';
  8234. }
  8235. if (isset($pl['opt']['mk']['tp']) AND ($pl['opt']['mk']['tp'] >= 0) AND ($pl['opt']['mk']['tp'] <= 6)) {
  8236. $annots .= ' /TP '.intval($pl['opt']['mk']['tp']);
  8237. }
  8238. $annots .= '>>';
  8239. } // end MK
  8240. // --- Entries for field dictionaries ---
  8241. if (isset($this->radiobutton_groups[$n][$pl['txt']])) {
  8242. // set parent
  8243. $annots .= ' /Parent '.$this->radiobutton_groups[$n][$pl['txt']].' 0 R';
  8244. }
  8245. if (isset($pl['opt']['t']) AND is_string($pl['opt']['t'])) {
  8246. $annots .= ' /T '.$this->_datastring($pl['opt']['t'], $annot_obj_id);
  8247. }
  8248. if (isset($pl['opt']['tu']) AND is_string($pl['opt']['tu'])) {
  8249. $annots .= ' /TU '.$this->_datastring($pl['opt']['tu'], $annot_obj_id);
  8250. }
  8251. if (isset($pl['opt']['tm']) AND is_string($pl['opt']['tm'])) {
  8252. $annots .= ' /TM '.$this->_datastring($pl['opt']['tm'], $annot_obj_id);
  8253. }
  8254. if (isset($pl['opt']['ff'])) {
  8255. if (is_array($pl['opt']['ff'])) {
  8256. // array of bit settings
  8257. $flag = 0;
  8258. foreach($pl['opt']['ff'] as $val) {
  8259. $flag += 1 << ($val - 1);
  8260. }
  8261. } else {
  8262. $flag = intval($pl['opt']['ff']);
  8263. }
  8264. $annots .= ' /Ff '.$flag;
  8265. }
  8266. if (isset($pl['opt']['maxlen'])) {
  8267. $annots .= ' /MaxLen '.intval($pl['opt']['maxlen']);
  8268. }
  8269. if (isset($pl['opt']['v'])) {
  8270. $annots .= ' /V';
  8271. if (is_array($pl['opt']['v'])) {
  8272. foreach ($pl['opt']['v'] AS $optval) {
  8273. if (is_float($optval)) {
  8274. $optval = sprintf('%F', $optval);
  8275. }
  8276. $annots .= ' '.$optval;
  8277. }
  8278. } else {
  8279. $annots .= ' '.$this->_textstring($pl['opt']['v'], $annot_obj_id);
  8280. }
  8281. }
  8282. if (isset($pl['opt']['dv'])) {
  8283. $annots .= ' /DV';
  8284. if (is_array($pl['opt']['dv'])) {
  8285. foreach ($pl['opt']['dv'] AS $optval) {
  8286. if (is_float($optval)) {
  8287. $optval = sprintf('%F', $optval);
  8288. }
  8289. $annots .= ' '.$optval;
  8290. }
  8291. } else {
  8292. $annots .= ' '.$this->_textstring($pl['opt']['dv'], $annot_obj_id);
  8293. }
  8294. }
  8295. if (isset($pl['opt']['rv'])) {
  8296. $annots .= ' /RV';
  8297. if (is_array($pl['opt']['rv'])) {
  8298. foreach ($pl['opt']['rv'] AS $optval) {
  8299. if (is_float($optval)) {
  8300. $optval = sprintf('%F', $optval);
  8301. }
  8302. $annots .= ' '.$optval;
  8303. }
  8304. } else {
  8305. $annots .= ' '.$this->_textstring($pl['opt']['rv'], $annot_obj_id);
  8306. }
  8307. }
  8308. if (isset($pl['opt']['a']) AND !empty($pl['opt']['a'])) {
  8309. $annots .= ' /A << '.$pl['opt']['a'].' >>';
  8310. }
  8311. if (isset($pl['opt']['aa']) AND !empty($pl['opt']['aa'])) {
  8312. $annots .= ' /AA << '.$pl['opt']['aa'].' >>';
  8313. }
  8314. if (isset($pl['opt']['da']) AND !empty($pl['opt']['da'])) {
  8315. $annots .= ' /DA ('.$pl['opt']['da'].')';
  8316. }
  8317. if (isset($pl['opt']['q']) AND ($pl['opt']['q'] >= 0) AND ($pl['opt']['q'] <= 2)) {
  8318. $annots .= ' /Q '.intval($pl['opt']['q']);
  8319. }
  8320. if (isset($pl['opt']['opt']) AND (is_array($pl['opt']['opt'])) AND !empty($pl['opt']['opt'])) {
  8321. $annots .= ' /Opt [';
  8322. foreach($pl['opt']['opt'] AS $copt) {
  8323. if (is_array($copt)) {
  8324. $annots .= ' ['.$this->_textstring($copt[0], $annot_obj_id).' '.$this->_textstring($copt[1], $annot_obj_id).']';
  8325. } else {
  8326. $annots .= ' '.$this->_textstring($copt, $annot_obj_id);
  8327. }
  8328. }
  8329. $annots .= ']';
  8330. }
  8331. if (isset($pl['opt']['ti'])) {
  8332. $annots .= ' /TI '.intval($pl['opt']['ti']);
  8333. }
  8334. if (isset($pl['opt']['i']) AND (is_array($pl['opt']['i'])) AND !empty($pl['opt']['i'])) {
  8335. $annots .= ' /I [';
  8336. foreach($pl['opt']['i'] AS $copt) {
  8337. $annots .= intval($copt).' ';
  8338. }
  8339. $annots .= ']';
  8340. }
  8341. break;
  8342. }
  8343. case 'screen': {
  8344. break;
  8345. }
  8346. case 'printermark': {
  8347. break;
  8348. }
  8349. case 'trapnet': {
  8350. break;
  8351. }
  8352. case 'watermark': {
  8353. break;
  8354. }
  8355. case '3d': {
  8356. break;
  8357. }
  8358. default: {
  8359. break;
  8360. }
  8361. }
  8362. $annots .= '>>';
  8363. // create new annotation object
  8364. $this->_out($this->_getobj($annot_obj_id)."\n".$annots."\n".'endobj');
  8365. if ($formfield AND !isset($this->radiobutton_groups[$n][$pl['txt']])) {
  8366. // store reference of form object
  8367. $this->form_obj_id[] = $annot_obj_id;
  8368. }
  8369. }
  8370. }
  8371. } // end for each page
  8372. }
  8373. /**
  8374. * Put appearance streams XObject used to define annotation's appearance states.
  8375. * @param $w (int) annotation width
  8376. * @param $h (int) annotation height
  8377. * @param $stream (string) appearance stream
  8378. * @return int object ID
  8379. * @protected
  8380. * @since 4.8.001 (2009-09-09)
  8381. */
  8382. protected function _putAPXObject($w=0, $h=0, $stream='') {
  8383. $stream = trim($stream);
  8384. $out = $this->_getobj()."\n";
  8385. $this->xobjects['AX'.$this->n] = array('n' => $this->n);
  8386. $out .= '<<';
  8387. $out .= ' /Type /XObject';
  8388. $out .= ' /Subtype /Form';
  8389. $out .= ' /FormType 1';
  8390. if ($this->compress) {
  8391. $stream = gzcompress($stream);
  8392. $out .= ' /Filter /FlateDecode';
  8393. }
  8394. $rect = sprintf('%F %F', $w, $h);
  8395. $out .= ' /BBox [0 0 '.$rect.']';
  8396. $out .= ' /Matrix [1 0 0 1 0 0]';
  8397. $out .= ' /Resources 2 0 R';
  8398. $stream = $this->_getrawstream($stream);
  8399. $out .= ' /Length '.strlen($stream);
  8400. $out .= ' >>';
  8401. $out .= ' stream'."\n".$stream."\n".'endstream';
  8402. $out .= "\n".'endobj';
  8403. $this->_out($out);
  8404. return $this->n;
  8405. }
  8406. /**
  8407. * Output fonts.
  8408. * @author Nicola Asuni
  8409. * @protected
  8410. */
  8411. protected function _putfonts() {
  8412. $nf = $this->n;
  8413. foreach ($this->diffs as $diff) {
  8414. //Encodings
  8415. $this->_newobj();
  8416. $this->_out('<< /Type /Encoding /BaseEncoding /WinAnsiEncoding /Differences ['.$diff.'] >>'."\n".'endobj');
  8417. }
  8418. $mqr = TCPDF_STATIC::get_mqr();
  8419. TCPDF_STATIC::set_mqr(false);
  8420. foreach ($this->FontFiles as $file => $info) {
  8421. // search and get font file to embedd
  8422. $fontfile = TCPDF_FONTS::getFontFullPath($file, $info['fontdir']);
  8423. if (!TCPDF_STATIC::empty_string($fontfile)) {
  8424. $font = file_get_contents($fontfile);
  8425. $compressed = (substr($file, -2) == '.z');
  8426. if ((!$compressed) AND (isset($info['length2']))) {
  8427. $header = (ord($font[0]) == 128);
  8428. if ($header) {
  8429. // strip first binary header
  8430. $font = substr($font, 6);
  8431. }
  8432. if ($header AND (ord($font[$info['length1']]) == 128)) {
  8433. // strip second binary header
  8434. $font = substr($font, 0, $info['length1']).substr($font, ($info['length1'] + 6));
  8435. }
  8436. } elseif ($info['subset'] AND ((!$compressed) OR ($compressed AND function_exists('gzcompress')))) {
  8437. if ($compressed) {
  8438. // uncompress font
  8439. $font = gzuncompress($font);
  8440. }
  8441. // merge subset characters
  8442. $subsetchars = array(); // used chars
  8443. foreach ($info['fontkeys'] as $fontkey) {
  8444. $fontinfo = $this->getFontBuffer($fontkey);
  8445. $subsetchars += $fontinfo['subsetchars'];
  8446. }
  8447. // rebuild a font subset
  8448. $font = TCPDF_FONTS::_getTrueTypeFontSubset($font, $subsetchars);
  8449. // calculate new font length
  8450. $info['length1'] = strlen($font);
  8451. if ($compressed) {
  8452. // recompress font
  8453. $font = gzcompress($font);
  8454. }
  8455. }
  8456. $this->_newobj();
  8457. $this->FontFiles[$file]['n'] = $this->n;
  8458. $stream = $this->_getrawstream($font);
  8459. $out = '<< /Length '.strlen($stream);
  8460. if ($compressed) {
  8461. $out .= ' /Filter /FlateDecode';
  8462. }
  8463. $out .= ' /Length1 '.$info['length1'];
  8464. if (isset($info['length2'])) {
  8465. $out .= ' /Length2 '.$info['length2'].' /Length3 0';
  8466. }
  8467. $out .= ' >>';
  8468. $out .= ' stream'."\n".$stream."\n".'endstream';
  8469. $out .= "\n".'endobj';
  8470. $this->_out($out);
  8471. }
  8472. }
  8473. TCPDF_STATIC::set_mqr($mqr);
  8474. foreach ($this->fontkeys as $k) {
  8475. //Font objects
  8476. $font = $this->getFontBuffer($k);
  8477. $type = $font['type'];
  8478. $name = $font['name'];
  8479. if ($type == 'core') {
  8480. // standard core font
  8481. $out = $this->_getobj($this->font_obj_ids[$k])."\n";
  8482. $out .= '<</Type /Font';
  8483. $out .= ' /Subtype /Type1';
  8484. $out .= ' /BaseFont /'.$name;
  8485. $out .= ' /Name /F'.$font['i'];
  8486. if ((strtolower($name) != 'symbol') AND (strtolower($name) != 'zapfdingbats')) {
  8487. $out .= ' /Encoding /WinAnsiEncoding';
  8488. }
  8489. if ($k == 'helvetica') {
  8490. // add default font for annotations
  8491. $this->annotation_fonts[$k] = $font['i'];
  8492. }
  8493. $out .= ' >>';
  8494. $out .= "\n".'endobj';
  8495. $this->_out($out);
  8496. } elseif (($type == 'Type1') OR ($type == 'TrueType')) {
  8497. // additional Type1 or TrueType font
  8498. $out = $this->_getobj($this->font_obj_ids[$k])."\n";
  8499. $out .= '<</Type /Font';
  8500. $out .= ' /Subtype /'.$type;
  8501. $out .= ' /BaseFont /'.$name;
  8502. $out .= ' /Name /F'.$font['i'];
  8503. $out .= ' /FirstChar 32 /LastChar 255';
  8504. $out .= ' /Widths '.($this->n + 1).' 0 R';
  8505. $out .= ' /FontDescriptor '.($this->n + 2).' 0 R';
  8506. if ($font['enc']) {
  8507. if (isset($font['diff'])) {
  8508. $out .= ' /Encoding '.($nf + $font['diff']).' 0 R';
  8509. } else {
  8510. $out .= ' /Encoding /WinAnsiEncoding';
  8511. }
  8512. }
  8513. $out .= ' >>';
  8514. $out .= "\n".'endobj';
  8515. $this->_out($out);
  8516. // Widths
  8517. $this->_newobj();
  8518. $s = '[';
  8519. for ($i = 32; $i < 256; ++$i) {
  8520. if (isset($font['cw'][$i])) {
  8521. $s .= $font['cw'][$i].' ';
  8522. } else {
  8523. $s .= $font['dw'].' ';
  8524. }
  8525. }
  8526. $s .= ']';
  8527. $s .= "\n".'endobj';
  8528. $this->_out($s);
  8529. //Descriptor
  8530. $this->_newobj();
  8531. $s = '<</Type /FontDescriptor /FontName /'.$name;
  8532. foreach ($font['desc'] as $fdk => $fdv) {
  8533. if (is_float($fdv)) {
  8534. $fdv = sprintf('%F', $fdv);
  8535. }
  8536. $s .= ' /'.$fdk.' '.$fdv.'';
  8537. }
  8538. if (!TCPDF_STATIC::empty_string($font['file'])) {
  8539. $s .= ' /FontFile'.($type == 'Type1' ? '' : '2').' '.$this->FontFiles[$font['file']]['n'].' 0 R';
  8540. }
  8541. $s .= '>>';
  8542. $s .= "\n".'endobj';
  8543. $this->_out($s);
  8544. } else {
  8545. // additional types
  8546. $mtd = '_put'.strtolower($type);
  8547. if (!method_exists($this, $mtd)) {
  8548. $this->Error('Unsupported font type: '.$type);
  8549. }
  8550. $this->$mtd($font);
  8551. }
  8552. }
  8553. }
  8554. /**
  8555. * Adds unicode fonts.<br>
  8556. * Based on PDF Reference 1.3 (section 5)
  8557. * @param $font (array) font data
  8558. * @protected
  8559. * @author Nicola Asuni
  8560. * @since 1.52.0.TC005 (2005-01-05)
  8561. */
  8562. protected function _puttruetypeunicode($font) {
  8563. $fontname = '';
  8564. if ($font['subset']) {
  8565. // change name for font subsetting
  8566. $subtag = sprintf('%06u', $font['i']);
  8567. $subtag = strtr($subtag, '0123456789', 'ABCDEFGHIJ');
  8568. $fontname .= $subtag.'+';
  8569. }
  8570. $fontname .= $font['name'];
  8571. // Type0 Font
  8572. // A composite font composed of other fonts, organized hierarchically
  8573. $out = $this->_getobj($this->font_obj_ids[$font['fontkey']])."\n";
  8574. $out .= '<< /Type /Font';
  8575. $out .= ' /Subtype /Type0';
  8576. $out .= ' /BaseFont /'.$fontname;
  8577. $out .= ' /Name /F'.$font['i'];
  8578. $out .= ' /Encoding /'.$font['enc'];
  8579. $out .= ' /ToUnicode '.($this->n + 1).' 0 R';
  8580. $out .= ' /DescendantFonts ['.($this->n + 2).' 0 R]';
  8581. $out .= ' >>';
  8582. $out .= "\n".'endobj';
  8583. $this->_out($out);
  8584. // ToUnicode map for Identity-H
  8585. $stream = TCPDF_FONT_DATA::$uni_identity_h;
  8586. // ToUnicode Object
  8587. $this->_newobj();
  8588. $stream = ($this->compress) ? gzcompress($stream) : $stream;
  8589. $filter = ($this->compress) ? '/Filter /FlateDecode ' : '';
  8590. $stream = $this->_getrawstream($stream);
  8591. $this->_out('<<'.$filter.'/Length '.strlen($stream).'>> stream'."\n".$stream."\n".'endstream'."\n".'endobj');
  8592. // CIDFontType2
  8593. // A CIDFont whose glyph descriptions are based on TrueType font technology
  8594. $oid = $this->_newobj();
  8595. $out = '<< /Type /Font';
  8596. $out .= ' /Subtype /CIDFontType2';
  8597. $out .= ' /BaseFont /'.$fontname;
  8598. // A dictionary containing entries that define the character collection of the CIDFont.
  8599. $cidinfo = '/Registry '.$this->_datastring($font['cidinfo']['Registry'], $oid);
  8600. $cidinfo .= ' /Ordering '.$this->_datastring($font['cidinfo']['Ordering'], $oid);
  8601. $cidinfo .= ' /Supplement '.$font['cidinfo']['Supplement'];
  8602. $out .= ' /CIDSystemInfo << '.$cidinfo.' >>';
  8603. $out .= ' /FontDescriptor '.($this->n + 1).' 0 R';
  8604. $out .= ' /DW '.$font['dw']; // default width
  8605. $out .= "\n".TCPDF_FONTS::_putfontwidths($font, 0);
  8606. if (isset($font['ctg']) AND (!TCPDF_STATIC::empty_string($font['ctg']))) {
  8607. $out .= "\n".'/CIDToGIDMap '.($this->n + 2).' 0 R';
  8608. }
  8609. $out .= ' >>';
  8610. $out .= "\n".'endobj';
  8611. $this->_out($out);
  8612. // Font descriptor
  8613. // A font descriptor describing the CIDFont default metrics other than its glyph widths
  8614. $this->_newobj();
  8615. $out = '<< /Type /FontDescriptor';
  8616. $out .= ' /FontName /'.$fontname;
  8617. foreach ($font['desc'] as $key => $value) {
  8618. if (is_float($value)) {
  8619. $value = sprintf('%F', $value);
  8620. }
  8621. $out .= ' /'.$key.' '.$value;
  8622. }
  8623. $fontdir = false;
  8624. if (!TCPDF_STATIC::empty_string($font['file'])) {
  8625. // A stream containing a TrueType font
  8626. $out .= ' /FontFile2 '.$this->FontFiles[$font['file']]['n'].' 0 R';
  8627. $fontdir = $this->FontFiles[$font['file']]['fontdir'];
  8628. }
  8629. $out .= ' >>';
  8630. $out .= "\n".'endobj';
  8631. $this->_out($out);
  8632. if (isset($font['ctg']) AND (!TCPDF_STATIC::empty_string($font['ctg']))) {
  8633. $this->_newobj();
  8634. // Embed CIDToGIDMap
  8635. // A specification of the mapping from CIDs to glyph indices
  8636. // search and get CTG font file to embedd
  8637. $ctgfile = strtolower($font['ctg']);
  8638. // search and get ctg font file to embedd
  8639. $fontfile = TCPDF_FONTS::getFontFullPath($ctgfile, $fontdir);
  8640. if (TCPDF_STATIC::empty_string($fontfile)) {
  8641. $this->Error('Font file not found: '.$ctgfile);
  8642. }
  8643. $stream = $this->_getrawstream(file_get_contents($fontfile));
  8644. $out = '<< /Length '.strlen($stream).'';
  8645. if (substr($fontfile, -2) == '.z') { // check file extension
  8646. // Decompresses data encoded using the public-domain
  8647. // zlib/deflate compression method, reproducing the
  8648. // original text or binary data
  8649. $out .= ' /Filter /FlateDecode';
  8650. }
  8651. $out .= ' >>';
  8652. $out .= ' stream'."\n".$stream."\n".'endstream';
  8653. $out .= "\n".'endobj';
  8654. $this->_out($out);
  8655. }
  8656. }
  8657. /**
  8658. * Output CID-0 fonts.
  8659. * A Type 0 CIDFont contains glyph descriptions based on the Adobe Type 1 font format
  8660. * @param $font (array) font data
  8661. * @protected
  8662. * @author Andrew Whitehead, Nicola Asuni, Yukihiro Nakadaira
  8663. * @since 3.2.000 (2008-06-23)
  8664. */
  8665. protected function _putcidfont0($font) {
  8666. $cidoffset = 0;
  8667. if (!isset($font['cw'][1])) {
  8668. $cidoffset = 31;
  8669. }
  8670. if (isset($font['cidinfo']['uni2cid'])) {
  8671. // convert unicode to cid.
  8672. $uni2cid = $font['cidinfo']['uni2cid'];
  8673. $cw = array();
  8674. foreach ($font['cw'] as $uni => $width) {
  8675. if (isset($uni2cid[$uni])) {
  8676. $cw[($uni2cid[$uni] + $cidoffset)] = $width;
  8677. } elseif ($uni < 256) {
  8678. $cw[$uni] = $width;
  8679. } // else unknown character
  8680. }
  8681. $font = array_merge($font, array('cw' => $cw));
  8682. }
  8683. $name = $font['name'];
  8684. $enc = $font['enc'];
  8685. if ($enc) {
  8686. $longname = $name.'-'.$enc;
  8687. } else {
  8688. $longname = $name;
  8689. }
  8690. $out = $this->_getobj($this->font_obj_ids[$font['fontkey']])."\n";
  8691. $out .= '<</Type /Font';
  8692. $out .= ' /Subtype /Type0';
  8693. $out .= ' /BaseFont /'.$longname;
  8694. $out .= ' /Name /F'.$font['i'];
  8695. if ($enc) {
  8696. $out .= ' /Encoding /'.$enc;
  8697. }
  8698. $out .= ' /DescendantFonts ['.($this->n + 1).' 0 R]';
  8699. $out .= ' >>';
  8700. $out .= "\n".'endobj';
  8701. $this->_out($out);
  8702. $oid = $this->_newobj();
  8703. $out = '<</Type /Font';
  8704. $out .= ' /Subtype /CIDFontType0';
  8705. $out .= ' /BaseFont /'.$name;
  8706. $cidinfo = '/Registry '.$this->_datastring($font['cidinfo']['Registry'], $oid);
  8707. $cidinfo .= ' /Ordering '.$this->_datastring($font['cidinfo']['Ordering'], $oid);
  8708. $cidinfo .= ' /Supplement '.$font['cidinfo']['Supplement'];
  8709. $out .= ' /CIDSystemInfo <<'.$cidinfo.'>>';
  8710. $out .= ' /FontDescriptor '.($this->n + 1).' 0 R';
  8711. $out .= ' /DW '.$font['dw'];
  8712. $out .= "\n".TCPDF_FONTS::_putfontwidths($font, $cidoffset);
  8713. $out .= ' >>';
  8714. $out .= "\n".'endobj';
  8715. $this->_out($out);
  8716. $this->_newobj();
  8717. $s = '<</Type /FontDescriptor /FontName /'.$name;
  8718. foreach ($font['desc'] as $k => $v) {
  8719. if ($k != 'Style') {
  8720. if (is_float($v)) {
  8721. $v = sprintf('%F', $v);
  8722. }
  8723. $s .= ' /'.$k.' '.$v.'';
  8724. }
  8725. }
  8726. $s .= '>>';
  8727. $s .= "\n".'endobj';
  8728. $this->_out($s);
  8729. }
  8730. /**
  8731. * Output images.
  8732. * @protected
  8733. */
  8734. protected function _putimages() {
  8735. $filter = ($this->compress) ? '/Filter /FlateDecode ' : '';
  8736. foreach ($this->imagekeys as $file) {
  8737. $info = $this->getImageBuffer($file);
  8738. // set object for alternate images array
  8739. if ((!$this->pdfa_mode) AND isset($info['altimgs']) AND !empty($info['altimgs'])) {
  8740. $altoid = $this->_newobj();
  8741. $out = '[';
  8742. foreach ($info['altimgs'] as $altimage) {
  8743. if (isset($this->xobjects['I'.$altimage[0]]['n'])) {
  8744. $out .= ' << /Image '.$this->xobjects['I'.$altimage[0]]['n'].' 0 R';
  8745. $out .= ' /DefaultForPrinting';
  8746. if ($altimage[1] === true) {
  8747. $out .= ' true';
  8748. } else {
  8749. $out .= ' false';
  8750. }
  8751. $out .= ' >>';
  8752. }
  8753. }
  8754. $out .= ' ]';
  8755. $out .= "\n".'endobj';
  8756. $this->_out($out);
  8757. }
  8758. // set image object
  8759. $oid = $this->_newobj();
  8760. $this->xobjects['I'.$info['i']] = array('n' => $oid);
  8761. $this->setImageSubBuffer($file, 'n', $this->n);
  8762. $out = '<</Type /XObject';
  8763. $out .= ' /Subtype /Image';
  8764. $out .= ' /Width '.$info['w'];
  8765. $out .= ' /Height '.$info['h'];
  8766. if (array_key_exists('masked', $info)) {
  8767. $out .= ' /SMask '.($this->n - 1).' 0 R';
  8768. }
  8769. // set color space
  8770. $icc = false;
  8771. if (isset($info['icc']) AND ($info['icc'] !== false)) {
  8772. // ICC Colour Space
  8773. $icc = true;
  8774. $out .= ' /ColorSpace [/ICCBased '.($this->n + 1).' 0 R]';
  8775. } elseif ($info['cs'] == 'Indexed') {
  8776. // Indexed Colour Space
  8777. $out .= ' /ColorSpace [/Indexed /DeviceRGB '.((strlen($info['pal']) / 3) - 1).' '.($this->n + 1).' 0 R]';
  8778. } else {
  8779. // Device Colour Space
  8780. $out .= ' /ColorSpace /'.$info['cs'];
  8781. }
  8782. if ($info['cs'] == 'DeviceCMYK') {
  8783. $out .= ' /Decode [1 0 1 0 1 0 1 0]';
  8784. }
  8785. $out .= ' /BitsPerComponent '.$info['bpc'];
  8786. if (isset($altoid) AND ($altoid > 0)) {
  8787. // reference to alternate images dictionary
  8788. $out .= ' /Alternates '.$altoid.' 0 R';
  8789. }
  8790. if (isset($info['exurl']) AND !empty($info['exurl'])) {
  8791. // external stream
  8792. $out .= ' /Length 0';
  8793. $out .= ' /F << /FS /URL /F '.$this->_datastring($info['exurl'], $oid).' >>';
  8794. if (isset($info['f'])) {
  8795. $out .= ' /FFilter /'.$info['f'];
  8796. }
  8797. $out .= ' >>';
  8798. $out .= ' stream'."\n".'endstream';
  8799. } else {
  8800. if (isset($info['f'])) {
  8801. $out .= ' /Filter /'.$info['f'];
  8802. }
  8803. if (isset($info['parms'])) {
  8804. $out .= ' '.$info['parms'];
  8805. }
  8806. if (isset($info['trns']) AND is_array($info['trns'])) {
  8807. $trns = '';
  8808. $count_info = count($info['trns']);
  8809. if ($info['cs'] == 'Indexed') {
  8810. $maxval =(pow(2, $info['bpc']) - 1);
  8811. for ($i = 0; $i < $count_info; ++$i) {
  8812. if (($info['trns'][$i] != 0) AND ($info['trns'][$i] != $maxval)) {
  8813. // this is not a binary type mask @TODO: create a SMask
  8814. $trns = '';
  8815. break;
  8816. } elseif (empty($trns) AND ($info['trns'][$i] == 0)) {
  8817. // store the first fully transparent value
  8818. $trns .= $i.' '.$i.' ';
  8819. }
  8820. }
  8821. } else {
  8822. // grayscale or RGB
  8823. for ($i = 0; $i < $count_info; ++$i) {
  8824. if ($info['trns'][$i] == 0) {
  8825. $trns .= $info['trns'][$i].' '.$info['trns'][$i].' ';
  8826. }
  8827. }
  8828. }
  8829. // Colour Key Masking
  8830. if (!empty($trns)) {
  8831. $out .= ' /Mask ['.$trns.']';
  8832. }
  8833. }
  8834. $stream = $this->_getrawstream($info['data']);
  8835. $out .= ' /Length '.strlen($stream).' >>';
  8836. $out .= ' stream'."\n".$stream."\n".'endstream';
  8837. }
  8838. $out .= "\n".'endobj';
  8839. $this->_out($out);
  8840. if ($icc) {
  8841. // ICC colour profile
  8842. $this->_newobj();
  8843. $icc = ($this->compress) ? gzcompress($info['icc']) : $info['icc'];
  8844. $icc = $this->_getrawstream($icc);
  8845. $this->_out('<</N '.$info['ch'].' /Alternate /'.$info['cs'].' '.$filter.'/Length '.strlen($icc).'>> stream'."\n".$icc."\n".'endstream'."\n".'endobj');
  8846. } elseif ($info['cs'] == 'Indexed') {
  8847. // colour palette
  8848. $this->_newobj();
  8849. $pal = ($this->compress) ? gzcompress($info['pal']) : $info['pal'];
  8850. $pal = $this->_getrawstream($pal);
  8851. $this->_out('<<'.$filter.'/Length '.strlen($pal).'>> stream'."\n".$pal."\n".'endstream'."\n".'endobj');
  8852. }
  8853. }
  8854. }
  8855. /**
  8856. * Output Form XObjects Templates.
  8857. * @author Nicola Asuni
  8858. * @since 5.8.017 (2010-08-24)
  8859. * @protected
  8860. * @see startTemplate(), endTemplate(), printTemplate()
  8861. */
  8862. protected function _putxobjects() {
  8863. foreach ($this->xobjects as $key => $data) {
  8864. if (isset($data['outdata'])) {
  8865. $stream = str_replace($this->epsmarker, '', trim($data['outdata']));
  8866. $out = $this->_getobj($data['n'])."\n";
  8867. $out .= '<<';
  8868. $out .= ' /Type /XObject';
  8869. $out .= ' /Subtype /Form';
  8870. $out .= ' /FormType 1';
  8871. if ($this->compress) {
  8872. $stream = gzcompress($stream);
  8873. $out .= ' /Filter /FlateDecode';
  8874. }
  8875. $out .= sprintf(' /BBox [%F %F %F %F]', ($data['x'] * $this->k), (-$data['y'] * $this->k), (($data['w'] + $data['x']) * $this->k), (($data['h'] - $data['y']) * $this->k));
  8876. $out .= ' /Matrix [1 0 0 1 0 0]';
  8877. $out .= ' /Resources <<';
  8878. $out .= ' /ProcSet [/PDF /Text /ImageB /ImageC /ImageI]';
  8879. if (!$this->pdfa_mode) {
  8880. // transparency
  8881. if (isset($data['extgstates']) AND !empty($data['extgstates'])) {
  8882. $out .= ' /ExtGState <<';
  8883. foreach ($data['extgstates'] as $k => $extgstate) {
  8884. if (isset($this->extgstates[$k]['name'])) {
  8885. $out .= ' /'.$this->extgstates[$k]['name'];
  8886. } else {
  8887. $out .= ' /GS'.$k;
  8888. }
  8889. $out .= ' '.$this->extgstates[$k]['n'].' 0 R';
  8890. }
  8891. $out .= ' >>';
  8892. }
  8893. if (isset($data['gradients']) AND !empty($data['gradients'])) {
  8894. $gp = '';
  8895. $gs = '';
  8896. foreach ($data['gradients'] as $id => $grad) {
  8897. // gradient patterns
  8898. $gp .= ' /p'.$id.' '.$this->gradients[$id]['pattern'].' 0 R';
  8899. // gradient shadings
  8900. $gs .= ' /Sh'.$id.' '.$this->gradients[$id]['id'].' 0 R';
  8901. }
  8902. $out .= ' /Pattern <<'.$gp.' >>';
  8903. $out .= ' /Shading <<'.$gs.' >>';
  8904. }
  8905. }
  8906. // spot colors
  8907. if (isset($data['spot_colors']) AND !empty($data['spot_colors'])) {
  8908. $out .= ' /ColorSpace <<';
  8909. foreach ($data['spot_colors'] as $name => $color) {
  8910. $out .= ' /CS'.$color['i'].' '.$this->spot_colors[$name]['n'].' 0 R';
  8911. }
  8912. $out .= ' >>';
  8913. }
  8914. // fonts
  8915. if (!empty($data['fonts'])) {
  8916. $out .= ' /Font <<';
  8917. foreach ($data['fonts'] as $fontkey => $fontid) {
  8918. $out .= ' /F'.$fontid.' '.$this->font_obj_ids[$fontkey].' 0 R';
  8919. }
  8920. $out .= ' >>';
  8921. }
  8922. // images or nested xobjects
  8923. if (!empty($data['images']) OR !empty($data['xobjects'])) {
  8924. $out .= ' /XObject <<';
  8925. foreach ($data['images'] as $imgid) {
  8926. $out .= ' /I'.$imgid.' '.$this->xobjects['I'.$imgid]['n'].' 0 R';
  8927. }
  8928. foreach ($data['xobjects'] as $sub_id => $sub_objid) {
  8929. $out .= ' /'.$sub_id.' '.$sub_objid['n'].' 0 R';
  8930. }
  8931. $out .= ' >>';
  8932. }
  8933. $out .= ' >>'; //end resources
  8934. if (isset($data['group']) AND ($data['group'] !== false)) {
  8935. // set transparency group
  8936. $out .= ' /Group << /Type /Group /S /Transparency';
  8937. if (is_array($data['group'])) {
  8938. if (isset($data['group']['CS']) AND !empty($data['group']['CS'])) {
  8939. $out .= ' /CS /'.$data['group']['CS'];
  8940. }
  8941. if (isset($data['group']['I'])) {
  8942. $out .= ' /I /'.($data['group']['I']===true?'true':'false');
  8943. }
  8944. if (isset($data['group']['K'])) {
  8945. $out .= ' /K /'.($data['group']['K']===true?'true':'false');
  8946. }
  8947. }
  8948. $out .= ' >>';
  8949. }
  8950. $stream = $this->_getrawstream($stream, $data['n']);
  8951. $out .= ' /Length '.strlen($stream);
  8952. $out .= ' >>';
  8953. $out .= ' stream'."\n".$stream."\n".'endstream';
  8954. $out .= "\n".'endobj';
  8955. $this->_out($out);
  8956. }
  8957. }
  8958. }
  8959. /**
  8960. * Output Spot Colors Resources.
  8961. * @protected
  8962. * @since 4.0.024 (2008-09-12)
  8963. */
  8964. protected function _putspotcolors() {
  8965. foreach ($this->spot_colors as $name => $color) {
  8966. $this->_newobj();
  8967. $this->spot_colors[$name]['n'] = $this->n;
  8968. $out = '[/Separation /'.str_replace(' ', '#20', $name);
  8969. $out .= ' /DeviceCMYK <<';
  8970. $out .= ' /Range [0 1 0 1 0 1 0 1] /C0 [0 0 0 0]';
  8971. $out .= ' '.sprintf('/C1 [%F %F %F %F] ', ($color['C'] / 100), ($color['M'] / 100), ($color['Y'] / 100), ($color['K'] / 100));
  8972. $out .= ' /FunctionType 2 /Domain [0 1] /N 1>>]';
  8973. $out .= "\n".'endobj';
  8974. $this->_out($out);
  8975. }
  8976. }
  8977. /**
  8978. * Return XObjects Dictionary.
  8979. * @return string XObjects dictionary
  8980. * @protected
  8981. * @since 5.8.014 (2010-08-23)
  8982. */
  8983. protected function _getxobjectdict() {
  8984. $out = '';
  8985. foreach ($this->xobjects as $id => $objid) {
  8986. $out .= ' /'.$id.' '.$objid['n'].' 0 R';
  8987. }
  8988. return $out;
  8989. }
  8990. /**
  8991. * Output Resources Dictionary.
  8992. * @protected
  8993. */
  8994. protected function _putresourcedict() {
  8995. $out = $this->_getobj(2)."\n";
  8996. $out .= '<< /ProcSet [/PDF /Text /ImageB /ImageC /ImageI]';
  8997. $out .= ' /Font <<';
  8998. foreach ($this->fontkeys as $fontkey) {
  8999. $font = $this->getFontBuffer($fontkey);
  9000. $out .= ' /F'.$font['i'].' '.$font['n'].' 0 R';
  9001. }
  9002. $out .= ' >>';
  9003. $out .= ' /XObject <<';
  9004. $out .= $this->_getxobjectdict();
  9005. $out .= ' >>';
  9006. // layers
  9007. if (!empty($this->pdflayers)) {
  9008. $out .= ' /Properties <<';
  9009. foreach ($this->pdflayers as $layer) {
  9010. $out .= ' /'.$layer['layer'].' '.$layer['objid'].' 0 R';
  9011. }
  9012. $out .= ' >>';
  9013. }
  9014. if (!$this->pdfa_mode) {
  9015. // transparency
  9016. if (isset($this->extgstates) AND !empty($this->extgstates)) {
  9017. $out .= ' /ExtGState <<';
  9018. foreach ($this->extgstates as $k => $extgstate) {
  9019. if (isset($extgstate['name'])) {
  9020. $out .= ' /'.$extgstate['name'];
  9021. } else {
  9022. $out .= ' /GS'.$k;
  9023. }
  9024. $out .= ' '.$extgstate['n'].' 0 R';
  9025. }
  9026. $out .= ' >>';
  9027. }
  9028. if (isset($this->gradients) AND !empty($this->gradients)) {
  9029. $gp = '';
  9030. $gs = '';
  9031. foreach ($this->gradients as $id => $grad) {
  9032. // gradient patterns
  9033. $gp .= ' /p'.$id.' '.$grad['pattern'].' 0 R';
  9034. // gradient shadings
  9035. $gs .= ' /Sh'.$id.' '.$grad['id'].' 0 R';
  9036. }
  9037. $out .= ' /Pattern <<'.$gp.' >>';
  9038. $out .= ' /Shading <<'.$gs.' >>';
  9039. }
  9040. }
  9041. // spot colors
  9042. if (isset($this->spot_colors) AND !empty($this->spot_colors)) {
  9043. $out .= ' /ColorSpace <<';
  9044. foreach ($this->spot_colors as $color) {
  9045. $out .= ' /CS'.$color['i'].' '.$color['n'].' 0 R';
  9046. }
  9047. $out .= ' >>';
  9048. }
  9049. $out .= ' >>';
  9050. $out .= "\n".'endobj';
  9051. $this->_out($out);
  9052. }
  9053. /**
  9054. * Output Resources.
  9055. * @protected
  9056. */
  9057. protected function _putresources() {
  9058. $this->_putextgstates();
  9059. $this->_putocg();
  9060. $this->_putfonts();
  9061. $this->_putimages();
  9062. $this->_putspotcolors();
  9063. $this->_putshaders();
  9064. $this->_putxobjects();
  9065. $this->_putresourcedict();
  9066. $this->_putdests();
  9067. $this->_putEmbeddedFiles();
  9068. $this->_putannotsobjs();
  9069. $this->_putjavascript();
  9070. $this->_putbookmarks();
  9071. $this->_putencryption();
  9072. }
  9073. /**
  9074. * Adds some Metadata information (Document Information Dictionary)
  9075. * (see Chapter 14.3.3 Document Information Dictionary of PDF32000_2008.pdf Reference)
  9076. * @return int object id
  9077. * @protected
  9078. */
  9079. protected function _putinfo() {
  9080. $oid = $this->_newobj();
  9081. $out = '<<';
  9082. // store current isunicode value
  9083. $prev_isunicode = $this->isunicode;
  9084. if ($this->docinfounicode) {
  9085. $this->isunicode = true;
  9086. }
  9087. if (!TCPDF_STATIC::empty_string($this->title)) {
  9088. // The document's title.
  9089. $out .= ' /Title '.$this->_textstring($this->title, $oid);
  9090. }
  9091. if (!TCPDF_STATIC::empty_string($this->author)) {
  9092. // The name of the person who created the document.
  9093. $out .= ' /Author '.$this->_textstring($this->author, $oid);
  9094. }
  9095. if (!TCPDF_STATIC::empty_string($this->subject)) {
  9096. // The subject of the document.
  9097. $out .= ' /Subject '.$this->_textstring($this->subject, $oid);
  9098. }
  9099. if (!TCPDF_STATIC::empty_string($this->keywords)) {
  9100. // Keywords associated with the document.
  9101. $out .= ' /Keywords '.$this->_textstring($this->keywords, $oid);
  9102. }
  9103. if (!TCPDF_STATIC::empty_string($this->creator)) {
  9104. // 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.
  9105. $out .= ' /Creator '.$this->_textstring($this->creator, $oid);
  9106. }
  9107. // restore previous isunicode value
  9108. $this->isunicode = $prev_isunicode;
  9109. // default producer
  9110. $out .= ' /Producer '.$this->_textstring(TCPDF_STATIC::getTCPDFProducer(), $oid);
  9111. // The date and time the document was created, in human-readable form
  9112. $out .= ' /CreationDate '.$this->_datestring(0, $this->doc_creation_timestamp);
  9113. // The date and time the document was most recently modified, in human-readable form
  9114. $out .= ' /ModDate '.$this->_datestring(0, $this->doc_modification_timestamp);
  9115. // A name object indicating whether the document has been modified to include trapping information
  9116. $out .= ' /Trapped /False';
  9117. $out .= ' >>';
  9118. $out .= "\n".'endobj';
  9119. $this->_out($out);
  9120. return $oid;
  9121. }
  9122. /**
  9123. * Set additional XMP data to be added on the default XMP data just before the end of "x:xmpmeta" tag.
  9124. * IMPORTANT: This data is added as-is without controls, so you have to validate your data before using this method!
  9125. * @param $xmp (string) Custom XMP data.
  9126. * @since 5.9.128 (2011-10-06)
  9127. * @public
  9128. */
  9129. public function setExtraXMP($xmp) {
  9130. $this->custom_xmp = $xmp;
  9131. }
  9132. /**
  9133. * Set additional XMP data to be added on the default XMP data just before the end of "rdf:RDF" tag.
  9134. * IMPORTANT: This data is added as-is without controls, so you have to validate your data before using this method!
  9135. * @param $xmp (string) Custom XMP RDF data.
  9136. * @since 6.3.0 (2019-09-19)
  9137. * @public
  9138. */
  9139. public function setExtraXMPRDF($xmp) {
  9140. $this->custom_xmp_rdf = $xmp;
  9141. }
  9142. /**
  9143. * Put XMP data object and return ID.
  9144. * @return (int) The object ID.
  9145. * @since 5.9.121 (2011-09-28)
  9146. * @protected
  9147. */
  9148. protected function _putXMP() {
  9149. $oid = $this->_newobj();
  9150. // store current isunicode value
  9151. $prev_isunicode = $this->isunicode;
  9152. $this->isunicode = true;
  9153. $prev_encrypted = $this->encrypted;
  9154. $this->encrypted = false;
  9155. // set XMP data
  9156. $xmp = '<?xpacket begin="'.TCPDF_FONTS::unichr(0xfeff, $this->isunicode).'" id="W5M0MpCehiHzreSzNTczkc9d"?>'."\n";
  9157. $xmp .= '<x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="Adobe XMP Core 4.2.1-c043 52.372728, 2009/01/18-15:08:04">'."\n";
  9158. $xmp .= "\t".'<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">'."\n";
  9159. $xmp .= "\t\t".'<rdf:Description rdf:about="" xmlns:dc="http://purl.org/dc/elements/1.1/">'."\n";
  9160. $xmp .= "\t\t\t".'<dc:format>application/pdf</dc:format>'."\n";
  9161. $xmp .= "\t\t\t".'<dc:title>'."\n";
  9162. $xmp .= "\t\t\t\t".'<rdf:Alt>'."\n";
  9163. $xmp .= "\t\t\t\t\t".'<rdf:li xml:lang="x-default">'.TCPDF_STATIC::_escapeXML($this->title).'</rdf:li>'."\n";
  9164. $xmp .= "\t\t\t\t".'</rdf:Alt>'."\n";
  9165. $xmp .= "\t\t\t".'</dc:title>'."\n";
  9166. $xmp .= "\t\t\t".'<dc:creator>'."\n";
  9167. $xmp .= "\t\t\t\t".'<rdf:Seq>'."\n";
  9168. $xmp .= "\t\t\t\t\t".'<rdf:li>'.TCPDF_STATIC::_escapeXML($this->author).'</rdf:li>'."\n";
  9169. $xmp .= "\t\t\t\t".'</rdf:Seq>'."\n";
  9170. $xmp .= "\t\t\t".'</dc:creator>'."\n";
  9171. $xmp .= "\t\t\t".'<dc:description>'."\n";
  9172. $xmp .= "\t\t\t\t".'<rdf:Alt>'."\n";
  9173. $xmp .= "\t\t\t\t\t".'<rdf:li xml:lang="x-default">'.TCPDF_STATIC::_escapeXML($this->subject).'</rdf:li>'."\n";
  9174. $xmp .= "\t\t\t\t".'</rdf:Alt>'."\n";
  9175. $xmp .= "\t\t\t".'</dc:description>'."\n";
  9176. $xmp .= "\t\t\t".'<dc:subject>'."\n";
  9177. $xmp .= "\t\t\t\t".'<rdf:Bag>'."\n";
  9178. $xmp .= "\t\t\t\t\t".'<rdf:li>'.TCPDF_STATIC::_escapeXML($this->keywords).'</rdf:li>'."\n";
  9179. $xmp .= "\t\t\t\t".'</rdf:Bag>'."\n";
  9180. $xmp .= "\t\t\t".'</dc:subject>'."\n";
  9181. $xmp .= "\t\t".'</rdf:Description>'."\n";
  9182. // convert doc creation date format
  9183. $dcdate = TCPDF_STATIC::getFormattedDate($this->doc_creation_timestamp);
  9184. $doccreationdate = substr($dcdate, 0, 4).'-'.substr($dcdate, 4, 2).'-'.substr($dcdate, 6, 2);
  9185. $doccreationdate .= 'T'.substr($dcdate, 8, 2).':'.substr($dcdate, 10, 2).':'.substr($dcdate, 12, 2);
  9186. $doccreationdate .= substr($dcdate, 14, 3).':'.substr($dcdate, 18, 2);
  9187. $doccreationdate = TCPDF_STATIC::_escapeXML($doccreationdate);
  9188. // convert doc modification date format
  9189. $dmdate = TCPDF_STATIC::getFormattedDate($this->doc_modification_timestamp);
  9190. $docmoddate = substr($dmdate, 0, 4).'-'.substr($dmdate, 4, 2).'-'.substr($dmdate, 6, 2);
  9191. $docmoddate .= 'T'.substr($dmdate, 8, 2).':'.substr($dmdate, 10, 2).':'.substr($dmdate, 12, 2);
  9192. $docmoddate .= substr($dmdate, 14, 3).':'.substr($dmdate, 18, 2);
  9193. $docmoddate = TCPDF_STATIC::_escapeXML($docmoddate);
  9194. $xmp .= "\t\t".'<rdf:Description rdf:about="" xmlns:xmp="http://ns.adobe.com/xap/1.0/">'."\n";
  9195. $xmp .= "\t\t\t".'<xmp:CreateDate>'.$doccreationdate.'</xmp:CreateDate>'."\n";
  9196. $xmp .= "\t\t\t".'<xmp:CreatorTool>'.$this->creator.'</xmp:CreatorTool>'."\n";
  9197. $xmp .= "\t\t\t".'<xmp:ModifyDate>'.$docmoddate.'</xmp:ModifyDate>'."\n";
  9198. $xmp .= "\t\t\t".'<xmp:MetadataDate>'.$doccreationdate.'</xmp:MetadataDate>'."\n";
  9199. $xmp .= "\t\t".'</rdf:Description>'."\n";
  9200. $xmp .= "\t\t".'<rdf:Description rdf:about="" xmlns:pdf="http://ns.adobe.com/pdf/1.3/">'."\n";
  9201. $xmp .= "\t\t\t".'<pdf:Keywords>'.TCPDF_STATIC::_escapeXML($this->keywords).'</pdf:Keywords>'."\n";
  9202. $xmp .= "\t\t\t".'<pdf:Producer>'.TCPDF_STATIC::_escapeXML(TCPDF_STATIC::getTCPDFProducer()).'</pdf:Producer>'."\n";
  9203. $xmp .= "\t\t".'</rdf:Description>'."\n";
  9204. $xmp .= "\t\t".'<rdf:Description rdf:about="" xmlns:xmpMM="http://ns.adobe.com/xap/1.0/mm/">'."\n";
  9205. $uuid = 'uuid:'.substr($this->file_id, 0, 8).'-'.substr($this->file_id, 8, 4).'-'.substr($this->file_id, 12, 4).'-'.substr($this->file_id, 16, 4).'-'.substr($this->file_id, 20, 12);
  9206. $xmp .= "\t\t\t".'<xmpMM:DocumentID>'.$uuid.'</xmpMM:DocumentID>'."\n";
  9207. $xmp .= "\t\t\t".'<xmpMM:InstanceID>'.$uuid.'</xmpMM:InstanceID>'."\n";
  9208. $xmp .= "\t\t".'</rdf:Description>'."\n";
  9209. if ($this->pdfa_mode) {
  9210. $xmp .= "\t\t".'<rdf:Description rdf:about="" xmlns:pdfaid="http://www.aiim.org/pdfa/ns/id/">'."\n";
  9211. $xmp .= "\t\t\t".'<pdfaid:part>'.$this->pdfa_version.'</pdfaid:part>'."\n";
  9212. $xmp .= "\t\t\t".'<pdfaid:conformance>B</pdfaid:conformance>'."\n";
  9213. $xmp .= "\t\t".'</rdf:Description>'."\n";
  9214. }
  9215. // XMP extension schemas
  9216. $xmp .= "\t\t".'<rdf:Description rdf:about="" xmlns:pdfaExtension="http://www.aiim.org/pdfa/ns/extension/" xmlns:pdfaSchema="http://www.aiim.org/pdfa/ns/schema#" xmlns:pdfaProperty="http://www.aiim.org/pdfa/ns/property#">'."\n";
  9217. $xmp .= "\t\t\t".'<pdfaExtension:schemas>'."\n";
  9218. $xmp .= "\t\t\t\t".'<rdf:Bag>'."\n";
  9219. $xmp .= "\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
  9220. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:namespaceURI>http://ns.adobe.com/pdf/1.3/</pdfaSchema:namespaceURI>'."\n";
  9221. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:prefix>pdf</pdfaSchema:prefix>'."\n";
  9222. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:schema>Adobe PDF Schema</pdfaSchema:schema>'."\n";
  9223. $xmp .= "\t\t\t\t\t".'</rdf:li>'."\n";
  9224. $xmp .= "\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
  9225. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:namespaceURI>http://ns.adobe.com/xap/1.0/mm/</pdfaSchema:namespaceURI>'."\n";
  9226. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:prefix>xmpMM</pdfaSchema:prefix>'."\n";
  9227. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:schema>XMP Media Management Schema</pdfaSchema:schema>'."\n";
  9228. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:property>'."\n";
  9229. $xmp .= "\t\t\t\t\t\t\t".'<rdf:Seq>'."\n";
  9230. $xmp .= "\t\t\t\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
  9231. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:category>internal</pdfaProperty:category>'."\n";
  9232. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:description>UUID based identifier for specific incarnation of a document</pdfaProperty:description>'."\n";
  9233. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:name>InstanceID</pdfaProperty:name>'."\n";
  9234. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:valueType>URI</pdfaProperty:valueType>'."\n";
  9235. $xmp .= "\t\t\t\t\t\t\t\t".'</rdf:li>'."\n";
  9236. $xmp .= "\t\t\t\t\t\t\t".'</rdf:Seq>'."\n";
  9237. $xmp .= "\t\t\t\t\t\t".'</pdfaSchema:property>'."\n";
  9238. $xmp .= "\t\t\t\t\t".'</rdf:li>'."\n";
  9239. $xmp .= "\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
  9240. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:namespaceURI>http://www.aiim.org/pdfa/ns/id/</pdfaSchema:namespaceURI>'."\n";
  9241. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:prefix>pdfaid</pdfaSchema:prefix>'."\n";
  9242. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:schema>PDF/A ID Schema</pdfaSchema:schema>'."\n";
  9243. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:property>'."\n";
  9244. $xmp .= "\t\t\t\t\t\t\t".'<rdf:Seq>'."\n";
  9245. $xmp .= "\t\t\t\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
  9246. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:category>internal</pdfaProperty:category>'."\n";
  9247. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:description>Part of PDF/A standard</pdfaProperty:description>'."\n";
  9248. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:name>part</pdfaProperty:name>'."\n";
  9249. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:valueType>Integer</pdfaProperty:valueType>'."\n";
  9250. $xmp .= "\t\t\t\t\t\t\t\t".'</rdf:li>'."\n";
  9251. $xmp .= "\t\t\t\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
  9252. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:category>internal</pdfaProperty:category>'."\n";
  9253. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:description>Amendment of PDF/A standard</pdfaProperty:description>'."\n";
  9254. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:name>amd</pdfaProperty:name>'."\n";
  9255. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:valueType>Text</pdfaProperty:valueType>'."\n";
  9256. $xmp .= "\t\t\t\t\t\t\t\t".'</rdf:li>'."\n";
  9257. $xmp .= "\t\t\t\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
  9258. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:category>internal</pdfaProperty:category>'."\n";
  9259. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:description>Conformance level of PDF/A standard</pdfaProperty:description>'."\n";
  9260. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:name>conformance</pdfaProperty:name>'."\n";
  9261. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:valueType>Text</pdfaProperty:valueType>'."\n";
  9262. $xmp .= "\t\t\t\t\t\t\t\t".'</rdf:li>'."\n";
  9263. $xmp .= "\t\t\t\t\t\t\t".'</rdf:Seq>'."\n";
  9264. $xmp .= "\t\t\t\t\t\t".'</pdfaSchema:property>'."\n";
  9265. $xmp .= "\t\t\t\t\t".'</rdf:li>'."\n";
  9266. $xmp .= "\t\t\t\t".'</rdf:Bag>'."\n";
  9267. $xmp .= "\t\t\t".'</pdfaExtension:schemas>'."\n";
  9268. $xmp .= "\t\t".'</rdf:Description>'."\n";
  9269. $xmp .= $this->custom_xmp_rdf;
  9270. $xmp .= "\t".'</rdf:RDF>'."\n";
  9271. $xmp .= $this->custom_xmp;
  9272. $xmp .= '</x:xmpmeta>'."\n";
  9273. $xmp .= '<?xpacket end="w"?>';
  9274. $out = '<< /Type /Metadata /Subtype /XML /Length '.strlen($xmp).' >> stream'."\n".$xmp."\n".'endstream'."\n".'endobj';
  9275. // restore previous isunicode value
  9276. $this->isunicode = $prev_isunicode;
  9277. $this->encrypted = $prev_encrypted;
  9278. $this->_out($out);
  9279. return $oid;
  9280. }
  9281. /**
  9282. * Output Catalog.
  9283. * @return int object id
  9284. * @protected
  9285. */
  9286. protected function _putcatalog() {
  9287. // put XMP
  9288. $xmpobj = $this->_putXMP();
  9289. // if required, add standard sRGB ICC colour profile
  9290. if ($this->pdfa_mode OR $this->force_srgb) {
  9291. $iccobj = $this->_newobj();
  9292. $icc = file_get_contents(dirname(__FILE__).'/include/sRGB.icc');
  9293. $filter = '';
  9294. if ($this->compress) {
  9295. $filter = ' /Filter /FlateDecode';
  9296. $icc = gzcompress($icc);
  9297. }
  9298. $icc = $this->_getrawstream($icc);
  9299. $this->_out('<</N 3 '.$filter.'/Length '.strlen($icc).'>> stream'."\n".$icc."\n".'endstream'."\n".'endobj');
  9300. }
  9301. // start catalog
  9302. $oid = $this->_newobj();
  9303. $out = '<< /Type /Catalog';
  9304. $out .= ' /Version /'.$this->PDFVersion;
  9305. //$out .= ' /Extensions <<>>';
  9306. $out .= ' /Pages 1 0 R';
  9307. //$out .= ' /PageLabels ' //...;
  9308. $out .= ' /Names <<';
  9309. if ((!$this->pdfa_mode) AND !empty($this->n_js)) {
  9310. $out .= ' /JavaScript '.$this->n_js;
  9311. }
  9312. if (!empty($this->efnames)) {
  9313. $out .= ' /EmbeddedFiles <</Names [';
  9314. foreach ($this->efnames AS $fn => $fref) {
  9315. $out .= ' '.$this->_datastring($fn).' '.$fref;
  9316. }
  9317. $out .= ' ]>>';
  9318. }
  9319. $out .= ' >>';
  9320. if (!empty($this->dests)) {
  9321. $out .= ' /Dests '.($this->n_dests).' 0 R';
  9322. }
  9323. $out .= $this->_putviewerpreferences();
  9324. if (isset($this->LayoutMode) AND (!TCPDF_STATIC::empty_string($this->LayoutMode))) {
  9325. $out .= ' /PageLayout /'.$this->LayoutMode;
  9326. }
  9327. if (isset($this->PageMode) AND (!TCPDF_STATIC::empty_string($this->PageMode))) {
  9328. $out .= ' /PageMode /'.$this->PageMode;
  9329. }
  9330. if (count($this->outlines) > 0) {
  9331. $out .= ' /Outlines '.$this->OutlineRoot.' 0 R';
  9332. $out .= ' /PageMode /UseOutlines';
  9333. }
  9334. //$out .= ' /Threads []';
  9335. if ($this->ZoomMode == 'fullpage') {
  9336. $out .= ' /OpenAction ['.$this->page_obj_id[1].' 0 R /Fit]';
  9337. } elseif ($this->ZoomMode == 'fullwidth') {
  9338. $out .= ' /OpenAction ['.$this->page_obj_id[1].' 0 R /FitH null]';
  9339. } elseif ($this->ZoomMode == 'real') {
  9340. $out .= ' /OpenAction ['.$this->page_obj_id[1].' 0 R /XYZ null null 1]';
  9341. } elseif (!is_string($this->ZoomMode)) {
  9342. $out .= sprintf(' /OpenAction ['.$this->page_obj_id[1].' 0 R /XYZ null null %F]', ($this->ZoomMode / 100));
  9343. }
  9344. //$out .= ' /AA <<>>';
  9345. //$out .= ' /URI <<>>';
  9346. $out .= ' /Metadata '.$xmpobj.' 0 R';
  9347. //$out .= ' /StructTreeRoot <<>>';
  9348. //$out .= ' /MarkInfo <<>>';
  9349. if (isset($this->l['a_meta_language'])) {
  9350. $out .= ' /Lang '.$this->_textstring($this->l['a_meta_language'], $oid);
  9351. }
  9352. //$out .= ' /SpiderInfo <<>>';
  9353. // set OutputIntent to sRGB IEC61966-2.1 if required
  9354. if ($this->pdfa_mode OR $this->force_srgb) {
  9355. $out .= ' /OutputIntents [<<';
  9356. $out .= ' /Type /OutputIntent';
  9357. $out .= ' /S /GTS_PDFA1';
  9358. $out .= ' /OutputCondition '.$this->_textstring('sRGB IEC61966-2.1', $oid);
  9359. $out .= ' /OutputConditionIdentifier '.$this->_textstring('sRGB IEC61966-2.1', $oid);
  9360. $out .= ' /RegistryName '.$this->_textstring('http://www.color.org', $oid);
  9361. $out .= ' /Info '.$this->_textstring('sRGB IEC61966-2.1', $oid);
  9362. $out .= ' /DestOutputProfile '.$iccobj.' 0 R';
  9363. $out .= ' >>]';
  9364. }
  9365. //$out .= ' /PieceInfo <<>>';
  9366. if (!empty($this->pdflayers)) {
  9367. $lyrobjs = '';
  9368. $lyrobjs_off = '';
  9369. $lyrobjs_lock = '';
  9370. foreach ($this->pdflayers as $layer) {
  9371. $layer_obj_ref = ' '.$layer['objid'].' 0 R';
  9372. $lyrobjs .= $layer_obj_ref;
  9373. if ($layer['view'] === false) {
  9374. $lyrobjs_off .= $layer_obj_ref;
  9375. }
  9376. if ($layer['lock']) {
  9377. $lyrobjs_lock .= $layer_obj_ref;
  9378. }
  9379. }
  9380. $out .= ' /OCProperties << /OCGs ['.$lyrobjs.']';
  9381. $out .= ' /D <<';
  9382. $out .= ' /Name '.$this->_textstring('Layers', $oid);
  9383. $out .= ' /Creator '.$this->_textstring('TCPDF', $oid);
  9384. $out .= ' /BaseState /ON';
  9385. $out .= ' /OFF ['.$lyrobjs_off.']';
  9386. $out .= ' /Locked ['.$lyrobjs_lock.']';
  9387. $out .= ' /Intent /View';
  9388. $out .= ' /AS [';
  9389. $out .= ' << /Event /Print /OCGs ['.$lyrobjs.'] /Category [/Print] >>';
  9390. $out .= ' << /Event /View /OCGs ['.$lyrobjs.'] /Category [/View] >>';
  9391. $out .= ' ]';
  9392. $out .= ' /Order ['.$lyrobjs.']';
  9393. $out .= ' /ListMode /AllPages';
  9394. //$out .= ' /RBGroups ['..']';
  9395. //$out .= ' /Locked ['..']';
  9396. $out .= ' >>';
  9397. $out .= ' >>';
  9398. }
  9399. // AcroForm
  9400. if (!empty($this->form_obj_id)
  9401. OR ($this->sign AND isset($this->signature_data['cert_type']))
  9402. OR !empty($this->empty_signature_appearance)) {
  9403. $out .= ' /AcroForm <<';
  9404. $objrefs = '';
  9405. if ($this->sign AND isset($this->signature_data['cert_type'])) {
  9406. // set reference for signature object
  9407. $objrefs .= $this->sig_obj_id.' 0 R';
  9408. }
  9409. if (!empty($this->empty_signature_appearance)) {
  9410. foreach ($this->empty_signature_appearance as $esa) {
  9411. // set reference for empty signature objects
  9412. $objrefs .= ' '.$esa['objid'].' 0 R';
  9413. }
  9414. }
  9415. if (!empty($this->form_obj_id)) {
  9416. foreach($this->form_obj_id as $objid) {
  9417. $objrefs .= ' '.$objid.' 0 R';
  9418. }
  9419. }
  9420. $out .= ' /Fields ['.$objrefs.']';
  9421. // It's better to turn off this value and set the appearance stream for each annotation (/AP) to avoid conflicts with signature fields.
  9422. if (empty($this->signature_data['approval']) OR ($this->signature_data['approval'] != 'A')) {
  9423. $out .= ' /NeedAppearances false';
  9424. }
  9425. if ($this->sign AND isset($this->signature_data['cert_type'])) {
  9426. if ($this->signature_data['cert_type'] > 0) {
  9427. $out .= ' /SigFlags 3';
  9428. } else {
  9429. $out .= ' /SigFlags 1';
  9430. }
  9431. }
  9432. //$out .= ' /CO ';
  9433. if (isset($this->annotation_fonts) AND !empty($this->annotation_fonts)) {
  9434. $out .= ' /DR <<';
  9435. $out .= ' /Font <<';
  9436. foreach ($this->annotation_fonts as $fontkey => $fontid) {
  9437. $out .= ' /F'.$fontid.' '.$this->font_obj_ids[$fontkey].' 0 R';
  9438. }
  9439. $out .= ' >> >>';
  9440. }
  9441. $font = $this->getFontBuffer('helvetica');
  9442. $out .= ' /DA (/F'.$font['i'].' 0 Tf 0 g)';
  9443. $out .= ' /Q '.(($this->rtl)?'2':'0');
  9444. //$out .= ' /XFA ';
  9445. $out .= ' >>';
  9446. // signatures
  9447. if ($this->sign AND isset($this->signature_data['cert_type'])
  9448. AND (empty($this->signature_data['approval']) OR ($this->signature_data['approval'] != 'A'))) {
  9449. if ($this->signature_data['cert_type'] > 0) {
  9450. $out .= ' /Perms << /DocMDP '.($this->sig_obj_id + 1).' 0 R >>';
  9451. } else {
  9452. $out .= ' /Perms << /UR3 '.($this->sig_obj_id + 1).' 0 R >>';
  9453. }
  9454. }
  9455. }
  9456. //$out .= ' /Legal <<>>';
  9457. //$out .= ' /Requirements []';
  9458. //$out .= ' /Collection <<>>';
  9459. //$out .= ' /NeedsRendering true';
  9460. $out .= ' >>';
  9461. $out .= "\n".'endobj';
  9462. $this->_out($out);
  9463. return $oid;
  9464. }
  9465. /**
  9466. * Output viewer preferences.
  9467. * @return string for viewer preferences
  9468. * @author Nicola asuni
  9469. * @since 3.1.000 (2008-06-09)
  9470. * @protected
  9471. */
  9472. protected function _putviewerpreferences() {
  9473. $vp = $this->viewer_preferences;
  9474. $out = ' /ViewerPreferences <<';
  9475. if ($this->rtl) {
  9476. $out .= ' /Direction /R2L';
  9477. } else {
  9478. $out .= ' /Direction /L2R';
  9479. }
  9480. if (isset($vp['HideToolbar']) AND ($vp['HideToolbar'])) {
  9481. $out .= ' /HideToolbar true';
  9482. }
  9483. if (isset($vp['HideMenubar']) AND ($vp['HideMenubar'])) {
  9484. $out .= ' /HideMenubar true';
  9485. }
  9486. if (isset($vp['HideWindowUI']) AND ($vp['HideWindowUI'])) {
  9487. $out .= ' /HideWindowUI true';
  9488. }
  9489. if (isset($vp['FitWindow']) AND ($vp['FitWindow'])) {
  9490. $out .= ' /FitWindow true';
  9491. }
  9492. if (isset($vp['CenterWindow']) AND ($vp['CenterWindow'])) {
  9493. $out .= ' /CenterWindow true';
  9494. }
  9495. if (isset($vp['DisplayDocTitle']) AND ($vp['DisplayDocTitle'])) {
  9496. $out .= ' /DisplayDocTitle true';
  9497. }
  9498. if (isset($vp['NonFullScreenPageMode'])) {
  9499. $out .= ' /NonFullScreenPageMode /'.$vp['NonFullScreenPageMode'];
  9500. }
  9501. if (isset($vp['ViewArea'])) {
  9502. $out .= ' /ViewArea /'.$vp['ViewArea'];
  9503. }
  9504. if (isset($vp['ViewClip'])) {
  9505. $out .= ' /ViewClip /'.$vp['ViewClip'];
  9506. }
  9507. if (isset($vp['PrintArea'])) {
  9508. $out .= ' /PrintArea /'.$vp['PrintArea'];
  9509. }
  9510. if (isset($vp['PrintClip'])) {
  9511. $out .= ' /PrintClip /'.$vp['PrintClip'];
  9512. }
  9513. if (isset($vp['PrintScaling'])) {
  9514. $out .= ' /PrintScaling /'.$vp['PrintScaling'];
  9515. }
  9516. if (isset($vp['Duplex']) AND (!TCPDF_STATIC::empty_string($vp['Duplex']))) {
  9517. $out .= ' /Duplex /'.$vp['Duplex'];
  9518. }
  9519. if (isset($vp['PickTrayByPDFSize'])) {
  9520. if ($vp['PickTrayByPDFSize']) {
  9521. $out .= ' /PickTrayByPDFSize true';
  9522. } else {
  9523. $out .= ' /PickTrayByPDFSize false';
  9524. }
  9525. }
  9526. if (isset($vp['PrintPageRange'])) {
  9527. $PrintPageRangeNum = '';
  9528. foreach ($vp['PrintPageRange'] as $k => $v) {
  9529. $PrintPageRangeNum .= ' '.($v - 1).'';
  9530. }
  9531. $out .= ' /PrintPageRange ['.substr($PrintPageRangeNum,1).']';
  9532. }
  9533. if (isset($vp['NumCopies'])) {
  9534. $out .= ' /NumCopies '.intval($vp['NumCopies']);
  9535. }
  9536. $out .= ' >>';
  9537. return $out;
  9538. }
  9539. /**
  9540. * Output PDF File Header (7.5.2).
  9541. * @protected
  9542. */
  9543. protected function _putheader() {
  9544. $this->_out('%PDF-'.$this->PDFVersion);
  9545. $this->_out('%'.chr(0xe2).chr(0xe3).chr(0xcf).chr(0xd3));
  9546. }
  9547. /**
  9548. * Output end of document (EOF).
  9549. * @protected
  9550. */
  9551. protected function _enddoc() {
  9552. if (isset($this->CurrentFont['fontkey']) AND isset($this->CurrentFont['subsetchars'])) {
  9553. // save subset chars of the previous font
  9554. $this->setFontSubBuffer($this->CurrentFont['fontkey'], 'subsetchars', $this->CurrentFont['subsetchars']);
  9555. }
  9556. $this->state = 1;
  9557. $this->_putheader();
  9558. $this->_putpages();
  9559. $this->_putresources();
  9560. // empty signature fields
  9561. if (!empty($this->empty_signature_appearance)) {
  9562. foreach ($this->empty_signature_appearance as $key => $esa) {
  9563. // widget annotation for empty signature
  9564. $out = $this->_getobj($esa['objid'])."\n";
  9565. $out .= '<< /Type /Annot';
  9566. $out .= ' /Subtype /Widget';
  9567. $out .= ' /Rect ['.$esa['rect'].']';
  9568. $out .= ' /P '.$this->page_obj_id[($esa['page'])].' 0 R'; // link to signature appearance page
  9569. $out .= ' /F 4';
  9570. $out .= ' /FT /Sig';
  9571. $signame = $esa['name'].sprintf(' [%03d]', ($key + 1));
  9572. $out .= ' /T '.$this->_textstring($signame, $esa['objid']);
  9573. $out .= ' /Ff 0';
  9574. $out .= ' >>';
  9575. $out .= "\n".'endobj';
  9576. $this->_out($out);
  9577. }
  9578. }
  9579. // Signature
  9580. if ($this->sign AND isset($this->signature_data['cert_type'])) {
  9581. // widget annotation for signature
  9582. $out = $this->_getobj($this->sig_obj_id)."\n";
  9583. $out .= '<< /Type /Annot';
  9584. $out .= ' /Subtype /Widget';
  9585. $out .= ' /Rect ['.$this->signature_appearance['rect'].']';
  9586. $out .= ' /P '.$this->page_obj_id[($this->signature_appearance['page'])].' 0 R'; // link to signature appearance page
  9587. $out .= ' /F 4';
  9588. $out .= ' /FT /Sig';
  9589. $out .= ' /T '.$this->_textstring($this->signature_appearance['name'], $this->sig_obj_id);
  9590. $out .= ' /Ff 0';
  9591. $out .= ' /V '.($this->sig_obj_id + 1).' 0 R';
  9592. $out .= ' >>';
  9593. $out .= "\n".'endobj';
  9594. $this->_out($out);
  9595. // signature
  9596. $this->_putsignature();
  9597. }
  9598. // Info
  9599. $objid_info = $this->_putinfo();
  9600. // Catalog
  9601. $objid_catalog = $this->_putcatalog();
  9602. // Cross-ref
  9603. $o = $this->bufferlen;
  9604. // XREF section
  9605. $this->_out('xref');
  9606. $this->_out('0 '.($this->n + 1));
  9607. $this->_out('0000000000 65535 f ');
  9608. $freegen = ($this->n + 2);
  9609. for ($i=1; $i <= $this->n; ++$i) {
  9610. if (!isset($this->offsets[$i]) AND ($i > 1)) {
  9611. $this->_out(sprintf('0000000000 %05d f ', $freegen));
  9612. ++$freegen;
  9613. } else {
  9614. $this->_out(sprintf('%010d 00000 n ', $this->offsets[$i]));
  9615. }
  9616. }
  9617. // TRAILER
  9618. $out = 'trailer'."\n";
  9619. $out .= '<<';
  9620. $out .= ' /Size '.($this->n + 1);
  9621. $out .= ' /Root '.$objid_catalog.' 0 R';
  9622. $out .= ' /Info '.$objid_info.' 0 R';
  9623. if ($this->encrypted) {
  9624. $out .= ' /Encrypt '.$this->encryptdata['objid'].' 0 R';
  9625. }
  9626. $out .= ' /ID [ <'.$this->file_id.'> <'.$this->file_id.'> ]';
  9627. $out .= ' >>';
  9628. $this->_out($out);
  9629. $this->_out('startxref');
  9630. $this->_out($o);
  9631. $this->_out('%%EOF');
  9632. $this->state = 3; // end-of-doc
  9633. }
  9634. /**
  9635. * Initialize a new page.
  9636. * @param $orientation (string) page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
  9637. * @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().
  9638. * @protected
  9639. * @see getPageSizeFromFormat(), setPageFormat()
  9640. */
  9641. protected function _beginpage($orientation='', $format='') {
  9642. ++$this->page;
  9643. $this->pageobjects[$this->page] = array();
  9644. $this->setPageBuffer($this->page, '');
  9645. // initialize array for graphics tranformation positions inside a page buffer
  9646. $this->transfmrk[$this->page] = array();
  9647. $this->state = 2;
  9648. if (TCPDF_STATIC::empty_string($orientation)) {
  9649. if (isset($this->CurOrientation)) {
  9650. $orientation = $this->CurOrientation;
  9651. } elseif ($this->fwPt > $this->fhPt) {
  9652. // landscape
  9653. $orientation = 'L';
  9654. } else {
  9655. // portrait
  9656. $orientation = 'P';
  9657. }
  9658. }
  9659. if (TCPDF_STATIC::empty_string($format)) {
  9660. $this->pagedim[$this->page] = $this->pagedim[($this->page - 1)];
  9661. $this->setPageOrientation($orientation);
  9662. } else {
  9663. $this->setPageFormat($format, $orientation);
  9664. }
  9665. if ($this->rtl) {
  9666. $this->x = $this->w - $this->rMargin;
  9667. } else {
  9668. $this->x = $this->lMargin;
  9669. }
  9670. $this->y = $this->tMargin;
  9671. if (isset($this->newpagegroup[$this->page])) {
  9672. // start a new group
  9673. $this->currpagegroup = $this->newpagegroup[$this->page];
  9674. $this->pagegroups[$this->currpagegroup] = 1;
  9675. } elseif (isset($this->currpagegroup) AND ($this->currpagegroup > 0)) {
  9676. ++$this->pagegroups[$this->currpagegroup];
  9677. }
  9678. }
  9679. /**
  9680. * Mark end of page.
  9681. * @protected
  9682. */
  9683. protected function _endpage() {
  9684. $this->setVisibility('all');
  9685. $this->state = 1;
  9686. }
  9687. /**
  9688. * Begin a new object and return the object number.
  9689. * @return int object number
  9690. * @protected
  9691. */
  9692. protected function _newobj() {
  9693. $this->_out($this->_getobj());
  9694. return $this->n;
  9695. }
  9696. /**
  9697. * Return the starting object string for the selected object ID.
  9698. * @param $objid (int) Object ID (leave empty to get a new ID).
  9699. * @return string the starting object string
  9700. * @protected
  9701. * @since 5.8.009 (2010-08-20)
  9702. */
  9703. protected function _getobj($objid='') {
  9704. if ($objid === '') {
  9705. ++$this->n;
  9706. $objid = $this->n;
  9707. }
  9708. $this->offsets[$objid] = $this->bufferlen;
  9709. $this->pageobjects[$this->page][] = $objid;
  9710. return $objid.' 0 obj';
  9711. }
  9712. /**
  9713. * Underline text.
  9714. * @param $x (int) X coordinate
  9715. * @param $y (int) Y coordinate
  9716. * @param $txt (string) text to underline
  9717. * @protected
  9718. */
  9719. protected function _dounderline($x, $y, $txt) {
  9720. $w = $this->GetStringWidth($txt);
  9721. return $this->_dounderlinew($x, $y, $w);
  9722. }
  9723. /**
  9724. * Underline for rectangular text area.
  9725. * @param $x (int) X coordinate
  9726. * @param $y (int) Y coordinate
  9727. * @param $w (int) width to underline
  9728. * @protected
  9729. * @since 4.8.008 (2009-09-29)
  9730. */
  9731. protected function _dounderlinew($x, $y, $w) {
  9732. $linew = - $this->CurrentFont['ut'] / 1000 * $this->FontSizePt;
  9733. return sprintf('%F %F %F %F re f', $x * $this->k, ((($this->h - $y) * $this->k) + $linew), $w * $this->k, $linew);
  9734. }
  9735. /**
  9736. * Line through text.
  9737. * @param $x (int) X coordinate
  9738. * @param $y (int) Y coordinate
  9739. * @param $txt (string) text to linethrough
  9740. * @protected
  9741. */
  9742. protected function _dolinethrough($x, $y, $txt) {
  9743. $w = $this->GetStringWidth($txt);
  9744. return $this->_dolinethroughw($x, $y, $w);
  9745. }
  9746. /**
  9747. * Line through for rectangular text area.
  9748. * @param $x (int) X coordinate
  9749. * @param $y (int) Y coordinate
  9750. * @param $w (int) line length (width)
  9751. * @protected
  9752. * @since 4.9.008 (2009-09-29)
  9753. */
  9754. protected function _dolinethroughw($x, $y, $w) {
  9755. $linew = - $this->CurrentFont['ut'] / 1000 * $this->FontSizePt;
  9756. return sprintf('%F %F %F %F re f', $x * $this->k, ((($this->h - $y) * $this->k) + $linew + ($this->FontSizePt / 3)), $w * $this->k, $linew);
  9757. }
  9758. /**
  9759. * Overline text.
  9760. * @param $x (int) X coordinate
  9761. * @param $y (int) Y coordinate
  9762. * @param $txt (string) text to overline
  9763. * @protected
  9764. * @since 4.9.015 (2010-04-19)
  9765. */
  9766. protected function _dooverline($x, $y, $txt) {
  9767. $w = $this->GetStringWidth($txt);
  9768. return $this->_dooverlinew($x, $y, $w);
  9769. }
  9770. /**
  9771. * Overline for rectangular text area.
  9772. * @param $x (int) X coordinate
  9773. * @param $y (int) Y coordinate
  9774. * @param $w (int) width to overline
  9775. * @protected
  9776. * @since 4.9.015 (2010-04-19)
  9777. */
  9778. protected function _dooverlinew($x, $y, $w) {
  9779. $linew = - $this->CurrentFont['ut'] / 1000 * $this->FontSizePt;
  9780. return sprintf('%F %F %F %F re f', $x * $this->k, (($this->h - $y + $this->FontAscent) * $this->k) - $linew, $w * $this->k, $linew);
  9781. }
  9782. /**
  9783. * Format a data string for meta information
  9784. * @param $s (string) data string to escape.
  9785. * @param $n (int) object ID
  9786. * @return string escaped string.
  9787. * @protected
  9788. */
  9789. protected function _datastring($s, $n=0) {
  9790. if ($n == 0) {
  9791. $n = $this->n;
  9792. }
  9793. $s = $this->_encrypt_data($n, $s);
  9794. return '('. TCPDF_STATIC::_escape($s).')';
  9795. }
  9796. /**
  9797. * Set the document creation timestamp
  9798. * @param $time (mixed) Document creation timestamp in seconds or date-time string.
  9799. * @public
  9800. * @since 5.9.152 (2012-03-23)
  9801. */
  9802. public function setDocCreationTimestamp($time) {
  9803. if (is_string($time)) {
  9804. $time = TCPDF_STATIC::getTimestamp($time);
  9805. }
  9806. $this->doc_creation_timestamp = intval($time);
  9807. }
  9808. /**
  9809. * Set the document modification timestamp
  9810. * @param $time (mixed) Document modification timestamp in seconds or date-time string.
  9811. * @public
  9812. * @since 5.9.152 (2012-03-23)
  9813. */
  9814. public function setDocModificationTimestamp($time) {
  9815. if (is_string($time)) {
  9816. $time = TCPDF_STATIC::getTimestamp($time);
  9817. }
  9818. $this->doc_modification_timestamp = intval($time);
  9819. }
  9820. /**
  9821. * Returns document creation timestamp in seconds.
  9822. * @return (int) Creation timestamp in seconds.
  9823. * @public
  9824. * @since 5.9.152 (2012-03-23)
  9825. */
  9826. public function getDocCreationTimestamp() {
  9827. return $this->doc_creation_timestamp;
  9828. }
  9829. /**
  9830. * Returns document modification timestamp in seconds.
  9831. * @return (int) Modfication timestamp in seconds.
  9832. * @public
  9833. * @since 5.9.152 (2012-03-23)
  9834. */
  9835. public function getDocModificationTimestamp() {
  9836. return $this->doc_modification_timestamp;
  9837. }
  9838. /**
  9839. * Returns a formatted date for meta information
  9840. * @param $n (int) Object ID.
  9841. * @param $timestamp (int) Timestamp to convert.
  9842. * @return string escaped date string.
  9843. * @protected
  9844. * @since 4.6.028 (2009-08-25)
  9845. */
  9846. protected function _datestring($n=0, $timestamp=0) {
  9847. if ((empty($timestamp)) OR ($timestamp < 0)) {
  9848. $timestamp = $this->doc_creation_timestamp;
  9849. }
  9850. return $this->_datastring('D:'.TCPDF_STATIC::getFormattedDate($timestamp), $n);
  9851. }
  9852. /**
  9853. * Format a text string for meta information
  9854. * @param $s (string) string to escape.
  9855. * @param $n (int) object ID
  9856. * @return string escaped string.
  9857. * @protected
  9858. */
  9859. protected function _textstring($s, $n=0) {
  9860. if ($this->isunicode) {
  9861. //Convert string to UTF-16BE
  9862. $s = TCPDF_FONTS::UTF8ToUTF16BE($s, true, $this->isunicode, $this->CurrentFont);
  9863. }
  9864. return $this->_datastring($s, $n);
  9865. }
  9866. /**
  9867. * get raw output stream.
  9868. * @param $s (string) string to output.
  9869. * @param $n (int) object reference for encryption mode
  9870. * @protected
  9871. * @author Nicola Asuni
  9872. * @since 5.5.000 (2010-06-22)
  9873. */
  9874. protected function _getrawstream($s, $n=0) {
  9875. if ($n <= 0) {
  9876. // default to current object
  9877. $n = $this->n;
  9878. }
  9879. return $this->_encrypt_data($n, $s);
  9880. }
  9881. /**
  9882. * Output a string to the document.
  9883. * @param $s (string) string to output.
  9884. * @protected
  9885. */
  9886. protected function _out($s) {
  9887. if ($this->state == 2) {
  9888. if ($this->inxobj) {
  9889. // we are inside an XObject template
  9890. $this->xobjects[$this->xobjid]['outdata'] .= $s."\n";
  9891. } elseif ((!$this->InFooter) AND isset($this->footerlen[$this->page]) AND ($this->footerlen[$this->page] > 0)) {
  9892. // puts data before page footer
  9893. $pagebuff = $this->getPageBuffer($this->page);
  9894. $page = substr($pagebuff, 0, -$this->footerlen[$this->page]);
  9895. $footer = substr($pagebuff, -$this->footerlen[$this->page]);
  9896. $this->setPageBuffer($this->page, $page.$s."\n".$footer);
  9897. // update footer position
  9898. $this->footerpos[$this->page] += strlen($s."\n");
  9899. } else {
  9900. // set page data
  9901. $this->setPageBuffer($this->page, $s."\n", true);
  9902. }
  9903. } elseif ($this->state > 0) {
  9904. // set general data
  9905. $this->setBuffer($s."\n");
  9906. }
  9907. }
  9908. /**
  9909. * Set header font.
  9910. * @param $font (array) Array describing the basic font parameters: (family, style, size).
  9911. * @public
  9912. * @since 1.1
  9913. */
  9914. public function setHeaderFont($font) {
  9915. $this->header_font = $font;
  9916. }
  9917. /**
  9918. * Get header font.
  9919. * @return array() Array describing the basic font parameters: (family, style, size).
  9920. * @public
  9921. * @since 4.0.012 (2008-07-24)
  9922. */
  9923. public function getHeaderFont() {
  9924. return $this->header_font;
  9925. }
  9926. /**
  9927. * Set footer font.
  9928. * @param $font (array) Array describing the basic font parameters: (family, style, size).
  9929. * @public
  9930. * @since 1.1
  9931. */
  9932. public function setFooterFont($font) {
  9933. $this->footer_font = $font;
  9934. }
  9935. /**
  9936. * Get Footer font.
  9937. * @return array() Array describing the basic font parameters: (family, style, size).
  9938. * @public
  9939. * @since 4.0.012 (2008-07-24)
  9940. */
  9941. public function getFooterFont() {
  9942. return $this->footer_font;
  9943. }
  9944. /**
  9945. * Set language array.
  9946. * @param $language (array)
  9947. * @public
  9948. * @since 1.1
  9949. */
  9950. public function setLanguageArray($language) {
  9951. $this->l = $language;
  9952. if (isset($this->l['a_meta_dir'])) {
  9953. $this->rtl = $this->l['a_meta_dir']=='rtl' ? true : false;
  9954. } else {
  9955. $this->rtl = false;
  9956. }
  9957. }
  9958. /**
  9959. * Returns the PDF data.
  9960. * @public
  9961. */
  9962. public function getPDFData() {
  9963. if ($this->state < 3) {
  9964. $this->Close();
  9965. }
  9966. return $this->buffer;
  9967. }
  9968. /**
  9969. * Output anchor link.
  9970. * @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;)
  9971. * @param $name (string) link name
  9972. * @param $fill (boolean) Indicates if the cell background must be painted (true) or transparent (false).
  9973. * @param $firstline (boolean) if true prints only the first line and return the remaining string.
  9974. * @param $color (array) array of RGB text color
  9975. * @param $style (string) font style (U, D, B, I)
  9976. * @param $firstblock (boolean) if true the string is the starting of a line.
  9977. * @return the number of cells used or the remaining text if $firstline = true;
  9978. * @public
  9979. */
  9980. public function addHtmlLink($url, $name, $fill=false, $firstline=false, $color='', $style=-1, $firstblock=false) {
  9981. if (isset($url[1]) AND ($url[0] == '#') AND is_numeric($url[1])) {
  9982. // convert url to internal link
  9983. $lnkdata = explode(',', $url);
  9984. if (isset($lnkdata[0]) ) {
  9985. $page = substr($lnkdata[0], 1);
  9986. if (isset($lnkdata[1]) AND (strlen($lnkdata[1]) > 0)) {
  9987. $lnky = floatval($lnkdata[1]);
  9988. } else {
  9989. $lnky = 0;
  9990. }
  9991. $url = $this->AddLink();
  9992. $this->SetLink($url, $lnky, $page);
  9993. }
  9994. }
  9995. // store current settings
  9996. $prevcolor = $this->fgcolor;
  9997. $prevstyle = $this->FontStyle;
  9998. if (empty($color)) {
  9999. $this->SetTextColorArray($this->htmlLinkColorArray);
  10000. } else {
  10001. $this->SetTextColorArray($color);
  10002. }
  10003. if ($style == -1) {
  10004. $this->SetFont('', $this->FontStyle.$this->htmlLinkFontStyle);
  10005. } else {
  10006. $this->SetFont('', $this->FontStyle.$style);
  10007. }
  10008. $ret = $this->Write($this->lasth, $name, $url, $fill, '', false, 0, $firstline, $firstblock, 0);
  10009. // restore settings
  10010. $this->SetFont('', $prevstyle);
  10011. $this->SetTextColorArray($prevcolor);
  10012. return $ret;
  10013. }
  10014. /**
  10015. * Converts pixels to User's Units.
  10016. * @param $px (int) pixels
  10017. * @return float value in user's unit
  10018. * @public
  10019. * @see setImageScale(), getImageScale()
  10020. */
  10021. public function pixelsToUnits($px) {
  10022. return ($px / ($this->imgscale * $this->k));
  10023. }
  10024. /**
  10025. * Reverse function for htmlentities.
  10026. * Convert entities in UTF-8.
  10027. * @param $text_to_convert (string) Text to convert.
  10028. * @return string converted text string
  10029. * @public
  10030. */
  10031. public function unhtmlentities($text_to_convert) {
  10032. return @html_entity_decode($text_to_convert, ENT_QUOTES, $this->encoding);
  10033. }
  10034. // ENCRYPTION METHODS ----------------------------------
  10035. /**
  10036. * Compute encryption key depending on object number where the encrypted data is stored.
  10037. * This is used for all strings and streams without crypt filter specifier.
  10038. * @param $n (int) object number
  10039. * @return int object key
  10040. * @protected
  10041. * @author Nicola Asuni
  10042. * @since 2.0.000 (2008-01-02)
  10043. */
  10044. protected function _objectkey($n) {
  10045. $objkey = $this->encryptdata['key'].pack('VXxx', $n);
  10046. if ($this->encryptdata['mode'] == 2) { // AES-128
  10047. // AES padding
  10048. $objkey .= "\x73\x41\x6C\x54"; // sAlT
  10049. }
  10050. $objkey = substr(TCPDF_STATIC::_md5_16($objkey), 0, (($this->encryptdata['Length'] / 8) + 5));
  10051. $objkey = substr($objkey, 0, 16);
  10052. return $objkey;
  10053. }
  10054. /**
  10055. * Encrypt the input string.
  10056. * @param $n (int) object number
  10057. * @param $s (string) data string to encrypt
  10058. * @return encrypted string
  10059. * @protected
  10060. * @author Nicola Asuni
  10061. * @since 5.0.005 (2010-05-11)
  10062. */
  10063. protected function _encrypt_data($n, $s) {
  10064. if (!$this->encrypted) {
  10065. return $s;
  10066. }
  10067. switch ($this->encryptdata['mode']) {
  10068. case 0: // RC4-40
  10069. case 1: { // RC4-128
  10070. $s = TCPDF_STATIC::_RC4($this->_objectkey($n), $s, $this->last_enc_key, $this->last_enc_key_c);
  10071. break;
  10072. }
  10073. case 2: { // AES-128
  10074. $s = TCPDF_STATIC::_AES($this->_objectkey($n), $s);
  10075. break;
  10076. }
  10077. case 3: { // AES-256
  10078. $s = TCPDF_STATIC::_AES($this->encryptdata['key'], $s);
  10079. break;
  10080. }
  10081. }
  10082. return $s;
  10083. }
  10084. /**
  10085. * Put encryption on PDF document.
  10086. * @protected
  10087. * @author Nicola Asuni
  10088. * @since 2.0.000 (2008-01-02)
  10089. */
  10090. protected function _putencryption() {
  10091. if (!$this->encrypted) {
  10092. return;
  10093. }
  10094. $this->encryptdata['objid'] = $this->_newobj();
  10095. $out = '<<';
  10096. if (!isset($this->encryptdata['Filter']) OR empty($this->encryptdata['Filter'])) {
  10097. $this->encryptdata['Filter'] = 'Standard';
  10098. }
  10099. $out .= ' /Filter /'.$this->encryptdata['Filter'];
  10100. if (isset($this->encryptdata['SubFilter']) AND !empty($this->encryptdata['SubFilter'])) {
  10101. $out .= ' /SubFilter /'.$this->encryptdata['SubFilter'];
  10102. }
  10103. if (!isset($this->encryptdata['V']) OR empty($this->encryptdata['V'])) {
  10104. $this->encryptdata['V'] = 1;
  10105. }
  10106. // V is a code specifying the algorithm to be used in encrypting and decrypting the document
  10107. $out .= ' /V '.$this->encryptdata['V'];
  10108. if (isset($this->encryptdata['Length']) AND !empty($this->encryptdata['Length'])) {
  10109. // The length of the encryption key, in bits. The value shall be a multiple of 8, in the range 40 to 256
  10110. $out .= ' /Length '.$this->encryptdata['Length'];
  10111. } else {
  10112. $out .= ' /Length 40';
  10113. }
  10114. if ($this->encryptdata['V'] >= 4) {
  10115. if (!isset($this->encryptdata['StmF']) OR empty($this->encryptdata['StmF'])) {
  10116. $this->encryptdata['StmF'] = 'Identity';
  10117. }
  10118. if (!isset($this->encryptdata['StrF']) OR empty($this->encryptdata['StrF'])) {
  10119. // The name of the crypt filter that shall be used when decrypting all strings in the document.
  10120. $this->encryptdata['StrF'] = 'Identity';
  10121. }
  10122. // A dictionary whose keys shall be crypt filter names and whose values shall be the corresponding crypt filter dictionaries.
  10123. if (isset($this->encryptdata['CF']) AND !empty($this->encryptdata['CF'])) {
  10124. $out .= ' /CF <<';
  10125. $out .= ' /'.$this->encryptdata['StmF'].' <<';
  10126. $out .= ' /Type /CryptFilter';
  10127. if (isset($this->encryptdata['CF']['CFM']) AND !empty($this->encryptdata['CF']['CFM'])) {
  10128. // The method used
  10129. $out .= ' /CFM /'.$this->encryptdata['CF']['CFM'];
  10130. if ($this->encryptdata['pubkey']) {
  10131. $out .= ' /Recipients [';
  10132. foreach ($this->encryptdata['Recipients'] as $rec) {
  10133. $out .= ' <'.$rec.'>';
  10134. }
  10135. $out .= ' ]';
  10136. if (isset($this->encryptdata['CF']['EncryptMetadata']) AND (!$this->encryptdata['CF']['EncryptMetadata'])) {
  10137. $out .= ' /EncryptMetadata false';
  10138. } else {
  10139. $out .= ' /EncryptMetadata true';
  10140. }
  10141. }
  10142. } else {
  10143. $out .= ' /CFM /None';
  10144. }
  10145. if (isset($this->encryptdata['CF']['AuthEvent']) AND !empty($this->encryptdata['CF']['AuthEvent'])) {
  10146. // The event to be used to trigger the authorization that is required to access encryption keys used by this filter.
  10147. $out .= ' /AuthEvent /'.$this->encryptdata['CF']['AuthEvent'];
  10148. } else {
  10149. $out .= ' /AuthEvent /DocOpen';
  10150. }
  10151. if (isset($this->encryptdata['CF']['Length']) AND !empty($this->encryptdata['CF']['Length'])) {
  10152. // The bit length of the encryption key.
  10153. $out .= ' /Length '.$this->encryptdata['CF']['Length'];
  10154. }
  10155. $out .= ' >> >>';
  10156. }
  10157. // The name of the crypt filter that shall be used by default when decrypting streams.
  10158. $out .= ' /StmF /'.$this->encryptdata['StmF'];
  10159. // The name of the crypt filter that shall be used when decrypting all strings in the document.
  10160. $out .= ' /StrF /'.$this->encryptdata['StrF'];
  10161. if (isset($this->encryptdata['EFF']) AND !empty($this->encryptdata['EFF'])) {
  10162. // The name of the crypt filter that shall be used when encrypting embedded file streams that do not have their own crypt filter specifier.
  10163. $out .= ' /EFF /'.$this->encryptdata[''];
  10164. }
  10165. }
  10166. // Additional encryption dictionary entries for the standard security handler
  10167. if ($this->encryptdata['pubkey']) {
  10168. if (($this->encryptdata['V'] < 4) AND isset($this->encryptdata['Recipients']) AND !empty($this->encryptdata['Recipients'])) {
  10169. $out .= ' /Recipients [';
  10170. foreach ($this->encryptdata['Recipients'] as $rec) {
  10171. $out .= ' <'.$rec.'>';
  10172. }
  10173. $out .= ' ]';
  10174. }
  10175. } else {
  10176. $out .= ' /R';
  10177. if ($this->encryptdata['V'] == 5) { // AES-256
  10178. $out .= ' 5';
  10179. $out .= ' /OE ('.TCPDF_STATIC::_escape($this->encryptdata['OE']).')';
  10180. $out .= ' /UE ('.TCPDF_STATIC::_escape($this->encryptdata['UE']).')';
  10181. $out .= ' /Perms ('.TCPDF_STATIC::_escape($this->encryptdata['perms']).')';
  10182. } elseif ($this->encryptdata['V'] == 4) { // AES-128
  10183. $out .= ' 4';
  10184. } elseif ($this->encryptdata['V'] < 2) { // RC-40
  10185. $out .= ' 2';
  10186. } else { // RC-128
  10187. $out .= ' 3';
  10188. }
  10189. $out .= ' /O ('.TCPDF_STATIC::_escape($this->encryptdata['O']).')';
  10190. $out .= ' /U ('.TCPDF_STATIC::_escape($this->encryptdata['U']).')';
  10191. $out .= ' /P '.$this->encryptdata['P'];
  10192. if (isset($this->encryptdata['EncryptMetadata']) AND (!$this->encryptdata['EncryptMetadata'])) {
  10193. $out .= ' /EncryptMetadata false';
  10194. } else {
  10195. $out .= ' /EncryptMetadata true';
  10196. }
  10197. }
  10198. $out .= ' >>';
  10199. $out .= "\n".'endobj';
  10200. $this->_out($out);
  10201. }
  10202. /**
  10203. * Compute U value (used for encryption)
  10204. * @return string U value
  10205. * @protected
  10206. * @since 2.0.000 (2008-01-02)
  10207. * @author Nicola Asuni
  10208. */
  10209. protected function _Uvalue() {
  10210. if ($this->encryptdata['mode'] == 0) { // RC4-40
  10211. return TCPDF_STATIC::_RC4($this->encryptdata['key'], TCPDF_STATIC::$enc_padding, $this->last_enc_key, $this->last_enc_key_c);
  10212. } elseif ($this->encryptdata['mode'] < 3) { // RC4-128, AES-128
  10213. $tmp = TCPDF_STATIC::_md5_16(TCPDF_STATIC::$enc_padding.$this->encryptdata['fileid']);
  10214. $enc = TCPDF_STATIC::_RC4($this->encryptdata['key'], $tmp, $this->last_enc_key, $this->last_enc_key_c);
  10215. $len = strlen($tmp);
  10216. for ($i = 1; $i <= 19; ++$i) {
  10217. $ek = '';
  10218. for ($j = 0; $j < $len; ++$j) {
  10219. $ek .= chr(ord($this->encryptdata['key'][$j]) ^ $i);
  10220. }
  10221. $enc = TCPDF_STATIC::_RC4($ek, $enc, $this->last_enc_key, $this->last_enc_key_c);
  10222. }
  10223. $enc .= str_repeat("\x00", 16);
  10224. return substr($enc, 0, 32);
  10225. } elseif ($this->encryptdata['mode'] == 3) { // AES-256
  10226. $seed = TCPDF_STATIC::_md5_16(TCPDF_STATIC::getRandomSeed());
  10227. // User Validation Salt
  10228. $this->encryptdata['UVS'] = substr($seed, 0, 8);
  10229. // User Key Salt
  10230. $this->encryptdata['UKS'] = substr($seed, 8, 16);
  10231. return hash('sha256', $this->encryptdata['user_password'].$this->encryptdata['UVS'], true).$this->encryptdata['UVS'].$this->encryptdata['UKS'];
  10232. }
  10233. }
  10234. /**
  10235. * Compute UE value (used for encryption)
  10236. * @return string UE value
  10237. * @protected
  10238. * @since 5.9.006 (2010-10-19)
  10239. * @author Nicola Asuni
  10240. */
  10241. protected function _UEvalue() {
  10242. $hashkey = hash('sha256', $this->encryptdata['user_password'].$this->encryptdata['UKS'], true);
  10243. return TCPDF_STATIC::_AESnopad($hashkey, $this->encryptdata['key']);
  10244. }
  10245. /**
  10246. * Compute O value (used for encryption)
  10247. * @return string O value
  10248. * @protected
  10249. * @since 2.0.000 (2008-01-02)
  10250. * @author Nicola Asuni
  10251. */
  10252. protected function _Ovalue() {
  10253. if ($this->encryptdata['mode'] < 3) { // RC4-40, RC4-128, AES-128
  10254. $tmp = TCPDF_STATIC::_md5_16($this->encryptdata['owner_password']);
  10255. if ($this->encryptdata['mode'] > 0) {
  10256. for ($i = 0; $i < 50; ++$i) {
  10257. $tmp = TCPDF_STATIC::_md5_16($tmp);
  10258. }
  10259. }
  10260. $owner_key = substr($tmp, 0, ($this->encryptdata['Length'] / 8));
  10261. $enc = TCPDF_STATIC::_RC4($owner_key, $this->encryptdata['user_password'], $this->last_enc_key, $this->last_enc_key_c);
  10262. if ($this->encryptdata['mode'] > 0) {
  10263. $len = strlen($owner_key);
  10264. for ($i = 1; $i <= 19; ++$i) {
  10265. $ek = '';
  10266. for ($j = 0; $j < $len; ++$j) {
  10267. $ek .= chr(ord($owner_key[$j]) ^ $i);
  10268. }
  10269. $enc = TCPDF_STATIC::_RC4($ek, $enc, $this->last_enc_key, $this->last_enc_key_c);
  10270. }
  10271. }
  10272. return $enc;
  10273. } elseif ($this->encryptdata['mode'] == 3) { // AES-256
  10274. $seed = TCPDF_STATIC::_md5_16(TCPDF_STATIC::getRandomSeed());
  10275. // Owner Validation Salt
  10276. $this->encryptdata['OVS'] = substr($seed, 0, 8);
  10277. // Owner Key Salt
  10278. $this->encryptdata['OKS'] = substr($seed, 8, 16);
  10279. return hash('sha256', $this->encryptdata['owner_password'].$this->encryptdata['OVS'].$this->encryptdata['U'], true).$this->encryptdata['OVS'].$this->encryptdata['OKS'];
  10280. }
  10281. }
  10282. /**
  10283. * Compute OE value (used for encryption)
  10284. * @return string OE value
  10285. * @protected
  10286. * @since 5.9.006 (2010-10-19)
  10287. * @author Nicola Asuni
  10288. */
  10289. protected function _OEvalue() {
  10290. $hashkey = hash('sha256', $this->encryptdata['owner_password'].$this->encryptdata['OKS'].$this->encryptdata['U'], true);
  10291. return TCPDF_STATIC::_AESnopad($hashkey, $this->encryptdata['key']);
  10292. }
  10293. /**
  10294. * Convert password for AES-256 encryption mode
  10295. * @param $password (string) password
  10296. * @return string password
  10297. * @protected
  10298. * @since 5.9.006 (2010-10-19)
  10299. * @author Nicola Asuni
  10300. */
  10301. protected function _fixAES256Password($password) {
  10302. $psw = ''; // password to be returned
  10303. $psw_array = TCPDF_FONTS::utf8Bidi(TCPDF_FONTS::UTF8StringToArray($password, $this->isunicode, $this->CurrentFont), $password, $this->rtl, $this->isunicode, $this->CurrentFont);
  10304. foreach ($psw_array as $c) {
  10305. $psw .= TCPDF_FONTS::unichr($c, $this->isunicode);
  10306. }
  10307. return substr($psw, 0, 127);
  10308. }
  10309. /**
  10310. * Compute encryption key
  10311. * @protected
  10312. * @since 2.0.000 (2008-01-02)
  10313. * @author Nicola Asuni
  10314. */
  10315. protected function _generateencryptionkey() {
  10316. $keybytelen = ($this->encryptdata['Length'] / 8);
  10317. if (!$this->encryptdata['pubkey']) { // standard mode
  10318. if ($this->encryptdata['mode'] == 3) { // AES-256
  10319. // generate 256 bit random key
  10320. $this->encryptdata['key'] = substr(hash('sha256', TCPDF_STATIC::getRandomSeed(), true), 0, $keybytelen);
  10321. // truncate passwords
  10322. $this->encryptdata['user_password'] = $this->_fixAES256Password($this->encryptdata['user_password']);
  10323. $this->encryptdata['owner_password'] = $this->_fixAES256Password($this->encryptdata['owner_password']);
  10324. // Compute U value
  10325. $this->encryptdata['U'] = $this->_Uvalue();
  10326. // Compute UE value
  10327. $this->encryptdata['UE'] = $this->_UEvalue();
  10328. // Compute O value
  10329. $this->encryptdata['O'] = $this->_Ovalue();
  10330. // Compute OE value
  10331. $this->encryptdata['OE'] = $this->_OEvalue();
  10332. // Compute P value
  10333. $this->encryptdata['P'] = $this->encryptdata['protection'];
  10334. // Computing the encryption dictionary's Perms (permissions) value
  10335. $perms = TCPDF_STATIC::getEncPermissionsString($this->encryptdata['protection']); // bytes 0-3
  10336. $perms .= chr(255).chr(255).chr(255).chr(255); // bytes 4-7
  10337. if (isset($this->encryptdata['CF']['EncryptMetadata']) AND (!$this->encryptdata['CF']['EncryptMetadata'])) { // byte 8
  10338. $perms .= 'F';
  10339. } else {
  10340. $perms .= 'T';
  10341. }
  10342. $perms .= 'adb'; // bytes 9-11
  10343. $perms .= 'nick'; // bytes 12-15
  10344. $this->encryptdata['perms'] = TCPDF_STATIC::_AESnopad($this->encryptdata['key'], $perms);
  10345. } else { // RC4-40, RC4-128, AES-128
  10346. // Pad passwords
  10347. $this->encryptdata['user_password'] = substr($this->encryptdata['user_password'].TCPDF_STATIC::$enc_padding, 0, 32);
  10348. $this->encryptdata['owner_password'] = substr($this->encryptdata['owner_password'].TCPDF_STATIC::$enc_padding, 0, 32);
  10349. // Compute O value
  10350. $this->encryptdata['O'] = $this->_Ovalue();
  10351. // get default permissions (reverse byte order)
  10352. $permissions = TCPDF_STATIC::getEncPermissionsString($this->encryptdata['protection']);
  10353. // Compute encryption key
  10354. $tmp = TCPDF_STATIC::_md5_16($this->encryptdata['user_password'].$this->encryptdata['O'].$permissions.$this->encryptdata['fileid']);
  10355. if ($this->encryptdata['mode'] > 0) {
  10356. for ($i = 0; $i < 50; ++$i) {
  10357. $tmp = TCPDF_STATIC::_md5_16(substr($tmp, 0, $keybytelen));
  10358. }
  10359. }
  10360. $this->encryptdata['key'] = substr($tmp, 0, $keybytelen);
  10361. // Compute U value
  10362. $this->encryptdata['U'] = $this->_Uvalue();
  10363. // Compute P value
  10364. $this->encryptdata['P'] = $this->encryptdata['protection'];
  10365. }
  10366. } else { // Public-Key mode
  10367. // random 20-byte seed
  10368. $seed = sha1(TCPDF_STATIC::getRandomSeed(), true);
  10369. $recipient_bytes = '';
  10370. foreach ($this->encryptdata['pubkeys'] as $pubkey) {
  10371. // for each public certificate
  10372. if (isset($pubkey['p'])) {
  10373. $pkprotection = TCPDF_STATIC::getUserPermissionCode($pubkey['p'], $this->encryptdata['mode']);
  10374. } else {
  10375. $pkprotection = $this->encryptdata['protection'];
  10376. }
  10377. // get default permissions (reverse byte order)
  10378. $pkpermissions = TCPDF_STATIC::getEncPermissionsString($pkprotection);
  10379. // envelope data
  10380. $envelope = $seed.$pkpermissions;
  10381. // write the envelope data to a temporary file
  10382. $tempkeyfile = TCPDF_STATIC::getObjFilename('key', $this->file_id);
  10383. $f = TCPDF_STATIC::fopenLocal($tempkeyfile, 'wb');
  10384. if (!$f) {
  10385. $this->Error('Unable to create temporary key file: '.$tempkeyfile);
  10386. }
  10387. $envelope_length = strlen($envelope);
  10388. fwrite($f, $envelope, $envelope_length);
  10389. fclose($f);
  10390. $tempencfile = TCPDF_STATIC::getObjFilename('enc', $this->file_id);
  10391. if (!openssl_pkcs7_encrypt($tempkeyfile, $tempencfile, $pubkey['c'], array(), PKCS7_BINARY | PKCS7_DETACHED)) {
  10392. $this->Error('Unable to encrypt the file: '.$tempkeyfile);
  10393. }
  10394. // read encryption signature
  10395. $signature = file_get_contents($tempencfile, false, null, $envelope_length);
  10396. // extract signature
  10397. $signature = substr($signature, strpos($signature, 'Content-Disposition'));
  10398. $tmparr = explode("\n\n", $signature);
  10399. $signature = trim($tmparr[1]);
  10400. unset($tmparr);
  10401. // decode signature
  10402. $signature = base64_decode($signature);
  10403. // convert signature to hex
  10404. $hexsignature = current(unpack('H*', $signature));
  10405. // store signature on recipients array
  10406. $this->encryptdata['Recipients'][] = $hexsignature;
  10407. // The bytes of each item in the Recipients array of PKCS#7 objects in the order in which they appear in the array
  10408. $recipient_bytes .= $signature;
  10409. }
  10410. // calculate encryption key
  10411. if ($this->encryptdata['mode'] == 3) { // AES-256
  10412. $this->encryptdata['key'] = substr(hash('sha256', $seed.$recipient_bytes, true), 0, $keybytelen);
  10413. } else { // RC4-40, RC4-128, AES-128
  10414. $this->encryptdata['key'] = substr(sha1($seed.$recipient_bytes, true), 0, $keybytelen);
  10415. }
  10416. }
  10417. }
  10418. /**
  10419. * Set document protection
  10420. * Remark: the protection against modification is for people who have the full Acrobat product.
  10421. * 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.
  10422. * 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.
  10423. * @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>
  10424. * @param $user_pass (String) user password. Empty by default.
  10425. * @param $owner_pass (String) owner password. If not specified, a random value is used.
  10426. * @param $mode (int) encryption strength: 0 = RC4 40 bit; 1 = RC4 128 bit; 2 = AES 128 bit; 3 = AES 256 bit.
  10427. * @param $pubkeys (String) array of recipients containing public-key certificates ('c') and permissions ('p'). For example: array(array('c' => 'file://../examples/data/cert/tcpdf.crt', 'p' => array('print')))
  10428. * @public
  10429. * @since 2.0.000 (2008-01-02)
  10430. * @author Nicola Asuni
  10431. */
  10432. 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) {
  10433. if ($this->pdfa_mode) {
  10434. // encryption is not allowed in PDF/A mode
  10435. return;
  10436. }
  10437. $this->encryptdata['protection'] = TCPDF_STATIC::getUserPermissionCode($permissions, $mode);
  10438. if (($pubkeys !== null) AND (is_array($pubkeys))) {
  10439. // public-key mode
  10440. $this->encryptdata['pubkeys'] = $pubkeys;
  10441. if ($mode == 0) {
  10442. // public-Key Security requires at least 128 bit
  10443. $mode = 1;
  10444. }
  10445. if (!function_exists('openssl_pkcs7_encrypt')) {
  10446. $this->Error('Public-Key Security requires openssl library.');
  10447. }
  10448. // Set Public-Key filter (available are: Entrust.PPKEF, Adobe.PPKLite, Adobe.PubSec)
  10449. $this->encryptdata['pubkey'] = true;
  10450. $this->encryptdata['Filter'] = 'Adobe.PubSec';
  10451. $this->encryptdata['StmF'] = 'DefaultCryptFilter';
  10452. $this->encryptdata['StrF'] = 'DefaultCryptFilter';
  10453. } else {
  10454. // standard mode (password mode)
  10455. $this->encryptdata['pubkey'] = false;
  10456. $this->encryptdata['Filter'] = 'Standard';
  10457. $this->encryptdata['StmF'] = 'StdCF';
  10458. $this->encryptdata['StrF'] = 'StdCF';
  10459. }
  10460. if ($mode > 1) { // AES
  10461. if (!extension_loaded('openssl') && !extension_loaded('mcrypt')) {
  10462. $this->Error('AES encryption requires openssl or mcrypt extension (http://www.php.net/manual/en/mcrypt.requirements.php).');
  10463. }
  10464. if (extension_loaded('openssl') && !in_array('aes-256-cbc', openssl_get_cipher_methods())) {
  10465. $this->Error('AES encryption requires openssl/aes-256-cbc cypher.');
  10466. }
  10467. if (extension_loaded('mcrypt') && mcrypt_get_cipher_name(MCRYPT_RIJNDAEL_128) === false) {
  10468. $this->Error('AES encryption requires MCRYPT_RIJNDAEL_128 cypher.');
  10469. }
  10470. if (($mode == 3) AND !function_exists('hash')) {
  10471. // the Hash extension requires no external libraries and is enabled by default as of PHP 5.1.2.
  10472. $this->Error('AES 256 encryption requires HASH Message Digest Framework (http://www.php.net/manual/en/book.hash.php).');
  10473. }
  10474. }
  10475. if ($owner_pass === null) {
  10476. $owner_pass = md5(TCPDF_STATIC::getRandomSeed());
  10477. }
  10478. $this->encryptdata['user_password'] = $user_pass;
  10479. $this->encryptdata['owner_password'] = $owner_pass;
  10480. $this->encryptdata['mode'] = $mode;
  10481. switch ($mode) {
  10482. case 0: { // RC4 40 bit
  10483. $this->encryptdata['V'] = 1;
  10484. $this->encryptdata['Length'] = 40;
  10485. $this->encryptdata['CF']['CFM'] = 'V2';
  10486. break;
  10487. }
  10488. case 1: { // RC4 128 bit
  10489. $this->encryptdata['V'] = 2;
  10490. $this->encryptdata['Length'] = 128;
  10491. $this->encryptdata['CF']['CFM'] = 'V2';
  10492. if ($this->encryptdata['pubkey']) {
  10493. $this->encryptdata['SubFilter'] = 'adbe.pkcs7.s4';
  10494. $this->encryptdata['Recipients'] = array();
  10495. }
  10496. break;
  10497. }
  10498. case 2: { // AES 128 bit
  10499. $this->encryptdata['V'] = 4;
  10500. $this->encryptdata['Length'] = 128;
  10501. $this->encryptdata['CF']['CFM'] = 'AESV2';
  10502. $this->encryptdata['CF']['Length'] = 128;
  10503. if ($this->encryptdata['pubkey']) {
  10504. $this->encryptdata['SubFilter'] = 'adbe.pkcs7.s5';
  10505. $this->encryptdata['Recipients'] = array();
  10506. }
  10507. break;
  10508. }
  10509. case 3: { // AES 256 bit
  10510. $this->encryptdata['V'] = 5;
  10511. $this->encryptdata['Length'] = 256;
  10512. $this->encryptdata['CF']['CFM'] = 'AESV3';
  10513. $this->encryptdata['CF']['Length'] = 256;
  10514. if ($this->encryptdata['pubkey']) {
  10515. $this->encryptdata['SubFilter'] = 'adbe.pkcs7.s5';
  10516. $this->encryptdata['Recipients'] = array();
  10517. }
  10518. break;
  10519. }
  10520. }
  10521. $this->encrypted = true;
  10522. $this->encryptdata['fileid'] = TCPDF_STATIC::convertHexStringToString($this->file_id);
  10523. $this->_generateencryptionkey();
  10524. }
  10525. // END OF ENCRYPTION FUNCTIONS -------------------------
  10526. // START TRANSFORMATIONS SECTION -----------------------
  10527. /**
  10528. * Starts a 2D tranformation saving current graphic state.
  10529. * This function must be called before scaling, mirroring, translation, rotation and skewing.
  10530. * Use StartTransform() before, and StopTransform() after the transformations to restore the normal behavior.
  10531. * @public
  10532. * @since 2.1.000 (2008-01-07)
  10533. * @see StartTransform(), StopTransform()
  10534. */
  10535. public function StartTransform() {
  10536. if ($this->state != 2) {
  10537. return;
  10538. }
  10539. $this->_outSaveGraphicsState();
  10540. if ($this->inxobj) {
  10541. // we are inside an XObject template
  10542. $this->xobjects[$this->xobjid]['transfmrk'][] = strlen($this->xobjects[$this->xobjid]['outdata']);
  10543. } else {
  10544. $this->transfmrk[$this->page][] = $this->pagelen[$this->page];
  10545. }
  10546. ++$this->transfmatrix_key;
  10547. $this->transfmatrix[$this->transfmatrix_key] = array();
  10548. }
  10549. /**
  10550. * Stops a 2D tranformation restoring previous graphic state.
  10551. * This function must be called after scaling, mirroring, translation, rotation and skewing.
  10552. * Use StartTransform() before, and StopTransform() after the transformations to restore the normal behavior.
  10553. * @public
  10554. * @since 2.1.000 (2008-01-07)
  10555. * @see StartTransform(), StopTransform()
  10556. */
  10557. public function StopTransform() {
  10558. if ($this->state != 2) {
  10559. return;
  10560. }
  10561. $this->_outRestoreGraphicsState();
  10562. if (isset($this->transfmatrix[$this->transfmatrix_key])) {
  10563. array_pop($this->transfmatrix[$this->transfmatrix_key]);
  10564. --$this->transfmatrix_key;
  10565. }
  10566. if ($this->inxobj) {
  10567. // we are inside an XObject template
  10568. array_pop($this->xobjects[$this->xobjid]['transfmrk']);
  10569. } else {
  10570. array_pop($this->transfmrk[$this->page]);
  10571. }
  10572. }
  10573. /**
  10574. * Horizontal Scaling.
  10575. * @param $s_x (float) scaling factor for width as percent. 0 is not allowed.
  10576. * @param $x (int) abscissa of the scaling center. Default is current x position
  10577. * @param $y (int) ordinate of the scaling center. Default is current y position
  10578. * @public
  10579. * @since 2.1.000 (2008-01-07)
  10580. * @see StartTransform(), StopTransform()
  10581. */
  10582. public function ScaleX($s_x, $x='', $y='') {
  10583. $this->Scale($s_x, 100, $x, $y);
  10584. }
  10585. /**
  10586. * Vertical Scaling.
  10587. * @param $s_y (float) scaling factor for height as percent. 0 is not allowed.
  10588. * @param $x (int) abscissa of the scaling center. Default is current x position
  10589. * @param $y (int) ordinate of the scaling center. Default is current y position
  10590. * @public
  10591. * @since 2.1.000 (2008-01-07)
  10592. * @see StartTransform(), StopTransform()
  10593. */
  10594. public function ScaleY($s_y, $x='', $y='') {
  10595. $this->Scale(100, $s_y, $x, $y);
  10596. }
  10597. /**
  10598. * Vertical and horizontal proportional Scaling.
  10599. * @param $s (float) scaling factor for width and height as percent. 0 is not allowed.
  10600. * @param $x (int) abscissa of the scaling center. Default is current x position
  10601. * @param $y (int) ordinate of the scaling center. Default is current y position
  10602. * @public
  10603. * @since 2.1.000 (2008-01-07)
  10604. * @see StartTransform(), StopTransform()
  10605. */
  10606. public function ScaleXY($s, $x='', $y='') {
  10607. $this->Scale($s, $s, $x, $y);
  10608. }
  10609. /**
  10610. * Vertical and horizontal non-proportional Scaling.
  10611. * @param $s_x (float) scaling factor for width as percent. 0 is not allowed.
  10612. * @param $s_y (float) scaling factor for height as percent. 0 is not allowed.
  10613. * @param $x (int) abscissa of the scaling center. Default is current x position
  10614. * @param $y (int) ordinate of the scaling center. Default is current y position
  10615. * @public
  10616. * @since 2.1.000 (2008-01-07)
  10617. * @see StartTransform(), StopTransform()
  10618. */
  10619. public function Scale($s_x, $s_y, $x='', $y='') {
  10620. if ($x === '') {
  10621. $x = $this->x;
  10622. }
  10623. if ($y === '') {
  10624. $y = $this->y;
  10625. }
  10626. if (($s_x == 0) OR ($s_y == 0)) {
  10627. $this->Error('Please do not use values equal to zero for scaling');
  10628. }
  10629. $y = ($this->h - $y) * $this->k;
  10630. $x *= $this->k;
  10631. //calculate elements of transformation matrix
  10632. $s_x /= 100;
  10633. $s_y /= 100;
  10634. $tm = array();
  10635. $tm[0] = $s_x;
  10636. $tm[1] = 0;
  10637. $tm[2] = 0;
  10638. $tm[3] = $s_y;
  10639. $tm[4] = $x * (1 - $s_x);
  10640. $tm[5] = $y * (1 - $s_y);
  10641. //scale the coordinate system
  10642. $this->Transform($tm);
  10643. }
  10644. /**
  10645. * Horizontal Mirroring.
  10646. * @param $x (int) abscissa of the point. Default is current x position
  10647. * @public
  10648. * @since 2.1.000 (2008-01-07)
  10649. * @see StartTransform(), StopTransform()
  10650. */
  10651. public function MirrorH($x='') {
  10652. $this->Scale(-100, 100, $x);
  10653. }
  10654. /**
  10655. * Verical Mirroring.
  10656. * @param $y (int) ordinate of the point. Default is current y position
  10657. * @public
  10658. * @since 2.1.000 (2008-01-07)
  10659. * @see StartTransform(), StopTransform()
  10660. */
  10661. public function MirrorV($y='') {
  10662. $this->Scale(100, -100, '', $y);
  10663. }
  10664. /**
  10665. * Point reflection mirroring.
  10666. * @param $x (int) abscissa of the point. Default is current x position
  10667. * @param $y (int) ordinate of the point. Default is current y position
  10668. * @public
  10669. * @since 2.1.000 (2008-01-07)
  10670. * @see StartTransform(), StopTransform()
  10671. */
  10672. public function MirrorP($x='',$y='') {
  10673. $this->Scale(-100, -100, $x, $y);
  10674. }
  10675. /**
  10676. * Reflection against a straight line through point (x, y) with the gradient angle (angle).
  10677. * @param $angle (float) gradient angle of the straight line. Default is 0 (horizontal line).
  10678. * @param $x (int) abscissa of the point. Default is current x position
  10679. * @param $y (int) ordinate of the point. Default is current y position
  10680. * @public
  10681. * @since 2.1.000 (2008-01-07)
  10682. * @see StartTransform(), StopTransform()
  10683. */
  10684. public function MirrorL($angle=0, $x='',$y='') {
  10685. $this->Scale(-100, 100, $x, $y);
  10686. $this->Rotate(-2*($angle-90), $x, $y);
  10687. }
  10688. /**
  10689. * Translate graphic object horizontally.
  10690. * @param $t_x (int) movement to the right (or left for RTL)
  10691. * @public
  10692. * @since 2.1.000 (2008-01-07)
  10693. * @see StartTransform(), StopTransform()
  10694. */
  10695. public function TranslateX($t_x) {
  10696. $this->Translate($t_x, 0);
  10697. }
  10698. /**
  10699. * Translate graphic object vertically.
  10700. * @param $t_y (int) movement to the bottom
  10701. * @public
  10702. * @since 2.1.000 (2008-01-07)
  10703. * @see StartTransform(), StopTransform()
  10704. */
  10705. public function TranslateY($t_y) {
  10706. $this->Translate(0, $t_y);
  10707. }
  10708. /**
  10709. * Translate graphic object horizontally and vertically.
  10710. * @param $t_x (int) movement to the right
  10711. * @param $t_y (int) movement to the bottom
  10712. * @public
  10713. * @since 2.1.000 (2008-01-07)
  10714. * @see StartTransform(), StopTransform()
  10715. */
  10716. public function Translate($t_x, $t_y) {
  10717. //calculate elements of transformation matrix
  10718. $tm = array();
  10719. $tm[0] = 1;
  10720. $tm[1] = 0;
  10721. $tm[2] = 0;
  10722. $tm[3] = 1;
  10723. $tm[4] = $t_x * $this->k;
  10724. $tm[5] = -$t_y * $this->k;
  10725. //translate the coordinate system
  10726. $this->Transform($tm);
  10727. }
  10728. /**
  10729. * Rotate object.
  10730. * @param $angle (float) angle in degrees for counter-clockwise rotation
  10731. * @param $x (int) abscissa of the rotation center. Default is current x position
  10732. * @param $y (int) ordinate of the rotation center. Default is current y position
  10733. * @public
  10734. * @since 2.1.000 (2008-01-07)
  10735. * @see StartTransform(), StopTransform()
  10736. */
  10737. public function Rotate($angle, $x='', $y='') {
  10738. if ($x === '') {
  10739. $x = $this->x;
  10740. }
  10741. if ($y === '') {
  10742. $y = $this->y;
  10743. }
  10744. $y = ($this->h - $y) * $this->k;
  10745. $x *= $this->k;
  10746. //calculate elements of transformation matrix
  10747. $tm = array();
  10748. $tm[0] = cos(deg2rad($angle));
  10749. $tm[1] = sin(deg2rad($angle));
  10750. $tm[2] = -$tm[1];
  10751. $tm[3] = $tm[0];
  10752. $tm[4] = $x + ($tm[1] * $y) - ($tm[0] * $x);
  10753. $tm[5] = $y - ($tm[0] * $y) - ($tm[1] * $x);
  10754. //rotate the coordinate system around ($x,$y)
  10755. $this->Transform($tm);
  10756. }
  10757. /**
  10758. * Skew horizontally.
  10759. * @param $angle_x (float) angle in degrees between -90 (skew to the left) and 90 (skew to the right)
  10760. * @param $x (int) abscissa of the skewing center. default is current x position
  10761. * @param $y (int) ordinate of the skewing center. default is current y position
  10762. * @public
  10763. * @since 2.1.000 (2008-01-07)
  10764. * @see StartTransform(), StopTransform()
  10765. */
  10766. public function SkewX($angle_x, $x='', $y='') {
  10767. $this->Skew($angle_x, 0, $x, $y);
  10768. }
  10769. /**
  10770. * Skew vertically.
  10771. * @param $angle_y (float) angle in degrees between -90 (skew to the bottom) and 90 (skew to the top)
  10772. * @param $x (int) abscissa of the skewing center. default is current x position
  10773. * @param $y (int) ordinate of the skewing center. default is current y position
  10774. * @public
  10775. * @since 2.1.000 (2008-01-07)
  10776. * @see StartTransform(), StopTransform()
  10777. */
  10778. public function SkewY($angle_y, $x='', $y='') {
  10779. $this->Skew(0, $angle_y, $x, $y);
  10780. }
  10781. /**
  10782. * Skew.
  10783. * @param $angle_x (float) angle in degrees between -90 (skew to the left) and 90 (skew to the right)
  10784. * @param $angle_y (float) angle in degrees between -90 (skew to the bottom) and 90 (skew to the top)
  10785. * @param $x (int) abscissa of the skewing center. default is current x position
  10786. * @param $y (int) ordinate of the skewing center. default is current y position
  10787. * @public
  10788. * @since 2.1.000 (2008-01-07)
  10789. * @see StartTransform(), StopTransform()
  10790. */
  10791. public function Skew($angle_x, $angle_y, $x='', $y='') {
  10792. if ($x === '') {
  10793. $x = $this->x;
  10794. }
  10795. if ($y === '') {
  10796. $y = $this->y;
  10797. }
  10798. if (($angle_x <= -90) OR ($angle_x >= 90) OR ($angle_y <= -90) OR ($angle_y >= 90)) {
  10799. $this->Error('Please use values between -90 and +90 degrees for Skewing.');
  10800. }
  10801. $x *= $this->k;
  10802. $y = ($this->h - $y) * $this->k;
  10803. //calculate elements of transformation matrix
  10804. $tm = array();
  10805. $tm[0] = 1;
  10806. $tm[1] = tan(deg2rad($angle_y));
  10807. $tm[2] = tan(deg2rad($angle_x));
  10808. $tm[3] = 1;
  10809. $tm[4] = -$tm[2] * $y;
  10810. $tm[5] = -$tm[1] * $x;
  10811. //skew the coordinate system
  10812. $this->Transform($tm);
  10813. }
  10814. /**
  10815. * Apply graphic transformations.
  10816. * @param $tm (array) transformation matrix
  10817. * @protected
  10818. * @since 2.1.000 (2008-01-07)
  10819. * @see StartTransform(), StopTransform()
  10820. */
  10821. protected function Transform($tm) {
  10822. if ($this->state != 2) {
  10823. return;
  10824. }
  10825. $this->_out(sprintf('%F %F %F %F %F %F cm', $tm[0], $tm[1], $tm[2], $tm[3], $tm[4], $tm[5]));
  10826. // add tranformation matrix
  10827. $this->transfmatrix[$this->transfmatrix_key][] = array('a' => $tm[0], 'b' => $tm[1], 'c' => $tm[2], 'd' => $tm[3], 'e' => $tm[4], 'f' => $tm[5]);
  10828. // update transformation mark
  10829. if ($this->inxobj) {
  10830. // we are inside an XObject template
  10831. if (end($this->xobjects[$this->xobjid]['transfmrk']) !== false) {
  10832. $key = key($this->xobjects[$this->xobjid]['transfmrk']);
  10833. $this->xobjects[$this->xobjid]['transfmrk'][$key] = strlen($this->xobjects[$this->xobjid]['outdata']);
  10834. }
  10835. } elseif (end($this->transfmrk[$this->page]) !== false) {
  10836. $key = key($this->transfmrk[$this->page]);
  10837. $this->transfmrk[$this->page][$key] = $this->pagelen[$this->page];
  10838. }
  10839. }
  10840. // END TRANSFORMATIONS SECTION -------------------------
  10841. // START GRAPHIC FUNCTIONS SECTION ---------------------
  10842. // The following section is based on the code provided by David Hernandez Sanz
  10843. /**
  10844. * 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.
  10845. * @param $width (float) The width.
  10846. * @public
  10847. * @since 1.0
  10848. * @see Line(), Rect(), Cell(), MultiCell()
  10849. */
  10850. public function SetLineWidth($width) {
  10851. //Set line width
  10852. $this->LineWidth = $width;
  10853. $this->linestyleWidth = sprintf('%F w', ($width * $this->k));
  10854. if ($this->state == 2) {
  10855. $this->_out($this->linestyleWidth);
  10856. }
  10857. }
  10858. /**
  10859. * Returns the current the line width.
  10860. * @return int Line width
  10861. * @public
  10862. * @since 2.1.000 (2008-01-07)
  10863. * @see Line(), SetLineWidth()
  10864. */
  10865. public function GetLineWidth() {
  10866. return $this->LineWidth;
  10867. }
  10868. /**
  10869. * Set line style.
  10870. * @param $style (array) Line style. Array with keys among the following:
  10871. * <ul>
  10872. * <li>width (float): Width of the line in user units.</li>
  10873. * <li>cap (string): Type of cap to put on the line. Possible values are:
  10874. * butt, round, square. The difference between "square" and "butt" is that
  10875. * "square" projects a flat end past the end of the line.</li>
  10876. * <li>join (string): Type of join. Possible values are: miter, round,
  10877. * bevel.</li>
  10878. * <li>dash (mixed): Dash pattern. Is 0 (without dash) or string with
  10879. * series of length values, which are the lengths of the on and off dashes.
  10880. * For example: "2" represents 2 on, 2 off, 2 on, 2 off, ...; "2,1" is 2 on,
  10881. * 1 off, 2 on, 1 off, ...</li>
  10882. * <li>phase (integer): Modifier on the dash pattern which is used to shift
  10883. * the point at which the pattern starts.</li>
  10884. * <li>color (array): Draw color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K) or array(C,M,Y,K,SpotColorName).</li>
  10885. * </ul>
  10886. * @param $ret (boolean) if true do not send the command.
  10887. * @return string the PDF command
  10888. * @public
  10889. * @since 2.1.000 (2008-01-08)
  10890. */
  10891. public function SetLineStyle($style, $ret=false) {
  10892. $s = ''; // string to be returned
  10893. if (!is_array($style)) {
  10894. return;
  10895. }
  10896. if (isset($style['width'])) {
  10897. $this->LineWidth = $style['width'];
  10898. $this->linestyleWidth = sprintf('%F w', ($style['width'] * $this->k));
  10899. $s .= $this->linestyleWidth.' ';
  10900. }
  10901. if (isset($style['cap'])) {
  10902. $ca = array('butt' => 0, 'round'=> 1, 'square' => 2);
  10903. if (isset($ca[$style['cap']])) {
  10904. $this->linestyleCap = $ca[$style['cap']].' J';
  10905. $s .= $this->linestyleCap.' ';
  10906. }
  10907. }
  10908. if (isset($style['join'])) {
  10909. $ja = array('miter' => 0, 'round' => 1, 'bevel' => 2);
  10910. if (isset($ja[$style['join']])) {
  10911. $this->linestyleJoin = $ja[$style['join']].' j';
  10912. $s .= $this->linestyleJoin.' ';
  10913. }
  10914. }
  10915. if (isset($style['dash'])) {
  10916. $dash_string = '';
  10917. if ($style['dash']) {
  10918. if (preg_match('/^.+,/', $style['dash']) > 0) {
  10919. $tab = explode(',', $style['dash']);
  10920. } else {
  10921. $tab = array($style['dash']);
  10922. }
  10923. $dash_string = '';
  10924. foreach ($tab as $i => $v) {
  10925. if ($i) {
  10926. $dash_string .= ' ';
  10927. }
  10928. $dash_string .= sprintf('%F', $v);
  10929. }
  10930. }
  10931. if (!isset($style['phase']) OR !$style['dash']) {
  10932. $style['phase'] = 0;
  10933. }
  10934. $this->linestyleDash = sprintf('[%s] %F d', $dash_string, $style['phase']);
  10935. $s .= $this->linestyleDash.' ';
  10936. }
  10937. if (isset($style['color'])) {
  10938. $s .= $this->SetDrawColorArray($style['color'], true).' ';
  10939. }
  10940. if (!$ret AND ($this->state == 2)) {
  10941. $this->_out($s);
  10942. }
  10943. return $s;
  10944. }
  10945. /**
  10946. * Begin a new subpath by moving the current point to coordinates (x, y), omitting any connecting line segment.
  10947. * @param $x (float) Abscissa of point.
  10948. * @param $y (float) Ordinate of point.
  10949. * @protected
  10950. * @since 2.1.000 (2008-01-08)
  10951. */
  10952. protected function _outPoint($x, $y) {
  10953. if ($this->state == 2) {
  10954. $this->_out(sprintf('%F %F m', ($x * $this->k), (($this->h - $y) * $this->k)));
  10955. }
  10956. }
  10957. /**
  10958. * Append a straight line segment from the current point to the point (x, y).
  10959. * The new current point shall be (x, y).
  10960. * @param $x (float) Abscissa of end point.
  10961. * @param $y (float) Ordinate of end point.
  10962. * @protected
  10963. * @since 2.1.000 (2008-01-08)
  10964. */
  10965. protected function _outLine($x, $y) {
  10966. if ($this->state == 2) {
  10967. $this->_out(sprintf('%F %F l', ($x * $this->k), (($this->h - $y) * $this->k)));
  10968. }
  10969. }
  10970. /**
  10971. * Append a rectangle to the current path as a complete subpath, with lower-left corner (x, y) and dimensions widthand height in user space.
  10972. * @param $x (float) Abscissa of upper-left corner.
  10973. * @param $y (float) Ordinate of upper-left corner.
  10974. * @param $w (float) Width.
  10975. * @param $h (float) Height.
  10976. * @param $op (string) options
  10977. * @protected
  10978. * @since 2.1.000 (2008-01-08)
  10979. */
  10980. protected function _outRect($x, $y, $w, $h, $op) {
  10981. if ($this->state == 2) {
  10982. $this->_out(sprintf('%F %F %F %F re %s', ($x * $this->k), (($this->h - $y) * $this->k), ($w * $this->k), (-$h * $this->k), $op));
  10983. }
  10984. }
  10985. /**
  10986. * Append a cubic Bezier curve to the current path. The curve shall extend from the current point to the point (x3, y3), using (x1, y1) and (x2, y2) as the Bezier control points.
  10987. * The new current point shall be (x3, y3).
  10988. * @param $x1 (float) Abscissa of control point 1.
  10989. * @param $y1 (float) Ordinate of control point 1.
  10990. * @param $x2 (float) Abscissa of control point 2.
  10991. * @param $y2 (float) Ordinate of control point 2.
  10992. * @param $x3 (float) Abscissa of end point.
  10993. * @param $y3 (float) Ordinate of end point.
  10994. * @protected
  10995. * @since 2.1.000 (2008-01-08)
  10996. */
  10997. protected function _outCurve($x1, $y1, $x2, $y2, $x3, $y3) {
  10998. if ($this->state == 2) {
  10999. $this->_out(sprintf('%F %F %F %F %F %F c', ($x1 * $this->k), (($this->h - $y1) * $this->k), ($x2 * $this->k), (($this->h - $y2) * $this->k), ($x3 * $this->k), (($this->h - $y3) * $this->k)));
  11000. }
  11001. }
  11002. /**
  11003. * Append a cubic Bezier curve to the current path. The curve shall extend from the current point to the point (x3, y3), using the current point and (x2, y2) as the Bezier control points.
  11004. * The new current point shall be (x3, y3).
  11005. * @param $x2 (float) Abscissa of control point 2.
  11006. * @param $y2 (float) Ordinate of control point 2.
  11007. * @param $x3 (float) Abscissa of end point.
  11008. * @param $y3 (float) Ordinate of end point.
  11009. * @protected
  11010. * @since 4.9.019 (2010-04-26)
  11011. */
  11012. protected function _outCurveV($x2, $y2, $x3, $y3) {
  11013. if ($this->state == 2) {
  11014. $this->_out(sprintf('%F %F %F %F v', ($x2 * $this->k), (($this->h - $y2) * $this->k), ($x3 * $this->k), (($this->h - $y3) * $this->k)));
  11015. }
  11016. }
  11017. /**
  11018. * Append a cubic Bezier curve to the current path. The curve shall extend from the current point to the point (x3, y3), using (x1, y1) and (x3, y3) as the Bezier control points.
  11019. * The new current point shall be (x3, y3).
  11020. * @param $x1 (float) Abscissa of control point 1.
  11021. * @param $y1 (float) Ordinate of control point 1.
  11022. * @param $x3 (float) Abscissa of end point.
  11023. * @param $y3 (float) Ordinate of end point.
  11024. * @protected
  11025. * @since 2.1.000 (2008-01-08)
  11026. */
  11027. protected function _outCurveY($x1, $y1, $x3, $y3) {
  11028. if ($this->state == 2) {
  11029. $this->_out(sprintf('%F %F %F %F y', ($x1 * $this->k), (($this->h - $y1) * $this->k), ($x3 * $this->k), (($this->h - $y3) * $this->k)));
  11030. }
  11031. }
  11032. /**
  11033. * Draws a line between two points.
  11034. * @param $x1 (float) Abscissa of first point.
  11035. * @param $y1 (float) Ordinate of first point.
  11036. * @param $x2 (float) Abscissa of second point.
  11037. * @param $y2 (float) Ordinate of second point.
  11038. * @param $style (array) Line style. Array like for SetLineStyle(). Default value: default line style (empty array).
  11039. * @public
  11040. * @since 1.0
  11041. * @see SetLineWidth(), SetDrawColor(), SetLineStyle()
  11042. */
  11043. public function Line($x1, $y1, $x2, $y2, $style=array()) {
  11044. if ($this->state != 2) {
  11045. return;
  11046. }
  11047. if (is_array($style)) {
  11048. $this->SetLineStyle($style);
  11049. }
  11050. $this->_outPoint($x1, $y1);
  11051. $this->_outLine($x2, $y2);
  11052. $this->_out('S');
  11053. }
  11054. /**
  11055. * Draws a rectangle.
  11056. * @param $x (float) Abscissa of upper-left corner.
  11057. * @param $y (float) Ordinate of upper-left corner.
  11058. * @param $w (float) Width.
  11059. * @param $h (float) Height.
  11060. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  11061. * @param $border_style (array) Border style of rectangle. Array with keys among the following:
  11062. * <ul>
  11063. * <li>all: Line style of all borders. Array like for SetLineStyle().</li>
  11064. * <li>L, T, R, B or combinations: Line style of left, top, right or bottom border. Array like for SetLineStyle().</li>
  11065. * </ul>
  11066. * If a key is not present or is null, the correspondent border is not drawn. Default value: default line style (empty array).
  11067. * @param $fill_color (array) Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K) or array(C,M,Y,K,SpotColorName). Default value: default color (empty array).
  11068. * @public
  11069. * @since 1.0
  11070. * @see SetLineStyle()
  11071. */
  11072. public function Rect($x, $y, $w, $h, $style='', $border_style=array(), $fill_color=array()) {
  11073. if ($this->state != 2) {
  11074. return;
  11075. }
  11076. if (empty($style)) {
  11077. $style = 'S';
  11078. }
  11079. if (!(strpos($style, 'F') === false) AND !empty($fill_color)) {
  11080. // set background color
  11081. $this->SetFillColorArray($fill_color);
  11082. }
  11083. if (!empty($border_style)) {
  11084. if (isset($border_style['all']) AND !empty($border_style['all'])) {
  11085. //set global style for border
  11086. $this->SetLineStyle($border_style['all']);
  11087. $border_style = array();
  11088. } else {
  11089. // remove stroke operator from style
  11090. $opnostroke = array('S' => '', 'D' => '', 's' => '', 'd' => '', 'B' => 'F', 'FD' => 'F', 'DF' => 'F', 'B*' => 'F*', 'F*D' => 'F*', 'DF*' => 'F*', 'b' => 'f', 'fd' => 'f', 'df' => 'f', 'b*' => 'f*', 'f*d' => 'f*', 'df*' => 'f*' );
  11091. if (isset($opnostroke[$style])) {
  11092. $style = $opnostroke[$style];
  11093. }
  11094. }
  11095. }
  11096. if (!empty($style)) {
  11097. $op = TCPDF_STATIC::getPathPaintOperator($style);
  11098. $this->_outRect($x, $y, $w, $h, $op);
  11099. }
  11100. if (!empty($border_style)) {
  11101. $border_style2 = array();
  11102. foreach ($border_style as $line => $value) {
  11103. $length = strlen($line);
  11104. for ($i = 0; $i < $length; ++$i) {
  11105. $border_style2[$line[$i]] = $value;
  11106. }
  11107. }
  11108. $border_style = $border_style2;
  11109. if (isset($border_style['L']) AND $border_style['L']) {
  11110. $this->Line($x, $y, $x, $y + $h, $border_style['L']);
  11111. }
  11112. if (isset($border_style['T']) AND $border_style['T']) {
  11113. $this->Line($x, $y, $x + $w, $y, $border_style['T']);
  11114. }
  11115. if (isset($border_style['R']) AND $border_style['R']) {
  11116. $this->Line($x + $w, $y, $x + $w, $y + $h, $border_style['R']);
  11117. }
  11118. if (isset($border_style['B']) AND $border_style['B']) {
  11119. $this->Line($x, $y + $h, $x + $w, $y + $h, $border_style['B']);
  11120. }
  11121. }
  11122. }
  11123. /**
  11124. * Draws a Bezier curve.
  11125. * The Bezier curve is a tangent to the line between the control points at
  11126. * either end of the curve.
  11127. * @param $x0 (float) Abscissa of start point.
  11128. * @param $y0 (float) Ordinate of start point.
  11129. * @param $x1 (float) Abscissa of control point 1.
  11130. * @param $y1 (float) Ordinate of control point 1.
  11131. * @param $x2 (float) Abscissa of control point 2.
  11132. * @param $y2 (float) Ordinate of control point 2.
  11133. * @param $x3 (float) Abscissa of end point.
  11134. * @param $y3 (float) Ordinate of end point.
  11135. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  11136. * @param $line_style (array) Line style of curve. Array like for SetLineStyle(). Default value: default line style (empty array).
  11137. * @param $fill_color (array) Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K) or array(C,M,Y,K,SpotColorName). Default value: default color (empty array).
  11138. * @public
  11139. * @see SetLineStyle()
  11140. * @since 2.1.000 (2008-01-08)
  11141. */
  11142. public function Curve($x0, $y0, $x1, $y1, $x2, $y2, $x3, $y3, $style='', $line_style=array(), $fill_color=array()) {
  11143. if ($this->state != 2) {
  11144. return;
  11145. }
  11146. if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
  11147. $this->SetFillColorArray($fill_color);
  11148. }
  11149. $op = TCPDF_STATIC::getPathPaintOperator($style);
  11150. if ($line_style) {
  11151. $this->SetLineStyle($line_style);
  11152. }
  11153. $this->_outPoint($x0, $y0);
  11154. $this->_outCurve($x1, $y1, $x2, $y2, $x3, $y3);
  11155. $this->_out($op);
  11156. }
  11157. /**
  11158. * Draws a poly-Bezier curve.
  11159. * Each Bezier curve segment is a tangent to the line between the control points at
  11160. * either end of the curve.
  11161. * @param $x0 (float) Abscissa of start point.
  11162. * @param $y0 (float) Ordinate of start point.
  11163. * @param $segments (float) An array of bezier descriptions. Format: array(x1, y1, x2, y2, x3, y3).
  11164. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  11165. * @param $line_style (array) Line style of curve. Array like for SetLineStyle(). Default value: default line style (empty array).
  11166. * @param $fill_color (array) Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K) or array(C,M,Y,K,SpotColorName). Default value: default color (empty array).
  11167. * @public
  11168. * @see SetLineStyle()
  11169. * @since 3.0008 (2008-05-12)
  11170. */
  11171. public function Polycurve($x0, $y0, $segments, $style='', $line_style=array(), $fill_color=array()) {
  11172. if ($this->state != 2) {
  11173. return;
  11174. }
  11175. if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
  11176. $this->SetFillColorArray($fill_color);
  11177. }
  11178. $op = TCPDF_STATIC::getPathPaintOperator($style);
  11179. if ($op == 'f') {
  11180. $line_style = array();
  11181. }
  11182. if ($line_style) {
  11183. $this->SetLineStyle($line_style);
  11184. }
  11185. $this->_outPoint($x0, $y0);
  11186. foreach ($segments as $segment) {
  11187. list($x1, $y1, $x2, $y2, $x3, $y3) = $segment;
  11188. $this->_outCurve($x1, $y1, $x2, $y2, $x3, $y3);
  11189. }
  11190. $this->_out($op);
  11191. }
  11192. /**
  11193. * Draws an ellipse.
  11194. * An ellipse is formed from n Bezier curves.
  11195. * @param $x0 (float) Abscissa of center point.
  11196. * @param $y0 (float) Ordinate of center point.
  11197. * @param $rx (float) Horizontal radius.
  11198. * @param $ry (float) Vertical radius (if ry = 0 then is a circle, see Circle()). Default value: 0.
  11199. * @param $angle: (float) Angle oriented (anti-clockwise). Default value: 0.
  11200. * @param $astart: (float) Angle start of draw line. Default value: 0.
  11201. * @param $afinish: (float) Angle finish of draw line. Default value: 360.
  11202. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  11203. * @param $line_style (array) Line style of ellipse. Array like for SetLineStyle(). Default value: default line style (empty array).
  11204. * @param $fill_color (array) Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K) or array(C,M,Y,K,SpotColorName). Default value: default color (empty array).
  11205. * @param $nc (integer) Number of curves used to draw a 90 degrees portion of ellipse.
  11206. * @author Nicola Asuni
  11207. * @public
  11208. * @since 2.1.000 (2008-01-08)
  11209. */
  11210. public function Ellipse($x0, $y0, $rx, $ry='', $angle=0, $astart=0, $afinish=360, $style='', $line_style=array(), $fill_color=array(), $nc=2) {
  11211. if ($this->state != 2) {
  11212. return;
  11213. }
  11214. if (TCPDF_STATIC::empty_string($ry) OR ($ry == 0)) {
  11215. $ry = $rx;
  11216. }
  11217. if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
  11218. $this->SetFillColorArray($fill_color);
  11219. }
  11220. $op = TCPDF_STATIC::getPathPaintOperator($style);
  11221. if ($op == 'f') {
  11222. $line_style = array();
  11223. }
  11224. if ($line_style) {
  11225. $this->SetLineStyle($line_style);
  11226. }
  11227. $this->_outellipticalarc($x0, $y0, $rx, $ry, $angle, $astart, $afinish, false, $nc, true, true, false);
  11228. $this->_out($op);
  11229. }
  11230. /**
  11231. * Append an elliptical arc to the current path.
  11232. * An ellipse is formed from n Bezier curves.
  11233. * @param $xc (float) Abscissa of center point.
  11234. * @param $yc (float) Ordinate of center point.
  11235. * @param $rx (float) Horizontal radius.
  11236. * @param $ry (float) Vertical radius (if ry = 0 then is a circle, see Circle()). Default value: 0.
  11237. * @param $xang: (float) Angle between the X-axis and the major axis of the ellipse. Default value: 0.
  11238. * @param $angs: (float) Angle start of draw line. Default value: 0.
  11239. * @param $angf: (float) Angle finish of draw line. Default value: 360.
  11240. * @param $pie (boolean) if true do not mark the border point (used to draw pie sectors).
  11241. * @param $nc (integer) Number of curves used to draw a 90 degrees portion of ellipse.
  11242. * @param $startpoint (boolean) if true output a starting point.
  11243. * @param $ccw (boolean) if true draws in counter-clockwise.
  11244. * @param $svg (boolean) if true the angles are in svg mode (already calculated).
  11245. * @return array bounding box coordinates (x min, y min, x max, y max)
  11246. * @author Nicola Asuni
  11247. * @protected
  11248. * @since 4.9.019 (2010-04-26)
  11249. */
  11250. protected function _outellipticalarc($xc, $yc, $rx, $ry, $xang=0, $angs=0, $angf=360, $pie=false, $nc=2, $startpoint=true, $ccw=true, $svg=false) {
  11251. if (($rx <= 0) OR ($ry < 0)) {
  11252. return;
  11253. }
  11254. $k = $this->k;
  11255. if ($nc < 2) {
  11256. $nc = 2;
  11257. }
  11258. $xmin = 2147483647;
  11259. $ymin = 2147483647;
  11260. $xmax = 0;
  11261. $ymax = 0;
  11262. if ($pie) {
  11263. // center of the arc
  11264. $this->_outPoint($xc, $yc);
  11265. }
  11266. $xang = deg2rad((float) $xang);
  11267. $angs = deg2rad((float) $angs);
  11268. $angf = deg2rad((float) $angf);
  11269. if ($svg) {
  11270. $as = $angs;
  11271. $af = $angf;
  11272. } else {
  11273. $as = atan2((sin($angs) / $ry), (cos($angs) / $rx));
  11274. $af = atan2((sin($angf) / $ry), (cos($angf) / $rx));
  11275. }
  11276. if ($as < 0) {
  11277. $as += (2 * M_PI);
  11278. }
  11279. if ($af < 0) {
  11280. $af += (2 * M_PI);
  11281. }
  11282. if ($ccw AND ($as > $af)) {
  11283. // reverse rotation
  11284. $as -= (2 * M_PI);
  11285. } elseif (!$ccw AND ($as < $af)) {
  11286. // reverse rotation
  11287. $af -= (2 * M_PI);
  11288. }
  11289. $total_angle = ($af - $as);
  11290. if ($nc < 2) {
  11291. $nc = 2;
  11292. }
  11293. // total arcs to draw
  11294. $nc *= (2 * abs($total_angle) / M_PI);
  11295. $nc = round($nc) + 1;
  11296. // angle of each arc
  11297. $arcang = ($total_angle / $nc);
  11298. // center point in PDF coordinates
  11299. $x0 = $xc;
  11300. $y0 = ($this->h - $yc);
  11301. // starting angle
  11302. $ang = $as;
  11303. $alpha = sin($arcang) * ((sqrt(4 + (3 * pow(tan(($arcang) / 2), 2))) - 1) / 3);
  11304. $cos_xang = cos($xang);
  11305. $sin_xang = sin($xang);
  11306. $cos_ang = cos($ang);
  11307. $sin_ang = sin($ang);
  11308. // first arc point
  11309. $px1 = $x0 + ($rx * $cos_xang * $cos_ang) - ($ry * $sin_xang * $sin_ang);
  11310. $py1 = $y0 + ($rx * $sin_xang * $cos_ang) + ($ry * $cos_xang * $sin_ang);
  11311. // first Bezier control point
  11312. $qx1 = ($alpha * ((-$rx * $cos_xang * $sin_ang) - ($ry * $sin_xang * $cos_ang)));
  11313. $qy1 = ($alpha * ((-$rx * $sin_xang * $sin_ang) + ($ry * $cos_xang * $cos_ang)));
  11314. if ($pie) {
  11315. // line from center to arc starting point
  11316. $this->_outLine($px1, $this->h - $py1);
  11317. } elseif ($startpoint) {
  11318. // arc starting point
  11319. $this->_outPoint($px1, $this->h - $py1);
  11320. }
  11321. // draw arcs
  11322. for ($i = 1; $i <= $nc; ++$i) {
  11323. // starting angle
  11324. $ang = $as + ($i * $arcang);
  11325. if ($i == $nc) {
  11326. $ang = $af;
  11327. }
  11328. $cos_ang = cos($ang);
  11329. $sin_ang = sin($ang);
  11330. // second arc point
  11331. $px2 = $x0 + ($rx * $cos_xang * $cos_ang) - ($ry * $sin_xang * $sin_ang);
  11332. $py2 = $y0 + ($rx * $sin_xang * $cos_ang) + ($ry * $cos_xang * $sin_ang);
  11333. // second Bezier control point
  11334. $qx2 = ($alpha * ((-$rx * $cos_xang * $sin_ang) - ($ry * $sin_xang * $cos_ang)));
  11335. $qy2 = ($alpha * ((-$rx * $sin_xang * $sin_ang) + ($ry * $cos_xang * $cos_ang)));
  11336. // draw arc
  11337. $cx1 = ($px1 + $qx1);
  11338. $cy1 = ($this->h - ($py1 + $qy1));
  11339. $cx2 = ($px2 - $qx2);
  11340. $cy2 = ($this->h - ($py2 - $qy2));
  11341. $cx3 = $px2;
  11342. $cy3 = ($this->h - $py2);
  11343. $this->_outCurve($cx1, $cy1, $cx2, $cy2, $cx3, $cy3);
  11344. // get bounding box coordinates
  11345. $xmin = min($xmin, $cx1, $cx2, $cx3);
  11346. $ymin = min($ymin, $cy1, $cy2, $cy3);
  11347. $xmax = max($xmax, $cx1, $cx2, $cx3);
  11348. $ymax = max($ymax, $cy1, $cy2, $cy3);
  11349. // move to next point
  11350. $px1 = $px2;
  11351. $py1 = $py2;
  11352. $qx1 = $qx2;
  11353. $qy1 = $qy2;
  11354. }
  11355. if ($pie) {
  11356. $this->_outLine($xc, $yc);
  11357. // get bounding box coordinates
  11358. $xmin = min($xmin, $xc);
  11359. $ymin = min($ymin, $yc);
  11360. $xmax = max($xmax, $xc);
  11361. $ymax = max($ymax, $yc);
  11362. }
  11363. return array($xmin, $ymin, $xmax, $ymax);
  11364. }
  11365. /**
  11366. * Draws a circle.
  11367. * A circle is formed from n Bezier curves.
  11368. * @param $x0 (float) Abscissa of center point.
  11369. * @param $y0 (float) Ordinate of center point.
  11370. * @param $r (float) Radius.
  11371. * @param $angstr: (float) Angle start of draw line. Default value: 0.
  11372. * @param $angend: (float) Angle finish of draw line. Default value: 360.
  11373. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  11374. * @param $line_style (array) Line style of circle. Array like for SetLineStyle(). Default value: default line style (empty array).
  11375. * @param $fill_color (array) Fill color. Format: array(red, green, blue). Default value: default color (empty array).
  11376. * @param $nc (integer) Number of curves used to draw a 90 degrees portion of circle.
  11377. * @public
  11378. * @since 2.1.000 (2008-01-08)
  11379. */
  11380. public function Circle($x0, $y0, $r, $angstr=0, $angend=360, $style='', $line_style=array(), $fill_color=array(), $nc=2) {
  11381. $this->Ellipse($x0, $y0, $r, $r, 0, $angstr, $angend, $style, $line_style, $fill_color, $nc);
  11382. }
  11383. /**
  11384. * Draws a polygonal line
  11385. * @param $p (array) Points 0 to ($np - 1). Array with values (x0, y0, x1, y1,..., x(np-1), y(np - 1))
  11386. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  11387. * @param $line_style (array) Line style of polygon. Array with keys among the following:
  11388. * <ul>
  11389. * <li>all: Line style of all lines. Array like for SetLineStyle().</li>
  11390. * <li>0 to ($np - 1): Line style of each line. Array like for SetLineStyle().</li>
  11391. * </ul>
  11392. * If a key is not present or is null, not draws the line. Default value is default line style (empty array).
  11393. * @param $fill_color (array) Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K) or array(C,M,Y,K,SpotColorName). Default value: default color (empty array).
  11394. * @since 4.8.003 (2009-09-15)
  11395. * @public
  11396. */
  11397. public function PolyLine($p, $style='', $line_style=array(), $fill_color=array()) {
  11398. $this->Polygon($p, $style, $line_style, $fill_color, false);
  11399. }
  11400. /**
  11401. * Draws a polygon.
  11402. * @param $p (array) Points 0 to ($np - 1). Array with values (x0, y0, x1, y1,..., x(np-1), y(np - 1))
  11403. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  11404. * @param $line_style (array) Line style of polygon. Array with keys among the following:
  11405. * <ul>
  11406. * <li>all: Line style of all lines. Array like for SetLineStyle().</li>
  11407. * <li>0 to ($np - 1): Line style of each line. Array like for SetLineStyle().</li>
  11408. * </ul>
  11409. * If a key is not present or is null, not draws the line. Default value is default line style (empty array).
  11410. * @param $fill_color (array) Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K) or array(C,M,Y,K,SpotColorName). Default value: default color (empty array).
  11411. * @param $closed (boolean) if true the polygon is closes, otherwise will remain open
  11412. * @public
  11413. * @since 2.1.000 (2008-01-08)
  11414. */
  11415. public function Polygon($p, $style='', $line_style=array(), $fill_color=array(), $closed=true) {
  11416. if ($this->state != 2) {
  11417. return;
  11418. }
  11419. $nc = count($p); // number of coordinates
  11420. $np = $nc / 2; // number of points
  11421. if ($closed) {
  11422. // close polygon by adding the first 2 points at the end (one line)
  11423. for ($i = 0; $i < 4; ++$i) {
  11424. $p[$nc + $i] = $p[$i];
  11425. }
  11426. // copy style for the last added line
  11427. if (isset($line_style[0])) {
  11428. $line_style[$np] = $line_style[0];
  11429. }
  11430. $nc += 4;
  11431. }
  11432. if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
  11433. $this->SetFillColorArray($fill_color);
  11434. }
  11435. $op = TCPDF_STATIC::getPathPaintOperator($style);
  11436. if ($op == 'f') {
  11437. $line_style = array();
  11438. }
  11439. $draw = true;
  11440. if ($line_style) {
  11441. if (isset($line_style['all'])) {
  11442. $this->SetLineStyle($line_style['all']);
  11443. } else {
  11444. $draw = false;
  11445. if ($op == 'B') {
  11446. // draw fill
  11447. $op = 'f';
  11448. $this->_outPoint($p[0], $p[1]);
  11449. for ($i = 2; $i < $nc; $i = $i + 2) {
  11450. $this->_outLine($p[$i], $p[$i + 1]);
  11451. }
  11452. $this->_out($op);
  11453. }
  11454. // draw outline
  11455. $this->_outPoint($p[0], $p[1]);
  11456. for ($i = 2; $i < $nc; $i = $i + 2) {
  11457. $line_num = ($i / 2) - 1;
  11458. if (isset($line_style[$line_num])) {
  11459. if ($line_style[$line_num] != 0) {
  11460. if (is_array($line_style[$line_num])) {
  11461. $this->_out('S');
  11462. $this->SetLineStyle($line_style[$line_num]);
  11463. $this->_outPoint($p[$i - 2], $p[$i - 1]);
  11464. $this->_outLine($p[$i], $p[$i + 1]);
  11465. $this->_out('S');
  11466. $this->_outPoint($p[$i], $p[$i + 1]);
  11467. } else {
  11468. $this->_outLine($p[$i], $p[$i + 1]);
  11469. }
  11470. }
  11471. } else {
  11472. $this->_outLine($p[$i], $p[$i + 1]);
  11473. }
  11474. }
  11475. $this->_out($op);
  11476. }
  11477. }
  11478. if ($draw) {
  11479. $this->_outPoint($p[0], $p[1]);
  11480. for ($i = 2; $i < $nc; $i = $i + 2) {
  11481. $this->_outLine($p[$i], $p[$i + 1]);
  11482. }
  11483. $this->_out($op);
  11484. }
  11485. }
  11486. /**
  11487. * Draws a regular polygon.
  11488. * @param $x0 (float) Abscissa of center point.
  11489. * @param $y0 (float) Ordinate of center point.
  11490. * @param $r: (float) Radius of inscribed circle.
  11491. * @param $ns (integer) Number of sides.
  11492. * @param $angle (float) Angle oriented (anti-clockwise). Default value: 0.
  11493. * @param $draw_circle (boolean) Draw inscribed circle or not. Default value: false.
  11494. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  11495. * @param $line_style (array) Line style of polygon sides. Array with keys among the following:
  11496. * <ul>
  11497. * <li>all: Line style of all sides. Array like for SetLineStyle().</li>
  11498. * <li>0 to ($ns - 1): Line style of each side. Array like for SetLineStyle().</li>
  11499. * </ul>
  11500. * If a key is not present or is null, not draws the side. Default value is default line style (empty array).
  11501. * @param $fill_color (array) Fill color. Format: array(red, green, blue). Default value: default color (empty array).
  11502. * @param $circle_style (string) Style of rendering of inscribed circle (if draws). Possible values are:
  11503. * <ul>
  11504. * <li>D or empty string: Draw (default).</li>
  11505. * <li>F: Fill.</li>
  11506. * <li>DF or FD: Draw and fill.</li>
  11507. * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
  11508. * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
  11509. * </ul>
  11510. * @param $circle_outLine_style (array) Line style of inscribed circle (if draws). Array like for SetLineStyle(). Default value: default line style (empty array).
  11511. * @param $circle_fill_color (array) Fill color of inscribed circle (if draws). Format: array(red, green, blue). Default value: default color (empty array).
  11512. * @public
  11513. * @since 2.1.000 (2008-01-08)
  11514. */
  11515. 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()) {
  11516. if (3 > $ns) {
  11517. $ns = 3;
  11518. }
  11519. if ($draw_circle) {
  11520. $this->Circle($x0, $y0, $r, 0, 360, $circle_style, $circle_outLine_style, $circle_fill_color);
  11521. }
  11522. $p = array();
  11523. for ($i = 0; $i < $ns; ++$i) {
  11524. $a = $angle + ($i * 360 / $ns);
  11525. $a_rad = deg2rad((float) $a);
  11526. $p[] = $x0 + ($r * sin($a_rad));
  11527. $p[] = $y0 + ($r * cos($a_rad));
  11528. }
  11529. $this->Polygon($p, $style, $line_style, $fill_color);
  11530. }
  11531. /**
  11532. * Draws a star polygon
  11533. * @param $x0 (float) Abscissa of center point.
  11534. * @param $y0 (float) Ordinate of center point.
  11535. * @param $r (float) Radius of inscribed circle.
  11536. * @param $nv (integer) Number of vertices.
  11537. * @param $ng (integer) Number of gap (if ($ng % $nv = 1) then is a regular polygon).
  11538. * @param $angle: (float) Angle oriented (anti-clockwise). Default value: 0.
  11539. * @param $draw_circle: (boolean) Draw inscribed circle or not. Default value is false.
  11540. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  11541. * @param $line_style (array) Line style of polygon sides. Array with keys among the following:
  11542. * <ul>
  11543. * <li>all: Line style of all sides. Array like for
  11544. * SetLineStyle().</li>
  11545. * <li>0 to (n - 1): Line style of each side. Array like for SetLineStyle().</li>
  11546. * </ul>
  11547. * If a key is not present or is null, not draws the side. Default value is default line style (empty array).
  11548. * @param $fill_color (array) Fill color. Format: array(red, green, blue). Default value: default color (empty array).
  11549. * @param $circle_style (string) Style of rendering of inscribed circle (if draws). Possible values are:
  11550. * <ul>
  11551. * <li>D or empty string: Draw (default).</li>
  11552. * <li>F: Fill.</li>
  11553. * <li>DF or FD: Draw and fill.</li>
  11554. * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
  11555. * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
  11556. * </ul>
  11557. * @param $circle_outLine_style (array) Line style of inscribed circle (if draws). Array like for SetLineStyle(). Default value: default line style (empty array).
  11558. * @param $circle_fill_color (array) Fill color of inscribed circle (if draws). Format: array(red, green, blue). Default value: default color (empty array).
  11559. * @public
  11560. * @since 2.1.000 (2008-01-08)
  11561. */
  11562. 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()) {
  11563. if ($nv < 2) {
  11564. $nv = 2;
  11565. }
  11566. if ($draw_circle) {
  11567. $this->Circle($x0, $y0, $r, 0, 360, $circle_style, $circle_outLine_style, $circle_fill_color);
  11568. }
  11569. $p2 = array();
  11570. $visited = array();
  11571. for ($i = 0; $i < $nv; ++$i) {
  11572. $a = $angle + ($i * 360 / $nv);
  11573. $a_rad = deg2rad((float) $a);
  11574. $p2[] = $x0 + ($r * sin($a_rad));
  11575. $p2[] = $y0 + ($r * cos($a_rad));
  11576. $visited[] = false;
  11577. }
  11578. $p = array();
  11579. $i = 0;
  11580. do {
  11581. $p[] = $p2[$i * 2];
  11582. $p[] = $p2[($i * 2) + 1];
  11583. $visited[$i] = true;
  11584. $i += $ng;
  11585. $i %= $nv;
  11586. } while (!$visited[$i]);
  11587. $this->Polygon($p, $style, $line_style, $fill_color);
  11588. }
  11589. /**
  11590. * Draws a rounded rectangle.
  11591. * @param $x (float) Abscissa of upper-left corner.
  11592. * @param $y (float) Ordinate of upper-left corner.
  11593. * @param $w (float) Width.
  11594. * @param $h (float) Height.
  11595. * @param $r (float) the radius of the circle used to round off the corners of the rectangle.
  11596. * @param $round_corner (string) Draws rounded corner or not. String with a 0 (not rounded i-corner) or 1 (rounded i-corner) in i-position. Positions are, in order and begin to 0: top right, bottom right, bottom left and top left. Default value: all rounded corner ("1111").
  11597. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  11598. * @param $border_style (array) Border style of rectangle. Array like for SetLineStyle(). Default value: default line style (empty array).
  11599. * @param $fill_color (array) Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K) or array(C,M,Y,K,SpotColorName). Default value: default color (empty array).
  11600. * @public
  11601. * @since 2.1.000 (2008-01-08)
  11602. */
  11603. public function RoundedRect($x, $y, $w, $h, $r, $round_corner='1111', $style='', $border_style=array(), $fill_color=array()) {
  11604. $this->RoundedRectXY($x, $y, $w, $h, $r, $r, $round_corner, $style, $border_style, $fill_color);
  11605. }
  11606. /**
  11607. * Draws a rounded rectangle.
  11608. * @param $x (float) Abscissa of upper-left corner.
  11609. * @param $y (float) Ordinate of upper-left corner.
  11610. * @param $w (float) Width.
  11611. * @param $h (float) Height.
  11612. * @param $rx (float) the x-axis radius of the ellipse used to round off the corners of the rectangle.
  11613. * @param $ry (float) the y-axis radius of the ellipse used to round off the corners of the rectangle.
  11614. * @param $round_corner (string) Draws rounded corner or not. String with a 0 (not rounded i-corner) or 1 (rounded i-corner) in i-position. Positions are, in order and begin to 0: top right, bottom right, bottom left and top left. Default value: all rounded corner ("1111").
  11615. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  11616. * @param $border_style (array) Border style of rectangle. Array like for SetLineStyle(). Default value: default line style (empty array).
  11617. * @param $fill_color (array) Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K) or array(C,M,Y,K,SpotColorName). Default value: default color (empty array).
  11618. * @public
  11619. * @since 4.9.019 (2010-04-22)
  11620. */
  11621. public function RoundedRectXY($x, $y, $w, $h, $rx, $ry, $round_corner='1111', $style='', $border_style=array(), $fill_color=array()) {
  11622. if ($this->state != 2) {
  11623. return;
  11624. }
  11625. if (($round_corner == '0000') OR (($rx == $ry) AND ($rx == 0))) {
  11626. // Not rounded
  11627. $this->Rect($x, $y, $w, $h, $style, $border_style, $fill_color);
  11628. return;
  11629. }
  11630. // Rounded
  11631. if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
  11632. $this->SetFillColorArray($fill_color);
  11633. }
  11634. $op = TCPDF_STATIC::getPathPaintOperator($style);
  11635. if ($op == 'f') {
  11636. $border_style = array();
  11637. }
  11638. if ($border_style) {
  11639. $this->SetLineStyle($border_style);
  11640. }
  11641. $MyArc = 4 / 3 * (sqrt(2) - 1);
  11642. $this->_outPoint($x + $rx, $y);
  11643. $xc = $x + $w - $rx;
  11644. $yc = $y + $ry;
  11645. $this->_outLine($xc, $y);
  11646. if ($round_corner[0]) {
  11647. $this->_outCurve($xc + ($rx * $MyArc), $yc - $ry, $xc + $rx, $yc - ($ry * $MyArc), $xc + $rx, $yc);
  11648. } else {
  11649. $this->_outLine($x + $w, $y);
  11650. }
  11651. $xc = $x + $w - $rx;
  11652. $yc = $y + $h - $ry;
  11653. $this->_outLine($x + $w, $yc);
  11654. if ($round_corner[1]) {
  11655. $this->_outCurve($xc + $rx, $yc + ($ry * $MyArc), $xc + ($rx * $MyArc), $yc + $ry, $xc, $yc + $ry);
  11656. } else {
  11657. $this->_outLine($x + $w, $y + $h);
  11658. }
  11659. $xc = $x + $rx;
  11660. $yc = $y + $h - $ry;
  11661. $this->_outLine($xc, $y + $h);
  11662. if ($round_corner[2]) {
  11663. $this->_outCurve($xc - ($rx * $MyArc), $yc + $ry, $xc - $rx, $yc + ($ry * $MyArc), $xc - $rx, $yc);
  11664. } else {
  11665. $this->_outLine($x, $y + $h);
  11666. }
  11667. $xc = $x + $rx;
  11668. $yc = $y + $ry;
  11669. $this->_outLine($x, $yc);
  11670. if ($round_corner[3]) {
  11671. $this->_outCurve($xc - $rx, $yc - ($ry * $MyArc), $xc - ($rx * $MyArc), $yc - $ry, $xc, $yc - $ry);
  11672. } else {
  11673. $this->_outLine($x, $y);
  11674. $this->_outLine($x + $rx, $y);
  11675. }
  11676. $this->_out($op);
  11677. }
  11678. /**
  11679. * Draws a grahic arrow.
  11680. * @param $x0 (float) Abscissa of first point.
  11681. * @param $y0 (float) Ordinate of first point.
  11682. * @param $x1 (float) Abscissa of second point.
  11683. * @param $y1 (float) Ordinate of second point.
  11684. * @param $head_style (int) (0 = draw only arrowhead arms, 1 = draw closed arrowhead, but no fill, 2 = closed and filled arrowhead, 3 = filled arrowhead)
  11685. * @param $arm_size (float) length of arrowhead arms
  11686. * @param $arm_angle (int) angle between an arm and the shaft
  11687. * @author Piotr Galecki, Nicola Asuni, Andy Meier
  11688. * @since 4.6.018 (2009-07-10)
  11689. */
  11690. public function Arrow($x0, $y0, $x1, $y1, $head_style=0, $arm_size=5, $arm_angle=15) {
  11691. // getting arrow direction angle
  11692. // 0 deg angle is when both arms go along X axis. angle grows clockwise.
  11693. $dir_angle = atan2(($y0 - $y1), ($x0 - $x1));
  11694. if ($dir_angle < 0) {
  11695. $dir_angle += (2 * M_PI);
  11696. }
  11697. $arm_angle = deg2rad($arm_angle);
  11698. $sx1 = $x1;
  11699. $sy1 = $y1;
  11700. if ($head_style > 0) {
  11701. // calculate the stopping point for the arrow shaft
  11702. $sx1 = $x1 + (($arm_size - $this->LineWidth) * cos($dir_angle));
  11703. $sy1 = $y1 + (($arm_size - $this->LineWidth) * sin($dir_angle));
  11704. }
  11705. // main arrow line / shaft
  11706. $this->Line($x0, $y0, $sx1, $sy1);
  11707. // left arrowhead arm tip
  11708. $x2L = $x1 + ($arm_size * cos($dir_angle + $arm_angle));
  11709. $y2L = $y1 + ($arm_size * sin($dir_angle + $arm_angle));
  11710. // right arrowhead arm tip
  11711. $x2R = $x1 + ($arm_size * cos($dir_angle - $arm_angle));
  11712. $y2R = $y1 + ($arm_size * sin($dir_angle - $arm_angle));
  11713. $mode = 'D';
  11714. $style = array();
  11715. switch ($head_style) {
  11716. case 0: {
  11717. // draw only arrowhead arms
  11718. $mode = 'D';
  11719. $style = array(1, 1, 0);
  11720. break;
  11721. }
  11722. case 1: {
  11723. // draw closed arrowhead, but no fill
  11724. $mode = 'D';
  11725. break;
  11726. }
  11727. case 2: {
  11728. // closed and filled arrowhead
  11729. $mode = 'DF';
  11730. break;
  11731. }
  11732. case 3: {
  11733. // filled arrowhead
  11734. $mode = 'F';
  11735. break;
  11736. }
  11737. }
  11738. $this->Polygon(array($x2L, $y2L, $x1, $y1, $x2R, $y2R), $mode, $style, array());
  11739. }
  11740. // END GRAPHIC FUNCTIONS SECTION -----------------------
  11741. /**
  11742. * Add a Named Destination.
  11743. * NOTE: destination names are unique, so only last entry will be saved.
  11744. * @param $name (string) Destination name.
  11745. * @param $y (float) Y position in user units of the destiantion on the selected page (default = -1 = current position; 0 = page start;).
  11746. * @param $page (int|string) Target page number (leave empty for current page). If you prefix a page number with the * character, then this page will not be changed when adding/deleting/moving pages.
  11747. * @param $x (float) X position in user units of the destiantion on the selected page (default = -1 = current position;).
  11748. * @return (string) Stripped named destination identifier or false in case of error.
  11749. * @public
  11750. * @author Christian Deligant, Nicola Asuni
  11751. * @since 5.9.097 (2011-06-23)
  11752. */
  11753. public function setDestination($name, $y=-1, $page='', $x=-1) {
  11754. // remove unsupported characters
  11755. $name = TCPDF_STATIC::encodeNameObject($name);
  11756. if (TCPDF_STATIC::empty_string($name)) {
  11757. return false;
  11758. }
  11759. if ($y == -1) {
  11760. $y = $this->GetY();
  11761. } elseif ($y < 0) {
  11762. $y = 0;
  11763. } elseif ($y > $this->h) {
  11764. $y = $this->h;
  11765. }
  11766. if ($x == -1) {
  11767. $x = $this->GetX();
  11768. } elseif ($x < 0) {
  11769. $x = 0;
  11770. } elseif ($x > $this->w) {
  11771. $x = $this->w;
  11772. }
  11773. $fixed = false;
  11774. if (!empty($page) AND ($page[0] == '*')) {
  11775. $page = intval(substr($page, 1));
  11776. // this page number will not be changed when moving/add/deleting pages
  11777. $fixed = true;
  11778. }
  11779. if (empty($page)) {
  11780. $page = $this->PageNo();
  11781. if (empty($page)) {
  11782. return;
  11783. }
  11784. }
  11785. $this->dests[$name] = array('x' => $x, 'y' => $y, 'p' => $page, 'f' => $fixed);
  11786. return $name;
  11787. }
  11788. /**
  11789. * Return the Named Destination array.
  11790. * @return (array) Named Destination array.
  11791. * @public
  11792. * @author Nicola Asuni
  11793. * @since 5.9.097 (2011-06-23)
  11794. */
  11795. public function getDestination() {
  11796. return $this->dests;
  11797. }
  11798. /**
  11799. * Insert Named Destinations.
  11800. * @protected
  11801. * @author Johannes G\FCntert, Nicola Asuni
  11802. * @since 5.9.098 (2011-06-23)
  11803. */
  11804. protected function _putdests() {
  11805. if (empty($this->dests)) {
  11806. return;
  11807. }
  11808. $this->n_dests = $this->_newobj();
  11809. $out = ' <<';
  11810. foreach($this->dests as $name => $o) {
  11811. $out .= ' /'.$name.' '.sprintf('[%u 0 R /XYZ %F %F null]', $this->page_obj_id[($o['p'])], ($o['x'] * $this->k), ($this->pagedim[$o['p']]['h'] - ($o['y'] * $this->k)));
  11812. }
  11813. $out .= ' >>';
  11814. $out .= "\n".'endobj';
  11815. $this->_out($out);
  11816. }
  11817. /**
  11818. * Adds a bookmark - alias for Bookmark().
  11819. * @param $txt (string) Bookmark description.
  11820. * @param $level (int) Bookmark level (minimum value is 0).
  11821. * @param $y (float) Y position in user units of the bookmark on the selected page (default = -1 = current position; 0 = page start;).
  11822. * @param $page (int|string) Target page number (leave empty for current page). If you prefix a page number with the * character, then this page will not be changed when adding/deleting/moving pages.
  11823. * @param $style (string) Font style: B = Bold, I = Italic, BI = Bold + Italic.
  11824. * @param $color (array) RGB color array (values from 0 to 255).
  11825. * @param $x (float) X position in user units of the bookmark on the selected page (default = -1 = current position;).
  11826. * @param $link (mixed) URL, or numerical link ID, or named destination (# character followed by the destination name), or embedded file (* character followed by the file name).
  11827. * @public
  11828. */
  11829. public function setBookmark($txt, $level=0, $y=-1, $page='', $style='', $color=array(0,0,0), $x=-1, $link='') {
  11830. $this->Bookmark($txt, $level, $y, $page, $style, $color, $x, $link);
  11831. }
  11832. /**
  11833. * Adds a bookmark.
  11834. * @param $txt (string) Bookmark description.
  11835. * @param $level (int) Bookmark level (minimum value is 0).
  11836. * @param $y (float) Y position in user units of the bookmark on the selected page (default = -1 = current position; 0 = page start;).
  11837. * @param $page (int|string) Target page number (leave empty for current page). If you prefix a page number with the * character, then this page will not be changed when adding/deleting/moving pages.
  11838. * @param $style (string) Font style: B = Bold, I = Italic, BI = Bold + Italic.
  11839. * @param $color (array) RGB color array (values from 0 to 255).
  11840. * @param $x (float) X position in user units of the bookmark on the selected page (default = -1 = current position;).
  11841. * @param $link (mixed) URL, or numerical link ID, or named destination (# character followed by the destination name), or embedded file (* character followed by the file name).
  11842. * @public
  11843. * @since 2.1.002 (2008-02-12)
  11844. */
  11845. public function Bookmark($txt, $level=0, $y=-1, $page='', $style='', $color=array(0,0,0), $x=-1, $link='') {
  11846. if ($level < 0) {
  11847. $level = 0;
  11848. }
  11849. if (isset($this->outlines[0])) {
  11850. $lastoutline = end($this->outlines);
  11851. $maxlevel = $lastoutline['l'] + 1;
  11852. } else {
  11853. $maxlevel = 0;
  11854. }
  11855. if ($level > $maxlevel) {
  11856. $level = $maxlevel;
  11857. }
  11858. if ($y == -1) {
  11859. $y = $this->GetY();
  11860. } elseif ($y < 0) {
  11861. $y = 0;
  11862. } elseif ($y > $this->h) {
  11863. $y = $this->h;
  11864. }
  11865. if ($x == -1) {
  11866. $x = $this->GetX();
  11867. } elseif ($x < 0) {
  11868. $x = 0;
  11869. } elseif ($x > $this->w) {
  11870. $x = $this->w;
  11871. }
  11872. $fixed = false;
  11873. if (!empty($page) AND ($page[0] == '*')) {
  11874. $page = intval(substr($page, 1));
  11875. // this page number will not be changed when moving/add/deleting pages
  11876. $fixed = true;
  11877. }
  11878. if (empty($page)) {
  11879. $page = $this->PageNo();
  11880. if (empty($page)) {
  11881. return;
  11882. }
  11883. }
  11884. $this->outlines[] = array('t' => $txt, 'l' => $level, 'x' => $x, 'y' => $y, 'p' => $page, 'f' => $fixed, 's' => strtoupper($style), 'c' => $color, 'u' => $link);
  11885. }
  11886. /**
  11887. * Sort bookmarks for page and key.
  11888. * @protected
  11889. * @since 5.9.119 (2011-09-19)
  11890. */
  11891. protected function sortBookmarks() {
  11892. // get sorting columns
  11893. $outline_p = array();
  11894. $outline_y = array();
  11895. foreach ($this->outlines as $key => $row) {
  11896. $outline_p[$key] = $row['p'];
  11897. $outline_k[$key] = $key;
  11898. }
  11899. // sort outlines by page and original position
  11900. array_multisort($outline_p, SORT_NUMERIC, SORT_ASC, $outline_k, SORT_NUMERIC, SORT_ASC, $this->outlines);
  11901. }
  11902. /**
  11903. * Create a bookmark PDF string.
  11904. * @protected
  11905. * @author Olivier Plathey, Nicola Asuni
  11906. * @since 2.1.002 (2008-02-12)
  11907. */
  11908. protected function _putbookmarks() {
  11909. $nb = count($this->outlines);
  11910. if ($nb == 0) {
  11911. return;
  11912. }
  11913. // sort bookmarks
  11914. $this->sortBookmarks();
  11915. $lru = array();
  11916. $level = 0;
  11917. foreach ($this->outlines as $i => $o) {
  11918. if ($o['l'] > 0) {
  11919. $parent = $lru[($o['l'] - 1)];
  11920. //Set parent and last pointers
  11921. $this->outlines[$i]['parent'] = $parent;
  11922. $this->outlines[$parent]['last'] = $i;
  11923. if ($o['l'] > $level) {
  11924. //Level increasing: set first pointer
  11925. $this->outlines[$parent]['first'] = $i;
  11926. }
  11927. } else {
  11928. $this->outlines[$i]['parent'] = $nb;
  11929. }
  11930. if (($o['l'] <= $level) AND ($i > 0)) {
  11931. //Set prev and next pointers
  11932. $prev = $lru[$o['l']];
  11933. $this->outlines[$prev]['next'] = $i;
  11934. $this->outlines[$i]['prev'] = $prev;
  11935. }
  11936. $lru[$o['l']] = $i;
  11937. $level = $o['l'];
  11938. }
  11939. //Outline items
  11940. $n = $this->n + 1;
  11941. $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';
  11942. foreach ($this->outlines as $i => $o) {
  11943. $oid = $this->_newobj();
  11944. // covert HTML title to string
  11945. $title = preg_replace($nltags, "\n", $o['t']);
  11946. $title = preg_replace("/[\r]+/si", '', $title);
  11947. $title = preg_replace("/[\n]+/si", "\n", $title);
  11948. $title = strip_tags($title);
  11949. $title = $this->stringTrim($title);
  11950. $out = '<</Title '.$this->_textstring($title, $oid);
  11951. $out .= ' /Parent '.($n + $o['parent']).' 0 R';
  11952. if (isset($o['prev'])) {
  11953. $out .= ' /Prev '.($n + $o['prev']).' 0 R';
  11954. }
  11955. if (isset($o['next'])) {
  11956. $out .= ' /Next '.($n + $o['next']).' 0 R';
  11957. }
  11958. if (isset($o['first'])) {
  11959. $out .= ' /First '.($n + $o['first']).' 0 R';
  11960. }
  11961. if (isset($o['last'])) {
  11962. $out .= ' /Last '.($n + $o['last']).' 0 R';
  11963. }
  11964. if (isset($o['u']) AND !empty($o['u'])) {
  11965. // link
  11966. if (is_string($o['u'])) {
  11967. if ($o['u'][0] == '#') {
  11968. // internal destination
  11969. $out .= ' /Dest /'.TCPDF_STATIC::encodeNameObject(substr($o['u'], 1));
  11970. } elseif ($o['u'][0] == '%') {
  11971. // embedded PDF file
  11972. $filename = basename(substr($o['u'], 1));
  11973. $out .= ' /A <</S /GoToE /D [0 /Fit] /NewWindow true /T << /R /C /P '.($o['p'] - 1).' /A '.$this->embeddedfiles[$filename]['a'].' >> >>';
  11974. } elseif ($o['u'][0] == '*') {
  11975. // embedded generic file
  11976. $filename = basename(substr($o['u'], 1));
  11977. $jsa = 'var D=event.target.doc;var MyData=D.dataObjects;for (var i in MyData) if (MyData[i].path=="'.$filename.'") D.exportDataObject( { cName : MyData[i].name, nLaunch : 2});';
  11978. $out .= ' /A <</S /JavaScript /JS '.$this->_textstring($jsa, $oid).'>>';
  11979. } else {
  11980. // external URI link
  11981. $out .= ' /A <</S /URI /URI '.$this->_datastring($this->unhtmlentities($o['u']), $oid).'>>';
  11982. }
  11983. } elseif (isset($this->links[$o['u']])) {
  11984. // internal link ID
  11985. $l = $this->links[$o['u']];
  11986. if (isset($this->page_obj_id[($l['p'])])) {
  11987. $out .= sprintf(' /Dest [%u 0 R /XYZ 0 %F null]', $this->page_obj_id[($l['p'])], ($this->pagedim[$l['p']]['h'] - ($l['y'] * $this->k)));
  11988. }
  11989. }
  11990. } elseif (isset($this->page_obj_id[($o['p'])])) {
  11991. // link to a page
  11992. $out .= ' '.sprintf('/Dest [%u 0 R /XYZ %F %F null]', $this->page_obj_id[($o['p'])], ($o['x'] * $this->k), ($this->pagedim[$o['p']]['h'] - ($o['y'] * $this->k)));
  11993. }
  11994. // set font style
  11995. $style = 0;
  11996. if (!empty($o['s'])) {
  11997. // bold
  11998. if (strpos($o['s'], 'B') !== false) {
  11999. $style |= 2;
  12000. }
  12001. // oblique
  12002. if (strpos($o['s'], 'I') !== false) {
  12003. $style |= 1;
  12004. }
  12005. }
  12006. $out .= sprintf(' /F %d', $style);
  12007. // set bookmark color
  12008. if (isset($o['c']) AND is_array($o['c']) AND (count($o['c']) == 3)) {
  12009. $color = array_values($o['c']);
  12010. $out .= sprintf(' /C [%F %F %F]', ($color[0] / 255), ($color[1] / 255), ($color[2] / 255));
  12011. } else {
  12012. // black
  12013. $out .= ' /C [0.0 0.0 0.0]';
  12014. }
  12015. $out .= ' /Count 0'; // normally closed item
  12016. $out .= ' >>';
  12017. $out .= "\n".'endobj';
  12018. $this->_out($out);
  12019. }
  12020. //Outline root
  12021. $this->OutlineRoot = $this->_newobj();
  12022. $this->_out('<< /Type /Outlines /First '.$n.' 0 R /Last '.($n + $lru[0]).' 0 R >>'."\n".'endobj');
  12023. }
  12024. // --- JAVASCRIPT ------------------------------------------------------
  12025. /**
  12026. * Adds a javascript
  12027. * @param $script (string) Javascript code
  12028. * @public
  12029. * @author Johannes G\FCntert, Nicola Asuni
  12030. * @since 2.1.002 (2008-02-12)
  12031. */
  12032. public function IncludeJS($script) {
  12033. $this->javascript .= $script;
  12034. }
  12035. /**
  12036. * Adds a javascript object and return object ID
  12037. * @param $script (string) Javascript code
  12038. * @param $onload (boolean) if true executes this object when opening the document
  12039. * @return int internal object ID
  12040. * @public
  12041. * @author Nicola Asuni
  12042. * @since 4.8.000 (2009-09-07)
  12043. */
  12044. public function addJavascriptObject($script, $onload=false) {
  12045. if ($this->pdfa_mode) {
  12046. // javascript is not allowed in PDF/A mode
  12047. return false;
  12048. }
  12049. ++$this->n;
  12050. $this->js_objects[$this->n] = array('n' => $this->n, 'js' => $script, 'onload' => $onload);
  12051. return $this->n;
  12052. }
  12053. /**
  12054. * Create a javascript PDF string.
  12055. * @protected
  12056. * @author Johannes G\FCntert, Nicola Asuni
  12057. * @since 2.1.002 (2008-02-12)
  12058. */
  12059. protected function _putjavascript() {
  12060. if ($this->pdfa_mode OR (empty($this->javascript) AND empty($this->js_objects))) {
  12061. return;
  12062. }
  12063. if (strpos($this->javascript, 'this.addField') > 0) {
  12064. if (!$this->ur['enabled']) {
  12065. //$this->setUserRights();
  12066. }
  12067. // the following two lines are used to avoid form fields duplication after saving
  12068. // The addField method only works when releasing user rights (UR3)
  12069. $jsa = sprintf("ftcpdfdocsaved=this.addField('%s','%s',%d,[%F,%F,%F,%F]);", 'tcpdfdocsaved', 'text', 0, 0, 1, 0, 1);
  12070. $jsb = "getField('tcpdfdocsaved').value='saved';";
  12071. $this->javascript = $jsa."\n".$this->javascript."\n".$jsb;
  12072. }
  12073. // name tree for javascript
  12074. $this->n_js = '<< /Names [';
  12075. if (!empty($this->javascript)) {
  12076. $this->n_js .= ' (EmbeddedJS) '.($this->n + 1).' 0 R';
  12077. }
  12078. if (!empty($this->js_objects)) {
  12079. foreach ($this->js_objects as $key => $val) {
  12080. if ($val['onload']) {
  12081. $this->n_js .= ' (JS'.$key.') '.$key.' 0 R';
  12082. }
  12083. }
  12084. }
  12085. $this->n_js .= ' ] >>';
  12086. // default Javascript object
  12087. if (!empty($this->javascript)) {
  12088. $obj_id = $this->_newobj();
  12089. $out = '<< /S /JavaScript';
  12090. $out .= ' /JS '.$this->_textstring($this->javascript, $obj_id);
  12091. $out .= ' >>';
  12092. $out .= "\n".'endobj';
  12093. $this->_out($out);
  12094. }
  12095. // additional Javascript objects
  12096. if (!empty($this->js_objects)) {
  12097. foreach ($this->js_objects as $key => $val) {
  12098. $out = $this->_getobj($key)."\n".' << /S /JavaScript /JS '.$this->_textstring($val['js'], $key).' >>'."\n".'endobj';
  12099. $this->_out($out);
  12100. }
  12101. }
  12102. }
  12103. /**
  12104. * Adds a javascript form field.
  12105. * @param $type (string) field type
  12106. * @param $name (string) field name
  12107. * @param $x (int) horizontal position
  12108. * @param $y (int) vertical position
  12109. * @param $w (int) width
  12110. * @param $h (int) height
  12111. * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
  12112. * @protected
  12113. * @author Denis Van Nuffelen, Nicola Asuni
  12114. * @since 2.1.002 (2008-02-12)
  12115. */
  12116. protected function _addfield($type, $name, $x, $y, $w, $h, $prop) {
  12117. if ($this->rtl) {
  12118. $x = $x - $w;
  12119. }
  12120. // the followind avoid fields duplication after saving the document
  12121. $this->javascript .= "if (getField('tcpdfdocsaved').value != 'saved') {";
  12122. $k = $this->k;
  12123. $this->javascript .= sprintf("f".$name."=this.addField('%s','%s',%u,[%F,%F,%F,%F]);", $name, $type, $this->PageNo()-1, $x*$k, ($this->h-$y)*$k+1, ($x+$w)*$k, ($this->h-$y-$h)*$k+1)."\n";
  12124. $this->javascript .= 'f'.$name.'.textSize='.$this->FontSizePt.";\n";
  12125. foreach($prop as $key => $val) {
  12126. if (strcmp(substr($key, -5), 'Color') == 0) {
  12127. $val = TCPDF_COLORS::_JScolor($val);
  12128. } else {
  12129. $val = "'".$val."'";
  12130. }
  12131. $this->javascript .= 'f'.$name.'.'.$key.'='.$val.";\n";
  12132. }
  12133. if ($this->rtl) {
  12134. $this->x -= $w;
  12135. } else {
  12136. $this->x += $w;
  12137. }
  12138. $this->javascript .= '}';
  12139. }
  12140. // --- FORM FIELDS -----------------------------------------------------
  12141. /**
  12142. * Set default properties for form fields.
  12143. * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
  12144. * @public
  12145. * @author Nicola Asuni
  12146. * @since 4.8.000 (2009-09-06)
  12147. */
  12148. public function setFormDefaultProp($prop=array()) {
  12149. $this->default_form_prop = $prop;
  12150. }
  12151. /**
  12152. * Return the default properties for form fields.
  12153. * @return array $prop javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
  12154. * @public
  12155. * @author Nicola Asuni
  12156. * @since 4.8.000 (2009-09-06)
  12157. */
  12158. public function getFormDefaultProp() {
  12159. return $this->default_form_prop;
  12160. }
  12161. /**
  12162. * Creates a text field
  12163. * @param $name (string) field name
  12164. * @param $w (float) Width of the rectangle
  12165. * @param $h (float) Height of the rectangle
  12166. * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
  12167. * @param $opt (array) annotation parameters. Possible values are described on official PDF32000_2008 reference.
  12168. * @param $x (float) Abscissa of the upper-left corner of the rectangle
  12169. * @param $y (float) Ordinate of the upper-left corner of the rectangle
  12170. * @param $js (boolean) if true put the field using JavaScript (requires Acrobat Writer to be rendered).
  12171. * @public
  12172. * @author Nicola Asuni
  12173. * @since 4.8.000 (2009-09-07)
  12174. */
  12175. public function TextField($name, $w, $h, $prop=array(), $opt=array(), $x='', $y='', $js=false) {
  12176. if ($x === '') {
  12177. $x = $this->x;
  12178. }
  12179. if ($y === '') {
  12180. $y = $this->y;
  12181. }
  12182. // check page for no-write regions and adapt page margins if necessary
  12183. list($x, $y) = $this->checkPageRegions($h, $x, $y);
  12184. if ($js) {
  12185. $this->_addfield('text', $name, $x, $y, $w, $h, $prop);
  12186. return;
  12187. }
  12188. // get default style
  12189. $prop = array_merge($this->getFormDefaultProp(), $prop);
  12190. // get annotation data
  12191. $popt = TCPDF_STATIC::getAnnotOptFromJSProp($prop, $this->spot_colors, $this->rtl);
  12192. // set default appearance stream
  12193. $this->annotation_fonts[$this->CurrentFont['fontkey']] = $this->CurrentFont['i'];
  12194. $fontstyle = sprintf('/F%d %F Tf %s', $this->CurrentFont['i'], $this->FontSizePt, $this->TextColor);
  12195. $popt['da'] = $fontstyle;
  12196. // build appearance stream
  12197. $popt['ap'] = array();
  12198. $popt['ap']['n'] = '/Tx BMC q '.$fontstyle.' ';
  12199. $text = '';
  12200. if (isset($prop['value']) AND !empty($prop['value'])) {
  12201. $text = $prop['value'];
  12202. } elseif (isset($opt['v']) AND !empty($opt['v'])) {
  12203. $text = $opt['v'];
  12204. }
  12205. $tmpid = $this->startTemplate($w, $h, false);
  12206. $align = '';
  12207. if (isset($popt['q'])) {
  12208. switch ($popt['q']) {
  12209. case 0: {
  12210. $align = 'L';
  12211. break;
  12212. }
  12213. case 1: {
  12214. $align = 'C';
  12215. break;
  12216. }
  12217. case 2: {
  12218. $align = 'R';
  12219. break;
  12220. }
  12221. default: {
  12222. $align = '';
  12223. break;
  12224. }
  12225. }
  12226. }
  12227. $this->MultiCell($w, $h, $text, 0, $align, false, 0, 0, 0, true, 0, false, true, 0, 'T', false);
  12228. $this->endTemplate();
  12229. --$this->n;
  12230. $popt['ap']['n'] .= $this->xobjects[$tmpid]['outdata'];
  12231. unset($this->xobjects[$tmpid]);
  12232. $popt['ap']['n'] .= 'Q EMC';
  12233. // merge options
  12234. $opt = array_merge($popt, $opt);
  12235. // remove some conflicting options
  12236. unset($opt['bs']);
  12237. // set remaining annotation data
  12238. $opt['Subtype'] = 'Widget';
  12239. $opt['ft'] = 'Tx';
  12240. $opt['t'] = $name;
  12241. // Additional annotation's parameters (check _putannotsobj() method):
  12242. //$opt['f']
  12243. //$opt['as']
  12244. //$opt['bs']
  12245. //$opt['be']
  12246. //$opt['c']
  12247. //$opt['border']
  12248. //$opt['h']
  12249. //$opt['mk'];
  12250. //$opt['mk']['r']
  12251. //$opt['mk']['bc'];
  12252. //$opt['mk']['bg'];
  12253. unset($opt['mk']['ca']);
  12254. unset($opt['mk']['rc']);
  12255. unset($opt['mk']['ac']);
  12256. unset($opt['mk']['i']);
  12257. unset($opt['mk']['ri']);
  12258. unset($opt['mk']['ix']);
  12259. unset($opt['mk']['if']);
  12260. //$opt['mk']['if']['sw'];
  12261. //$opt['mk']['if']['s'];
  12262. //$opt['mk']['if']['a'];
  12263. //$opt['mk']['if']['fb'];
  12264. unset($opt['mk']['tp']);
  12265. //$opt['tu']
  12266. //$opt['tm']
  12267. //$opt['ff']
  12268. //$opt['v']
  12269. //$opt['dv']
  12270. //$opt['a']
  12271. //$opt['aa']
  12272. //$opt['q']
  12273. $this->Annotation($x, $y, $w, $h, $name, $opt, 0);
  12274. if ($this->rtl) {
  12275. $this->x -= $w;
  12276. } else {
  12277. $this->x += $w;
  12278. }
  12279. }
  12280. /**
  12281. * Creates a RadioButton field.
  12282. * @param $name (string) Field name.
  12283. * @param $w (int) Width of the radio button.
  12284. * @param $prop (array) Javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
  12285. * @param $opt (array) Annotation parameters. Possible values are described on official PDF32000_2008 reference.
  12286. * @param $onvalue (string) Value to be returned if selected.
  12287. * @param $checked (boolean) Define the initial state.
  12288. * @param $x (float) Abscissa of the upper-left corner of the rectangle
  12289. * @param $y (float) Ordinate of the upper-left corner of the rectangle
  12290. * @param $js (boolean) If true put the field using JavaScript (requires Acrobat Writer to be rendered).
  12291. * @public
  12292. * @author Nicola Asuni
  12293. * @since 4.8.000 (2009-09-07)
  12294. */
  12295. public function RadioButton($name, $w, $prop=array(), $opt=array(), $onvalue='On', $checked=false, $x='', $y='', $js=false) {
  12296. if ($x === '') {
  12297. $x = $this->x;
  12298. }
  12299. if ($y === '') {
  12300. $y = $this->y;
  12301. }
  12302. // check page for no-write regions and adapt page margins if necessary
  12303. list($x, $y) = $this->checkPageRegions($w, $x, $y);
  12304. if ($js) {
  12305. $this->_addfield('radiobutton', $name, $x, $y, $w, $w, $prop);
  12306. return;
  12307. }
  12308. if (TCPDF_STATIC::empty_string($onvalue)) {
  12309. $onvalue = 'On';
  12310. }
  12311. if ($checked) {
  12312. $defval = $onvalue;
  12313. } else {
  12314. $defval = 'Off';
  12315. }
  12316. // set font
  12317. $font = 'zapfdingbats';
  12318. if ($this->pdfa_mode) {
  12319. // all fonts must be embedded
  12320. $font = 'pdfa'.$font;
  12321. }
  12322. $this->AddFont($font);
  12323. $tmpfont = $this->getFontBuffer($font);
  12324. // set data for parent group
  12325. if (!isset($this->radiobutton_groups[$this->page])) {
  12326. $this->radiobutton_groups[$this->page] = array();
  12327. }
  12328. if (!isset($this->radiobutton_groups[$this->page][$name])) {
  12329. $this->radiobutton_groups[$this->page][$name] = array();
  12330. ++$this->n;
  12331. $this->radiobutton_groups[$this->page][$name]['n'] = $this->n;
  12332. $this->radio_groups[] = $this->n;
  12333. }
  12334. $kid = ($this->n + 1);
  12335. // save object ID to be added on Kids entry on parent object
  12336. $this->radiobutton_groups[$this->page][$name][] = array('kid' => $kid, 'def' => $defval);
  12337. // get default style
  12338. $prop = array_merge($this->getFormDefaultProp(), $prop);
  12339. $prop['NoToggleToOff'] = 'true';
  12340. $prop['Radio'] = 'true';
  12341. $prop['borderStyle'] = 'inset';
  12342. // get annotation data
  12343. $popt = TCPDF_STATIC::getAnnotOptFromJSProp($prop, $this->spot_colors, $this->rtl);
  12344. // set additional default options
  12345. $this->annotation_fonts[$tmpfont['fontkey']] = $tmpfont['i'];
  12346. $fontstyle = sprintf('/F%d %F Tf %s', $tmpfont['i'], $this->FontSizePt, $this->TextColor);
  12347. $popt['da'] = $fontstyle;
  12348. // build appearance stream
  12349. $popt['ap'] = array();
  12350. $popt['ap']['n'] = array();
  12351. $fx = ((($w - $this->getAbsFontMeasure($tmpfont['cw'][108])) / 2) * $this->k);
  12352. $fy = (($w - ((($tmpfont['desc']['Ascent'] - $tmpfont['desc']['Descent']) * $this->FontSizePt / 1000) / $this->k)) * $this->k);
  12353. $popt['ap']['n'][$onvalue] = sprintf('q %s BT /F%d %F Tf %F %F Td ('.chr(108).') Tj ET Q', $this->TextColor, $tmpfont['i'], $this->FontSizePt, $fx, $fy);
  12354. $popt['ap']['n']['Off'] = sprintf('q %s BT /F%d %F Tf %F %F Td ('.chr(109).') Tj ET Q', $this->TextColor, $tmpfont['i'], $this->FontSizePt, $fx, $fy);
  12355. if (!isset($popt['mk'])) {
  12356. $popt['mk'] = array();
  12357. }
  12358. $popt['mk']['ca'] = '(l)';
  12359. // merge options
  12360. $opt = array_merge($popt, $opt);
  12361. // set remaining annotation data
  12362. $opt['Subtype'] = 'Widget';
  12363. $opt['ft'] = 'Btn';
  12364. if ($checked) {
  12365. $opt['v'] = array('/'.$onvalue);
  12366. $opt['as'] = $onvalue;
  12367. } else {
  12368. $opt['as'] = 'Off';
  12369. }
  12370. // store readonly flag
  12371. if (!isset($this->radiobutton_groups[$this->page][$name]['#readonly#'])) {
  12372. $this->radiobutton_groups[$this->page][$name]['#readonly#'] = false;
  12373. }
  12374. $this->radiobutton_groups[$this->page][$name]['#readonly#'] |= ($opt['f'] & 64);
  12375. $this->Annotation($x, $y, $w, $w, $name, $opt, 0);
  12376. if ($this->rtl) {
  12377. $this->x -= $w;
  12378. } else {
  12379. $this->x += $w;
  12380. }
  12381. }
  12382. /**
  12383. * Creates a List-box field
  12384. * @param $name (string) field name
  12385. * @param $w (int) width
  12386. * @param $h (int) height
  12387. * @param $values (array) array containing the list of values.
  12388. * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
  12389. * @param $opt (array) annotation parameters. Possible values are described on official PDF32000_2008 reference.
  12390. * @param $x (float) Abscissa of the upper-left corner of the rectangle
  12391. * @param $y (float) Ordinate of the upper-left corner of the rectangle
  12392. * @param $js (boolean) if true put the field using JavaScript (requires Acrobat Writer to be rendered).
  12393. * @public
  12394. * @author Nicola Asuni
  12395. * @since 4.8.000 (2009-09-07)
  12396. */
  12397. public function ListBox($name, $w, $h, $values, $prop=array(), $opt=array(), $x='', $y='', $js=false) {
  12398. if ($x === '') {
  12399. $x = $this->x;
  12400. }
  12401. if ($y === '') {
  12402. $y = $this->y;
  12403. }
  12404. // check page for no-write regions and adapt page margins if necessary
  12405. list($x, $y) = $this->checkPageRegions($h, $x, $y);
  12406. if ($js) {
  12407. $this->_addfield('listbox', $name, $x, $y, $w, $h, $prop);
  12408. $s = '';
  12409. foreach ($values as $value) {
  12410. if (is_array($value)) {
  12411. $s .= ',[\''.addslashes($value[1]).'\',\''.addslashes($value[0]).'\']';
  12412. } else {
  12413. $s .= ',[\''.addslashes($value).'\',\''.addslashes($value).'\']';
  12414. }
  12415. }
  12416. $this->javascript .= 'f'.$name.'.setItems('.substr($s, 1).');'."\n";
  12417. return;
  12418. }
  12419. // get default style
  12420. $prop = array_merge($this->getFormDefaultProp(), $prop);
  12421. // get annotation data
  12422. $popt = TCPDF_STATIC::getAnnotOptFromJSProp($prop, $this->spot_colors, $this->rtl);
  12423. // set additional default values
  12424. $this->annotation_fonts[$this->CurrentFont['fontkey']] = $this->CurrentFont['i'];
  12425. $fontstyle = sprintf('/F%d %F Tf %s', $this->CurrentFont['i'], $this->FontSizePt, $this->TextColor);
  12426. $popt['da'] = $fontstyle;
  12427. // build appearance stream
  12428. $popt['ap'] = array();
  12429. $popt['ap']['n'] = '/Tx BMC q '.$fontstyle.' ';
  12430. $text = '';
  12431. foreach($values as $item) {
  12432. if (is_array($item)) {
  12433. $text .= $item[1]."\n";
  12434. } else {
  12435. $text .= $item."\n";
  12436. }
  12437. }
  12438. $tmpid = $this->startTemplate($w, $h, false);
  12439. $this->MultiCell($w, $h, $text, 0, '', false, 0, 0, 0, true, 0, false, true, 0, 'T', false);
  12440. $this->endTemplate();
  12441. --$this->n;
  12442. $popt['ap']['n'] .= $this->xobjects[$tmpid]['outdata'];
  12443. unset($this->xobjects[$tmpid]);
  12444. $popt['ap']['n'] .= 'Q EMC';
  12445. // merge options
  12446. $opt = array_merge($popt, $opt);
  12447. // set remaining annotation data
  12448. $opt['Subtype'] = 'Widget';
  12449. $opt['ft'] = 'Ch';
  12450. $opt['t'] = $name;
  12451. $opt['opt'] = $values;
  12452. unset($opt['mk']['ca']);
  12453. unset($opt['mk']['rc']);
  12454. unset($opt['mk']['ac']);
  12455. unset($opt['mk']['i']);
  12456. unset($opt['mk']['ri']);
  12457. unset($opt['mk']['ix']);
  12458. unset($opt['mk']['if']);
  12459. unset($opt['mk']['tp']);
  12460. $this->Annotation($x, $y, $w, $h, $name, $opt, 0);
  12461. if ($this->rtl) {
  12462. $this->x -= $w;
  12463. } else {
  12464. $this->x += $w;
  12465. }
  12466. }
  12467. /**
  12468. * Creates a Combo-box field
  12469. * @param $name (string) field name
  12470. * @param $w (int) width
  12471. * @param $h (int) height
  12472. * @param $values (array) array containing the list of values.
  12473. * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
  12474. * @param $opt (array) annotation parameters. Possible values are described on official PDF32000_2008 reference.
  12475. * @param $x (float) Abscissa of the upper-left corner of the rectangle
  12476. * @param $y (float) Ordinate of the upper-left corner of the rectangle
  12477. * @param $js (boolean) if true put the field using JavaScript (requires Acrobat Writer to be rendered).
  12478. * @public
  12479. * @author Nicola Asuni
  12480. * @since 4.8.000 (2009-09-07)
  12481. */
  12482. public function ComboBox($name, $w, $h, $values, $prop=array(), $opt=array(), $x='', $y='', $js=false) {
  12483. if ($x === '') {
  12484. $x = $this->x;
  12485. }
  12486. if ($y === '') {
  12487. $y = $this->y;
  12488. }
  12489. // check page for no-write regions and adapt page margins if necessary
  12490. list($x, $y) = $this->checkPageRegions($h, $x, $y);
  12491. if ($js) {
  12492. $this->_addfield('combobox', $name, $x, $y, $w, $h, $prop);
  12493. $s = '';
  12494. foreach ($values as $value) {
  12495. if (is_array($value)) {
  12496. $s .= ',[\''.addslashes($value[1]).'\',\''.addslashes($value[0]).'\']';
  12497. } else {
  12498. $s .= ',[\''.addslashes($value).'\',\''.addslashes($value).'\']';
  12499. }
  12500. }
  12501. $this->javascript .= 'f'.$name.'.setItems('.substr($s, 1).');'."\n";
  12502. return;
  12503. }
  12504. // get default style
  12505. $prop = array_merge($this->getFormDefaultProp(), $prop);
  12506. $prop['Combo'] = true;
  12507. // get annotation data
  12508. $popt = TCPDF_STATIC::getAnnotOptFromJSProp($prop, $this->spot_colors, $this->rtl);
  12509. // set additional default options
  12510. $this->annotation_fonts[$this->CurrentFont['fontkey']] = $this->CurrentFont['i'];
  12511. $fontstyle = sprintf('/F%d %F Tf %s', $this->CurrentFont['i'], $this->FontSizePt, $this->TextColor);
  12512. $popt['da'] = $fontstyle;
  12513. // build appearance stream
  12514. $popt['ap'] = array();
  12515. $popt['ap']['n'] = '/Tx BMC q '.$fontstyle.' ';
  12516. $text = '';
  12517. foreach($values as $item) {
  12518. if (is_array($item)) {
  12519. $text .= $item[1]."\n";
  12520. } else {
  12521. $text .= $item."\n";
  12522. }
  12523. }
  12524. $tmpid = $this->startTemplate($w, $h, false);
  12525. $this->MultiCell($w, $h, $text, 0, '', false, 0, 0, 0, true, 0, false, true, 0, 'T', false);
  12526. $this->endTemplate();
  12527. --$this->n;
  12528. $popt['ap']['n'] .= $this->xobjects[$tmpid]['outdata'];
  12529. unset($this->xobjects[$tmpid]);
  12530. $popt['ap']['n'] .= 'Q EMC';
  12531. // merge options
  12532. $opt = array_merge($popt, $opt);
  12533. // set remaining annotation data
  12534. $opt['Subtype'] = 'Widget';
  12535. $opt['ft'] = 'Ch';
  12536. $opt['t'] = $name;
  12537. $opt['opt'] = $values;
  12538. unset($opt['mk']['ca']);
  12539. unset($opt['mk']['rc']);
  12540. unset($opt['mk']['ac']);
  12541. unset($opt['mk']['i']);
  12542. unset($opt['mk']['ri']);
  12543. unset($opt['mk']['ix']);
  12544. unset($opt['mk']['if']);
  12545. unset($opt['mk']['tp']);
  12546. $this->Annotation($x, $y, $w, $h, $name, $opt, 0);
  12547. if ($this->rtl) {
  12548. $this->x -= $w;
  12549. } else {
  12550. $this->x += $w;
  12551. }
  12552. }
  12553. /**
  12554. * Creates a CheckBox field
  12555. * @param $name (string) field name
  12556. * @param $w (int) width
  12557. * @param $checked (boolean) define the initial state.
  12558. * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
  12559. * @param $opt (array) annotation parameters. Possible values are described on official PDF32000_2008 reference.
  12560. * @param $onvalue (string) value to be returned if selected.
  12561. * @param $x (float) Abscissa of the upper-left corner of the rectangle
  12562. * @param $y (float) Ordinate of the upper-left corner of the rectangle
  12563. * @param $js (boolean) if true put the field using JavaScript (requires Acrobat Writer to be rendered).
  12564. * @public
  12565. * @author Nicola Asuni
  12566. * @since 4.8.000 (2009-09-07)
  12567. */
  12568. public function CheckBox($name, $w, $checked=false, $prop=array(), $opt=array(), $onvalue='Yes', $x='', $y='', $js=false) {
  12569. if ($x === '') {
  12570. $x = $this->x;
  12571. }
  12572. if ($y === '') {
  12573. $y = $this->y;
  12574. }
  12575. // check page for no-write regions and adapt page margins if necessary
  12576. list($x, $y) = $this->checkPageRegions($w, $x, $y);
  12577. if ($js) {
  12578. $this->_addfield('checkbox', $name, $x, $y, $w, $w, $prop);
  12579. return;
  12580. }
  12581. if (!isset($prop['value'])) {
  12582. $prop['value'] = array('Yes');
  12583. }
  12584. // get default style
  12585. $prop = array_merge($this->getFormDefaultProp(), $prop);
  12586. $prop['borderStyle'] = 'inset';
  12587. // get annotation data
  12588. $popt = TCPDF_STATIC::getAnnotOptFromJSProp($prop, $this->spot_colors, $this->rtl);
  12589. // set additional default options
  12590. $font = 'zapfdingbats';
  12591. if ($this->pdfa_mode) {
  12592. // all fonts must be embedded
  12593. $font = 'pdfa'.$font;
  12594. }
  12595. $this->AddFont($font);
  12596. $tmpfont = $this->getFontBuffer($font);
  12597. $this->annotation_fonts[$tmpfont['fontkey']] = $tmpfont['i'];
  12598. $fontstyle = sprintf('/F%d %F Tf %s', $tmpfont['i'], $this->FontSizePt, $this->TextColor);
  12599. $popt['da'] = $fontstyle;
  12600. // build appearance stream
  12601. $popt['ap'] = array();
  12602. $popt['ap']['n'] = array();
  12603. $fx = ((($w - $this->getAbsFontMeasure($tmpfont['cw'][110])) / 2) * $this->k);
  12604. $fy = (($w - ((($tmpfont['desc']['Ascent'] - $tmpfont['desc']['Descent']) * $this->FontSizePt / 1000) / $this->k)) * $this->k);
  12605. $popt['ap']['n']['Yes'] = sprintf('q %s BT /F%d %F Tf %F %F Td ('.chr(110).') Tj ET Q', $this->TextColor, $tmpfont['i'], $this->FontSizePt, $fx, $fy);
  12606. $popt['ap']['n']['Off'] = sprintf('q %s BT /F%d %F Tf %F %F Td ('.chr(111).') Tj ET Q', $this->TextColor, $tmpfont['i'], $this->FontSizePt, $fx, $fy);
  12607. // merge options
  12608. $opt = array_merge($popt, $opt);
  12609. // set remaining annotation data
  12610. $opt['Subtype'] = 'Widget';
  12611. $opt['ft'] = 'Btn';
  12612. $opt['t'] = $name;
  12613. if (TCPDF_STATIC::empty_string($onvalue)) {
  12614. $onvalue = 'Yes';
  12615. }
  12616. $opt['opt'] = array($onvalue);
  12617. if ($checked) {
  12618. $opt['v'] = array('/Yes');
  12619. $opt['as'] = 'Yes';
  12620. } else {
  12621. $opt['v'] = array('/Off');
  12622. $opt['as'] = 'Off';
  12623. }
  12624. $this->Annotation($x, $y, $w, $w, $name, $opt, 0);
  12625. if ($this->rtl) {
  12626. $this->x -= $w;
  12627. } else {
  12628. $this->x += $w;
  12629. }
  12630. }
  12631. /**
  12632. * Creates a button field
  12633. * @param $name (string) field name
  12634. * @param $w (int) width
  12635. * @param $h (int) height
  12636. * @param $caption (string) caption.
  12637. * @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.
  12638. * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
  12639. * @param $opt (array) annotation parameters. Possible values are described on official PDF32000_2008 reference.
  12640. * @param $x (float) Abscissa of the upper-left corner of the rectangle
  12641. * @param $y (float) Ordinate of the upper-left corner of the rectangle
  12642. * @param $js (boolean) if true put the field using JavaScript (requires Acrobat Writer to be rendered).
  12643. * @public
  12644. * @author Nicola Asuni
  12645. * @since 4.8.000 (2009-09-07)
  12646. */
  12647. public function Button($name, $w, $h, $caption, $action, $prop=array(), $opt=array(), $x='', $y='', $js=false) {
  12648. if ($x === '') {
  12649. $x = $this->x;
  12650. }
  12651. if ($y === '') {
  12652. $y = $this->y;
  12653. }
  12654. // check page for no-write regions and adapt page margins if necessary
  12655. list($x, $y) = $this->checkPageRegions($h, $x, $y);
  12656. if ($js) {
  12657. $this->_addfield('button', $name, $this->x, $this->y, $w, $h, $prop);
  12658. $this->javascript .= 'f'.$name.".buttonSetCaption('".addslashes($caption)."');\n";
  12659. $this->javascript .= 'f'.$name.".setAction('MouseUp','".addslashes($action)."');\n";
  12660. $this->javascript .= 'f'.$name.".highlight='push';\n";
  12661. $this->javascript .= 'f'.$name.".print=false;\n";
  12662. return;
  12663. }
  12664. // get default style
  12665. $prop = array_merge($this->getFormDefaultProp(), $prop);
  12666. $prop['Pushbutton'] = 'true';
  12667. $prop['highlight'] = 'push';
  12668. $prop['display'] = 'display.noPrint';
  12669. // get annotation data
  12670. $popt = TCPDF_STATIC::getAnnotOptFromJSProp($prop, $this->spot_colors, $this->rtl);
  12671. $this->annotation_fonts[$this->CurrentFont['fontkey']] = $this->CurrentFont['i'];
  12672. $fontstyle = sprintf('/F%d %F Tf %s', $this->CurrentFont['i'], $this->FontSizePt, $this->TextColor);
  12673. $popt['da'] = $fontstyle;
  12674. // build appearance stream
  12675. $popt['ap'] = array();
  12676. $popt['ap']['n'] = '/Tx BMC q '.$fontstyle.' ';
  12677. $tmpid = $this->startTemplate($w, $h, false);
  12678. $bw = (2 / $this->k); // border width
  12679. $border = array(
  12680. 'L' => array('width' => $bw, 'cap' => 'square', 'join' => 'miter', 'dash' => 0, 'color' => array(231)),
  12681. 'R' => array('width' => $bw, 'cap' => 'square', 'join' => 'miter', 'dash' => 0, 'color' => array(51)),
  12682. 'T' => array('width' => $bw, 'cap' => 'square', 'join' => 'miter', 'dash' => 0, 'color' => array(231)),
  12683. 'B' => array('width' => $bw, 'cap' => 'square', 'join' => 'miter', 'dash' => 0, 'color' => array(51)));
  12684. $this->SetFillColor(204);
  12685. $this->Cell($w, $h, $caption, $border, 0, 'C', true, '', 1, false, 'T', 'M');
  12686. $this->endTemplate();
  12687. --$this->n;
  12688. $popt['ap']['n'] .= $this->xobjects[$tmpid]['outdata'];
  12689. unset($this->xobjects[$tmpid]);
  12690. $popt['ap']['n'] .= 'Q EMC';
  12691. // set additional default options
  12692. if (!isset($popt['mk'])) {
  12693. $popt['mk'] = array();
  12694. }
  12695. $ann_obj_id = ($this->n + 1);
  12696. if (!empty($action) AND !is_array($action)) {
  12697. $ann_obj_id = ($this->n + 2);
  12698. }
  12699. $popt['mk']['ca'] = $this->_textstring($caption, $ann_obj_id);
  12700. $popt['mk']['rc'] = $this->_textstring($caption, $ann_obj_id);
  12701. $popt['mk']['ac'] = $this->_textstring($caption, $ann_obj_id);
  12702. // merge options
  12703. $opt = array_merge($popt, $opt);
  12704. // set remaining annotation data
  12705. $opt['Subtype'] = 'Widget';
  12706. $opt['ft'] = 'Btn';
  12707. $opt['t'] = $caption;
  12708. $opt['v'] = $name;
  12709. if (!empty($action)) {
  12710. if (is_array($action)) {
  12711. // form action options as on section 12.7.5 of PDF32000_2008.
  12712. $opt['aa'] = '/D <<';
  12713. $bmode = array('SubmitForm', 'ResetForm', 'ImportData');
  12714. foreach ($action AS $key => $val) {
  12715. if (($key == 'S') AND in_array($val, $bmode)) {
  12716. $opt['aa'] .= ' /S /'.$val;
  12717. } elseif (($key == 'F') AND (!empty($val))) {
  12718. $opt['aa'] .= ' /F '.$this->_datastring($val, $ann_obj_id);
  12719. } elseif (($key == 'Fields') AND is_array($val) AND !empty($val)) {
  12720. $opt['aa'] .= ' /Fields [';
  12721. foreach ($val AS $field) {
  12722. $opt['aa'] .= ' '.$this->_textstring($field, $ann_obj_id);
  12723. }
  12724. $opt['aa'] .= ']';
  12725. } elseif (($key == 'Flags')) {
  12726. $ff = 0;
  12727. if (is_array($val)) {
  12728. foreach ($val AS $flag) {
  12729. switch ($flag) {
  12730. case 'Include/Exclude': {
  12731. $ff += 1 << 0;
  12732. break;
  12733. }
  12734. case 'IncludeNoValueFields': {
  12735. $ff += 1 << 1;
  12736. break;
  12737. }
  12738. case 'ExportFormat': {
  12739. $ff += 1 << 2;
  12740. break;
  12741. }
  12742. case 'GetMethod': {
  12743. $ff += 1 << 3;
  12744. break;
  12745. }
  12746. case 'SubmitCoordinates': {
  12747. $ff += 1 << 4;
  12748. break;
  12749. }
  12750. case 'XFDF': {
  12751. $ff += 1 << 5;
  12752. break;
  12753. }
  12754. case 'IncludeAppendSaves': {
  12755. $ff += 1 << 6;
  12756. break;
  12757. }
  12758. case 'IncludeAnnotations': {
  12759. $ff += 1 << 7;
  12760. break;
  12761. }
  12762. case 'SubmitPDF': {
  12763. $ff += 1 << 8;
  12764. break;
  12765. }
  12766. case 'CanonicalFormat': {
  12767. $ff += 1 << 9;
  12768. break;
  12769. }
  12770. case 'ExclNonUserAnnots': {
  12771. $ff += 1 << 10;
  12772. break;
  12773. }
  12774. case 'ExclFKey': {
  12775. $ff += 1 << 11;
  12776. break;
  12777. }
  12778. case 'EmbedForm': {
  12779. $ff += 1 << 13;
  12780. break;
  12781. }
  12782. }
  12783. }
  12784. } else {
  12785. $ff = intval($val);
  12786. }
  12787. $opt['aa'] .= ' /Flags '.$ff;
  12788. }
  12789. }
  12790. $opt['aa'] .= ' >>';
  12791. } else {
  12792. // Javascript action or raw action command
  12793. $js_obj_id = $this->addJavascriptObject($action);
  12794. $opt['aa'] = '/D '.$js_obj_id.' 0 R';
  12795. }
  12796. }
  12797. $this->Annotation($x, $y, $w, $h, $name, $opt, 0);
  12798. if ($this->rtl) {
  12799. $this->x -= $w;
  12800. } else {
  12801. $this->x += $w;
  12802. }
  12803. }
  12804. // --- END FORMS FIELDS ------------------------------------------------
  12805. /**
  12806. * Add certification signature (DocMDP or UR3)
  12807. * You can set only one signature type
  12808. * @protected
  12809. * @author Nicola Asuni
  12810. * @since 4.6.008 (2009-05-07)
  12811. */
  12812. protected function _putsignature() {
  12813. if ((!$this->sign) OR (!isset($this->signature_data['cert_type']))) {
  12814. return;
  12815. }
  12816. $sigobjid = ($this->sig_obj_id + 1);
  12817. $out = $this->_getobj($sigobjid)."\n";
  12818. $out .= '<< /Type /Sig';
  12819. $out .= ' /Filter /Adobe.PPKLite';
  12820. $out .= ' /SubFilter /adbe.pkcs7.detached';
  12821. $out .= ' '.TCPDF_STATIC::$byterange_string;
  12822. $out .= ' /Contents<'.str_repeat('0', $this->signature_max_length).'>';
  12823. if (empty($this->signature_data['approval']) OR ($this->signature_data['approval'] != 'A')) {
  12824. $out .= ' /Reference ['; // array of signature reference dictionaries
  12825. $out .= ' << /Type /SigRef';
  12826. if ($this->signature_data['cert_type'] > 0) {
  12827. $out .= ' /TransformMethod /DocMDP';
  12828. $out .= ' /TransformParams <<';
  12829. $out .= ' /Type /TransformParams';
  12830. $out .= ' /P '.$this->signature_data['cert_type'];
  12831. $out .= ' /V /1.2';
  12832. } else {
  12833. $out .= ' /TransformMethod /UR3';
  12834. $out .= ' /TransformParams <<';
  12835. $out .= ' /Type /TransformParams';
  12836. $out .= ' /V /2.2';
  12837. if (!TCPDF_STATIC::empty_string($this->ur['document'])) {
  12838. $out .= ' /Document['.$this->ur['document'].']';
  12839. }
  12840. if (!TCPDF_STATIC::empty_string($this->ur['form'])) {
  12841. $out .= ' /Form['.$this->ur['form'].']';
  12842. }
  12843. if (!TCPDF_STATIC::empty_string($this->ur['signature'])) {
  12844. $out .= ' /Signature['.$this->ur['signature'].']';
  12845. }
  12846. if (!TCPDF_STATIC::empty_string($this->ur['annots'])) {
  12847. $out .= ' /Annots['.$this->ur['annots'].']';
  12848. }
  12849. if (!TCPDF_STATIC::empty_string($this->ur['ef'])) {
  12850. $out .= ' /EF['.$this->ur['ef'].']';
  12851. }
  12852. if (!TCPDF_STATIC::empty_string($this->ur['formex'])) {
  12853. $out .= ' /FormEX['.$this->ur['formex'].']';
  12854. }
  12855. }
  12856. $out .= ' >>'; // close TransformParams
  12857. // optional digest data (values must be calculated and replaced later)
  12858. //$out .= ' /Data ********** 0 R';
  12859. //$out .= ' /DigestMethod/MD5';
  12860. //$out .= ' /DigestLocation[********** 34]';
  12861. //$out .= ' /DigestValue<********************************>';
  12862. $out .= ' >>';
  12863. $out .= ' ]'; // end of reference
  12864. }
  12865. if (isset($this->signature_data['info']['Name']) AND !TCPDF_STATIC::empty_string($this->signature_data['info']['Name'])) {
  12866. $out .= ' /Name '.$this->_textstring($this->signature_data['info']['Name'], $sigobjid);
  12867. }
  12868. if (isset($this->signature_data['info']['Location']) AND !TCPDF_STATIC::empty_string($this->signature_data['info']['Location'])) {
  12869. $out .= ' /Location '.$this->_textstring($this->signature_data['info']['Location'], $sigobjid);
  12870. }
  12871. if (isset($this->signature_data['info']['Reason']) AND !TCPDF_STATIC::empty_string($this->signature_data['info']['Reason'])) {
  12872. $out .= ' /Reason '.$this->_textstring($this->signature_data['info']['Reason'], $sigobjid);
  12873. }
  12874. if (isset($this->signature_data['info']['ContactInfo']) AND !TCPDF_STATIC::empty_string($this->signature_data['info']['ContactInfo'])) {
  12875. $out .= ' /ContactInfo '.$this->_textstring($this->signature_data['info']['ContactInfo'], $sigobjid);
  12876. }
  12877. $out .= ' /M '.$this->_datestring($sigobjid, $this->doc_modification_timestamp);
  12878. $out .= ' >>';
  12879. $out .= "\n".'endobj';
  12880. $this->_out($out);
  12881. }
  12882. /**
  12883. * Set User's Rights for PDF Reader
  12884. * WARNING: This is experimental and currently do not work.
  12885. * Check the PDF Reference 8.7.1 Transform Methods,
  12886. * Table 8.105 Entries in the UR transform parameters dictionary
  12887. * @param $enable (boolean) if true enable user's rights on PDF reader
  12888. * @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.
  12889. * @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.
  12890. * @param $form (string) Names specifying additional form-field-related usage rights for the document. Valid names are: /Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate
  12891. * @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.
  12892. * @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
  12893. Names specifying additional embedded-files-related usage rights for the document.
  12894. * @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.
  12895. * @public
  12896. * @author Nicola Asuni
  12897. * @since 2.9.000 (2008-03-26)
  12898. */
  12899. public function setUserRights(
  12900. $enable=true,
  12901. $document='/FullSave',
  12902. $annots='/Create/Delete/Modify/Copy/Import/Export',
  12903. $form='/Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate',
  12904. $signature='/Modify',
  12905. $ef='/Create/Delete/Modify/Import',
  12906. $formex='') {
  12907. $this->ur['enabled'] = $enable;
  12908. $this->ur['document'] = $document;
  12909. $this->ur['annots'] = $annots;
  12910. $this->ur['form'] = $form;
  12911. $this->ur['signature'] = $signature;
  12912. $this->ur['ef'] = $ef;
  12913. $this->ur['formex'] = $formex;
  12914. if (!$this->sign) {
  12915. $this->setSignature('', '', '', '', 0, array());
  12916. }
  12917. }
  12918. /**
  12919. * Enable document signature (requires the OpenSSL Library).
  12920. * The digital signature improve document authenticity and integrity and allows o enable extra features on Acrobat Reader.
  12921. * To create self-signed signature: openssl req -x509 -nodes -days 365000 -newkey rsa:1024 -keyout tcpdf.crt -out tcpdf.crt
  12922. * To export crt to p12: openssl pkcs12 -export -in tcpdf.crt -out tcpdf.p12
  12923. * To convert pfx certificate to pem: openssl pkcs12 -in tcpdf.pfx -out tcpdf.crt -nodes
  12924. * @param $signing_cert (mixed) signing certificate (string or filename prefixed with 'file://')
  12925. * @param $private_key (mixed) private key (string or filename prefixed with 'file://')
  12926. * @param $private_key_password (string) password
  12927. * @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.
  12928. * @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.
  12929. * @param $info (array) array of option information: Name, Location, Reason, ContactInfo.
  12930. * @param $approval (string) Enable approval signature eg. for PDF incremental update
  12931. * @public
  12932. * @author Nicola Asuni
  12933. * @since 4.6.005 (2009-04-24)
  12934. */
  12935. public function setSignature($signing_cert='', $private_key='', $private_key_password='', $extracerts='', $cert_type=2, $info=array(), $approval='') {
  12936. // to create self-signed signature: openssl req -x509 -nodes -days 365000 -newkey rsa:1024 -keyout tcpdf.crt -out tcpdf.crt
  12937. // to export crt to p12: openssl pkcs12 -export -in tcpdf.crt -out tcpdf.p12
  12938. // to convert pfx certificate to pem: openssl
  12939. // OpenSSL> pkcs12 -in <cert.pfx> -out <cert.crt> -nodes
  12940. $this->sign = true;
  12941. ++$this->n;
  12942. $this->sig_obj_id = $this->n; // signature widget
  12943. ++$this->n; // signature object ($this->sig_obj_id + 1)
  12944. $this->signature_data = array();
  12945. if (strlen($signing_cert) == 0) {
  12946. $this->Error('Please provide a certificate file and password!');
  12947. }
  12948. if (strlen($private_key) == 0) {
  12949. $private_key = $signing_cert;
  12950. }
  12951. $this->signature_data['signcert'] = $signing_cert;
  12952. $this->signature_data['privkey'] = $private_key;
  12953. $this->signature_data['password'] = $private_key_password;
  12954. $this->signature_data['extracerts'] = $extracerts;
  12955. $this->signature_data['cert_type'] = $cert_type;
  12956. $this->signature_data['info'] = $info;
  12957. $this->signature_data['approval'] = $approval;
  12958. }
  12959. /**
  12960. * Set the digital signature appearance (a cliccable rectangle area to get signature properties)
  12961. * @param $x (float) Abscissa of the upper-left corner.
  12962. * @param $y (float) Ordinate of the upper-left corner.
  12963. * @param $w (float) Width of the signature area.
  12964. * @param $h (float) Height of the signature area.
  12965. * @param $page (int) option page number (if < 0 the current page is used).
  12966. * @param $name (string) Name of the signature.
  12967. * @public
  12968. * @author Nicola Asuni
  12969. * @since 5.3.011 (2010-06-17)
  12970. */
  12971. public function setSignatureAppearance($x=0, $y=0, $w=0, $h=0, $page=-1, $name='') {
  12972. $this->signature_appearance = $this->getSignatureAppearanceArray($x, $y, $w, $h, $page, $name);
  12973. }
  12974. /**
  12975. * Add an empty digital signature appearance (a cliccable rectangle area to get signature properties)
  12976. * @param $x (float) Abscissa of the upper-left corner.
  12977. * @param $y (float) Ordinate of the upper-left corner.
  12978. * @param $w (float) Width of the signature area.
  12979. * @param $h (float) Height of the signature area.
  12980. * @param $page (int) option page number (if < 0 the current page is used).
  12981. * @param $name (string) Name of the signature.
  12982. * @public
  12983. * @author Nicola Asuni
  12984. * @since 5.9.101 (2011-07-06)
  12985. */
  12986. public function addEmptySignatureAppearance($x=0, $y=0, $w=0, $h=0, $page=-1, $name='') {
  12987. ++$this->n;
  12988. $this->empty_signature_appearance[] = array('objid' => $this->n) + $this->getSignatureAppearanceArray($x, $y, $w, $h, $page, $name);
  12989. }
  12990. /**
  12991. * Get the array that defines the signature appearance (page and rectangle coordinates).
  12992. * @param $x (float) Abscissa of the upper-left corner.
  12993. * @param $y (float) Ordinate of the upper-left corner.
  12994. * @param $w (float) Width of the signature area.
  12995. * @param $h (float) Height of the signature area.
  12996. * @param $page (int) option page number (if < 0 the current page is used).
  12997. * @param $name (string) Name of the signature.
  12998. * @return (array) Array defining page and rectangle coordinates of signature appearance.
  12999. * @protected
  13000. * @author Nicola Asuni
  13001. * @since 5.9.101 (2011-07-06)
  13002. */
  13003. protected function getSignatureAppearanceArray($x=0, $y=0, $w=0, $h=0, $page=-1, $name='') {
  13004. $sigapp = array();
  13005. if (($page < 1) OR ($page > $this->numpages)) {
  13006. $sigapp['page'] = $this->page;
  13007. } else {
  13008. $sigapp['page'] = intval($page);
  13009. }
  13010. if (empty($name)) {
  13011. $sigapp['name'] = 'Signature';
  13012. } else {
  13013. $sigapp['name'] = $name;
  13014. }
  13015. $a = $x * $this->k;
  13016. $b = $this->pagedim[($sigapp['page'])]['h'] - (($y + $h) * $this->k);
  13017. $c = $w * $this->k;
  13018. $d = $h * $this->k;
  13019. $sigapp['rect'] = sprintf('%F %F %F %F', $a, $b, ($a + $c), ($b + $d));
  13020. return $sigapp;
  13021. }
  13022. /**
  13023. * Enable document timestamping (requires the OpenSSL Library).
  13024. * The trusted timestamping improve document security that means that no one should be able to change the document once it has been recorded.
  13025. * Use with digital signature only!
  13026. * @param $tsa_host (string) Time Stamping Authority (TSA) server (prefixed with 'https://')
  13027. * @param $tsa_username (string) Specifies the username for TSA authorization (optional) OR specifies the TSA authorization PEM file (see: example_66.php, optional)
  13028. * @param $tsa_password (string) Specifies the password for TSA authorization (optional)
  13029. * @param $tsa_cert (string) Specifies the location of TSA certificate for authorization (optional for cURL)
  13030. * @public
  13031. * @author Richard Stockinger
  13032. * @since 6.0.090 (2014-06-16)
  13033. */
  13034. public function setTimeStamp($tsa_host='', $tsa_username='', $tsa_password='', $tsa_cert='') {
  13035. $this->tsa_data = array();
  13036. if (!function_exists('curl_init')) {
  13037. $this->Error('Please enable cURL PHP extension!');
  13038. }
  13039. if (strlen($tsa_host) == 0) {
  13040. $this->Error('Please specify the host of Time Stamping Authority (TSA)!');
  13041. }
  13042. $this->tsa_data['tsa_host'] = $tsa_host;
  13043. if (is_file($tsa_username)) {
  13044. $this->tsa_data['tsa_auth'] = $tsa_username;
  13045. } else {
  13046. $this->tsa_data['tsa_username'] = $tsa_username;
  13047. }
  13048. $this->tsa_data['tsa_password'] = $tsa_password;
  13049. $this->tsa_data['tsa_cert'] = $tsa_cert;
  13050. $this->tsa_timestamp = true;
  13051. }
  13052. /**
  13053. * NOT YET IMPLEMENTED
  13054. * Request TSA for a timestamp
  13055. * @param $signature (string) Digital signature as binary string
  13056. * @return (string) Timestamped digital signature
  13057. * @protected
  13058. * @author Richard Stockinger
  13059. * @since 6.0.090 (2014-06-16)
  13060. */
  13061. protected function applyTSA($signature) {
  13062. if (!$this->tsa_timestamp) {
  13063. return $signature;
  13064. }
  13065. //@TODO: implement this feature
  13066. return $signature;
  13067. }
  13068. /**
  13069. * Create a new page group.
  13070. * NOTE: call this function before calling AddPage()
  13071. * @param $page (int) starting group page (leave empty for next page).
  13072. * @public
  13073. * @since 3.0.000 (2008-03-27)
  13074. */
  13075. public function startPageGroup($page='') {
  13076. if (empty($page)) {
  13077. $page = $this->page + 1;
  13078. }
  13079. $this->newpagegroup[$page] = sizeof($this->newpagegroup) + 1;
  13080. }
  13081. /**
  13082. * Set the starting page number.
  13083. * @param $num (int) Starting page number.
  13084. * @since 5.9.093 (2011-06-16)
  13085. * @public
  13086. */
  13087. public function setStartingPageNumber($num=1) {
  13088. $this->starting_page_number = max(0, intval($num));
  13089. }
  13090. /**
  13091. * Returns the string alias used right align page numbers.
  13092. * If the current font is unicode type, the returned string wil contain an additional open curly brace.
  13093. * @return string
  13094. * @since 5.9.099 (2011-06-27)
  13095. * @public
  13096. */
  13097. public function getAliasRightShift() {
  13098. // calculate aproximatively the ratio between widths of aliases and replacements.
  13099. $ref = '{'.TCPDF_STATIC::$alias_right_shift.'}{'.TCPDF_STATIC::$alias_tot_pages.'}{'.TCPDF_STATIC::$alias_num_page.'}';
  13100. $rep = str_repeat(' ', $this->GetNumChars($ref));
  13101. $wrep = $this->GetStringWidth($rep);
  13102. if ($wrep > 0) {
  13103. $wdiff = max(1, ($this->GetStringWidth($ref) / $wrep));
  13104. } else {
  13105. $wdiff = 1;
  13106. }
  13107. $sdiff = sprintf('%F', $wdiff);
  13108. $alias = TCPDF_STATIC::$alias_right_shift.$sdiff.'}';
  13109. if ($this->isUnicodeFont()) {
  13110. $alias = '{'.$alias;
  13111. }
  13112. return $alias;
  13113. }
  13114. /**
  13115. * Returns the string alias used for the total number of pages.
  13116. * If the current font is unicode type, the returned string is surrounded by additional curly braces.
  13117. * This alias will be replaced by the total number of pages in the document.
  13118. * @return string
  13119. * @since 4.0.018 (2008-08-08)
  13120. * @public
  13121. */
  13122. public function getAliasNbPages() {
  13123. if ($this->isUnicodeFont()) {
  13124. return '{'.TCPDF_STATIC::$alias_tot_pages.'}';
  13125. }
  13126. return TCPDF_STATIC::$alias_tot_pages;
  13127. }
  13128. /**
  13129. * Returns the string alias used for the page number.
  13130. * If the current font is unicode type, the returned string is surrounded by additional curly braces.
  13131. * This alias will be replaced by the page number.
  13132. * @return string
  13133. * @since 4.5.000 (2009-01-02)
  13134. * @public
  13135. */
  13136. public function getAliasNumPage() {
  13137. if ($this->isUnicodeFont()) {
  13138. return '{'.TCPDF_STATIC::$alias_num_page.'}';
  13139. }
  13140. return TCPDF_STATIC::$alias_num_page;
  13141. }
  13142. /**
  13143. * Return the alias for the total number of pages in the current page group.
  13144. * If the current font is unicode type, the returned string is surrounded by additional curly braces.
  13145. * This alias will be replaced by the total number of pages in this group.
  13146. * @return alias of the current page group
  13147. * @public
  13148. * @since 3.0.000 (2008-03-27)
  13149. */
  13150. public function getPageGroupAlias() {
  13151. if ($this->isUnicodeFont()) {
  13152. return '{'.TCPDF_STATIC::$alias_group_tot_pages.'}';
  13153. }
  13154. return TCPDF_STATIC::$alias_group_tot_pages;
  13155. }
  13156. /**
  13157. * Return the alias for the page number on the current page group.
  13158. * If the current font is unicode type, the returned string is surrounded by additional curly braces.
  13159. * This alias will be replaced by the page number (relative to the belonging group).
  13160. * @return alias of the current page group
  13161. * @public
  13162. * @since 4.5.000 (2009-01-02)
  13163. */
  13164. public function getPageNumGroupAlias() {
  13165. if ($this->isUnicodeFont()) {
  13166. return '{'.TCPDF_STATIC::$alias_group_num_page.'}';
  13167. }
  13168. return TCPDF_STATIC::$alias_group_num_page;
  13169. }
  13170. /**
  13171. * Return the current page in the group.
  13172. * @return current page in the group
  13173. * @public
  13174. * @since 3.0.000 (2008-03-27)
  13175. */
  13176. public function getGroupPageNo() {
  13177. return $this->pagegroups[$this->currpagegroup];
  13178. }
  13179. /**
  13180. * Returns the current group page number formatted as a string.
  13181. * @public
  13182. * @since 4.3.003 (2008-11-18)
  13183. * @see PaneNo(), formatPageNumber()
  13184. */
  13185. public function getGroupPageNoFormatted() {
  13186. return TCPDF_STATIC::formatPageNumber($this->getGroupPageNo());
  13187. }
  13188. /**
  13189. * Returns the current page number formatted as a string.
  13190. * @public
  13191. * @since 4.2.005 (2008-11-06)
  13192. * @see PaneNo(), formatPageNumber()
  13193. */
  13194. public function PageNoFormatted() {
  13195. return TCPDF_STATIC::formatPageNumber($this->PageNo());
  13196. }
  13197. /**
  13198. * Put pdf layers.
  13199. * @protected
  13200. * @since 3.0.000 (2008-03-27)
  13201. */
  13202. protected function _putocg() {
  13203. if (empty($this->pdflayers)) {
  13204. return;
  13205. }
  13206. foreach ($this->pdflayers as $key => $layer) {
  13207. $this->pdflayers[$key]['objid'] = $this->_newobj();
  13208. $out = '<< /Type /OCG';
  13209. $out .= ' /Name '.$this->_textstring($layer['name'], $this->pdflayers[$key]['objid']);
  13210. $out .= ' /Usage <<';
  13211. if (isset($layer['print']) AND ($layer['print'] !== NULL)) {
  13212. $out .= ' /Print <</PrintState /'.($layer['print']?'ON':'OFF').'>>';
  13213. }
  13214. $out .= ' /View <</ViewState /'.($layer['view']?'ON':'OFF').'>>';
  13215. $out .= ' >> >>';
  13216. $out .= "\n".'endobj';
  13217. $this->_out($out);
  13218. }
  13219. }
  13220. /**
  13221. * Start a new pdf layer.
  13222. * @param $name (string) Layer name (only a-z letters and numbers). Leave empty for automatic name.
  13223. * @param $print (boolean|null) Set to TRUE to print this layer, FALSE to not print and NULL to not set this option
  13224. * @param $view (boolean) Set to true to view this layer.
  13225. * @param $lock (boolean) If true lock the layer
  13226. * @public
  13227. * @since 5.9.102 (2011-07-13)
  13228. */
  13229. public function startLayer($name='', $print=true, $view=true, $lock=true) {
  13230. if ($this->state != 2) {
  13231. return;
  13232. }
  13233. $layer = sprintf('LYR%03d', (count($this->pdflayers) + 1));
  13234. if (empty($name)) {
  13235. $name = $layer;
  13236. } else {
  13237. $name = preg_replace('/[^a-zA-Z0-9_\-]/', '', $name);
  13238. }
  13239. $this->pdflayers[] = array('layer' => $layer, 'name' => $name, 'print' => $print, 'view' => $view, 'lock' => $lock);
  13240. $this->openMarkedContent = true;
  13241. $this->_out('/OC /'.$layer.' BDC');
  13242. }
  13243. /**
  13244. * End the current PDF layer.
  13245. * @public
  13246. * @since 5.9.102 (2011-07-13)
  13247. */
  13248. public function endLayer() {
  13249. if ($this->state != 2) {
  13250. return;
  13251. }
  13252. if ($this->openMarkedContent) {
  13253. // close existing open marked-content layer
  13254. $this->_out('EMC');
  13255. $this->openMarkedContent = false;
  13256. }
  13257. }
  13258. /**
  13259. * Set the visibility of the successive elements.
  13260. * This can be useful, for instance, to put a background
  13261. * image or color that will show on screen but won't print.
  13262. * @param $v (string) visibility mode. Legal values are: all, print, screen or view.
  13263. * @public
  13264. * @since 3.0.000 (2008-03-27)
  13265. */
  13266. public function setVisibility($v) {
  13267. if ($this->state != 2) {
  13268. return;
  13269. }
  13270. $this->endLayer();
  13271. switch($v) {
  13272. case 'print': {
  13273. $this->startLayer('Print', true, false);
  13274. break;
  13275. }
  13276. case 'view':
  13277. case 'screen': {
  13278. $this->startLayer('View', false, true);
  13279. break;
  13280. }
  13281. case 'all': {
  13282. $this->_out('');
  13283. break;
  13284. }
  13285. default: {
  13286. $this->Error('Incorrect visibility: '.$v);
  13287. break;
  13288. }
  13289. }
  13290. }
  13291. /**
  13292. * Add transparency parameters to the current extgstate
  13293. * @param $parms (array) parameters
  13294. * @return the number of extgstates
  13295. * @protected
  13296. * @since 3.0.000 (2008-03-27)
  13297. */
  13298. protected function addExtGState($parms) {
  13299. if ($this->pdfa_mode) {
  13300. // transparencies are not allowed in PDF/A mode
  13301. return;
  13302. }
  13303. // check if this ExtGState already exist
  13304. foreach ($this->extgstates as $i => $ext) {
  13305. if ($ext['parms'] == $parms) {
  13306. if ($this->inxobj) {
  13307. // we are inside an XObject template
  13308. $this->xobjects[$this->xobjid]['extgstates'][$i] = $ext;
  13309. }
  13310. // return reference to existing ExtGState
  13311. return $i;
  13312. }
  13313. }
  13314. $n = (count($this->extgstates) + 1);
  13315. $this->extgstates[$n] = array('parms' => $parms);
  13316. if ($this->inxobj) {
  13317. // we are inside an XObject template
  13318. $this->xobjects[$this->xobjid]['extgstates'][$n] = $this->extgstates[$n];
  13319. }
  13320. return $n;
  13321. }
  13322. /**
  13323. * Add an extgstate
  13324. * @param $gs (array) extgstate
  13325. * @protected
  13326. * @since 3.0.000 (2008-03-27)
  13327. */
  13328. protected function setExtGState($gs) {
  13329. if ($this->pdfa_mode OR ($this->state != 2)) {
  13330. // transparency is not allowed in PDF/A mode
  13331. return;
  13332. }
  13333. $this->_out(sprintf('/GS%d gs', $gs));
  13334. }
  13335. /**
  13336. * Put extgstates for object transparency
  13337. * @protected
  13338. * @since 3.0.000 (2008-03-27)
  13339. */
  13340. protected function _putextgstates() {
  13341. foreach ($this->extgstates as $i => $ext) {
  13342. $this->extgstates[$i]['n'] = $this->_newobj();
  13343. $out = '<< /Type /ExtGState';
  13344. foreach ($ext['parms'] as $k => $v) {
  13345. if (is_float($v)) {
  13346. $v = sprintf('%F', $v);
  13347. } elseif ($v === true) {
  13348. $v = 'true';
  13349. } elseif ($v === false) {
  13350. $v = 'false';
  13351. }
  13352. $out .= ' /'.$k.' '.$v;
  13353. }
  13354. $out .= ' >>';
  13355. $out .= "\n".'endobj';
  13356. $this->_out($out);
  13357. }
  13358. }
  13359. /**
  13360. * Set overprint mode for stroking (OP) and non-stroking (op) painting operations.
  13361. * (Check the "Entries in a Graphics State Parameter Dictionary" on PDF 32000-1:2008).
  13362. * @param $stroking (boolean) If true apply overprint for stroking operations.
  13363. * @param $nonstroking (boolean) If true apply overprint for painting operations other than stroking.
  13364. * @param $mode (integer) Overprint mode: (0 = each source colour component value replaces the value previously painted for the corresponding device colorant; 1 = a tint value of 0.0 for a source colour component shall leave the corresponding component of the previously painted colour unchanged).
  13365. * @public
  13366. * @since 5.9.152 (2012-03-23)
  13367. */
  13368. public function setOverprint($stroking=true, $nonstroking='', $mode=0) {
  13369. if ($this->state != 2) {
  13370. return;
  13371. }
  13372. $stroking = $stroking ? true : false;
  13373. if (TCPDF_STATIC::empty_string($nonstroking)) {
  13374. // default value if not set
  13375. $nonstroking = $stroking;
  13376. } else {
  13377. $nonstroking = $nonstroking ? true : false;
  13378. }
  13379. if (($mode != 0) AND ($mode != 1)) {
  13380. $mode = 0;
  13381. }
  13382. $this->overprint = array('OP' => $stroking, 'op' => $nonstroking, 'OPM' => $mode);
  13383. $gs = $this->addExtGState($this->overprint);
  13384. $this->setExtGState($gs);
  13385. }
  13386. /**
  13387. * Get the overprint mode array (OP, op, OPM).
  13388. * (Check the "Entries in a Graphics State Parameter Dictionary" on PDF 32000-1:2008).
  13389. * @return array.
  13390. * @public
  13391. * @since 5.9.152 (2012-03-23)
  13392. */
  13393. public function getOverprint() {
  13394. return $this->overprint;
  13395. }
  13396. /**
  13397. * Set alpha for stroking (CA) and non-stroking (ca) operations.
  13398. * @param $stroking (float) Alpha value for stroking operations: real value from 0 (transparent) to 1 (opaque).
  13399. * @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
  13400. * @param $nonstroking (float) Alpha value for non-stroking operations: real value from 0 (transparent) to 1 (opaque).
  13401. * @param $ais (boolean)
  13402. * @public
  13403. * @since 3.0.000 (2008-03-27)
  13404. */
  13405. public function setAlpha($stroking=1, $bm='Normal', $nonstroking='', $ais=false) {
  13406. if ($this->pdfa_mode) {
  13407. // transparency is not allowed in PDF/A mode
  13408. return;
  13409. }
  13410. $stroking = floatval($stroking);
  13411. if (TCPDF_STATIC::empty_string($nonstroking)) {
  13412. // default value if not set
  13413. $nonstroking = $stroking;
  13414. } else {
  13415. $nonstroking = floatval($nonstroking);
  13416. }
  13417. if ($bm[0] == '/') {
  13418. // remove trailing slash
  13419. $bm = substr($bm, 1);
  13420. }
  13421. if (!in_array($bm, array('Normal', 'Multiply', 'Screen', 'Overlay', 'Darken', 'Lighten', 'ColorDodge', 'ColorBurn', 'HardLight', 'SoftLight', 'Difference', 'Exclusion', 'Hue', 'Saturation', 'Color', 'Luminosity'))) {
  13422. $bm = 'Normal';
  13423. }
  13424. $ais = $ais ? true : false;
  13425. $this->alpha = array('CA' => $stroking, 'ca' => $nonstroking, 'BM' => '/'.$bm, 'AIS' => $ais);
  13426. $gs = $this->addExtGState($this->alpha);
  13427. $this->setExtGState($gs);
  13428. }
  13429. /**
  13430. * Get the alpha mode array (CA, ca, BM, AIS).
  13431. * (Check the "Entries in a Graphics State Parameter Dictionary" on PDF 32000-1:2008).
  13432. * @return array.
  13433. * @public
  13434. * @since 5.9.152 (2012-03-23)
  13435. */
  13436. public function getAlpha() {
  13437. return $this->alpha;
  13438. }
  13439. /**
  13440. * Set the default JPEG compression quality (1-100)
  13441. * @param $quality (int) JPEG quality, integer between 1 and 100
  13442. * @public
  13443. * @since 3.0.000 (2008-03-27)
  13444. */
  13445. public function setJPEGQuality($quality) {
  13446. if (($quality < 1) OR ($quality > 100)) {
  13447. $quality = 75;
  13448. }
  13449. $this->jpeg_quality = intval($quality);
  13450. }
  13451. /**
  13452. * Set the default number of columns in a row for HTML tables.
  13453. * @param $cols (int) number of columns
  13454. * @public
  13455. * @since 3.0.014 (2008-06-04)
  13456. */
  13457. public function setDefaultTableColumns($cols=4) {
  13458. $this->default_table_columns = intval($cols);
  13459. }
  13460. /**
  13461. * Set the height of the cell (line height) respect the font height.
  13462. * @param $h (int) cell proportion respect font height (typical value = 1.25).
  13463. * @public
  13464. * @since 3.0.014 (2008-06-04)
  13465. */
  13466. public function setCellHeightRatio($h) {
  13467. $this->cell_height_ratio = $h;
  13468. }
  13469. /**
  13470. * return the height of cell repect font height.
  13471. * @public
  13472. * @since 4.0.012 (2008-07-24)
  13473. */
  13474. public function getCellHeightRatio() {
  13475. return $this->cell_height_ratio;
  13476. }
  13477. /**
  13478. * Set the PDF version (check PDF reference for valid values).
  13479. * @param $version (string) PDF document version.
  13480. * @public
  13481. * @since 3.1.000 (2008-06-09)
  13482. */
  13483. public function setPDFVersion($version='1.7') {
  13484. if ($this->pdfa_mode && $this->pdfa_version == 1 ) {
  13485. // PDF/A mode
  13486. $this->PDFVersion = '1.4';
  13487. } else {
  13488. $this->PDFVersion = $version;
  13489. }
  13490. }
  13491. /**
  13492. * Set the viewer preferences dictionary controlling the way the document is to be presented on the screen or in print.
  13493. * (see Section 8.1 of PDF reference, "Viewer Preferences").
  13494. * <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 pri
  13495. * @param $preferences (array) array of options.
  13496. * @author Nicola Asuni
  13497. * @public
  13498. * @since 3.1.000 (2008-06-09)
  13499. */
  13500. public function setViewerPreferences($preferences) {
  13501. $this->viewer_preferences = $preferences;
  13502. }
  13503. /**
  13504. * Paints color transition registration bars
  13505. * @param $x (float) abscissa of the top left corner of the rectangle.
  13506. * @param $y (float) ordinate of the top left corner of the rectangle.
  13507. * @param $w (float) width of the rectangle.
  13508. * @param $h (float) height of the rectangle.
  13509. * @param $transition (boolean) if true prints tcolor transitions to white.
  13510. * @param $vertical (boolean) if true prints bar vertically.
  13511. * @param $colors (string) colors to print separated by comma. Valid values are: A,W,R,G,B,C,M,Y,K,RGB,CMYK,ALL,ALLSPOT,<SPOT_COLOR_NAME>. Where: A = grayscale black, W = grayscale white, R = RGB red, G RGB green, B RGB blue, C = CMYK cyan, M = CMYK magenta, Y = CMYK yellow, K = CMYK key/black, RGB = RGB registration color, CMYK = CMYK registration color, ALL = Spot registration color, ALLSPOT = print all defined spot colors, <SPOT_COLOR_NAME> = name of the spot color to print.
  13512. * @author Nicola Asuni
  13513. * @since 4.9.000 (2010-03-26)
  13514. * @public
  13515. */
  13516. public function colorRegistrationBar($x, $y, $w, $h, $transition=true, $vertical=false, $colors='A,R,G,B,C,M,Y,K') {
  13517. if (strpos($colors, 'ALLSPOT') !== false) {
  13518. // expand spot colors
  13519. $spot_colors = '';
  13520. foreach ($this->spot_colors as $spot_color_name => $v) {
  13521. $spot_colors .= ','.$spot_color_name;
  13522. }
  13523. if (!empty($spot_colors)) {
  13524. $spot_colors = substr($spot_colors, 1);
  13525. $colors = str_replace('ALLSPOT', $spot_colors, $colors);
  13526. } else {
  13527. $colors = str_replace('ALLSPOT', 'NONE', $colors);
  13528. }
  13529. }
  13530. $bars = explode(',', $colors);
  13531. $numbars = count($bars); // number of bars to print
  13532. if ($numbars <= 0) {
  13533. return;
  13534. }
  13535. // set bar measures
  13536. if ($vertical) {
  13537. $coords = array(0, 0, 0, 1);
  13538. $wb = $w / $numbars; // bar width
  13539. $hb = $h; // bar height
  13540. $xd = $wb; // delta x
  13541. $yd = 0; // delta y
  13542. } else {
  13543. $coords = array(1, 0, 0, 0);
  13544. $wb = $w; // bar width
  13545. $hb = $h / $numbars; // bar height
  13546. $xd = 0; // delta x
  13547. $yd = $hb; // delta y
  13548. }
  13549. $xb = $x;
  13550. $yb = $y;
  13551. foreach ($bars as $col) {
  13552. switch ($col) {
  13553. // set transition colors
  13554. case 'A': { // BLACK (GRAYSCALE)
  13555. $col_a = array(255);
  13556. $col_b = array(0);
  13557. break;
  13558. }
  13559. case 'W': { // WHITE (GRAYSCALE)
  13560. $col_a = array(0);
  13561. $col_b = array(255);
  13562. break;
  13563. }
  13564. case 'R': { // RED (RGB)
  13565. $col_a = array(255,255,255);
  13566. $col_b = array(255,0,0);
  13567. break;
  13568. }
  13569. case 'G': { // GREEN (RGB)
  13570. $col_a = array(255,255,255);
  13571. $col_b = array(0,255,0);
  13572. break;
  13573. }
  13574. case 'B': { // BLUE (RGB)
  13575. $col_a = array(255,255,255);
  13576. $col_b = array(0,0,255);
  13577. break;
  13578. }
  13579. case 'C': { // CYAN (CMYK)
  13580. $col_a = array(0,0,0,0);
  13581. $col_b = array(100,0,0,0);
  13582. break;
  13583. }
  13584. case 'M': { // MAGENTA (CMYK)
  13585. $col_a = array(0,0,0,0);
  13586. $col_b = array(0,100,0,0);
  13587. break;
  13588. }
  13589. case 'Y': { // YELLOW (CMYK)
  13590. $col_a = array(0,0,0,0);
  13591. $col_b = array(0,0,100,0);
  13592. break;
  13593. }
  13594. case 'K': { // KEY - BLACK (CMYK)
  13595. $col_a = array(0,0,0,0);
  13596. $col_b = array(0,0,0,100);
  13597. break;
  13598. }
  13599. case 'RGB': { // BLACK REGISTRATION (RGB)
  13600. $col_a = array(255,255,255);
  13601. $col_b = array(0,0,0);
  13602. break;
  13603. }
  13604. case 'CMYK': { // BLACK REGISTRATION (CMYK)
  13605. $col_a = array(0,0,0,0);
  13606. $col_b = array(100,100,100,100);
  13607. break;
  13608. }
  13609. case 'ALL': { // SPOT COLOR REGISTRATION
  13610. $col_a = array(0,0,0,0,'None');
  13611. $col_b = array(100,100,100,100,'All');
  13612. break;
  13613. }
  13614. case 'NONE': { // SKIP THIS COLOR
  13615. $col_a = array(0,0,0,0,'None');
  13616. $col_b = array(0,0,0,0,'None');
  13617. break;
  13618. }
  13619. default: { // SPECIFIC SPOT COLOR NAME
  13620. $col_a = array(0,0,0,0,'None');
  13621. $col_b = TCPDF_COLORS::getSpotColor($col, $this->spot_colors);
  13622. if ($col_b === false) {
  13623. // in case of error defaults to the registration color
  13624. $col_b = array(100,100,100,100,'All');
  13625. }
  13626. break;
  13627. }
  13628. }
  13629. if ($col != 'NONE') {
  13630. if ($transition) {
  13631. // color gradient
  13632. $this->LinearGradient($xb, $yb, $wb, $hb, $col_a, $col_b, $coords);
  13633. } else {
  13634. $this->SetFillColorArray($col_b);
  13635. // colored rectangle
  13636. $this->Rect($xb, $yb, $wb, $hb, 'F', array());
  13637. }
  13638. $xb += $xd;
  13639. $yb += $yd;
  13640. }
  13641. }
  13642. }
  13643. /**
  13644. * Paints crop marks.
  13645. * @param $x (float) abscissa of the crop mark center.
  13646. * @param $y (float) ordinate of the crop mark center.
  13647. * @param $w (float) width of the crop mark.
  13648. * @param $h (float) height of the crop mark.
  13649. * @param $type (string) type of crop mark, one symbol per type separated by comma: T = TOP, F = BOTTOM, L = LEFT, R = RIGHT, TL = A = TOP-LEFT, TR = B = TOP-RIGHT, BL = C = BOTTOM-LEFT, BR = D = BOTTOM-RIGHT.
  13650. * @param $color (array) crop mark color (default spot registration color).
  13651. * @author Nicola Asuni
  13652. * @since 4.9.000 (2010-03-26)
  13653. * @public
  13654. */
  13655. public function cropMark($x, $y, $w, $h, $type='T,R,B,L', $color=array(100,100,100,100,'All')) {
  13656. $this->SetLineStyle(array('width' => (0.5 / $this->k), 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => $color));
  13657. $type = strtoupper($type);
  13658. $type = preg_replace('/[^A-Z\-\,]*/', '', $type);
  13659. // split type in single components
  13660. $type = str_replace('-', ',', $type);
  13661. $type = str_replace('TL', 'T,L', $type);
  13662. $type = str_replace('TR', 'T,R', $type);
  13663. $type = str_replace('BL', 'F,L', $type);
  13664. $type = str_replace('BR', 'F,R', $type);
  13665. $type = str_replace('A', 'T,L', $type);
  13666. $type = str_replace('B', 'T,R', $type);
  13667. $type = str_replace('T,RO', 'BO', $type);
  13668. $type = str_replace('C', 'F,L', $type);
  13669. $type = str_replace('D', 'F,R', $type);
  13670. $crops = explode(',', strtoupper($type));
  13671. // remove duplicates
  13672. $crops = array_unique($crops);
  13673. $dw = ($w / 4); // horizontal space to leave before the intersection point
  13674. $dh = ($h / 4); // vertical space to leave before the intersection point
  13675. foreach ($crops as $crop) {
  13676. switch ($crop) {
  13677. case 'T':
  13678. case 'TOP': {
  13679. $x1 = $x;
  13680. $y1 = ($y - $h);
  13681. $x2 = $x;
  13682. $y2 = ($y - $dh);
  13683. break;
  13684. }
  13685. case 'F':
  13686. case 'BOTTOM': {
  13687. $x1 = $x;
  13688. $y1 = ($y + $dh);
  13689. $x2 = $x;
  13690. $y2 = ($y + $h);
  13691. break;
  13692. }
  13693. case 'L':
  13694. case 'LEFT': {
  13695. $x1 = ($x - $w);
  13696. $y1 = $y;
  13697. $x2 = ($x - $dw);
  13698. $y2 = $y;
  13699. break;
  13700. }
  13701. case 'R':
  13702. case 'RIGHT': {
  13703. $x1 = ($x + $dw);
  13704. $y1 = $y;
  13705. $x2 = ($x + $w);
  13706. $y2 = $y;
  13707. break;
  13708. }
  13709. }
  13710. $this->Line($x1, $y1, $x2, $y2);
  13711. }
  13712. }
  13713. /**
  13714. * Paints a registration mark
  13715. * @param $x (float) abscissa of the registration mark center.
  13716. * @param $y (float) ordinate of the registration mark center.
  13717. * @param $r (float) radius of the crop mark.
  13718. * @param $double (boolean) if true print two concentric crop marks.
  13719. * @param $cola (array) crop mark color (default spot registration color 'All').
  13720. * @param $colb (array) second crop mark color (default spot registration color 'None').
  13721. * @author Nicola Asuni
  13722. * @since 4.9.000 (2010-03-26)
  13723. * @public
  13724. */
  13725. public function registrationMark($x, $y, $r, $double=false, $cola=array(100,100,100,100,'All'), $colb=array(0,0,0,0,'None')) {
  13726. $line_style = array('width' => max((0.5 / $this->k),($r / 30)), 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => $cola);
  13727. $this->SetFillColorArray($cola);
  13728. $this->PieSector($x, $y, $r, 90, 180, 'F');
  13729. $this->PieSector($x, $y, $r, 270, 360, 'F');
  13730. $this->Circle($x, $y, $r, 0, 360, 'C', $line_style, array(), 8);
  13731. if ($double) {
  13732. $ri = $r * 0.5;
  13733. $this->SetFillColorArray($colb);
  13734. $this->PieSector($x, $y, $ri, 90, 180, 'F');
  13735. $this->PieSector($x, $y, $ri, 270, 360, 'F');
  13736. $this->SetFillColorArray($cola);
  13737. $this->PieSector($x, $y, $ri, 0, 90, 'F');
  13738. $this->PieSector($x, $y, $ri, 180, 270, 'F');
  13739. $this->Circle($x, $y, $ri, 0, 360, 'C', $line_style, array(), 8);
  13740. }
  13741. }
  13742. /**
  13743. * Paints a CMYK registration mark
  13744. * @param $x (float) abscissa of the registration mark center.
  13745. * @param $y (float) ordinate of the registration mark center.
  13746. * @param $r (float) radius of the crop mark.
  13747. * @author Nicola Asuni
  13748. * @since 6.0.038 (2013-09-30)
  13749. * @public
  13750. */
  13751. public function registrationMarkCMYK($x, $y, $r) {
  13752. // line width
  13753. $lw = max((0.5 / $this->k),($r / 8));
  13754. // internal radius
  13755. $ri = ($r * 0.6);
  13756. // external radius
  13757. $re = ($r * 1.3);
  13758. // Cyan
  13759. $this->SetFillColorArray(array(100,0,0,0));
  13760. $this->PieSector($x, $y, $ri, 270, 360, 'F');
  13761. // Magenta
  13762. $this->SetFillColorArray(array(0,100,0,0));
  13763. $this->PieSector($x, $y, $ri, 0, 90, 'F');
  13764. // Yellow
  13765. $this->SetFillColorArray(array(0,0,100,0));
  13766. $this->PieSector($x, $y, $ri, 90, 180, 'F');
  13767. // Key - black
  13768. $this->SetFillColorArray(array(0,0,0,100));
  13769. $this->PieSector($x, $y, $ri, 180, 270, 'F');
  13770. // registration color
  13771. $line_style = array('width' => $lw, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(100,100,100,100,'All'));
  13772. $this->SetFillColorArray(array(100,100,100,100,'All'));
  13773. // external circle
  13774. $this->Circle($x, $y, $r, 0, 360, 'C', $line_style, array(), 8);
  13775. // cross lines
  13776. $this->Line($x, ($y - $re), $x, ($y - $ri));
  13777. $this->Line($x, ($y + $ri), $x, ($y + $re));
  13778. $this->Line(($x - $re), $y, ($x - $ri), $y);
  13779. $this->Line(($x + $ri), $y, ($x + $re), $y);
  13780. }
  13781. /**
  13782. * Paints a linear colour gradient.
  13783. * @param $x (float) abscissa of the top left corner of the rectangle.
  13784. * @param $y (float) ordinate of the top left corner of the rectangle.
  13785. * @param $w (float) width of the rectangle.
  13786. * @param $h (float) height of the rectangle.
  13787. * @param $col1 (array) first color (Grayscale, RGB or CMYK components).
  13788. * @param $col2 (array) second color (Grayscale, RGB or CMYK components).
  13789. * @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).
  13790. * @author Andreas W\FCrmser, Nicola Asuni
  13791. * @since 3.1.000 (2008-06-09)
  13792. * @public
  13793. */
  13794. public function LinearGradient($x, $y, $w, $h, $col1=array(), $col2=array(), $coords=array(0,0,1,0)) {
  13795. $this->Clip($x, $y, $w, $h);
  13796. $this->Gradient(2, $coords, array(array('color' => $col1, 'offset' => 0, 'exponent' => 1), array('color' => $col2, 'offset' => 1, 'exponent' => 1)), array(), false);
  13797. }
  13798. /**
  13799. * Paints a radial colour gradient.
  13800. * @param $x (float) abscissa of the top left corner of the rectangle.
  13801. * @param $y (float) ordinate of the top left corner of the rectangle.
  13802. * @param $w (float) width of the rectangle.
  13803. * @param $h (float) height of the rectangle.
  13804. * @param $col1 (array) first color (Grayscale, RGB or CMYK components).
  13805. * @param $col2 (array) second color (Grayscale, RGB or CMYK components).
  13806. * @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.
  13807. * @author Andreas W\FCrmser, Nicola Asuni
  13808. * @since 3.1.000 (2008-06-09)
  13809. * @public
  13810. */
  13811. public function RadialGradient($x, $y, $w, $h, $col1=array(), $col2=array(), $coords=array(0.5,0.5,0.5,0.5,1)) {
  13812. $this->Clip($x, $y, $w, $h);
  13813. $this->Gradient(3, $coords, array(array('color' => $col1, 'offset' => 0, 'exponent' => 1), array('color' => $col2, 'offset' => 1, 'exponent' => 1)), array(), false);
  13814. }
  13815. /**
  13816. * Paints a coons patch mesh.
  13817. * @param $x (float) abscissa of the top left corner of the rectangle.
  13818. * @param $y (float) ordinate of the top left corner of the rectangle.
  13819. * @param $w (float) width of the rectangle.
  13820. * @param $h (float) height of the rectangle.
  13821. * @param $col1 (array) first color (lower left corner) (RGB components).
  13822. * @param $col2 (array) second color (lower right corner) (RGB components).
  13823. * @param $col3 (array) third color (upper right corner) (RGB components).
  13824. * @param $col4 (array) fourth color (upper left corner) (RGB components).
  13825. * @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>
  13826. * @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
  13827. * @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
  13828. * @param $antialias (boolean) A flag indicating whether to filter the shading function to prevent aliasing artifacts.
  13829. * @author Andreas W\FCrmser, Nicola Asuni
  13830. * @since 3.1.000 (2008-06-09)
  13831. * @public
  13832. */
  13833. 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) {
  13834. if ($this->pdfa_mode OR ($this->state != 2)) {
  13835. return;
  13836. }
  13837. $this->Clip($x, $y, $w, $h);
  13838. $n = count($this->gradients) + 1;
  13839. $this->gradients[$n] = array();
  13840. $this->gradients[$n]['type'] = 6; //coons patch mesh
  13841. $this->gradients[$n]['coords'] = array();
  13842. $this->gradients[$n]['antialias'] = $antialias;
  13843. $this->gradients[$n]['colors'] = array();
  13844. $this->gradients[$n]['transparency'] = false;
  13845. //check the coords array if it is the simple array or the multi patch array
  13846. if (!isset($coords[0]['f'])) {
  13847. //simple array -> convert to multi patch array
  13848. if (!isset($col1[1])) {
  13849. $col1[1] = $col1[2] = $col1[0];
  13850. }
  13851. if (!isset($col2[1])) {
  13852. $col2[1] = $col2[2] = $col2[0];
  13853. }
  13854. if (!isset($col3[1])) {
  13855. $col3[1] = $col3[2] = $col3[0];
  13856. }
  13857. if (!isset($col4[1])) {
  13858. $col4[1] = $col4[2] = $col4[0];
  13859. }
  13860. $patch_array[0]['f'] = 0;
  13861. $patch_array[0]['points'] = $coords;
  13862. $patch_array[0]['colors'][0]['r'] = $col1[0];
  13863. $patch_array[0]['colors'][0]['g'] = $col1[1];
  13864. $patch_array[0]['colors'][0]['b'] = $col1[2];
  13865. $patch_array[0]['colors'][1]['r'] = $col2[0];
  13866. $patch_array[0]['colors'][1]['g'] = $col2[1];
  13867. $patch_array[0]['colors'][1]['b'] = $col2[2];
  13868. $patch_array[0]['colors'][2]['r'] = $col3[0];
  13869. $patch_array[0]['colors'][2]['g'] = $col3[1];
  13870. $patch_array[0]['colors'][2]['b'] = $col3[2];
  13871. $patch_array[0]['colors'][3]['r'] = $col4[0];
  13872. $patch_array[0]['colors'][3]['g'] = $col4[1];
  13873. $patch_array[0]['colors'][3]['b'] = $col4[2];
  13874. } else {
  13875. //multi patch array
  13876. $patch_array = $coords;
  13877. }
  13878. $bpcd = 65535; //16 bits per coordinate
  13879. //build the data stream
  13880. $this->gradients[$n]['stream'] = '';
  13881. $count_patch = count($patch_array);
  13882. for ($i=0; $i < $count_patch; ++$i) {
  13883. $this->gradients[$n]['stream'] .= chr($patch_array[$i]['f']); //start with the edge flag as 8 bit
  13884. $count_points = count($patch_array[$i]['points']);
  13885. for ($j=0; $j < $count_points; ++$j) {
  13886. //each point as 16 bit
  13887. $patch_array[$i]['points'][$j] = (($patch_array[$i]['points'][$j] - $coords_min) / ($coords_max - $coords_min)) * $bpcd;
  13888. if ($patch_array[$i]['points'][$j] < 0) {
  13889. $patch_array[$i]['points'][$j] = 0;
  13890. }
  13891. if ($patch_array[$i]['points'][$j] > $bpcd) {
  13892. $patch_array[$i]['points'][$j] = $bpcd;
  13893. }
  13894. $this->gradients[$n]['stream'] .= chr(floor($patch_array[$i]['points'][$j] / 256));
  13895. $this->gradients[$n]['stream'] .= chr(floor($patch_array[$i]['points'][$j] % 256));
  13896. }
  13897. $count_cols = count($patch_array[$i]['colors']);
  13898. for ($j=0; $j < $count_cols; ++$j) {
  13899. //each color component as 8 bit
  13900. $this->gradients[$n]['stream'] .= chr($patch_array[$i]['colors'][$j]['r']);
  13901. $this->gradients[$n]['stream'] .= chr($patch_array[$i]['colors'][$j]['g']);
  13902. $this->gradients[$n]['stream'] .= chr($patch_array[$i]['colors'][$j]['b']);
  13903. }
  13904. }
  13905. //paint the gradient
  13906. $this->_out('/Sh'.$n.' sh');
  13907. //restore previous Graphic State
  13908. $this->_outRestoreGraphicsState();
  13909. if ($this->inxobj) {
  13910. // we are inside an XObject template
  13911. $this->xobjects[$this->xobjid]['gradients'][$n] = $this->gradients[$n];
  13912. }
  13913. }
  13914. /**
  13915. * Set a rectangular clipping area.
  13916. * @param $x (float) abscissa of the top left corner of the rectangle (or top right corner for RTL mode).
  13917. * @param $y (float) ordinate of the top left corner of the rectangle.
  13918. * @param $w (float) width of the rectangle.
  13919. * @param $h (float) height of the rectangle.
  13920. * @author Andreas W\FCrmser, Nicola Asuni
  13921. * @since 3.1.000 (2008-06-09)
  13922. * @protected
  13923. */
  13924. protected function Clip($x, $y, $w, $h) {
  13925. if ($this->state != 2) {
  13926. return;
  13927. }
  13928. if ($this->rtl) {
  13929. $x = $this->w - $x - $w;
  13930. }
  13931. //save current Graphic State
  13932. $s = 'q';
  13933. //set clipping area
  13934. $s .= sprintf(' %F %F %F %F re W n', $x*$this->k, ($this->h-$y)*$this->k, $w*$this->k, -$h*$this->k);
  13935. //set up transformation matrix for gradient
  13936. $s .= sprintf(' %F 0 0 %F %F %F cm', $w*$this->k, $h*$this->k, $x*$this->k, ($this->h-($y+$h))*$this->k);
  13937. $this->_out($s);
  13938. }
  13939. /**
  13940. * Output gradient.
  13941. * @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)
  13942. * @param $coords (array) array of coordinates.
  13943. * @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).
  13944. * @param $background (array) An array of colour components appropriate to the colour space, specifying a single background colour value.
  13945. * @param $antialias (boolean) A flag indicating whether to filter the shading function to prevent aliasing artifacts.
  13946. * @author Nicola Asuni
  13947. * @since 3.1.000 (2008-06-09)
  13948. * @public
  13949. */
  13950. public function Gradient($type, $coords, $stops, $background=array(), $antialias=false) {
  13951. if ($this->pdfa_mode OR ($this->state != 2)) {
  13952. return;
  13953. }
  13954. $n = count($this->gradients) + 1;
  13955. $this->gradients[$n] = array();
  13956. $this->gradients[$n]['type'] = $type;
  13957. $this->gradients[$n]['coords'] = $coords;
  13958. $this->gradients[$n]['antialias'] = $antialias;
  13959. $this->gradients[$n]['colors'] = array();
  13960. $this->gradients[$n]['transparency'] = false;
  13961. // color space
  13962. $numcolspace = count($stops[0]['color']);
  13963. $bcolor = array_values($background);
  13964. switch($numcolspace) {
  13965. case 5: // SPOT
  13966. case 4: { // CMYK
  13967. $this->gradients[$n]['colspace'] = 'DeviceCMYK';
  13968. if (!empty($background)) {
  13969. $this->gradients[$n]['background'] = sprintf('%F %F %F %F', $bcolor[0]/100, $bcolor[1]/100, $bcolor[2]/100, $bcolor[3]/100);
  13970. }
  13971. break;
  13972. }
  13973. case 3: { // RGB
  13974. $this->gradients[$n]['colspace'] = 'DeviceRGB';
  13975. if (!empty($background)) {
  13976. $this->gradients[$n]['background'] = sprintf('%F %F %F', $bcolor[0]/255, $bcolor[1]/255, $bcolor[2]/255);
  13977. }
  13978. break;
  13979. }
  13980. case 1: { // GRAY SCALE
  13981. $this->gradients[$n]['colspace'] = 'DeviceGray';
  13982. if (!empty($background)) {
  13983. $this->gradients[$n]['background'] = sprintf('%F', $bcolor[0]/255);
  13984. }
  13985. break;
  13986. }
  13987. }
  13988. $num_stops = count($stops);
  13989. $last_stop_id = $num_stops - 1;
  13990. foreach ($stops as $key => $stop) {
  13991. $this->gradients[$n]['colors'][$key] = array();
  13992. // offset represents a location along the gradient vector
  13993. if (isset($stop['offset'])) {
  13994. $this->gradients[$n]['colors'][$key]['offset'] = $stop['offset'];
  13995. } else {
  13996. if ($key == 0) {
  13997. $this->gradients[$n]['colors'][$key]['offset'] = 0;
  13998. } elseif ($key == $last_stop_id) {
  13999. $this->gradients[$n]['colors'][$key]['offset'] = 1;
  14000. } else {
  14001. $offsetstep = (1 - $this->gradients[$n]['colors'][($key - 1)]['offset']) / ($num_stops - $key);
  14002. $this->gradients[$n]['colors'][$key]['offset'] = $this->gradients[$n]['colors'][($key - 1)]['offset'] + $offsetstep;
  14003. }
  14004. }
  14005. if (isset($stop['opacity'])) {
  14006. $this->gradients[$n]['colors'][$key]['opacity'] = $stop['opacity'];
  14007. if ((!$this->pdfa_mode) AND ($stop['opacity'] < 1)) {
  14008. $this->gradients[$n]['transparency'] = true;
  14009. }
  14010. } else {
  14011. $this->gradients[$n]['colors'][$key]['opacity'] = 1;
  14012. }
  14013. // exponent for the exponential interpolation function
  14014. if (isset($stop['exponent'])) {
  14015. $this->gradients[$n]['colors'][$key]['exponent'] = $stop['exponent'];
  14016. } else {
  14017. $this->gradients[$n]['colors'][$key]['exponent'] = 1;
  14018. }
  14019. // set colors
  14020. $color = array_values($stop['color']);
  14021. switch($numcolspace) {
  14022. case 5: // SPOT
  14023. case 4: { // CMYK
  14024. $this->gradients[$n]['colors'][$key]['color'] = sprintf('%F %F %F %F', $color[0]/100, $color[1]/100, $color[2]/100, $color[3]/100);
  14025. break;
  14026. }
  14027. case 3: { // RGB
  14028. $this->gradients[$n]['colors'][$key]['color'] = sprintf('%F %F %F', $color[0]/255, $color[1]/255, $color[2]/255);
  14029. break;
  14030. }
  14031. case 1: { // GRAY SCALE
  14032. $this->gradients[$n]['colors'][$key]['color'] = sprintf('%F', $color[0]/255);
  14033. break;
  14034. }
  14035. }
  14036. }
  14037. if ($this->gradients[$n]['transparency']) {
  14038. // paint luminosity gradient
  14039. $this->_out('/TGS'.$n.' gs');
  14040. }
  14041. //paint the gradient
  14042. $this->_out('/Sh'.$n.' sh');
  14043. //restore previous Graphic State
  14044. $this->_outRestoreGraphicsState();
  14045. if ($this->inxobj) {
  14046. // we are inside an XObject template
  14047. $this->xobjects[$this->xobjid]['gradients'][$n] = $this->gradients[$n];
  14048. }
  14049. }
  14050. /**
  14051. * Output gradient shaders.
  14052. * @author Nicola Asuni
  14053. * @since 3.1.000 (2008-06-09)
  14054. * @protected
  14055. */
  14056. function _putshaders() {
  14057. if ($this->pdfa_mode) {
  14058. return;
  14059. }
  14060. $idt = count($this->gradients); //index for transparency gradients
  14061. foreach ($this->gradients as $id => $grad) {
  14062. if (($grad['type'] == 2) OR ($grad['type'] == 3)) {
  14063. $fc = $this->_newobj();
  14064. $out = '<<';
  14065. $out .= ' /FunctionType 3';
  14066. $out .= ' /Domain [0 1]';
  14067. $functions = '';
  14068. $bounds = '';
  14069. $encode = '';
  14070. $i = 1;
  14071. $num_cols = count($grad['colors']);
  14072. $lastcols = $num_cols - 1;
  14073. for ($i = 1; $i < $num_cols; ++$i) {
  14074. $functions .= ($fc + $i).' 0 R ';
  14075. if ($i < $lastcols) {
  14076. $bounds .= sprintf('%F ', $grad['colors'][$i]['offset']);
  14077. }
  14078. $encode .= '0 1 ';
  14079. }
  14080. $out .= ' /Functions ['.trim($functions).']';
  14081. $out .= ' /Bounds ['.trim($bounds).']';
  14082. $out .= ' /Encode ['.trim($encode).']';
  14083. $out .= ' >>';
  14084. $out .= "\n".'endobj';
  14085. $this->_out($out);
  14086. for ($i = 1; $i < $num_cols; ++$i) {
  14087. $this->_newobj();
  14088. $out = '<<';
  14089. $out .= ' /FunctionType 2';
  14090. $out .= ' /Domain [0 1]';
  14091. $out .= ' /C0 ['.$grad['colors'][($i - 1)]['color'].']';
  14092. $out .= ' /C1 ['.$grad['colors'][$i]['color'].']';
  14093. $out .= ' /N '.$grad['colors'][$i]['exponent'];
  14094. $out .= ' >>';
  14095. $out .= "\n".'endobj';
  14096. $this->_out($out);
  14097. }
  14098. // set transparency functions
  14099. if ($grad['transparency']) {
  14100. $ft = $this->_newobj();
  14101. $out = '<<';
  14102. $out .= ' /FunctionType 3';
  14103. $out .= ' /Domain [0 1]';
  14104. $functions = '';
  14105. $i = 1;
  14106. $num_cols = count($grad['colors']);
  14107. for ($i = 1; $i < $num_cols; ++$i) {
  14108. $functions .= ($ft + $i).' 0 R ';
  14109. }
  14110. $out .= ' /Functions ['.trim($functions).']';
  14111. $out .= ' /Bounds ['.trim($bounds).']';
  14112. $out .= ' /Encode ['.trim($encode).']';
  14113. $out .= ' >>';
  14114. $out .= "\n".'endobj';
  14115. $this->_out($out);
  14116. for ($i = 1; $i < $num_cols; ++$i) {
  14117. $this->_newobj();
  14118. $out = '<<';
  14119. $out .= ' /FunctionType 2';
  14120. $out .= ' /Domain [0 1]';
  14121. $out .= ' /C0 ['.$grad['colors'][($i - 1)]['opacity'].']';
  14122. $out .= ' /C1 ['.$grad['colors'][$i]['opacity'].']';
  14123. $out .= ' /N '.$grad['colors'][$i]['exponent'];
  14124. $out .= ' >>';
  14125. $out .= "\n".'endobj';
  14126. $this->_out($out);
  14127. }
  14128. }
  14129. }
  14130. // set shading object
  14131. $this->_newobj();
  14132. $out = '<< /ShadingType '.$grad['type'];
  14133. if (isset($grad['colspace'])) {
  14134. $out .= ' /ColorSpace /'.$grad['colspace'];
  14135. } else {
  14136. $out .= ' /ColorSpace /DeviceRGB';
  14137. }
  14138. if (isset($grad['background']) AND !empty($grad['background'])) {
  14139. $out .= ' /Background ['.$grad['background'].']';
  14140. }
  14141. if (isset($grad['antialias']) AND ($grad['antialias'] === true)) {
  14142. $out .= ' /AntiAlias true';
  14143. }
  14144. if ($grad['type'] == 2) {
  14145. $out .= ' '.sprintf('/Coords [%F %F %F %F]', $grad['coords'][0], $grad['coords'][1], $grad['coords'][2], $grad['coords'][3]);
  14146. $out .= ' /Domain [0 1]';
  14147. $out .= ' /Function '.$fc.' 0 R';
  14148. $out .= ' /Extend [true true]';
  14149. $out .= ' >>';
  14150. } elseif ($grad['type'] == 3) {
  14151. //x0, y0, r0, x1, y1, r1
  14152. //at this this time radius of inner circle is 0
  14153. $out .= ' '.sprintf('/Coords [%F %F 0 %F %F %F]', $grad['coords'][0], $grad['coords'][1], $grad['coords'][2], $grad['coords'][3], $grad['coords'][4]);
  14154. $out .= ' /Domain [0 1]';
  14155. $out .= ' /Function '.$fc.' 0 R';
  14156. $out .= ' /Extend [true true]';
  14157. $out .= ' >>';
  14158. } elseif ($grad['type'] == 6) {
  14159. $out .= ' /BitsPerCoordinate 16';
  14160. $out .= ' /BitsPerComponent 8';
  14161. $out .= ' /Decode[0 1 0 1 0 1 0 1 0 1]';
  14162. $out .= ' /BitsPerFlag 8';
  14163. $stream = $this->_getrawstream($grad['stream']);
  14164. $out .= ' /Length '.strlen($stream);
  14165. $out .= ' >>';
  14166. $out .= ' stream'."\n".$stream."\n".'endstream';
  14167. }
  14168. $out .= "\n".'endobj';
  14169. $this->_out($out);
  14170. if ($grad['transparency']) {
  14171. $shading_transparency = preg_replace('/\/ColorSpace \/[^\s]+/si', '/ColorSpace /DeviceGray', $out);
  14172. $shading_transparency = preg_replace('/\/Function [0-9]+ /si', '/Function '.$ft.' ', $shading_transparency);
  14173. }
  14174. $this->gradients[$id]['id'] = $this->n;
  14175. // set pattern object
  14176. $this->_newobj();
  14177. $out = '<< /Type /Pattern /PatternType 2';
  14178. $out .= ' /Shading '.$this->gradients[$id]['id'].' 0 R';
  14179. $out .= ' >>';
  14180. $out .= "\n".'endobj';
  14181. $this->_out($out);
  14182. $this->gradients[$id]['pattern'] = $this->n;
  14183. // set shading and pattern for transparency mask
  14184. if ($grad['transparency']) {
  14185. // luminosity pattern
  14186. $idgs = $id + $idt;
  14187. $this->_newobj();
  14188. $this->_out($shading_transparency);
  14189. $this->gradients[$idgs]['id'] = $this->n;
  14190. $this->_newobj();
  14191. $out = '<< /Type /Pattern /PatternType 2';
  14192. $out .= ' /Shading '.$this->gradients[$idgs]['id'].' 0 R';
  14193. $out .= ' >>';
  14194. $out .= "\n".'endobj';
  14195. $this->_out($out);
  14196. $this->gradients[$idgs]['pattern'] = $this->n;
  14197. // luminosity XObject
  14198. $oid = $this->_newobj();
  14199. $this->xobjects['LX'.$oid] = array('n' => $oid);
  14200. $filter = '';
  14201. $stream = 'q /a0 gs /Pattern cs /p'.$idgs.' scn 0 0 '.$this->wPt.' '.$this->hPt.' re f Q';
  14202. if ($this->compress) {
  14203. $filter = ' /Filter /FlateDecode';
  14204. $stream = gzcompress($stream);
  14205. }
  14206. $stream = $this->_getrawstream($stream);
  14207. $out = '<< /Type /XObject /Subtype /Form /FormType 1'.$filter;
  14208. $out .= ' /Length '.strlen($stream);
  14209. $rect = sprintf('%F %F', $this->wPt, $this->hPt);
  14210. $out .= ' /BBox [0 0 '.$rect.']';
  14211. $out .= ' /Group << /Type /Group /S /Transparency /CS /DeviceGray >>';
  14212. $out .= ' /Resources <<';
  14213. $out .= ' /ExtGState << /a0 << /ca 1 /CA 1 >> >>';
  14214. $out .= ' /Pattern << /p'.$idgs.' '.$this->gradients[$idgs]['pattern'].' 0 R >>';
  14215. $out .= ' >>';
  14216. $out .= ' >> ';
  14217. $out .= ' stream'."\n".$stream."\n".'endstream';
  14218. $out .= "\n".'endobj';
  14219. $this->_out($out);
  14220. // SMask
  14221. $this->_newobj();
  14222. $out = '<< /Type /Mask /S /Luminosity /G '.($this->n - 1).' 0 R >>'."\n".'endobj';
  14223. $this->_out($out);
  14224. // ExtGState
  14225. $this->_newobj();
  14226. $out = '<< /Type /ExtGState /SMask '.($this->n - 1).' 0 R /AIS false >>'."\n".'endobj';
  14227. $this->_out($out);
  14228. $this->extgstates[] = array('n' => $this->n, 'name' => 'TGS'.$id);
  14229. }
  14230. }
  14231. }
  14232. /**
  14233. * Draw the sector of a circle.
  14234. * It can be used for instance to render pie charts.
  14235. * @param $xc (float) abscissa of the center.
  14236. * @param $yc (float) ordinate of the center.
  14237. * @param $r (float) radius.
  14238. * @param $a (float) start angle (in degrees).
  14239. * @param $b (float) end angle (in degrees).
  14240. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  14241. * @param $cw: (float) indicates whether to go clockwise (default: true).
  14242. * @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.
  14243. * @author Maxime Delorme, Nicola Asuni
  14244. * @since 3.1.000 (2008-06-09)
  14245. * @public
  14246. */
  14247. public function PieSector($xc, $yc, $r, $a, $b, $style='FD', $cw=true, $o=90) {
  14248. $this->PieSectorXY($xc, $yc, $r, $r, $a, $b, $style, $cw, $o);
  14249. }
  14250. /**
  14251. * Draw the sector of an ellipse.
  14252. * It can be used for instance to render pie charts.
  14253. * @param $xc (float) abscissa of the center.
  14254. * @param $yc (float) ordinate of the center.
  14255. * @param $rx (float) the x-axis radius.
  14256. * @param $ry (float) the y-axis radius.
  14257. * @param $a (float) start angle (in degrees).
  14258. * @param $b (float) end angle (in degrees).
  14259. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  14260. * @param $cw: (float) indicates whether to go clockwise.
  14261. * @param $o: (float) origin of angles (0 for 3 o'clock, 90 for noon, 180 for 9 o'clock, 270 for 6 o'clock).
  14262. * @param $nc (integer) Number of curves used to draw a 90 degrees portion of arc.
  14263. * @author Maxime Delorme, Nicola Asuni
  14264. * @since 3.1.000 (2008-06-09)
  14265. * @public
  14266. */
  14267. public function PieSectorXY($xc, $yc, $rx, $ry, $a, $b, $style='FD', $cw=false, $o=0, $nc=2) {
  14268. if ($this->state != 2) {
  14269. return;
  14270. }
  14271. if ($this->rtl) {
  14272. $xc = ($this->w - $xc);
  14273. }
  14274. $op = TCPDF_STATIC::getPathPaintOperator($style);
  14275. if ($op == 'f') {
  14276. $line_style = array();
  14277. }
  14278. if ($cw) {
  14279. $d = $b;
  14280. $b = (360 - $a + $o);
  14281. $a = (360 - $d + $o);
  14282. } else {
  14283. $b += $o;
  14284. $a += $o;
  14285. }
  14286. $this->_outellipticalarc($xc, $yc, $rx, $ry, 0, $a, $b, true, $nc);
  14287. $this->_out($op);
  14288. }
  14289. /**
  14290. * Embed vector-based Adobe Illustrator (AI) or AI-compatible EPS files.
  14291. * NOTE: EPS is not yet fully implemented, use the setRasterizeVectorImages() method to enable/disable rasterization of vector images using ImageMagick library.
  14292. * Only vector drawing is supported, not text or bitmap.
  14293. * 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).
  14294. * @param $file (string) Name of the file containing the image or a '@' character followed by the EPS/AI data string.
  14295. * @param $x (float) Abscissa of the upper-left corner.
  14296. * @param $y (float) Ordinate of the upper-left corner.
  14297. * @param $w (float) Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
  14298. * @param $h (float) Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
  14299. * @param $link (mixed) URL or identifier returned by AddLink().
  14300. * @param $useBoundingBox (boolean) specifies whether to position the bounding box (true) or the complete canvas (false) at location (x,y). Default value is true.
  14301. * @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>
  14302. * @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>
  14303. * @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)))
  14304. * @param $fitonpage (boolean) if true the image is resized to not exceed page dimensions.
  14305. * @param $fixoutvals (boolean) if true remove values outside the bounding box.
  14306. * @author Valentin Schmidt, Nicola Asuni
  14307. * @since 3.1.000 (2008-06-09)
  14308. * @public
  14309. */
  14310. public function ImageEps($file, $x='', $y='', $w=0, $h=0, $link='', $useBoundingBox=true, $align='', $palign='', $border=0, $fitonpage=false, $fixoutvals=false) {
  14311. if ($this->state != 2) {
  14312. return;
  14313. }
  14314. if ($this->rasterize_vector_images AND ($w > 0) AND ($h > 0)) {
  14315. // convert EPS to raster image using GD or ImageMagick libraries
  14316. return $this->Image($file, $x, $y, $w, $h, 'EPS', $link, $align, true, 300, $palign, false, false, $border, false, false, $fitonpage);
  14317. }
  14318. if ($x === '') {
  14319. $x = $this->x;
  14320. }
  14321. if ($y === '') {
  14322. $y = $this->y;
  14323. }
  14324. // check page for no-write regions and adapt page margins if necessary
  14325. list($x, $y) = $this->checkPageRegions($h, $x, $y);
  14326. $k = $this->k;
  14327. if ($file[0] === '@') { // image from string
  14328. $data = substr($file, 1);
  14329. } else { // EPS/AI file
  14330. $data = TCPDF_STATIC::fileGetContents($file);
  14331. }
  14332. if ($data === FALSE) {
  14333. $this->Error('EPS file not found: '.$file);
  14334. }
  14335. $regs = array();
  14336. // EPS/AI compatibility check (only checks files created by Adobe Illustrator!)
  14337. preg_match("/%%Creator:([^\r\n]+)/", $data, $regs); # find Creator
  14338. if (count($regs) > 1) {
  14339. $version_str = trim($regs[1]); # e.g. "Adobe Illustrator(R) 8.0"
  14340. if (strpos($version_str, 'Adobe Illustrator') !== false) {
  14341. $versexp = explode(' ', $version_str);
  14342. $version = (float)array_pop($versexp);
  14343. if ($version >= 9) {
  14344. $this->Error('This version of Adobe Illustrator file is not supported: '.$file);
  14345. }
  14346. }
  14347. }
  14348. // strip binary bytes in front of PS-header
  14349. $start = strpos($data, '%!PS-Adobe');
  14350. if ($start > 0) {
  14351. $data = substr($data, $start);
  14352. }
  14353. // find BoundingBox params
  14354. preg_match("/%%BoundingBox:([^\r\n]+)/", $data, $regs);
  14355. if (count($regs) > 1) {
  14356. list($x1, $y1, $x2, $y2) = explode(' ', trim($regs[1]));
  14357. } else {
  14358. $this->Error('No BoundingBox found in EPS/AI file: '.$file);
  14359. }
  14360. $start = strpos($data, '%%EndSetup');
  14361. if ($start === false) {
  14362. $start = strpos($data, '%%EndProlog');
  14363. }
  14364. if ($start === false) {
  14365. $start = strpos($data, '%%BoundingBox');
  14366. }
  14367. $data = substr($data, $start);
  14368. $end = strpos($data, '%%PageTrailer');
  14369. if ($end===false) {
  14370. $end = strpos($data, 'showpage');
  14371. }
  14372. if ($end) {
  14373. $data = substr($data, 0, $end);
  14374. }
  14375. // calculate image width and height on document
  14376. if (($w <= 0) AND ($h <= 0)) {
  14377. $w = ($x2 - $x1) / $k;
  14378. $h = ($y2 - $y1) / $k;
  14379. } elseif ($w <= 0) {
  14380. $w = ($x2-$x1) / $k * ($h / (($y2 - $y1) / $k));
  14381. } elseif ($h <= 0) {
  14382. $h = ($y2 - $y1) / $k * ($w / (($x2 - $x1) / $k));
  14383. }
  14384. // fit the image on available space
  14385. list($w, $h, $x, $y) = $this->fitBlock($w, $h, $x, $y, $fitonpage);
  14386. if ($this->rasterize_vector_images) {
  14387. // convert EPS to raster image using GD or ImageMagick libraries
  14388. return $this->Image($file, $x, $y, $w, $h, 'EPS', $link, $align, true, 300, $palign, false, false, $border, false, false, $fitonpage);
  14389. }
  14390. // set scaling factors
  14391. $scale_x = $w / (($x2 - $x1) / $k);
  14392. $scale_y = $h / (($y2 - $y1) / $k);
  14393. // set alignment
  14394. $this->img_rb_y = $y + $h;
  14395. // set alignment
  14396. if ($this->rtl) {
  14397. if ($palign == 'L') {
  14398. $ximg = $this->lMargin;
  14399. } elseif ($palign == 'C') {
  14400. $ximg = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
  14401. } elseif ($palign == 'R') {
  14402. $ximg = $this->w - $this->rMargin - $w;
  14403. } else {
  14404. $ximg = $x - $w;
  14405. }
  14406. $this->img_rb_x = $ximg;
  14407. } else {
  14408. if ($palign == 'L') {
  14409. $ximg = $this->lMargin;
  14410. } elseif ($palign == 'C') {
  14411. $ximg = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
  14412. } elseif ($palign == 'R') {
  14413. $ximg = $this->w - $this->rMargin - $w;
  14414. } else {
  14415. $ximg = $x;
  14416. }
  14417. $this->img_rb_x = $ximg + $w;
  14418. }
  14419. if ($useBoundingBox) {
  14420. $dx = $ximg * $k - $x1;
  14421. $dy = $y * $k - $y1;
  14422. } else {
  14423. $dx = $ximg * $k;
  14424. $dy = $y * $k;
  14425. }
  14426. // save the current graphic state
  14427. $this->_out('q'.$this->epsmarker);
  14428. // translate
  14429. $this->_out(sprintf('%F %F %F %F %F %F cm', 1, 0, 0, 1, $dx, $dy + ($this->hPt - (2 * $y * $k) - ($y2 - $y1))));
  14430. // scale
  14431. if (isset($scale_x)) {
  14432. $this->_out(sprintf('%F %F %F %F %F %F cm', $scale_x, 0, 0, $scale_y, $x1 * (1 - $scale_x), $y2 * (1 - $scale_y)));
  14433. }
  14434. // handle pc/unix/mac line endings
  14435. $lines = preg_split('/[\r\n]+/si', $data, -1, PREG_SPLIT_NO_EMPTY);
  14436. $u=0;
  14437. $cnt = count($lines);
  14438. for ($i=0; $i < $cnt; ++$i) {
  14439. $line = $lines[$i];
  14440. if (($line == '') OR ($line[0] == '%')) {
  14441. continue;
  14442. }
  14443. $len = strlen($line);
  14444. // check for spot color names
  14445. $color_name = '';
  14446. if (strcasecmp('x', substr(trim($line), -1)) == 0) {
  14447. if (preg_match('/\([^\)]*\)/', $line, $matches) > 0) {
  14448. // extract spot color name
  14449. $color_name = $matches[0];
  14450. // remove color name from string
  14451. $line = str_replace(' '.$color_name, '', $line);
  14452. // remove pharentesis from color name
  14453. $color_name = substr($color_name, 1, -1);
  14454. }
  14455. }
  14456. $chunks = explode(' ', $line);
  14457. $cmd = trim(array_pop($chunks));
  14458. // RGB
  14459. if (($cmd == 'Xa') OR ($cmd == 'XA')) {
  14460. $b = array_pop($chunks);
  14461. $g = array_pop($chunks);
  14462. $r = array_pop($chunks);
  14463. $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!
  14464. continue;
  14465. }
  14466. $skip = false;
  14467. if ($fixoutvals) {
  14468. // check for values outside the bounding box
  14469. switch ($cmd) {
  14470. case 'm':
  14471. case 'l':
  14472. case 'L': {
  14473. // skip values outside bounding box
  14474. foreach ($chunks as $key => $val) {
  14475. if ((($key % 2) == 0) AND (($val < $x1) OR ($val > $x2))) {
  14476. $skip = true;
  14477. } elseif ((($key % 2) != 0) AND (($val < $y1) OR ($val > $y2))) {
  14478. $skip = true;
  14479. }
  14480. }
  14481. }
  14482. }
  14483. }
  14484. switch ($cmd) {
  14485. case 'm':
  14486. case 'l':
  14487. case 'v':
  14488. case 'y':
  14489. case 'c':
  14490. case 'k':
  14491. case 'K':
  14492. case 'g':
  14493. case 'G':
  14494. case 's':
  14495. case 'S':
  14496. case 'J':
  14497. case 'j':
  14498. case 'w':
  14499. case 'M':
  14500. case 'd':
  14501. case 'n': {
  14502. if ($skip) {
  14503. break;
  14504. }
  14505. $this->_out($line);
  14506. break;
  14507. }
  14508. case 'x': {// custom fill color
  14509. if (empty($color_name)) {
  14510. // CMYK color
  14511. list($col_c, $col_m, $col_y, $col_k) = $chunks;
  14512. $this->_out(''.$col_c.' '.$col_m.' '.$col_y.' '.$col_k.' k');
  14513. } else {
  14514. // Spot Color (CMYK + tint)
  14515. list($col_c, $col_m, $col_y, $col_k, $col_t) = $chunks;
  14516. $this->AddSpotColor($color_name, ($col_c * 100), ($col_m * 100), ($col_y * 100), ($col_k * 100));
  14517. $color_cmd = sprintf('/CS%d cs %F scn', $this->spot_colors[$color_name]['i'], (1 - $col_t));
  14518. $this->_out($color_cmd);
  14519. }
  14520. break;
  14521. }
  14522. case 'X': { // custom stroke color
  14523. if (empty($color_name)) {
  14524. // CMYK color
  14525. list($col_c, $col_m, $col_y, $col_k) = $chunks;
  14526. $this->_out(''.$col_c.' '.$col_m.' '.$col_y.' '.$col_k.' K');
  14527. } else {
  14528. // Spot Color (CMYK + tint)
  14529. list($col_c, $col_m, $col_y, $col_k, $col_t) = $chunks;
  14530. $this->AddSpotColor($color_name, ($col_c * 100), ($col_m * 100), ($col_y * 100), ($col_k * 100));
  14531. $color_cmd = sprintf('/CS%d CS %F SCN', $this->spot_colors[$color_name]['i'], (1 - $col_t));
  14532. $this->_out($color_cmd);
  14533. }
  14534. break;
  14535. }
  14536. case 'Y':
  14537. case 'N':
  14538. case 'V':
  14539. case 'L':
  14540. case 'C': {
  14541. if ($skip) {
  14542. break;
  14543. }
  14544. $line[($len - 1)] = strtolower($cmd);
  14545. $this->_out($line);
  14546. break;
  14547. }
  14548. case 'b':
  14549. case 'B': {
  14550. $this->_out($cmd . '*');
  14551. break;
  14552. }
  14553. case 'f':
  14554. case 'F': {
  14555. if ($u > 0) {
  14556. $isU = false;
  14557. $max = min(($i + 5), $cnt);
  14558. for ($j = ($i + 1); $j < $max; ++$j) {
  14559. $isU = ($isU OR (($lines[$j] == 'U') OR ($lines[$j] == '*U')));
  14560. }
  14561. if ($isU) {
  14562. $this->_out('f*');
  14563. }
  14564. } else {
  14565. $this->_out('f*');
  14566. }
  14567. break;
  14568. }
  14569. case '*u': {
  14570. ++$u;
  14571. break;
  14572. }
  14573. case '*U': {
  14574. --$u;
  14575. break;
  14576. }
  14577. }
  14578. }
  14579. // restore previous graphic state
  14580. $this->_out($this->epsmarker.'Q');
  14581. if (!empty($border)) {
  14582. $bx = $this->x;
  14583. $by = $this->y;
  14584. $this->x = $ximg;
  14585. if ($this->rtl) {
  14586. $this->x += $w;
  14587. }
  14588. $this->y = $y;
  14589. $this->Cell($w, $h, '', $border, 0, '', 0, '', 0, true);
  14590. $this->x = $bx;
  14591. $this->y = $by;
  14592. }
  14593. if ($link) {
  14594. $this->Link($ximg, $y, $w, $h, $link, 0);
  14595. }
  14596. // set pointer to align the next text/objects
  14597. switch($align) {
  14598. case 'T':{
  14599. $this->y = $y;
  14600. $this->x = $this->img_rb_x;
  14601. break;
  14602. }
  14603. case 'M':{
  14604. $this->y = $y + round($h/2);
  14605. $this->x = $this->img_rb_x;
  14606. break;
  14607. }
  14608. case 'B':{
  14609. $this->y = $this->img_rb_y;
  14610. $this->x = $this->img_rb_x;
  14611. break;
  14612. }
  14613. case 'N':{
  14614. $this->SetY($this->img_rb_y);
  14615. break;
  14616. }
  14617. default:{
  14618. break;
  14619. }
  14620. }
  14621. $this->endlinex = $this->img_rb_x;
  14622. }
  14623. /**
  14624. * Set document barcode.
  14625. * @param $bc (string) barcode
  14626. * @public
  14627. */
  14628. public function setBarcode($bc='') {
  14629. $this->barcode = $bc;
  14630. }
  14631. /**
  14632. * Get current barcode.
  14633. * @return string
  14634. * @public
  14635. * @since 4.0.012 (2008-07-24)
  14636. */
  14637. public function getBarcode() {
  14638. return $this->barcode;
  14639. }
  14640. /**
  14641. * Print a Linear Barcode.
  14642. * @param $code (string) code to print
  14643. * @param $type (string) type of barcode (see tcpdf_barcodes_1d.php for supported formats).
  14644. * @param $x (int) x position in user units (empty string = current x position)
  14645. * @param $y (int) y position in user units (empty string = current y position)
  14646. * @param $w (int) width in user units (empty string = remaining page width)
  14647. * @param $h (int) height in user units (empty string = remaining page height)
  14648. * @param $xres (float) width of the smallest bar in user units (empty string = default value = 0.4mm)
  14649. * @param $style (array) array of options:<ul>
  14650. * <li>boolean $style['border'] if true prints a border</li>
  14651. * <li>int $style['padding'] padding to leave around the barcode in user units (set to 'auto' for automatic padding)</li>
  14652. * <li>int $style['hpadding'] horizontal padding in user units (set to 'auto' for automatic padding)</li>
  14653. * <li>int $style['vpadding'] vertical padding in user units (set to 'auto' for automatic padding)</li>
  14654. * <li>array $style['fgcolor'] color array for bars and text</li>
  14655. * <li>mixed $style['bgcolor'] color array for background (set to false for transparent)</li>
  14656. * <li>boolean $style['text'] if true prints text below the barcode</li>
  14657. * <li>string $style['label'] override default label</li>
  14658. * <li>string $style['font'] font name for text</li><li>int $style['fontsize'] font size for text</li>
  14659. * <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>
  14660. * <li>string $style['position'] horizontal position of the containing barcode cell on the page: L = left margin; C = center; R = right margin.</li>
  14661. * <li>string $style['align'] horizontal position of the barcode on the containing rectangle: L = left; C = center; R = right.</li>
  14662. * <li>string $style['stretch'] if true stretch the barcode to best fit the available width, otherwise uses $xres resolution for a single bar.</li>
  14663. * <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>
  14664. * <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>
  14665. * @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>
  14666. * @author Nicola Asuni
  14667. * @since 3.1.000 (2008-06-09)
  14668. * @public
  14669. */
  14670. public function write1DBarcode($code, $type, $x='', $y='', $w='', $h='', $xres='', $style=array(), $align='') {
  14671. if (TCPDF_STATIC::empty_string(trim($code))) {
  14672. return;
  14673. }
  14674. require_once(dirname(__FILE__).'/tcpdf_barcodes_1d.php');
  14675. // save current graphic settings
  14676. $gvars = $this->getGraphicVars();
  14677. // create new barcode object
  14678. $barcodeobj = new TCPDFBarcode($code, $type);
  14679. $arrcode = $barcodeobj->getBarcodeArray();
  14680. if (($arrcode === false) OR empty($arrcode) OR ($arrcode['maxw'] <= 0)) {
  14681. $this->Error('Error in 1D barcode string');
  14682. }
  14683. if ($arrcode['maxh'] <= 0) {
  14684. $arrcode['maxh'] = 1;
  14685. }
  14686. // set default values
  14687. if (!isset($style['position'])) {
  14688. $style['position'] = '';
  14689. } elseif ($style['position'] == 'S') {
  14690. // keep this for backward compatibility
  14691. $style['position'] = '';
  14692. $style['stretch'] = true;
  14693. }
  14694. if (!isset($style['fitwidth'])) {
  14695. if (!isset($style['stretch'])) {
  14696. $style['fitwidth'] = true;
  14697. } else {
  14698. $style['fitwidth'] = false;
  14699. }
  14700. }
  14701. if ($style['fitwidth']) {
  14702. // disable stretch
  14703. $style['stretch'] = false;
  14704. }
  14705. if (!isset($style['stretch'])) {
  14706. if (($w === '') OR ($w <= 0)) {
  14707. $style['stretch'] = false;
  14708. } else {
  14709. $style['stretch'] = true;
  14710. }
  14711. }
  14712. if (!isset($style['fgcolor'])) {
  14713. $style['fgcolor'] = array(0,0,0); // default black
  14714. }
  14715. if (!isset($style['bgcolor'])) {
  14716. $style['bgcolor'] = false; // default transparent
  14717. }
  14718. if (!isset($style['border'])) {
  14719. $style['border'] = false;
  14720. }
  14721. $fontsize = 0;
  14722. if (!isset($style['text'])) {
  14723. $style['text'] = false;
  14724. }
  14725. if ($style['text'] AND isset($style['font'])) {
  14726. if (isset($style['fontsize'])) {
  14727. $fontsize = $style['fontsize'];
  14728. }
  14729. $this->SetFont($style['font'], '', $fontsize);
  14730. }
  14731. if (!isset($style['stretchtext'])) {
  14732. $style['stretchtext'] = 4;
  14733. }
  14734. if ($x === '') {
  14735. $x = $this->x;
  14736. }
  14737. if ($y === '') {
  14738. $y = $this->y;
  14739. }
  14740. // check page for no-write regions and adapt page margins if necessary
  14741. list($x, $y) = $this->checkPageRegions($h, $x, $y);
  14742. if (($w === '') OR ($w <= 0)) {
  14743. if ($this->rtl) {
  14744. $w = $x - $this->lMargin;
  14745. } else {
  14746. $w = $this->w - $this->rMargin - $x;
  14747. }
  14748. }
  14749. // padding
  14750. if (!isset($style['padding'])) {
  14751. $padding = 0;
  14752. } elseif ($style['padding'] === 'auto') {
  14753. $padding = 10 * ($w / ($arrcode['maxw'] + 20));
  14754. } else {
  14755. $padding = floatval($style['padding']);
  14756. }
  14757. // horizontal padding
  14758. if (!isset($style['hpadding'])) {
  14759. $hpadding = $padding;
  14760. } elseif ($style['hpadding'] === 'auto') {
  14761. $hpadding = 10 * ($w / ($arrcode['maxw'] + 20));
  14762. } else {
  14763. $hpadding = floatval($style['hpadding']);
  14764. }
  14765. // vertical padding
  14766. if (!isset($style['vpadding'])) {
  14767. $vpadding = $padding;
  14768. } elseif ($style['vpadding'] === 'auto') {
  14769. $vpadding = ($hpadding / 2);
  14770. } else {
  14771. $vpadding = floatval($style['vpadding']);
  14772. }
  14773. // calculate xres (single bar width)
  14774. $max_xres = ($w - (2 * $hpadding)) / $arrcode['maxw'];
  14775. if ($style['stretch']) {
  14776. $xres = $max_xres;
  14777. } else {
  14778. if (TCPDF_STATIC::empty_string($xres)) {
  14779. $xres = (0.141 * $this->k); // default bar width = 0.4 mm
  14780. }
  14781. if ($xres > $max_xres) {
  14782. // correct xres to fit on $w
  14783. $xres = $max_xres;
  14784. }
  14785. if ((isset($style['padding']) AND ($style['padding'] === 'auto'))
  14786. OR (isset($style['hpadding']) AND ($style['hpadding'] === 'auto'))) {
  14787. $hpadding = 10 * $xres;
  14788. if (isset($style['vpadding']) AND ($style['vpadding'] === 'auto')) {
  14789. $vpadding = ($hpadding / 2);
  14790. }
  14791. }
  14792. }
  14793. if ($style['fitwidth']) {
  14794. $wold = $w;
  14795. $w = (($arrcode['maxw'] * $xres) + (2 * $hpadding));
  14796. if (isset($style['cellfitalign'])) {
  14797. switch ($style['cellfitalign']) {
  14798. case 'L': {
  14799. if ($this->rtl) {
  14800. $x -= ($wold - $w);
  14801. }
  14802. break;
  14803. }
  14804. case 'R': {
  14805. if (!$this->rtl) {
  14806. $x += ($wold - $w);
  14807. }
  14808. break;
  14809. }
  14810. case 'C': {
  14811. if ($this->rtl) {
  14812. $x -= (($wold - $w) / 2);
  14813. } else {
  14814. $x += (($wold - $w) / 2);
  14815. }
  14816. break;
  14817. }
  14818. default : {
  14819. break;
  14820. }
  14821. }
  14822. }
  14823. }
  14824. $text_height = $this->getCellHeight($fontsize / $this->k);
  14825. // height
  14826. if (($h === '') OR ($h <= 0)) {
  14827. // set default height
  14828. $h = (($arrcode['maxw'] * $xres) / 3) + (2 * $vpadding) + $text_height;
  14829. }
  14830. $barh = $h - $text_height - (2 * $vpadding);
  14831. if ($barh <=0) {
  14832. // try to reduce font or padding to fit barcode on available height
  14833. if ($text_height > $h) {
  14834. $fontsize = (($h * $this->k) / (4 * $this->cell_height_ratio));
  14835. $text_height = $this->getCellHeight($fontsize / $this->k);
  14836. $this->SetFont($style['font'], '', $fontsize);
  14837. }
  14838. if ($vpadding > 0) {
  14839. $vpadding = (($h - $text_height) / 4);
  14840. }
  14841. $barh = $h - $text_height - (2 * $vpadding);
  14842. }
  14843. // fit the barcode on available space
  14844. list($w, $h, $x, $y) = $this->fitBlock($w, $h, $x, $y, false);
  14845. // set alignment
  14846. $this->img_rb_y = $y + $h;
  14847. // set alignment
  14848. if ($this->rtl) {
  14849. if ($style['position'] == 'L') {
  14850. $xpos = $this->lMargin;
  14851. } elseif ($style['position'] == 'C') {
  14852. $xpos = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
  14853. } elseif ($style['position'] == 'R') {
  14854. $xpos = $this->w - $this->rMargin - $w;
  14855. } else {
  14856. $xpos = $x - $w;
  14857. }
  14858. $this->img_rb_x = $xpos;
  14859. } else {
  14860. if ($style['position'] == 'L') {
  14861. $xpos = $this->lMargin;
  14862. } elseif ($style['position'] == 'C') {
  14863. $xpos = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
  14864. } elseif ($style['position'] == 'R') {
  14865. $xpos = $this->w - $this->rMargin - $w;
  14866. } else {
  14867. $xpos = $x;
  14868. }
  14869. $this->img_rb_x = $xpos + $w;
  14870. }
  14871. $xpos_rect = $xpos;
  14872. if (!isset($style['align'])) {
  14873. $style['align'] = 'C';
  14874. }
  14875. switch ($style['align']) {
  14876. case 'L': {
  14877. $xpos = $xpos_rect + $hpadding;
  14878. break;
  14879. }
  14880. case 'R': {
  14881. $xpos = $xpos_rect + ($w - ($arrcode['maxw'] * $xres)) - $hpadding;
  14882. break;
  14883. }
  14884. case 'C':
  14885. default : {
  14886. $xpos = $xpos_rect + (($w - ($arrcode['maxw'] * $xres)) / 2);
  14887. break;
  14888. }
  14889. }
  14890. $xpos_text = $xpos;
  14891. // barcode is always printed in LTR direction
  14892. $tempRTL = $this->rtl;
  14893. $this->rtl = false;
  14894. // print background color
  14895. if ($style['bgcolor']) {
  14896. $this->Rect($xpos_rect, $y, $w, $h, $style['border'] ? 'DF' : 'F', '', $style['bgcolor']);
  14897. } elseif ($style['border']) {
  14898. $this->Rect($xpos_rect, $y, $w, $h, 'D');
  14899. }
  14900. // set foreground color
  14901. $this->SetDrawColorArray($style['fgcolor']);
  14902. $this->SetTextColorArray($style['fgcolor']);
  14903. // print bars
  14904. foreach ($arrcode['bcode'] as $k => $v) {
  14905. $bw = ($v['w'] * $xres);
  14906. if ($v['t']) {
  14907. // draw a vertical bar
  14908. $ypos = $y + $vpadding + ($v['p'] * $barh / $arrcode['maxh']);
  14909. $this->Rect($xpos, $ypos, $bw, ($v['h'] * $barh / $arrcode['maxh']), 'F', array(), $style['fgcolor']);
  14910. }
  14911. $xpos += $bw;
  14912. }
  14913. // print text
  14914. if ($style['text']) {
  14915. if (isset($style['label']) AND !TCPDF_STATIC::empty_string($style['label'])) {
  14916. $label = $style['label'];
  14917. } else {
  14918. $label = $code;
  14919. }
  14920. $txtwidth = ($arrcode['maxw'] * $xres);
  14921. if ($this->GetStringWidth($label) > $txtwidth) {
  14922. $style['stretchtext'] = 2;
  14923. }
  14924. // print text
  14925. $this->x = $xpos_text;
  14926. $this->y = $y + $vpadding + $barh;
  14927. $cellpadding = $this->cell_padding;
  14928. $this->SetCellPadding(0);
  14929. $this->Cell($txtwidth, '', $label, 0, 0, 'C', false, '', $style['stretchtext'], false, 'T', 'T');
  14930. $this->cell_padding = $cellpadding;
  14931. }
  14932. // restore original direction
  14933. $this->rtl = $tempRTL;
  14934. // restore previous settings
  14935. $this->setGraphicVars($gvars);
  14936. // set pointer to align the next text/objects
  14937. switch($align) {
  14938. case 'T':{
  14939. $this->y = $y;
  14940. $this->x = $this->img_rb_x;
  14941. break;
  14942. }
  14943. case 'M':{
  14944. $this->y = $y + round($h / 2);
  14945. $this->x = $this->img_rb_x;
  14946. break;
  14947. }
  14948. case 'B':{
  14949. $this->y = $this->img_rb_y;
  14950. $this->x = $this->img_rb_x;
  14951. break;
  14952. }
  14953. case 'N':{
  14954. $this->SetY($this->img_rb_y);
  14955. break;
  14956. }
  14957. default:{
  14958. break;
  14959. }
  14960. }
  14961. $this->endlinex = $this->img_rb_x;
  14962. }
  14963. /**
  14964. * Print 2D Barcode.
  14965. * @param $code (string) code to print
  14966. * @param $type (string) type of barcode (see tcpdf_barcodes_2d.php for supported formats).
  14967. * @param $x (int) x position in user units
  14968. * @param $y (int) y position in user units
  14969. * @param $w (int) width in user units
  14970. * @param $h (int) height in user units
  14971. * @param $style (array) array of options:<ul>
  14972. * <li>boolean $style['border'] if true prints a border around the barcode</li>
  14973. * <li>int $style['padding'] padding to leave around the barcode in barcode units (set to 'auto' for automatic padding)</li>
  14974. * <li>int $style['hpadding'] horizontal padding in barcode units (set to 'auto' for automatic padding)</li>
  14975. * <li>int $style['vpadding'] vertical padding in barcode units (set to 'auto' for automatic padding)</li>
  14976. * <li>int $style['module_width'] width of a single module in points</li>
  14977. * <li>int $style['module_height'] height of a single module in points</li>
  14978. * <li>array $style['fgcolor'] color array for bars and text</li>
  14979. * <li>mixed $style['bgcolor'] color array for background or false for transparent</li>
  14980. * <li>string $style['position'] barcode position on the page: L = left margin; C = center; R = right margin; S = stretch</li>
  14981. * @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>
  14982. * @param $distort (boolean) if true distort the barcode to fit width and height, otherwise preserve aspect ratio
  14983. * @author Nicola Asuni
  14984. * @since 4.5.037 (2009-04-07)
  14985. * @public
  14986. */
  14987. public function write2DBarcode($code, $type, $x='', $y='', $w='', $h='', $style=array(), $align='', $distort=false) {
  14988. if (TCPDF_STATIC::empty_string(trim($code))) {
  14989. return;
  14990. }
  14991. require_once(dirname(__FILE__).'/tcpdf_barcodes_2d.php');
  14992. // save current graphic settings
  14993. $gvars = $this->getGraphicVars();
  14994. // create new barcode object
  14995. $barcodeobj = new TCPDF2DBarcode($code, $type);
  14996. $arrcode = $barcodeobj->getBarcodeArray();
  14997. if (($arrcode === false) OR empty($arrcode) OR !isset($arrcode['num_rows']) OR ($arrcode['num_rows'] == 0) OR !isset($arrcode['num_cols']) OR ($arrcode['num_cols'] == 0)) {
  14998. $this->Error('Error in 2D barcode string');
  14999. }
  15000. // set default values
  15001. if (!isset($style['position'])) {
  15002. $style['position'] = '';
  15003. }
  15004. if (!isset($style['fgcolor'])) {
  15005. $style['fgcolor'] = array(0,0,0); // default black
  15006. }
  15007. if (!isset($style['bgcolor'])) {
  15008. $style['bgcolor'] = false; // default transparent
  15009. }
  15010. if (!isset($style['border'])) {
  15011. $style['border'] = false;
  15012. }
  15013. // padding
  15014. if (!isset($style['padding'])) {
  15015. $style['padding'] = 0;
  15016. } elseif ($style['padding'] === 'auto') {
  15017. $style['padding'] = 4;
  15018. }
  15019. if (!isset($style['hpadding'])) {
  15020. $style['hpadding'] = $style['padding'];
  15021. } elseif ($style['hpadding'] === 'auto') {
  15022. $style['hpadding'] = 4;
  15023. }
  15024. if (!isset($style['vpadding'])) {
  15025. $style['vpadding'] = $style['padding'];
  15026. } elseif ($style['vpadding'] === 'auto') {
  15027. $style['vpadding'] = 4;
  15028. }
  15029. $hpad = (2 * $style['hpadding']);
  15030. $vpad = (2 * $style['vpadding']);
  15031. // cell (module) dimension
  15032. if (!isset($style['module_width'])) {
  15033. $style['module_width'] = 1; // width of a single module in points
  15034. }
  15035. if (!isset($style['module_height'])) {
  15036. $style['module_height'] = 1; // height of a single module in points
  15037. }
  15038. if ($x === '') {
  15039. $x = $this->x;
  15040. }
  15041. if ($y === '') {
  15042. $y = $this->y;
  15043. }
  15044. // check page for no-write regions and adapt page margins if necessary
  15045. list($x, $y) = $this->checkPageRegions($h, $x, $y);
  15046. // number of barcode columns and rows
  15047. $rows = $arrcode['num_rows'];
  15048. $cols = $arrcode['num_cols'];
  15049. if (($rows <= 0) || ($cols <= 0)){
  15050. $this->Error('Error in 2D barcode string');
  15051. }
  15052. // module width and height
  15053. $mw = $style['module_width'];
  15054. $mh = $style['module_height'];
  15055. if (($mw <= 0) OR ($mh <= 0)) {
  15056. $this->Error('Error in 2D barcode string');
  15057. }
  15058. // get max dimensions
  15059. if ($this->rtl) {
  15060. $maxw = $x - $this->lMargin;
  15061. } else {
  15062. $maxw = $this->w - $this->rMargin - $x;
  15063. }
  15064. $maxh = ($this->h - $this->tMargin - $this->bMargin);
  15065. $ratioHW = ((($rows * $mh) + $hpad) / (($cols * $mw) + $vpad));
  15066. $ratioWH = ((($cols * $mw) + $vpad) / (($rows * $mh) + $hpad));
  15067. if (!$distort) {
  15068. if (($maxw * $ratioHW) > $maxh) {
  15069. $maxw = $maxh * $ratioWH;
  15070. }
  15071. if (($maxh * $ratioWH) > $maxw) {
  15072. $maxh = $maxw * $ratioHW;
  15073. }
  15074. }
  15075. // set maximum dimensions
  15076. if ($w > $maxw) {
  15077. $w = $maxw;
  15078. }
  15079. if ($h > $maxh) {
  15080. $h = $maxh;
  15081. }
  15082. // set dimensions
  15083. if ((($w === '') OR ($w <= 0)) AND (($h === '') OR ($h <= 0))) {
  15084. $w = ($cols + $hpad) * ($mw / $this->k);
  15085. $h = ($rows + $vpad) * ($mh / $this->k);
  15086. } elseif (($w === '') OR ($w <= 0)) {
  15087. $w = $h * $ratioWH;
  15088. } elseif (($h === '') OR ($h <= 0)) {
  15089. $h = $w * $ratioHW;
  15090. }
  15091. // barcode size (excluding padding)
  15092. $bw = ($w * $cols) / ($cols + $hpad);
  15093. $bh = ($h * $rows) / ($rows + $vpad);
  15094. // dimension of single barcode cell unit
  15095. $cw = $bw / $cols;
  15096. $ch = $bh / $rows;
  15097. if (!$distort) {
  15098. if (($cw / $ch) > ($mw / $mh)) {
  15099. // correct horizontal distortion
  15100. $cw = $ch * $mw / $mh;
  15101. $bw = $cw * $cols;
  15102. $style['hpadding'] = ($w - $bw) / (2 * $cw);
  15103. } else {
  15104. // correct vertical distortion
  15105. $ch = $cw * $mh / $mw;
  15106. $bh = $ch * $rows;
  15107. $style['vpadding'] = ($h - $bh) / (2 * $ch);
  15108. }
  15109. }
  15110. // fit the barcode on available space
  15111. list($w, $h, $x, $y) = $this->fitBlock($w, $h, $x, $y, false);
  15112. // set alignment
  15113. $this->img_rb_y = $y + $h;
  15114. // set alignment
  15115. if ($this->rtl) {
  15116. if ($style['position'] == 'L') {
  15117. $xpos = $this->lMargin;
  15118. } elseif ($style['position'] == 'C') {
  15119. $xpos = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
  15120. } elseif ($style['position'] == 'R') {
  15121. $xpos = $this->w - $this->rMargin - $w;
  15122. } else {
  15123. $xpos = $x - $w;
  15124. }
  15125. $this->img_rb_x = $xpos;
  15126. } else {
  15127. if ($style['position'] == 'L') {
  15128. $xpos = $this->lMargin;
  15129. } elseif ($style['position'] == 'C') {
  15130. $xpos = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
  15131. } elseif ($style['position'] == 'R') {
  15132. $xpos = $this->w - $this->rMargin - $w;
  15133. } else {
  15134. $xpos = $x;
  15135. }
  15136. $this->img_rb_x = $xpos + $w;
  15137. }
  15138. $xstart = $xpos + ($style['hpadding'] * $cw);
  15139. $ystart = $y + ($style['vpadding'] * $ch);
  15140. // barcode is always printed in LTR direction
  15141. $tempRTL = $this->rtl;
  15142. $this->rtl = false;
  15143. // print background color
  15144. if ($style['bgcolor']) {
  15145. $this->Rect($xpos, $y, $w, $h, $style['border'] ? 'DF' : 'F', '', $style['bgcolor']);
  15146. } elseif ($style['border']) {
  15147. $this->Rect($xpos, $y, $w, $h, 'D');
  15148. }
  15149. // set foreground color
  15150. $this->SetDrawColorArray($style['fgcolor']);
  15151. // print barcode cells
  15152. // for each row
  15153. for ($r = 0; $r < $rows; ++$r) {
  15154. $xr = $xstart;
  15155. // for each column
  15156. for ($c = 0; $c < $cols; ++$c) {
  15157. if ($arrcode['bcode'][$r][$c] == 1) {
  15158. // draw a single barcode cell
  15159. $this->Rect($xr, $ystart, $cw, $ch, 'F', array(), $style['fgcolor']);
  15160. }
  15161. $xr += $cw;
  15162. }
  15163. $ystart += $ch;
  15164. }
  15165. // restore original direction
  15166. $this->rtl = $tempRTL;
  15167. // restore previous settings
  15168. $this->setGraphicVars($gvars);
  15169. // set pointer to align the next text/objects
  15170. switch($align) {
  15171. case 'T':{
  15172. $this->y = $y;
  15173. $this->x = $this->img_rb_x;
  15174. break;
  15175. }
  15176. case 'M':{
  15177. $this->y = $y + round($h/2);
  15178. $this->x = $this->img_rb_x;
  15179. break;
  15180. }
  15181. case 'B':{
  15182. $this->y = $this->img_rb_y;
  15183. $this->x = $this->img_rb_x;
  15184. break;
  15185. }
  15186. case 'N':{
  15187. $this->SetY($this->img_rb_y);
  15188. break;
  15189. }
  15190. default:{
  15191. break;
  15192. }
  15193. }
  15194. $this->endlinex = $this->img_rb_x;
  15195. }
  15196. /**
  15197. * Returns an array containing current margins:
  15198. * <ul>
  15199. <li>$ret['left'] = left margin</li>
  15200. <li>$ret['right'] = right margin</li>
  15201. <li>$ret['top'] = top margin</li>
  15202. <li>$ret['bottom'] = bottom margin</li>
  15203. <li>$ret['header'] = header margin</li>
  15204. <li>$ret['footer'] = footer margin</li>
  15205. <li>$ret['cell'] = cell padding array</li>
  15206. <li>$ret['padding_left'] = cell left padding</li>
  15207. <li>$ret['padding_top'] = cell top padding</li>
  15208. <li>$ret['padding_right'] = cell right padding</li>
  15209. <li>$ret['padding_bottom'] = cell bottom padding</li>
  15210. * </ul>
  15211. * @return array containing all margins measures
  15212. * @public
  15213. * @since 3.2.000 (2008-06-23)
  15214. */
  15215. public function getMargins() {
  15216. $ret = array(
  15217. 'left' => $this->lMargin,
  15218. 'right' => $this->rMargin,
  15219. 'top' => $this->tMargin,
  15220. 'bottom' => $this->bMargin,
  15221. 'header' => $this->header_margin,
  15222. 'footer' => $this->footer_margin,
  15223. 'cell' => $this->cell_padding,
  15224. 'padding_left' => $this->cell_padding['L'],
  15225. 'padding_top' => $this->cell_padding['T'],
  15226. 'padding_right' => $this->cell_padding['R'],
  15227. 'padding_bottom' => $this->cell_padding['B']
  15228. );
  15229. return $ret;
  15230. }
  15231. /**
  15232. * Returns an array containing original margins:
  15233. * <ul>
  15234. <li>$ret['left'] = left margin</li>
  15235. <li>$ret['right'] = right margin</li>
  15236. * </ul>
  15237. * @return array containing all margins measures
  15238. * @public
  15239. * @since 4.0.012 (2008-07-24)
  15240. */
  15241. public function getOriginalMargins() {
  15242. $ret = array(
  15243. 'left' => $this->original_lMargin,
  15244. 'right' => $this->original_rMargin
  15245. );
  15246. return $ret;
  15247. }
  15248. /**
  15249. * Returns the current font size.
  15250. * @return current font size
  15251. * @public
  15252. * @since 3.2.000 (2008-06-23)
  15253. */
  15254. public function getFontSize() {
  15255. return $this->FontSize;
  15256. }
  15257. /**
  15258. * Returns the current font size in points unit.
  15259. * @return current font size in points unit
  15260. * @public
  15261. * @since 3.2.000 (2008-06-23)
  15262. */
  15263. public function getFontSizePt() {
  15264. return $this->FontSizePt;
  15265. }
  15266. /**
  15267. * Returns the current font family name.
  15268. * @return string current font family name
  15269. * @public
  15270. * @since 4.3.008 (2008-12-05)
  15271. */
  15272. public function getFontFamily() {
  15273. return $this->FontFamily;
  15274. }
  15275. /**
  15276. * Returns the current font style.
  15277. * @return string current font style
  15278. * @public
  15279. * @since 4.3.008 (2008-12-05)
  15280. */
  15281. public function getFontStyle() {
  15282. return $this->FontStyle;
  15283. }
  15284. /**
  15285. * Cleanup HTML code (requires HTML Tidy library).
  15286. * @param $html (string) htmlcode to fix
  15287. * @param $default_css (string) CSS commands to add
  15288. * @param $tagvs (array) parameters for setHtmlVSpace method
  15289. * @param $tidy_options (array) options for tidy_parse_string function
  15290. * @return string XHTML code cleaned up
  15291. * @author Nicola Asuni
  15292. * @public
  15293. * @since 5.9.017 (2010-11-16)
  15294. * @see setHtmlVSpace()
  15295. */
  15296. public function fixHTMLCode($html, $default_css='', $tagvs='', $tidy_options='') {
  15297. return TCPDF_STATIC::fixHTMLCode($html, $default_css, $tagvs, $tidy_options, $this->tagvspaces);
  15298. }
  15299. /**
  15300. * Returns the border width from CSS property
  15301. * @param $width (string) border width
  15302. * @return int with in user units
  15303. * @protected
  15304. * @since 5.7.000 (2010-08-02)
  15305. */
  15306. protected function getCSSBorderWidth($width) {
  15307. if ($width == 'thin') {
  15308. $width = (2 / $this->k);
  15309. } elseif ($width == 'medium') {
  15310. $width = (4 / $this->k);
  15311. } elseif ($width == 'thick') {
  15312. $width = (6 / $this->k);
  15313. } else {
  15314. $width = $this->getHTMLUnitToUnits($width, 1, 'px', false);
  15315. }
  15316. return $width;
  15317. }
  15318. /**
  15319. * Returns the border dash style from CSS property
  15320. * @param $style (string) border style to convert
  15321. * @return int sash style (return -1 in case of none or hidden border)
  15322. * @protected
  15323. * @since 5.7.000 (2010-08-02)
  15324. */
  15325. protected function getCSSBorderDashStyle($style) {
  15326. switch (strtolower($style)) {
  15327. case 'none':
  15328. case 'hidden': {
  15329. $dash = -1;
  15330. break;
  15331. }
  15332. case 'dotted': {
  15333. $dash = 1;
  15334. break;
  15335. }
  15336. case 'dashed': {
  15337. $dash = 3;
  15338. break;
  15339. }
  15340. case 'double':
  15341. case 'groove':
  15342. case 'ridge':
  15343. case 'inset':
  15344. case 'outset':
  15345. case 'solid':
  15346. default: {
  15347. $dash = 0;
  15348. break;
  15349. }
  15350. }
  15351. return $dash;
  15352. }
  15353. /**
  15354. * Returns the border style array from CSS border properties
  15355. * @param $cssborder (string) border properties
  15356. * @return array containing border properties
  15357. * @protected
  15358. * @since 5.7.000 (2010-08-02)
  15359. */
  15360. protected function getCSSBorderStyle($cssborder) {
  15361. $bprop = preg_split('/[\s]+/', trim($cssborder));
  15362. $border = array(); // value to be returned
  15363. switch (count($bprop)) {
  15364. case 3: {
  15365. $width = $bprop[0];
  15366. $style = $bprop[1];
  15367. $color = $bprop[2];
  15368. break;
  15369. }
  15370. case 2: {
  15371. $width = 'medium';
  15372. $style = $bprop[0];
  15373. $color = $bprop[1];
  15374. break;
  15375. }
  15376. case 1: {
  15377. $width = 'medium';
  15378. $style = $bprop[0];
  15379. $color = 'black';
  15380. break;
  15381. }
  15382. default: {
  15383. $width = 'medium';
  15384. $style = 'solid';
  15385. $color = 'black';
  15386. break;
  15387. }
  15388. }
  15389. if ($style == 'none') {
  15390. return array();
  15391. }
  15392. $border['cap'] = 'square';
  15393. $border['join'] = 'miter';
  15394. $border['dash'] = $this->getCSSBorderDashStyle($style);
  15395. if ($border['dash'] < 0) {
  15396. return array();
  15397. }
  15398. $border['width'] = $this->getCSSBorderWidth($width);
  15399. $border['color'] = TCPDF_COLORS::convertHTMLColorToDec($color, $this->spot_colors);
  15400. return $border;
  15401. }
  15402. /**
  15403. * Get the internal Cell padding from CSS attribute.
  15404. * @param $csspadding (string) padding properties
  15405. * @param $width (float) width of the containing element
  15406. * @return array of cell paddings
  15407. * @public
  15408. * @since 5.9.000 (2010-10-04)
  15409. */
  15410. public function getCSSPadding($csspadding, $width=0) {
  15411. $padding = preg_split('/[\s]+/', trim($csspadding));
  15412. $cell_padding = array(); // value to be returned
  15413. switch (count($padding)) {
  15414. case 4: {
  15415. $cell_padding['T'] = $padding[0];
  15416. $cell_padding['R'] = $padding[1];
  15417. $cell_padding['B'] = $padding[2];
  15418. $cell_padding['L'] = $padding[3];
  15419. break;
  15420. }
  15421. case 3: {
  15422. $cell_padding['T'] = $padding[0];
  15423. $cell_padding['R'] = $padding[1];
  15424. $cell_padding['B'] = $padding[2];
  15425. $cell_padding['L'] = $padding[1];
  15426. break;
  15427. }
  15428. case 2: {
  15429. $cell_padding['T'] = $padding[0];
  15430. $cell_padding['R'] = $padding[1];
  15431. $cell_padding['B'] = $padding[0];
  15432. $cell_padding['L'] = $padding[1];
  15433. break;
  15434. }
  15435. case 1: {
  15436. $cell_padding['T'] = $padding[0];
  15437. $cell_padding['R'] = $padding[0];
  15438. $cell_padding['B'] = $padding[0];
  15439. $cell_padding['L'] = $padding[0];
  15440. break;
  15441. }
  15442. default: {
  15443. return $this->cell_padding;
  15444. }
  15445. }
  15446. if ($width == 0) {
  15447. $width = $this->w - $this->lMargin - $this->rMargin;
  15448. }
  15449. $cell_padding['T'] = $this->getHTMLUnitToUnits($cell_padding['T'], $width, 'px', false);
  15450. $cell_padding['R'] = $this->getHTMLUnitToUnits($cell_padding['R'], $width, 'px', false);
  15451. $cell_padding['B'] = $this->getHTMLUnitToUnits($cell_padding['B'], $width, 'px', false);
  15452. $cell_padding['L'] = $this->getHTMLUnitToUnits($cell_padding['L'], $width, 'px', false);
  15453. return $cell_padding;
  15454. }
  15455. /**
  15456. * Get the internal Cell margin from CSS attribute.
  15457. * @param $cssmargin (string) margin properties
  15458. * @param $width (float) width of the containing element
  15459. * @return array of cell margins
  15460. * @public
  15461. * @since 5.9.000 (2010-10-04)
  15462. */
  15463. public function getCSSMargin($cssmargin, $width=0) {
  15464. $margin = preg_split('/[\s]+/', trim($cssmargin));
  15465. $cell_margin = array(); // value to be returned
  15466. switch (count($margin)) {
  15467. case 4: {
  15468. $cell_margin['T'] = $margin[0];
  15469. $cell_margin['R'] = $margin[1];
  15470. $cell_margin['B'] = $margin[2];
  15471. $cell_margin['L'] = $margin[3];
  15472. break;
  15473. }
  15474. case 3: {
  15475. $cell_margin['T'] = $margin[0];
  15476. $cell_margin['R'] = $margin[1];
  15477. $cell_margin['B'] = $margin[2];
  15478. $cell_margin['L'] = $margin[1];
  15479. break;
  15480. }
  15481. case 2: {
  15482. $cell_margin['T'] = $margin[0];
  15483. $cell_margin['R'] = $margin[1];
  15484. $cell_margin['B'] = $margin[0];
  15485. $cell_margin['L'] = $margin[1];
  15486. break;
  15487. }
  15488. case 1: {
  15489. $cell_margin['T'] = $margin[0];
  15490. $cell_margin['R'] = $margin[0];
  15491. $cell_margin['B'] = $margin[0];
  15492. $cell_margin['L'] = $margin[0];
  15493. break;
  15494. }
  15495. default: {
  15496. return $this->cell_margin;
  15497. }
  15498. }
  15499. if ($width == 0) {
  15500. $width = $this->w - $this->lMargin - $this->rMargin;
  15501. }
  15502. $cell_margin['T'] = $this->getHTMLUnitToUnits(str_replace('auto', '0', $cell_margin['T']), $width, 'px', false);
  15503. $cell_margin['R'] = $this->getHTMLUnitToUnits(str_replace('auto', '0', $cell_margin['R']), $width, 'px', false);
  15504. $cell_margin['B'] = $this->getHTMLUnitToUnits(str_replace('auto', '0', $cell_margin['B']), $width, 'px', false);
  15505. $cell_margin['L'] = $this->getHTMLUnitToUnits(str_replace('auto', '0', $cell_margin['L']), $width, 'px', false);
  15506. return $cell_margin;
  15507. }
  15508. /**
  15509. * Get the border-spacing from CSS attribute.
  15510. * @param $cssbspace (string) border-spacing CSS properties
  15511. * @param $width (float) width of the containing element
  15512. * @return array of border spacings
  15513. * @public
  15514. * @since 5.9.010 (2010-10-27)
  15515. */
  15516. public function getCSSBorderMargin($cssbspace, $width=0) {
  15517. $space = preg_split('/[\s]+/', trim($cssbspace));
  15518. $border_spacing = array(); // value to be returned
  15519. switch (count($space)) {
  15520. case 2: {
  15521. $border_spacing['H'] = $space[0];
  15522. $border_spacing['V'] = $space[1];
  15523. break;
  15524. }
  15525. case 1: {
  15526. $border_spacing['H'] = $space[0];
  15527. $border_spacing['V'] = $space[0];
  15528. break;
  15529. }
  15530. default: {
  15531. return array('H' => 0, 'V' => 0);
  15532. }
  15533. }
  15534. if ($width == 0) {
  15535. $width = $this->w - $this->lMargin - $this->rMargin;
  15536. }
  15537. $border_spacing['H'] = $this->getHTMLUnitToUnits($border_spacing['H'], $width, 'px', false);
  15538. $border_spacing['V'] = $this->getHTMLUnitToUnits($border_spacing['V'], $width, 'px', false);
  15539. return $border_spacing;
  15540. }
  15541. /**
  15542. * Returns the letter-spacing value from CSS value
  15543. * @param $spacing (string) letter-spacing value
  15544. * @param $parent (float) font spacing (tracking) value of the parent element
  15545. * @return float quantity to increases or decreases the space between characters in a text.
  15546. * @protected
  15547. * @since 5.9.000 (2010-10-02)
  15548. */
  15549. protected function getCSSFontSpacing($spacing, $parent=0) {
  15550. $val = 0; // value to be returned
  15551. $spacing = trim($spacing);
  15552. switch ($spacing) {
  15553. case 'normal': {
  15554. $val = 0;
  15555. break;
  15556. }
  15557. case 'inherit': {
  15558. if ($parent == 'normal') {
  15559. $val = 0;
  15560. } else {
  15561. $val = $parent;
  15562. }
  15563. break;
  15564. }
  15565. default: {
  15566. $val = $this->getHTMLUnitToUnits($spacing, 0, 'px', false);
  15567. }
  15568. }
  15569. return $val;
  15570. }
  15571. /**
  15572. * Returns the percentage of font stretching from CSS value
  15573. * @param $stretch (string) stretch mode
  15574. * @param $parent (float) stretch value of the parent element
  15575. * @return float font stretching percentage
  15576. * @protected
  15577. * @since 5.9.000 (2010-10-02)
  15578. */
  15579. protected function getCSSFontStretching($stretch, $parent=100) {
  15580. $val = 100; // value to be returned
  15581. $stretch = trim($stretch);
  15582. switch ($stretch) {
  15583. case 'ultra-condensed': {
  15584. $val = 40;
  15585. break;
  15586. }
  15587. case 'extra-condensed': {
  15588. $val = 55;
  15589. break;
  15590. }
  15591. case 'condensed': {
  15592. $val = 70;
  15593. break;
  15594. }
  15595. case 'semi-condensed': {
  15596. $val = 85;
  15597. break;
  15598. }
  15599. case 'normal': {
  15600. $val = 100;
  15601. break;
  15602. }
  15603. case 'semi-expanded': {
  15604. $val = 115;
  15605. break;
  15606. }
  15607. case 'expanded': {
  15608. $val = 130;
  15609. break;
  15610. }
  15611. case 'extra-expanded': {
  15612. $val = 145;
  15613. break;
  15614. }
  15615. case 'ultra-expanded': {
  15616. $val = 160;
  15617. break;
  15618. }
  15619. case 'wider': {
  15620. $val = ($parent + 10);
  15621. break;
  15622. }
  15623. case 'narrower': {
  15624. $val = ($parent - 10);
  15625. break;
  15626. }
  15627. case 'inherit': {
  15628. if ($parent == 'normal') {
  15629. $val = 100;
  15630. } else {
  15631. $val = $parent;
  15632. }
  15633. break;
  15634. }
  15635. default: {
  15636. $val = $this->getHTMLUnitToUnits($stretch, 100, '%', false);
  15637. }
  15638. }
  15639. return $val;
  15640. }
  15641. /**
  15642. * Convert HTML string containing font size value to points
  15643. * @param $val (string) String containing font size value and unit.
  15644. * @param $refsize (float) Reference font size in points.
  15645. * @param $parent_size (float) Parent font size in points.
  15646. * @param $defaultunit (string) Default unit (can be one of the following: %, em, ex, px, in, mm, pc, pt).
  15647. * @return float value in points
  15648. * @public
  15649. */
  15650. public function getHTMLFontUnits($val, $refsize=12, $parent_size=12, $defaultunit='pt') {
  15651. $refsize = TCPDF_FONTS::getFontRefSize($refsize);
  15652. $parent_size = TCPDF_FONTS::getFontRefSize($parent_size, $refsize);
  15653. switch ($val) {
  15654. case 'xx-small': {
  15655. $size = ($refsize - 4);
  15656. break;
  15657. }
  15658. case 'x-small': {
  15659. $size = ($refsize - 3);
  15660. break;
  15661. }
  15662. case 'small': {
  15663. $size = ($refsize - 2);
  15664. break;
  15665. }
  15666. case 'medium': {
  15667. $size = $refsize;
  15668. break;
  15669. }
  15670. case 'large': {
  15671. $size = ($refsize + 2);
  15672. break;
  15673. }
  15674. case 'x-large': {
  15675. $size = ($refsize + 4);
  15676. break;
  15677. }
  15678. case 'xx-large': {
  15679. $size = ($refsize + 6);
  15680. break;
  15681. }
  15682. case 'smaller': {
  15683. $size = ($parent_size - 3);
  15684. break;
  15685. }
  15686. case 'larger': {
  15687. $size = ($parent_size + 3);
  15688. break;
  15689. }
  15690. default: {
  15691. $size = $this->getHTMLUnitToUnits($val, $parent_size, $defaultunit, true);
  15692. }
  15693. }
  15694. return $size;
  15695. }
  15696. /**
  15697. * Returns the HTML DOM array.
  15698. * @param $html (string) html code
  15699. * @return array
  15700. * @protected
  15701. * @since 3.2.000 (2008-06-20)
  15702. */
  15703. protected function getHtmlDomArray($html) {
  15704. // array of CSS styles ( selector => properties).
  15705. $css = array();
  15706. // get CSS array defined at previous call
  15707. $matches = array();
  15708. if (preg_match_all('/<cssarray>([^\<]*)<\/cssarray>/isU', $html, $matches) > 0) {
  15709. if (isset($matches[1][0])) {
  15710. $css = array_merge($css, json_decode($this->unhtmlentities($matches[1][0]), true));
  15711. }
  15712. $html = preg_replace('/<cssarray>(.*?)<\/cssarray>/isU', '', $html);
  15713. }
  15714. // extract external CSS files
  15715. $matches = array();
  15716. if (preg_match_all('/<link([^\>]*)>/isU', $html, $matches) > 0) {
  15717. foreach ($matches[1] as $key => $link) {
  15718. $type = array();
  15719. if (preg_match('/type[\s]*=[\s]*"text\/css"/', $link, $type)) {
  15720. $type = array();
  15721. preg_match('/media[\s]*=[\s]*"([^"]*)"/', $link, $type);
  15722. // get 'all' and 'print' media, other media types are discarded
  15723. // (all, braille, embossed, handheld, print, projection, screen, speech, tty, tv)
  15724. if (empty($type) OR (isset($type[1]) AND (($type[1] == 'all') OR ($type[1] == 'print')))) {
  15725. $type = array();
  15726. if (preg_match('/href[\s]*=[\s]*"([^"]*)"/', $link, $type) > 0) {
  15727. // read CSS data file
  15728. $cssdata = TCPDF_STATIC::fileGetContents(trim($type[1]));
  15729. if (($cssdata !== FALSE) AND (strlen($cssdata) > 0)) {
  15730. $css = array_merge($css, TCPDF_STATIC::extractCSSproperties($cssdata));
  15731. }
  15732. }
  15733. }
  15734. }
  15735. }
  15736. }
  15737. // extract style tags
  15738. $matches = array();
  15739. if (preg_match_all('/<style([^\>]*)>([^\<]*)<\/style>/isU', $html, $matches) > 0) {
  15740. foreach ($matches[1] as $key => $media) {
  15741. $type = array();
  15742. preg_match('/media[\s]*=[\s]*"([^"]*)"/', $media, $type);
  15743. // get 'all' and 'print' media, other media types are discarded
  15744. // (all, braille, embossed, handheld, print, projection, screen, speech, tty, tv)
  15745. if (empty($type) OR (isset($type[1]) AND (($type[1] == 'all') OR ($type[1] == 'print')))) {
  15746. $cssdata = $matches[2][$key];
  15747. $css = array_merge($css, TCPDF_STATIC::extractCSSproperties($cssdata));
  15748. }
  15749. }
  15750. }
  15751. // create a special tag to contain the CSS array (used for table content)
  15752. $csstagarray = '<cssarray>'.htmlentities(json_encode($css)).'</cssarray>';
  15753. // remove head and style blocks
  15754. $html = preg_replace('/<head([^\>]*)>(.*?)<\/head>/siU', '', $html);
  15755. $html = preg_replace('/<style([^\>]*)>([^\<]*)<\/style>/isU', '', $html);
  15756. // define block tags
  15757. $blocktags = array('blockquote','br','dd','dl','div','dt','h1','h2','h3','h4','h5','h6','hr','li','ol','p','pre','ul','tcpdf','table','tr','td');
  15758. // define self-closing tags
  15759. $selfclosingtags = array('area','base','basefont','br','hr','input','img','link','meta');
  15760. // remove all unsupported tags (the line below lists all supported tags)
  15761. $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>');
  15762. //replace some blank characters
  15763. $html = preg_replace('/<pre/', '<xre', $html); // preserve pre tag
  15764. $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);
  15765. $html = preg_replace('@(\r\n|\r)@', "\n", $html);
  15766. $repTable = array("\t" => ' ', "\0" => ' ', "\x0B" => ' ', "\\" => "\\\\");
  15767. $html = strtr($html, $repTable);
  15768. $offset = 0;
  15769. while (($offset < strlen($html)) AND ($pos = strpos($html, '</pre>', $offset)) !== false) {
  15770. $html_a = substr($html, 0, $offset);
  15771. $html_b = substr($html, $offset, ($pos - $offset + 6));
  15772. while (preg_match("'<xre([^\>]*)>(.*?)\n(.*?)</pre>'si", $html_b)) {
  15773. // preserve newlines on <pre> tag
  15774. $html_b = preg_replace("'<xre([^\>]*)>(.*?)\n(.*?)</pre>'si", "<xre\\1>\\2<br />\\3</pre>", $html_b);
  15775. }
  15776. while (preg_match("'<xre([^\>]*)>(.*?)".$this->re_space['p']."(.*?)</pre>'".$this->re_space['m'], $html_b)) {
  15777. // preserve spaces on <pre> tag
  15778. $html_b = preg_replace("'<xre([^\>]*)>(.*?)".$this->re_space['p']."(.*?)</pre>'".$this->re_space['m'], "<xre\\1>\\2&nbsp;\\3</pre>", $html_b);
  15779. }
  15780. $html = $html_a.$html_b.substr($html, $pos + 6);
  15781. $offset = strlen($html_a.$html_b);
  15782. }
  15783. $offset = 0;
  15784. while (($offset < strlen($html)) AND ($pos = strpos($html, '</textarea>', $offset)) !== false) {
  15785. $html_a = substr($html, 0, $offset);
  15786. $html_b = substr($html, $offset, ($pos - $offset + 11));
  15787. while (preg_match("'<textarea([^\>]*)>(.*?)\n(.*?)</textarea>'si", $html_b)) {
  15788. // preserve newlines on <textarea> tag
  15789. $html_b = preg_replace("'<textarea([^\>]*)>(.*?)\n(.*?)</textarea>'si", "<textarea\\1>\\2<TBR>\\3</textarea>", $html_b);
  15790. $html_b = preg_replace("'<textarea([^\>]*)>(.*?)[\"](.*?)</textarea>'si", "<textarea\\1>\\2''\\3</textarea>", $html_b);
  15791. }
  15792. $html = $html_a.$html_b.substr($html, $pos + 11);
  15793. $offset = strlen($html_a.$html_b);
  15794. }
  15795. $html = preg_replace('/([\s]*)<option/si', '<option', $html);
  15796. $html = preg_replace('/<\/option>([\s]*)/si', '</option>', $html);
  15797. $offset = 0;
  15798. while (($offset < strlen($html)) AND ($pos = strpos($html, '</option>', $offset)) !== false) {
  15799. $html_a = substr($html, 0, $offset);
  15800. $html_b = substr($html, $offset, ($pos - $offset + 9));
  15801. while (preg_match("'<option([^\>]*)>(.*?)</option>'si", $html_b)) {
  15802. $html_b = preg_replace("'<option([\s]+)value=\"([^\"]*)\"([^\>]*)>(.*?)</option>'si", "\\2#!TaB!#\\4#!NwL!#", $html_b);
  15803. $html_b = preg_replace("'<option([^\>]*)>(.*?)</option>'si", "\\2#!NwL!#", $html_b);
  15804. }
  15805. $html = $html_a.$html_b.substr($html, $pos + 9);
  15806. $offset = strlen($html_a.$html_b);
  15807. }
  15808. if (preg_match("'</select'si", $html)) {
  15809. $html = preg_replace("'<select([^\>]*)>'si", "<select\\1 opt=\"", $html);
  15810. $html = preg_replace("'#!NwL!#</select>'si", "\" />", $html);
  15811. }
  15812. $html = str_replace("\n", ' ', $html);
  15813. // restore textarea newlines
  15814. $html = str_replace('<TBR>', "\n", $html);
  15815. // remove extra spaces from code
  15816. $html = preg_replace('/[\s]+<\/(table|tr|ul|ol|dl)>/', '</\\1>', $html);
  15817. $html = preg_replace('/'.$this->re_space['p'].'+<\/(td|th|li|dt|dd)>/'.$this->re_space['m'], '</\\1>', $html);
  15818. $html = preg_replace('/[\s]+<(tr|td|th|li|dt|dd)/', '<\\1', $html);
  15819. $html = preg_replace('/'.$this->re_space['p'].'+<(ul|ol|dl|br)/'.$this->re_space['m'], '<\\1', $html);
  15820. $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);
  15821. $html = preg_replace('/<\/(td|th)>/', '<marker style="font-size:0"/></\\1>', $html);
  15822. $html = preg_replace('/<\/table>([\s]*)<marker style="font-size:0"\/>/', '</table>', $html);
  15823. $html = preg_replace('/'.$this->re_space['p'].'+<img/'.$this->re_space['m'], chr(32).'<img', $html);
  15824. $html = preg_replace('/<img([^\>]*)>[\s]+([^\<])/xi', '<img\\1>&nbsp;\\2', $html);
  15825. $html = preg_replace('/<img([^\>]*)>/xi', '<img\\1><span><marker style="font-size:0"/></span>', $html);
  15826. $html = preg_replace('/<xre/', '<pre', $html); // restore pre tag
  15827. $html = preg_replace('/<textarea([^\>]*)>([^\<]*)<\/textarea>/xi', '<textarea\\1 value="\\2" />', $html);
  15828. $html = preg_replace('/<li([^\>]*)><\/li>/', '<li\\1>&nbsp;</li>', $html);
  15829. $html = preg_replace('/<li([^\>]*)>'.$this->re_space['p'].'*<img/'.$this->re_space['m'], '<li\\1><font size="1">&nbsp;</font><img', $html);
  15830. $html = preg_replace('/<([^\>\/]*)>[\s]/', '<\\1>&nbsp;', $html); // preserve some spaces
  15831. $html = preg_replace('/[\s]<\/([^\>]*)>/', '&nbsp;</\\1>', $html); // preserve some spaces
  15832. $html = preg_replace('/<su([bp])/', '<zws/><su\\1', $html); // fix sub/sup alignment
  15833. $html = preg_replace('/<\/su([bp])>/', '</su\\1><zws/>', $html); // fix sub/sup alignment
  15834. $html = preg_replace('/'.$this->re_space['p'].'+/'.$this->re_space['m'], chr(32), $html); // replace multiple spaces with a single space
  15835. // trim string
  15836. $html = $this->stringTrim($html);
  15837. // fix br tag after li
  15838. $html = preg_replace('/<li><br([^\>]*)>/', '<li> <br\\1>', $html);
  15839. // fix first image tag alignment
  15840. $html = preg_replace('/^<img/', '<span style="font-size:0"><br /></span> <img', $html, 1);
  15841. // pattern for generic tag
  15842. $tagpattern = '/(<[^>]+>)/';
  15843. // explodes the string
  15844. $a = preg_split($tagpattern, $html, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  15845. // count elements
  15846. $maxel = count($a);
  15847. $elkey = 0;
  15848. $key = 0;
  15849. // create an array of elements
  15850. $dom = array();
  15851. $dom[$key] = array();
  15852. // set inheritable properties fot the first void element
  15853. // 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
  15854. $dom[$key]['tag'] = false;
  15855. $dom[$key]['block'] = false;
  15856. $dom[$key]['value'] = '';
  15857. $dom[$key]['parent'] = 0;
  15858. $dom[$key]['hide'] = false;
  15859. $dom[$key]['fontname'] = $this->FontFamily;
  15860. $dom[$key]['fontstyle'] = $this->FontStyle;
  15861. $dom[$key]['fontsize'] = $this->FontSizePt;
  15862. $dom[$key]['font-stretch'] = $this->font_stretching;
  15863. $dom[$key]['letter-spacing'] = $this->font_spacing;
  15864. $dom[$key]['stroke'] = $this->textstrokewidth;
  15865. $dom[$key]['fill'] = (($this->textrendermode % 2) == 0);
  15866. $dom[$key]['clip'] = ($this->textrendermode > 3);
  15867. $dom[$key]['line-height'] = $this->cell_height_ratio;
  15868. $dom[$key]['bgcolor'] = false;
  15869. $dom[$key]['fgcolor'] = $this->fgcolor; // color
  15870. $dom[$key]['strokecolor'] = $this->strokecolor;
  15871. $dom[$key]['align'] = '';
  15872. $dom[$key]['listtype'] = '';
  15873. $dom[$key]['text-indent'] = 0;
  15874. $dom[$key]['text-transform'] = '';
  15875. $dom[$key]['border'] = array();
  15876. $dom[$key]['dir'] = $this->rtl?'rtl':'ltr';
  15877. $thead = false; // true when we are inside the THEAD tag
  15878. ++$key;
  15879. $level = array();
  15880. array_push($level, 0); // root
  15881. while ($elkey < $maxel) {
  15882. $dom[$key] = array();
  15883. $element = $a[$elkey];
  15884. $dom[$key]['elkey'] = $elkey;
  15885. if (preg_match($tagpattern, $element)) {
  15886. // html tag
  15887. $element = substr($element, 1, -1);
  15888. // get tag name
  15889. preg_match('/[\/]?([a-zA-Z0-9]*)/', $element, $tag);
  15890. $tagname = strtolower($tag[1]);
  15891. // check if we are inside a table header
  15892. if ($tagname == 'thead') {
  15893. if ($element[0] == '/') {
  15894. $thead = false;
  15895. } else {
  15896. $thead = true;
  15897. }
  15898. ++$elkey;
  15899. continue;
  15900. }
  15901. $dom[$key]['tag'] = true;
  15902. $dom[$key]['value'] = $tagname;
  15903. if (in_array($dom[$key]['value'], $blocktags)) {
  15904. $dom[$key]['block'] = true;
  15905. } else {
  15906. $dom[$key]['block'] = false;
  15907. }
  15908. if ($element[0] == '/') {
  15909. // *** closing html tag
  15910. $dom[$key]['opening'] = false;
  15911. $dom[$key]['parent'] = end($level);
  15912. array_pop($level);
  15913. $dom[$key]['hide'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['hide'];
  15914. $dom[$key]['fontname'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fontname'];
  15915. $dom[$key]['fontstyle'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fontstyle'];
  15916. $dom[$key]['fontsize'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fontsize'];
  15917. $dom[$key]['font-stretch'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['font-stretch'];
  15918. $dom[$key]['letter-spacing'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['letter-spacing'];
  15919. $dom[$key]['stroke'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['stroke'];
  15920. $dom[$key]['fill'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fill'];
  15921. $dom[$key]['clip'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['clip'];
  15922. $dom[$key]['line-height'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['line-height'];
  15923. $dom[$key]['bgcolor'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['bgcolor'];
  15924. $dom[$key]['fgcolor'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fgcolor'];
  15925. $dom[$key]['strokecolor'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['strokecolor'];
  15926. $dom[$key]['align'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['align'];
  15927. $dom[$key]['text-transform'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['text-transform'];
  15928. $dom[$key]['dir'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['dir'];
  15929. if (isset($dom[($dom[($dom[$key]['parent'])]['parent'])]['listtype'])) {
  15930. $dom[$key]['listtype'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['listtype'];
  15931. }
  15932. // set the number of columns in table tag
  15933. if (($dom[$key]['value'] == 'tr') AND (!isset($dom[($dom[($dom[$key]['parent'])]['parent'])]['cols']))) {
  15934. $dom[($dom[($dom[$key]['parent'])]['parent'])]['cols'] = $dom[($dom[$key]['parent'])]['cols'];
  15935. }
  15936. if (($dom[$key]['value'] == 'td') OR ($dom[$key]['value'] == 'th')) {
  15937. $dom[($dom[$key]['parent'])]['content'] = $csstagarray;
  15938. for ($i = ($dom[$key]['parent'] + 1); $i < $key; ++$i) {
  15939. $dom[($dom[$key]['parent'])]['content'] .= stripslashes($a[$dom[$i]['elkey']]);
  15940. }
  15941. $key = $i;
  15942. // mark nested tables
  15943. $dom[($dom[$key]['parent'])]['content'] = str_replace('<table', '<table nested="true"', $dom[($dom[$key]['parent'])]['content']);
  15944. // remove thead sections from nested tables
  15945. $dom[($dom[$key]['parent'])]['content'] = str_replace('<thead>', '', $dom[($dom[$key]['parent'])]['content']);
  15946. $dom[($dom[$key]['parent'])]['content'] = str_replace('</thead>', '', $dom[($dom[$key]['parent'])]['content']);
  15947. }
  15948. // store header rows on a new table
  15949. if (($dom[$key]['value'] == 'tr') AND ($dom[($dom[$key]['parent'])]['thead'] === true)) {
  15950. if (TCPDF_STATIC::empty_string($dom[($dom[($dom[$key]['parent'])]['parent'])]['thead'])) {
  15951. $dom[($dom[($dom[$key]['parent'])]['parent'])]['thead'] = $csstagarray.$a[$dom[($dom[($dom[$key]['parent'])]['parent'])]['elkey']];
  15952. }
  15953. for ($i = $dom[$key]['parent']; $i <= $key; ++$i) {
  15954. $dom[($dom[($dom[$key]['parent'])]['parent'])]['thead'] .= $a[$dom[$i]['elkey']];
  15955. }
  15956. if (!isset($dom[($dom[$key]['parent'])]['attribute'])) {
  15957. $dom[($dom[$key]['parent'])]['attribute'] = array();
  15958. }
  15959. // header elements must be always contained in a single page
  15960. $dom[($dom[$key]['parent'])]['attribute']['nobr'] = 'true';
  15961. }
  15962. if (($dom[$key]['value'] == 'table') AND (!TCPDF_STATIC::empty_string($dom[($dom[$key]['parent'])]['thead']))) {
  15963. // remove the nobr attributes from the table header
  15964. $dom[($dom[$key]['parent'])]['thead'] = str_replace(' nobr="true"', '', $dom[($dom[$key]['parent'])]['thead']);
  15965. $dom[($dom[$key]['parent'])]['thead'] .= '</tablehead>';
  15966. }
  15967. } else {
  15968. // *** opening or self-closing html tag
  15969. $dom[$key]['opening'] = true;
  15970. $dom[$key]['parent'] = end($level);
  15971. if ((substr($element, -1, 1) == '/') OR (in_array($dom[$key]['value'], $selfclosingtags))) {
  15972. // self-closing tag
  15973. $dom[$key]['self'] = true;
  15974. } else {
  15975. // opening tag
  15976. array_push($level, $key);
  15977. $dom[$key]['self'] = false;
  15978. }
  15979. // copy some values from parent
  15980. $parentkey = 0;
  15981. if ($key > 0) {
  15982. $parentkey = $dom[$key]['parent'];
  15983. $dom[$key]['hide'] = $dom[$parentkey]['hide'];
  15984. $dom[$key]['fontname'] = $dom[$parentkey]['fontname'];
  15985. $dom[$key]['fontstyle'] = $dom[$parentkey]['fontstyle'];
  15986. $dom[$key]['fontsize'] = $dom[$parentkey]['fontsize'];
  15987. $dom[$key]['font-stretch'] = $dom[$parentkey]['font-stretch'];
  15988. $dom[$key]['letter-spacing'] = $dom[$parentkey]['letter-spacing'];
  15989. $dom[$key]['stroke'] = $dom[$parentkey]['stroke'];
  15990. $dom[$key]['fill'] = $dom[$parentkey]['fill'];
  15991. $dom[$key]['clip'] = $dom[$parentkey]['clip'];
  15992. $dom[$key]['line-height'] = $dom[$parentkey]['line-height'];
  15993. $dom[$key]['bgcolor'] = $dom[$parentkey]['bgcolor'];
  15994. $dom[$key]['fgcolor'] = $dom[$parentkey]['fgcolor'];
  15995. $dom[$key]['strokecolor'] = $dom[$parentkey]['strokecolor'];
  15996. $dom[$key]['align'] = $dom[$parentkey]['align'];
  15997. $dom[$key]['listtype'] = $dom[$parentkey]['listtype'];
  15998. $dom[$key]['text-indent'] = $dom[$parentkey]['text-indent'];
  15999. $dom[$key]['text-transform'] = $dom[$parentkey]['text-transform'];
  16000. $dom[$key]['border'] = array();
  16001. $dom[$key]['dir'] = $dom[$parentkey]['dir'];
  16002. }
  16003. // get attributes
  16004. preg_match_all('/([^=\s]*)[\s]*=[\s]*"([^"]*)"/', $element, $attr_array, PREG_PATTERN_ORDER);
  16005. $dom[$key]['attribute'] = array(); // reset attribute array
  16006. foreach($attr_array[1] as $id => $name) {
  16007. $dom[$key]['attribute'][strtolower($name)] = $attr_array[2][$id];
  16008. }
  16009. if (!empty($css)) {
  16010. // merge CSS style to current style
  16011. list($dom[$key]['csssel'], $dom[$key]['cssdata']) = TCPDF_STATIC::getCSSdataArray($dom, $key, $css);
  16012. $dom[$key]['attribute']['style'] = TCPDF_STATIC::getTagStyleFromCSSarray($dom[$key]['cssdata']);
  16013. }
  16014. // split style attributes
  16015. if (isset($dom[$key]['attribute']['style']) AND !empty($dom[$key]['attribute']['style'])) {
  16016. // get style attributes
  16017. preg_match_all('/([^;:\s]*):([^;]*)/', $dom[$key]['attribute']['style'], $style_array, PREG_PATTERN_ORDER);
  16018. $dom[$key]['style'] = array(); // reset style attribute array
  16019. foreach($style_array[1] as $id => $name) {
  16020. // in case of duplicate attribute the last replace the previous
  16021. $dom[$key]['style'][strtolower($name)] = trim($style_array[2][$id]);
  16022. }
  16023. // --- get some style attributes ---
  16024. // text direction
  16025. if (isset($dom[$key]['style']['direction'])) {
  16026. $dom[$key]['dir'] = $dom[$key]['style']['direction'];
  16027. }
  16028. // display
  16029. if (isset($dom[$key]['style']['display'])) {
  16030. $dom[$key]['hide'] = (trim(strtolower($dom[$key]['style']['display'])) == 'none');
  16031. }
  16032. // font family
  16033. if (isset($dom[$key]['style']['font-family'])) {
  16034. $dom[$key]['fontname'] = $this->getFontFamilyName($dom[$key]['style']['font-family']);
  16035. }
  16036. // list-style-type
  16037. if (isset($dom[$key]['style']['list-style-type'])) {
  16038. $dom[$key]['listtype'] = trim(strtolower($dom[$key]['style']['list-style-type']));
  16039. if ($dom[$key]['listtype'] == 'inherit') {
  16040. $dom[$key]['listtype'] = $dom[$parentkey]['listtype'];
  16041. }
  16042. }
  16043. // text-indent
  16044. if (isset($dom[$key]['style']['text-indent'])) {
  16045. $dom[$key]['text-indent'] = $this->getHTMLUnitToUnits($dom[$key]['style']['text-indent']);
  16046. if ($dom[$key]['text-indent'] == 'inherit') {
  16047. $dom[$key]['text-indent'] = $dom[$parentkey]['text-indent'];
  16048. }
  16049. }
  16050. // text-transform
  16051. if (isset($dom[$key]['style']['text-transform'])) {
  16052. $dom[$key]['text-transform'] = $dom[$key]['style']['text-transform'];
  16053. }
  16054. // font size
  16055. if (isset($dom[$key]['style']['font-size'])) {
  16056. $fsize = trim($dom[$key]['style']['font-size']);
  16057. $dom[$key]['fontsize'] = $this->getHTMLFontUnits($fsize, $dom[0]['fontsize'], $dom[$parentkey]['fontsize'], 'pt');
  16058. }
  16059. // font-stretch
  16060. if (isset($dom[$key]['style']['font-stretch'])) {
  16061. $dom[$key]['font-stretch'] = $this->getCSSFontStretching($dom[$key]['style']['font-stretch'], $dom[$parentkey]['font-stretch']);
  16062. }
  16063. // letter-spacing
  16064. if (isset($dom[$key]['style']['letter-spacing'])) {
  16065. $dom[$key]['letter-spacing'] = $this->getCSSFontSpacing($dom[$key]['style']['letter-spacing'], $dom[$parentkey]['letter-spacing']);
  16066. }
  16067. // line-height (internally is the cell height ratio)
  16068. if (isset($dom[$key]['style']['line-height'])) {
  16069. $lineheight = trim($dom[$key]['style']['line-height']);
  16070. switch ($lineheight) {
  16071. // A normal line height. This is default
  16072. case 'normal': {
  16073. $dom[$key]['line-height'] = $dom[0]['line-height'];
  16074. break;
  16075. }
  16076. case 'inherit': {
  16077. $dom[$key]['line-height'] = $dom[$parentkey]['line-height'];
  16078. }
  16079. default: {
  16080. if (is_numeric($lineheight)) {
  16081. // convert to percentage of font height
  16082. $lineheight = ($lineheight * 100).'%';
  16083. }
  16084. $dom[$key]['line-height'] = $this->getHTMLUnitToUnits($lineheight, 1, '%', true);
  16085. if (substr($lineheight, -1) !== '%') {
  16086. if ($dom[$key]['fontsize'] <= 0) {
  16087. $dom[$key]['line-height'] = 1;
  16088. } else {
  16089. $dom[$key]['line-height'] = (($dom[$key]['line-height'] - $this->cell_padding['T'] - $this->cell_padding['B']) / $dom[$key]['fontsize']);
  16090. }
  16091. }
  16092. }
  16093. }
  16094. }
  16095. // font style
  16096. if (isset($dom[$key]['style']['font-weight'])) {
  16097. if (strtolower($dom[$key]['style']['font-weight'][0]) == 'n') {
  16098. if (strpos($dom[$key]['fontstyle'], 'B') !== false) {
  16099. $dom[$key]['fontstyle'] = str_replace('B', '', $dom[$key]['fontstyle']);
  16100. }
  16101. } elseif (strtolower($dom[$key]['style']['font-weight'][0]) == 'b') {
  16102. $dom[$key]['fontstyle'] .= 'B';
  16103. }
  16104. }
  16105. if (isset($dom[$key]['style']['font-style']) AND (strtolower($dom[$key]['style']['font-style'][0]) == 'i')) {
  16106. $dom[$key]['fontstyle'] .= 'I';
  16107. }
  16108. // font color
  16109. if (isset($dom[$key]['style']['color']) AND (!TCPDF_STATIC::empty_string($dom[$key]['style']['color']))) {
  16110. $dom[$key]['fgcolor'] = TCPDF_COLORS::convertHTMLColorToDec($dom[$key]['style']['color'], $this->spot_colors);
  16111. } elseif ($dom[$key]['value'] == 'a') {
  16112. $dom[$key]['fgcolor'] = $this->htmlLinkColorArray;
  16113. }
  16114. // background color
  16115. if (isset($dom[$key]['style']['background-color']) AND (!TCPDF_STATIC::empty_string($dom[$key]['style']['background-color']))) {
  16116. $dom[$key]['bgcolor'] = TCPDF_COLORS::convertHTMLColorToDec($dom[$key]['style']['background-color'], $this->spot_colors);
  16117. }
  16118. // text-decoration
  16119. if (isset($dom[$key]['style']['text-decoration'])) {
  16120. $decors = explode(' ', strtolower($dom[$key]['style']['text-decoration']));
  16121. foreach ($decors as $dec) {
  16122. $dec = trim($dec);
  16123. if (!TCPDF_STATIC::empty_string($dec)) {
  16124. if ($dec[0] == 'u') {
  16125. // underline
  16126. $dom[$key]['fontstyle'] .= 'U';
  16127. } elseif ($dec[0] == 'l') {
  16128. // line-through
  16129. $dom[$key]['fontstyle'] .= 'D';
  16130. } elseif ($dec[0] == 'o') {
  16131. // overline
  16132. $dom[$key]['fontstyle'] .= 'O';
  16133. }
  16134. }
  16135. }
  16136. } elseif ($dom[$key]['value'] == 'a') {
  16137. $dom[$key]['fontstyle'] = $this->htmlLinkFontStyle;
  16138. }
  16139. // check for width attribute
  16140. if (isset($dom[$key]['style']['width'])) {
  16141. $dom[$key]['width'] = $dom[$key]['style']['width'];
  16142. }
  16143. // check for height attribute
  16144. if (isset($dom[$key]['style']['height'])) {
  16145. $dom[$key]['height'] = $dom[$key]['style']['height'];
  16146. }
  16147. // check for text alignment
  16148. if (isset($dom[$key]['style']['text-align'])) {
  16149. $dom[$key]['align'] = strtoupper($dom[$key]['style']['text-align'][0]);
  16150. }
  16151. // check for CSS border properties
  16152. if (isset($dom[$key]['style']['border'])) {
  16153. $borderstyle = $this->getCSSBorderStyle($dom[$key]['style']['border']);
  16154. if (!empty($borderstyle)) {
  16155. $dom[$key]['border']['LTRB'] = $borderstyle;
  16156. }
  16157. }
  16158. if (isset($dom[$key]['style']['border-color'])) {
  16159. $brd_colors = preg_split('/[\s]+/', trim($dom[$key]['style']['border-color']));
  16160. if (isset($brd_colors[3])) {
  16161. $dom[$key]['border']['L']['color'] = TCPDF_COLORS::convertHTMLColorToDec($brd_colors[3], $this->spot_colors);
  16162. }
  16163. if (isset($brd_colors[1])) {
  16164. $dom[$key]['border']['R']['color'] = TCPDF_COLORS::convertHTMLColorToDec($brd_colors[1], $this->spot_colors);
  16165. }
  16166. if (isset($brd_colors[0])) {
  16167. $dom[$key]['border']['T']['color'] = TCPDF_COLORS::convertHTMLColorToDec($brd_colors[0], $this->spot_colors);
  16168. }
  16169. if (isset($brd_colors[2])) {
  16170. $dom[$key]['border']['B']['color'] = TCPDF_COLORS::convertHTMLColorToDec($brd_colors[2], $this->spot_colors);
  16171. }
  16172. }
  16173. if (isset($dom[$key]['style']['border-width'])) {
  16174. $brd_widths = preg_split('/[\s]+/', trim($dom[$key]['style']['border-width']));
  16175. if (isset($brd_widths[3])) {
  16176. $dom[$key]['border']['L']['width'] = $this->getCSSBorderWidth($brd_widths[3]);
  16177. }
  16178. if (isset($brd_widths[1])) {
  16179. $dom[$key]['border']['R']['width'] = $this->getCSSBorderWidth($brd_widths[1]);
  16180. }
  16181. if (isset($brd_widths[0])) {
  16182. $dom[$key]['border']['T']['width'] = $this->getCSSBorderWidth($brd_widths[0]);
  16183. }
  16184. if (isset($brd_widths[2])) {
  16185. $dom[$key]['border']['B']['width'] = $this->getCSSBorderWidth($brd_widths[2]);
  16186. }
  16187. }
  16188. if (isset($dom[$key]['style']['border-style'])) {
  16189. $brd_styles = preg_split('/[\s]+/', trim($dom[$key]['style']['border-style']));
  16190. if (isset($brd_styles[3]) AND ($brd_styles[3]!='none')) {
  16191. $dom[$key]['border']['L']['cap'] = 'square';
  16192. $dom[$key]['border']['L']['join'] = 'miter';
  16193. $dom[$key]['border']['L']['dash'] = $this->getCSSBorderDashStyle($brd_styles[3]);
  16194. if ($dom[$key]['border']['L']['dash'] < 0) {
  16195. $dom[$key]['border']['L'] = array();
  16196. }
  16197. }
  16198. if (isset($brd_styles[1])) {
  16199. $dom[$key]['border']['R']['cap'] = 'square';
  16200. $dom[$key]['border']['R']['join'] = 'miter';
  16201. $dom[$key]['border']['R']['dash'] = $this->getCSSBorderDashStyle($brd_styles[1]);
  16202. if ($dom[$key]['border']['R']['dash'] < 0) {
  16203. $dom[$key]['border']['R'] = array();
  16204. }
  16205. }
  16206. if (isset($brd_styles[0])) {
  16207. $dom[$key]['border']['T']['cap'] = 'square';
  16208. $dom[$key]['border']['T']['join'] = 'miter';
  16209. $dom[$key]['border']['T']['dash'] = $this->getCSSBorderDashStyle($brd_styles[0]);
  16210. if ($dom[$key]['border']['T']['dash'] < 0) {
  16211. $dom[$key]['border']['T'] = array();
  16212. }
  16213. }
  16214. if (isset($brd_styles[2])) {
  16215. $dom[$key]['border']['B']['cap'] = 'square';
  16216. $dom[$key]['border']['B']['join'] = 'miter';
  16217. $dom[$key]['border']['B']['dash'] = $this->getCSSBorderDashStyle($brd_styles[2]);
  16218. if ($dom[$key]['border']['B']['dash'] < 0) {
  16219. $dom[$key]['border']['B'] = array();
  16220. }
  16221. }
  16222. }
  16223. $cellside = array('L' => 'left', 'R' => 'right', 'T' => 'top', 'B' => 'bottom');
  16224. foreach ($cellside as $bsk => $bsv) {
  16225. if (isset($dom[$key]['style']['border-'.$bsv])) {
  16226. $borderstyle = $this->getCSSBorderStyle($dom[$key]['style']['border-'.$bsv]);
  16227. if (!empty($borderstyle)) {
  16228. $dom[$key]['border'][$bsk] = $borderstyle;
  16229. }
  16230. }
  16231. if (isset($dom[$key]['style']['border-'.$bsv.'-color'])) {
  16232. $dom[$key]['border'][$bsk]['color'] = TCPDF_COLORS::convertHTMLColorToDec($dom[$key]['style']['border-'.$bsv.'-color'], $this->spot_colors);
  16233. }
  16234. if (isset($dom[$key]['style']['border-'.$bsv.'-width'])) {
  16235. $dom[$key]['border'][$bsk]['width'] = $this->getCSSBorderWidth($dom[$key]['style']['border-'.$bsv.'-width']);
  16236. }
  16237. if (isset($dom[$key]['style']['border-'.$bsv.'-style'])) {
  16238. $dom[$key]['border'][$bsk]['dash'] = $this->getCSSBorderDashStyle($dom[$key]['style']['border-'.$bsv.'-style']);
  16239. if ($dom[$key]['border'][$bsk]['dash'] < 0) {
  16240. $dom[$key]['border'][$bsk] = array();
  16241. }
  16242. }
  16243. }
  16244. // check for CSS padding properties
  16245. if (isset($dom[$key]['style']['padding'])) {
  16246. $dom[$key]['padding'] = $this->getCSSPadding($dom[$key]['style']['padding']);
  16247. } else {
  16248. $dom[$key]['padding'] = $this->cell_padding;
  16249. }
  16250. foreach ($cellside as $psk => $psv) {
  16251. if (isset($dom[$key]['style']['padding-'.$psv])) {
  16252. $dom[$key]['padding'][$psk] = $this->getHTMLUnitToUnits($dom[$key]['style']['padding-'.$psv], 0, 'px', false);
  16253. }
  16254. }
  16255. // check for CSS margin properties
  16256. if (isset($dom[$key]['style']['margin'])) {
  16257. $dom[$key]['margin'] = $this->getCSSMargin($dom[$key]['style']['margin']);
  16258. } else {
  16259. $dom[$key]['margin'] = $this->cell_margin;
  16260. }
  16261. foreach ($cellside as $psk => $psv) {
  16262. if (isset($dom[$key]['style']['margin-'.$psv])) {
  16263. $dom[$key]['margin'][$psk] = $this->getHTMLUnitToUnits(str_replace('auto', '0', $dom[$key]['style']['margin-'.$psv]), 0, 'px', false);
  16264. }
  16265. }
  16266. // check for CSS border-spacing properties
  16267. if (isset($dom[$key]['style']['border-spacing'])) {
  16268. $dom[$key]['border-spacing'] = $this->getCSSBorderMargin($dom[$key]['style']['border-spacing']);
  16269. }
  16270. // page-break-inside
  16271. if (isset($dom[$key]['style']['page-break-inside']) AND ($dom[$key]['style']['page-break-inside'] == 'avoid')) {
  16272. $dom[$key]['attribute']['nobr'] = 'true';
  16273. }
  16274. // page-break-before
  16275. if (isset($dom[$key]['style']['page-break-before'])) {
  16276. if ($dom[$key]['style']['page-break-before'] == 'always') {
  16277. $dom[$key]['attribute']['pagebreak'] = 'true';
  16278. } elseif ($dom[$key]['style']['page-break-before'] == 'left') {
  16279. $dom[$key]['attribute']['pagebreak'] = 'left';
  16280. } elseif ($dom[$key]['style']['page-break-before'] == 'right') {
  16281. $dom[$key]['attribute']['pagebreak'] = 'right';
  16282. }
  16283. }
  16284. // page-break-after
  16285. if (isset($dom[$key]['style']['page-break-after'])) {
  16286. if ($dom[$key]['style']['page-break-after'] == 'always') {
  16287. $dom[$key]['attribute']['pagebreakafter'] = 'true';
  16288. } elseif ($dom[$key]['style']['page-break-after'] == 'left') {
  16289. $dom[$key]['attribute']['pagebreakafter'] = 'left';
  16290. } elseif ($dom[$key]['style']['page-break-after'] == 'right') {
  16291. $dom[$key]['attribute']['pagebreakafter'] = 'right';
  16292. }
  16293. }
  16294. }
  16295. if (isset($dom[$key]['attribute']['display'])) {
  16296. $dom[$key]['hide'] = (trim(strtolower($dom[$key]['attribute']['display'])) == 'none');
  16297. }
  16298. if (isset($dom[$key]['attribute']['border']) AND ($dom[$key]['attribute']['border'] != 0)) {
  16299. $borderstyle = $this->getCSSBorderStyle($dom[$key]['attribute']['border'].' solid black');
  16300. if (!empty($borderstyle)) {
  16301. $dom[$key]['border']['LTRB'] = $borderstyle;
  16302. }
  16303. }
  16304. // check for font tag
  16305. if ($dom[$key]['value'] == 'font') {
  16306. // font family
  16307. if (isset($dom[$key]['attribute']['face'])) {
  16308. $dom[$key]['fontname'] = $this->getFontFamilyName($dom[$key]['attribute']['face']);
  16309. }
  16310. // font size
  16311. if (isset($dom[$key]['attribute']['size'])) {
  16312. if ($key > 0) {
  16313. if ($dom[$key]['attribute']['size'][0] == '+') {
  16314. $dom[$key]['fontsize'] = $dom[($dom[$key]['parent'])]['fontsize'] + intval(substr($dom[$key]['attribute']['size'], 1));
  16315. } elseif ($dom[$key]['attribute']['size'][0] == '-') {
  16316. $dom[$key]['fontsize'] = $dom[($dom[$key]['parent'])]['fontsize'] - intval(substr($dom[$key]['attribute']['size'], 1));
  16317. } else {
  16318. $dom[$key]['fontsize'] = intval($dom[$key]['attribute']['size']);
  16319. }
  16320. } else {
  16321. $dom[$key]['fontsize'] = intval($dom[$key]['attribute']['size']);
  16322. }
  16323. }
  16324. }
  16325. // force natural alignment for lists
  16326. if ((($dom[$key]['value'] == 'ul') OR ($dom[$key]['value'] == 'ol') OR ($dom[$key]['value'] == 'dl'))
  16327. AND (!isset($dom[$key]['align']) OR TCPDF_STATIC::empty_string($dom[$key]['align']) OR ($dom[$key]['align'] != 'J'))) {
  16328. if ($this->rtl) {
  16329. $dom[$key]['align'] = 'R';
  16330. } else {
  16331. $dom[$key]['align'] = 'L';
  16332. }
  16333. }
  16334. if (($dom[$key]['value'] == 'small') OR ($dom[$key]['value'] == 'sup') OR ($dom[$key]['value'] == 'sub')) {
  16335. if (!isset($dom[$key]['attribute']['size']) AND !isset($dom[$key]['style']['font-size'])) {
  16336. $dom[$key]['fontsize'] = $dom[$key]['fontsize'] * K_SMALL_RATIO;
  16337. }
  16338. }
  16339. if (($dom[$key]['value'] == 'strong') OR ($dom[$key]['value'] == 'b')) {
  16340. $dom[$key]['fontstyle'] .= 'B';
  16341. }
  16342. if (($dom[$key]['value'] == 'em') OR ($dom[$key]['value'] == 'i')) {
  16343. $dom[$key]['fontstyle'] .= 'I';
  16344. }
  16345. if ($dom[$key]['value'] == 'u') {
  16346. $dom[$key]['fontstyle'] .= 'U';
  16347. }
  16348. if (($dom[$key]['value'] == 'del') OR ($dom[$key]['value'] == 's') OR ($dom[$key]['value'] == 'strike')) {
  16349. $dom[$key]['fontstyle'] .= 'D';
  16350. }
  16351. if (!isset($dom[$key]['style']['text-decoration']) AND ($dom[$key]['value'] == 'a')) {
  16352. $dom[$key]['fontstyle'] = $this->htmlLinkFontStyle;
  16353. }
  16354. if (($dom[$key]['value'] == 'pre') OR ($dom[$key]['value'] == 'tt')) {
  16355. $dom[$key]['fontname'] = $this->default_monospaced_font;
  16356. }
  16357. if (!empty($dom[$key]['value']) AND ($dom[$key]['value'][0] == 'h') AND (intval($dom[$key]['value'][1]) > 0) AND (intval($dom[$key]['value'][1]) < 7)) {
  16358. // headings h1, h2, h3, h4, h5, h6
  16359. if (!isset($dom[$key]['attribute']['size']) AND !isset($dom[$key]['style']['font-size'])) {
  16360. $headsize = (4 - intval($dom[$key]['value'][1])) * 2;
  16361. $dom[$key]['fontsize'] = $dom[0]['fontsize'] + $headsize;
  16362. }
  16363. if (!isset($dom[$key]['style']['font-weight'])) {
  16364. $dom[$key]['fontstyle'] .= 'B';
  16365. }
  16366. }
  16367. if (($dom[$key]['value'] == 'table')) {
  16368. $dom[$key]['rows'] = 0; // number of rows
  16369. $dom[$key]['trids'] = array(); // IDs of TR elements
  16370. $dom[$key]['thead'] = ''; // table header rows
  16371. }
  16372. if (($dom[$key]['value'] == 'tr')) {
  16373. $dom[$key]['cols'] = 0;
  16374. if ($thead) {
  16375. $dom[$key]['thead'] = true;
  16376. // rows on thead block are printed as a separate table
  16377. } else {
  16378. $dom[$key]['thead'] = false;
  16379. // store the number of rows on table element
  16380. ++$dom[($dom[$key]['parent'])]['rows'];
  16381. // store the TR elements IDs on table element
  16382. array_push($dom[($dom[$key]['parent'])]['trids'], $key);
  16383. }
  16384. }
  16385. if (($dom[$key]['value'] == 'th') OR ($dom[$key]['value'] == 'td')) {
  16386. if (isset($dom[$key]['attribute']['colspan'])) {
  16387. $colspan = intval($dom[$key]['attribute']['colspan']);
  16388. } else {
  16389. $colspan = 1;
  16390. }
  16391. $dom[$key]['attribute']['colspan'] = $colspan;
  16392. $dom[($dom[$key]['parent'])]['cols'] += $colspan;
  16393. }
  16394. // text direction
  16395. if (isset($dom[$key]['attribute']['dir'])) {
  16396. $dom[$key]['dir'] = $dom[$key]['attribute']['dir'];
  16397. }
  16398. // set foreground color attribute
  16399. if (isset($dom[$key]['attribute']['color']) AND (!TCPDF_STATIC::empty_string($dom[$key]['attribute']['color']))) {
  16400. $dom[$key]['fgcolor'] = TCPDF_COLORS::convertHTMLColorToDec($dom[$key]['attribute']['color'], $this->spot_colors);
  16401. } elseif (!isset($dom[$key]['style']['color']) AND ($dom[$key]['value'] == 'a')) {
  16402. $dom[$key]['fgcolor'] = $this->htmlLinkColorArray;
  16403. }
  16404. // set background color attribute
  16405. if (isset($dom[$key]['attribute']['bgcolor']) AND (!TCPDF_STATIC::empty_string($dom[$key]['attribute']['bgcolor']))) {
  16406. $dom[$key]['bgcolor'] = TCPDF_COLORS::convertHTMLColorToDec($dom[$key]['attribute']['bgcolor'], $this->spot_colors);
  16407. }
  16408. // set stroke color attribute
  16409. if (isset($dom[$key]['attribute']['strokecolor']) AND (!TCPDF_STATIC::empty_string($dom[$key]['attribute']['strokecolor']))) {
  16410. $dom[$key]['strokecolor'] = TCPDF_COLORS::convertHTMLColorToDec($dom[$key]['attribute']['strokecolor'], $this->spot_colors);
  16411. }
  16412. // check for width attribute
  16413. if (isset($dom[$key]['attribute']['width'])) {
  16414. $dom[$key]['width'] = $dom[$key]['attribute']['width'];
  16415. }
  16416. // check for height attribute
  16417. if (isset($dom[$key]['attribute']['height'])) {
  16418. $dom[$key]['height'] = $dom[$key]['attribute']['height'];
  16419. }
  16420. // check for text alignment
  16421. if (isset($dom[$key]['attribute']['align']) AND (!TCPDF_STATIC::empty_string($dom[$key]['attribute']['align'])) AND ($dom[$key]['value'] !== 'img')) {
  16422. $dom[$key]['align'] = strtoupper($dom[$key]['attribute']['align'][0]);
  16423. }
  16424. // check for text rendering mode (the following attributes do not exist in HTML)
  16425. if (isset($dom[$key]['attribute']['stroke'])) {
  16426. // font stroke width
  16427. $dom[$key]['stroke'] = $this->getHTMLUnitToUnits($dom[$key]['attribute']['stroke'], $dom[$key]['fontsize'], 'pt', true);
  16428. }
  16429. if (isset($dom[$key]['attribute']['fill'])) {
  16430. // font fill
  16431. if ($dom[$key]['attribute']['fill'] == 'true') {
  16432. $dom[$key]['fill'] = true;
  16433. } else {
  16434. $dom[$key]['fill'] = false;
  16435. }
  16436. }
  16437. if (isset($dom[$key]['attribute']['clip'])) {
  16438. // clipping mode
  16439. if ($dom[$key]['attribute']['clip'] == 'true') {
  16440. $dom[$key]['clip'] = true;
  16441. } else {
  16442. $dom[$key]['clip'] = false;
  16443. }
  16444. }
  16445. } // end opening tag
  16446. } else {
  16447. // text
  16448. $dom[$key]['tag'] = false;
  16449. $dom[$key]['block'] = false;
  16450. $dom[$key]['parent'] = end($level);
  16451. $dom[$key]['dir'] = $dom[$dom[$key]['parent']]['dir'];
  16452. if (!empty($dom[$dom[$key]['parent']]['text-transform'])) {
  16453. // text-transform for unicode requires mb_convert_case (Multibyte String Functions)
  16454. if (function_exists('mb_convert_case')) {
  16455. $ttm = array('capitalize' => MB_CASE_TITLE, 'uppercase' => MB_CASE_UPPER, 'lowercase' => MB_CASE_LOWER);
  16456. if (isset($ttm[$dom[$dom[$key]['parent']]['text-transform']])) {
  16457. $element = mb_convert_case($element, $ttm[$dom[$dom[$key]['parent']]['text-transform']], $this->encoding);
  16458. }
  16459. } elseif (!$this->isunicode) {
  16460. switch ($dom[$dom[$key]['parent']]['text-transform']) {
  16461. case 'capitalize': {
  16462. $element = ucwords(strtolower($element));
  16463. break;
  16464. }
  16465. case 'uppercase': {
  16466. $element = strtoupper($element);
  16467. break;
  16468. }
  16469. case 'lowercase': {
  16470. $element = strtolower($element);
  16471. break;
  16472. }
  16473. }
  16474. }
  16475. }
  16476. $dom[$key]['value'] = stripslashes($this->unhtmlentities($element));
  16477. }
  16478. ++$elkey;
  16479. ++$key;
  16480. }
  16481. return $dom;
  16482. }
  16483. /**
  16484. * Returns the string used to find spaces
  16485. * @return string
  16486. * @protected
  16487. * @author Nicola Asuni
  16488. * @since 4.8.024 (2010-01-15)
  16489. */
  16490. protected function getSpaceString() {
  16491. $spacestr = chr(32);
  16492. if ($this->isUnicodeFont()) {
  16493. $spacestr = chr(0).chr(32);
  16494. }
  16495. return $spacestr;
  16496. }
  16497. /**
  16498. * Return an hash code used to ensure that the serialized data has been generated by this TCPDF instance.
  16499. * @param $data (string) serialized data
  16500. * @return string
  16501. * @public static
  16502. */
  16503. protected function getHashForTCPDFtagParams($data) {
  16504. return md5(strlen($data).$this->file_id.$data);
  16505. }
  16506. /**
  16507. * Serialize an array of parameters to be used with TCPDF tag in HTML code.
  16508. * @param $data (array) parameters array
  16509. * @return string containing serialized data
  16510. * @public static
  16511. */
  16512. public function serializeTCPDFtagParameters($data) {
  16513. $encoded = urlencode(json_encode($data));
  16514. return $this->getHashForTCPDFtagParams($encoded).$encoded;
  16515. }
  16516. /**
  16517. * Unserialize parameters to be used with TCPDF tag in HTML code.
  16518. * @param $data (string) serialized data
  16519. * @return array containing unserialized data
  16520. * @protected static
  16521. */
  16522. protected function unserializeTCPDFtagParameters($data) {
  16523. $hash = substr($data, 0, 32);
  16524. $encoded = substr($data, 32);
  16525. if ($hash != $this->getHashForTCPDFtagParams($encoded)) {
  16526. $this->Error('Invalid parameters');
  16527. }
  16528. return json_decode(urldecode($encoded), true);
  16529. }
  16530. /**
  16531. * Prints a cell (rectangular area) with optional borders, background color and html text string.
  16532. * 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 />
  16533. * If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting.
  16534. * IMPORTANT: The HTML must be well formatted - try to clean-up it using an application like HTML-Tidy before submitting.
  16535. * 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
  16536. * NOTE: all the HTML attributes must be enclosed in double-quote.
  16537. * @param $w (float) Cell width. If 0, the cell extends up to the right margin.
  16538. * @param $h (float) Cell minimum height. The cell extends automatically if needed.
  16539. * @param $x (float) upper-left corner X coordinate
  16540. * @param $y (float) upper-left corner Y coordinate
  16541. * @param $html (string) html text to print. Default value: empty string.
  16542. * @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)))
  16543. * @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>
  16544. Putting 1 is equivalent to putting 0 and calling Ln() just after. Default value: 0.
  16545. * @param $fill (boolean) Indicates if the cell background must be painted (true) or transparent (false).
  16546. * @param $reseth (boolean) if true reset the last cell height (default true).
  16547. * @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>
  16548. * @param $autopadding (boolean) if true, uses internal padding and automatically adjust it to account for line width.
  16549. * @see Multicell(), writeHTML()
  16550. * @public
  16551. */
  16552. public function writeHTMLCell($w, $h, $x, $y, $html='', $border=0, $ln=0, $fill=false, $reseth=true, $align='', $autopadding=true) {
  16553. return $this->MultiCell($w, $h, $html, $border, $align, $fill, $ln, $x, $y, $reseth, 0, true, $autopadding, 0, 'T', false);
  16554. }
  16555. /**
  16556. * Allows to preserve some HTML formatting (limited support).<br />
  16557. * IMPORTANT: The HTML must be well formatted - try to clean-up it using an application like HTML-Tidy before submitting.
  16558. * 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
  16559. * NOTE: all the HTML attributes must be enclosed in double-quote.
  16560. * @param $html (string) text to display
  16561. * @param $ln (boolean) if true add a new line after text (default = true)
  16562. * @param $fill (boolean) Indicates if the background must be painted (true) or transparent (false).
  16563. * @param $reseth (boolean) if true reset the last cell height (default false).
  16564. * @param $cell (boolean) if true add the current left (or right for RTL) padding to each Write (default false).
  16565. * @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>
  16566. * @public
  16567. */
  16568. public function writeHTML($html, $ln=true, $fill=false, $reseth=false, $cell=false, $align='') {
  16569. $gvars = $this->getGraphicVars();
  16570. // store current values
  16571. $prev_cell_margin = $this->cell_margin;
  16572. $prev_cell_padding = $this->cell_padding;
  16573. $prevPage = $this->page;
  16574. $prevlMargin = $this->lMargin;
  16575. $prevrMargin = $this->rMargin;
  16576. $curfontname = $this->FontFamily;
  16577. $curfontstyle = $this->FontStyle;
  16578. $curfontsize = $this->FontSizePt;
  16579. $curfontascent = $this->getFontAscent($curfontname, $curfontstyle, $curfontsize);
  16580. $curfontdescent = $this->getFontDescent($curfontname, $curfontstyle, $curfontsize);
  16581. $curfontstretcing = $this->font_stretching;
  16582. $curfonttracking = $this->font_spacing;
  16583. $this->newline = true;
  16584. $newline = true;
  16585. $startlinepage = $this->page;
  16586. $minstartliney = $this->y;
  16587. $maxbottomliney = 0;
  16588. $startlinex = $this->x;
  16589. $startliney = $this->y;
  16590. $yshift = 0;
  16591. $loop = 0;
  16592. $curpos = 0;
  16593. $this_method_vars = array();
  16594. $undo = false;
  16595. $fontaligned = false;
  16596. $reverse_dir = false; // true when the text direction is reversed
  16597. $this->premode = false;
  16598. if ($this->inxobj) {
  16599. // we are inside an XObject template
  16600. $pask = count($this->xobjects[$this->xobjid]['annotations']);
  16601. } elseif (isset($this->PageAnnots[$this->page])) {
  16602. $pask = count($this->PageAnnots[$this->page]);
  16603. } else {
  16604. $pask = 0;
  16605. }
  16606. if ($this->inxobj) {
  16607. // we are inside an XObject template
  16608. $startlinepos = strlen($this->xobjects[$this->xobjid]['outdata']);
  16609. } elseif (!$this->InFooter) {
  16610. if (isset($this->footerlen[$this->page])) {
  16611. $this->footerpos[$this->page] = $this->pagelen[$this->page] - $this->footerlen[$this->page];
  16612. } else {
  16613. $this->footerpos[$this->page] = $this->pagelen[$this->page];
  16614. }
  16615. $startlinepos = $this->footerpos[$this->page];
  16616. } else {
  16617. // we are inside the footer
  16618. $startlinepos = $this->pagelen[$this->page];
  16619. }
  16620. $lalign = $align;
  16621. $plalign = $align;
  16622. if ($this->rtl) {
  16623. $w = $this->x - $this->lMargin;
  16624. } else {
  16625. $w = $this->w - $this->rMargin - $this->x;
  16626. }
  16627. $w -= ($this->cell_padding['L'] + $this->cell_padding['R']);
  16628. if ($cell) {
  16629. if ($this->rtl) {
  16630. $this->x -= $this->cell_padding['R'];
  16631. $this->lMargin += $this->cell_padding['L'];
  16632. } else {
  16633. $this->x += $this->cell_padding['L'];
  16634. $this->rMargin += $this->cell_padding['R'];
  16635. }
  16636. }
  16637. if ($this->customlistindent >= 0) {
  16638. $this->listindent = $this->customlistindent;
  16639. } else {
  16640. $this->listindent = $this->GetStringWidth('000000');
  16641. }
  16642. $this->listindentlevel = 0;
  16643. // save previous states
  16644. $prev_cell_height_ratio = $this->cell_height_ratio;
  16645. $prev_listnum = $this->listnum;
  16646. $prev_listordered = $this->listordered;
  16647. $prev_listcount = $this->listcount;
  16648. $prev_lispacer = $this->lispacer;
  16649. $this->listnum = 0;
  16650. $this->listordered = array();
  16651. $this->listcount = array();
  16652. $this->lispacer = '';
  16653. if ((TCPDF_STATIC::empty_string($this->lasth)) OR ($reseth)) {
  16654. // reset row height
  16655. $this->resetLastH();
  16656. }
  16657. $dom = $this->getHtmlDomArray($html);
  16658. $maxel = count($dom);
  16659. $key = 0;
  16660. while ($key < $maxel) {
  16661. if ($dom[$key]['tag'] AND $dom[$key]['opening'] AND $dom[$key]['hide']) {
  16662. // store the node key
  16663. $hidden_node_key = $key;
  16664. if ($dom[$key]['self']) {
  16665. // skip just this self-closing tag
  16666. ++$key;
  16667. } else {
  16668. // skip this and all children tags
  16669. while (($key < $maxel) AND (!$dom[$key]['tag'] OR $dom[$key]['opening'] OR ($dom[$key]['parent'] != $hidden_node_key))) {
  16670. // skip hidden objects
  16671. ++$key;
  16672. }
  16673. ++$key;
  16674. }
  16675. }
  16676. if ($dom[$key]['tag'] AND isset($dom[$key]['attribute']['pagebreak'])) {
  16677. // check for pagebreak
  16678. if (($dom[$key]['attribute']['pagebreak'] == 'true') OR ($dom[$key]['attribute']['pagebreak'] == 'left') OR ($dom[$key]['attribute']['pagebreak'] == 'right')) {
  16679. // add a page (or trig AcceptPageBreak() for multicolumn mode)
  16680. $this->checkPageBreak($this->PageBreakTrigger + 1);
  16681. $this->htmlvspace = ($this->PageBreakTrigger + 1);
  16682. }
  16683. if ((($dom[$key]['attribute']['pagebreak'] == 'left') AND (((!$this->rtl) AND (($this->page % 2) == 0)) OR (($this->rtl) AND (($this->page % 2) != 0))))
  16684. OR (($dom[$key]['attribute']['pagebreak'] == 'right') AND (((!$this->rtl) AND (($this->page % 2) != 0)) OR (($this->rtl) AND (($this->page % 2) == 0))))) {
  16685. // add a page (or trig AcceptPageBreak() for multicolumn mode)
  16686. $this->checkPageBreak($this->PageBreakTrigger + 1);
  16687. $this->htmlvspace = ($this->PageBreakTrigger + 1);
  16688. }
  16689. }
  16690. if ($dom[$key]['tag'] AND $dom[$key]['opening'] AND isset($dom[$key]['attribute']['nobr']) AND ($dom[$key]['attribute']['nobr'] == 'true')) {
  16691. if (isset($dom[($dom[$key]['parent'])]['attribute']['nobr']) AND ($dom[($dom[$key]['parent'])]['attribute']['nobr'] == 'true')) {
  16692. $dom[$key]['attribute']['nobr'] = false;
  16693. } else {
  16694. // store current object
  16695. $this->startTransaction();
  16696. // save this method vars
  16697. $this_method_vars['html'] = $html;
  16698. $this_method_vars['ln'] = $ln;
  16699. $this_method_vars['fill'] = $fill;
  16700. $this_method_vars['reseth'] = $reseth;
  16701. $this_method_vars['cell'] = $cell;
  16702. $this_method_vars['align'] = $align;
  16703. $this_method_vars['gvars'] = $gvars;
  16704. $this_method_vars['prevPage'] = $prevPage;
  16705. $this_method_vars['prev_cell_margin'] = $prev_cell_margin;
  16706. $this_method_vars['prev_cell_padding'] = $prev_cell_padding;
  16707. $this_method_vars['prevlMargin'] = $prevlMargin;
  16708. $this_method_vars['prevrMargin'] = $prevrMargin;
  16709. $this_method_vars['curfontname'] = $curfontname;
  16710. $this_method_vars['curfontstyle'] = $curfontstyle;
  16711. $this_method_vars['curfontsize'] = $curfontsize;
  16712. $this_method_vars['curfontascent'] = $curfontascent;
  16713. $this_method_vars['curfontdescent'] = $curfontdescent;
  16714. $this_method_vars['curfontstretcing'] = $curfontstretcing;
  16715. $this_method_vars['curfonttracking'] = $curfonttracking;
  16716. $this_method_vars['minstartliney'] = $minstartliney;
  16717. $this_method_vars['maxbottomliney'] = $maxbottomliney;
  16718. $this_method_vars['yshift'] = $yshift;
  16719. $this_method_vars['startlinepage'] = $startlinepage;
  16720. $this_method_vars['startlinepos'] = $startlinepos;
  16721. $this_method_vars['startlinex'] = $startlinex;
  16722. $this_method_vars['startliney'] = $startliney;
  16723. $this_method_vars['newline'] = $newline;
  16724. $this_method_vars['loop'] = $loop;
  16725. $this_method_vars['curpos'] = $curpos;
  16726. $this_method_vars['pask'] = $pask;
  16727. $this_method_vars['lalign'] = $lalign;
  16728. $this_method_vars['plalign'] = $plalign;
  16729. $this_method_vars['w'] = $w;
  16730. $this_method_vars['prev_cell_height_ratio'] = $prev_cell_height_ratio;
  16731. $this_method_vars['prev_listnum'] = $prev_listnum;
  16732. $this_method_vars['prev_listordered'] = $prev_listordered;
  16733. $this_method_vars['prev_listcount'] = $prev_listcount;
  16734. $this_method_vars['prev_lispacer'] = $prev_lispacer;
  16735. $this_method_vars['fontaligned'] = $fontaligned;
  16736. $this_method_vars['key'] = $key;
  16737. $this_method_vars['dom'] = $dom;
  16738. }
  16739. }
  16740. // print THEAD block
  16741. if (($dom[$key]['value'] == 'tr') AND isset($dom[$key]['thead']) AND $dom[$key]['thead']) {
  16742. if (isset($dom[$key]['parent']) AND isset($dom[$dom[$key]['parent']]['thead']) AND !TCPDF_STATIC::empty_string($dom[$dom[$key]['parent']]['thead'])) {
  16743. $this->inthead = true;
  16744. // print table header (thead)
  16745. $this->writeHTML($this->thead, false, false, false, false, '');
  16746. // check if we are on a new page or on a new column
  16747. if (($this->y < $this->start_transaction_y) OR ($this->checkPageBreak($this->lasth, '', false))) {
  16748. // we are on a new page or on a new column and the total object height is less than the available vertical space.
  16749. // restore previous object
  16750. $this->rollbackTransaction(true);
  16751. // restore previous values
  16752. foreach ($this_method_vars as $vkey => $vval) {
  16753. $$vkey = $vval;
  16754. }
  16755. // disable table header
  16756. $tmp_thead = $this->thead;
  16757. $this->thead = '';
  16758. // add a page (or trig AcceptPageBreak() for multicolumn mode)
  16759. $pre_y = $this->y;
  16760. if ((!$this->checkPageBreak($this->PageBreakTrigger + 1)) AND ($this->y < $pre_y)) {
  16761. // fix for multicolumn mode
  16762. $startliney = $this->y;
  16763. }
  16764. $this->start_transaction_page = $this->page;
  16765. $this->start_transaction_y = $this->y;
  16766. // restore table header
  16767. $this->thead = $tmp_thead;
  16768. // fix table border properties
  16769. if (isset($dom[$dom[$key]['parent']]['attribute']['cellspacing'])) {
  16770. $tmp_cellspacing = $this->getHTMLUnitToUnits($dom[$dom[$key]['parent']]['attribute']['cellspacing'], 1, 'px');
  16771. } elseif (isset($dom[$dom[$key]['parent']]['border-spacing'])) {
  16772. $tmp_cellspacing = $dom[$dom[$key]['parent']]['border-spacing']['V'];
  16773. } else {
  16774. $tmp_cellspacing = 0;
  16775. }
  16776. $dom[$dom[$key]['parent']]['borderposition']['page'] = $this->page;
  16777. $dom[$dom[$key]['parent']]['borderposition']['column'] = $this->current_column;
  16778. $dom[$dom[$key]['parent']]['borderposition']['y'] = $this->y + $tmp_cellspacing;
  16779. $xoffset = ($this->x - $dom[$dom[$key]['parent']]['borderposition']['x']);
  16780. $dom[$dom[$key]['parent']]['borderposition']['x'] += $xoffset;
  16781. $dom[$dom[$key]['parent']]['borderposition']['xmax'] += $xoffset;
  16782. // print table header (thead)
  16783. $this->writeHTML($this->thead, false, false, false, false, '');
  16784. }
  16785. }
  16786. // move $key index forward to skip THEAD block
  16787. while ( ($key < $maxel) AND (!(
  16788. ($dom[$key]['tag'] AND $dom[$key]['opening'] AND ($dom[$key]['value'] == 'tr') AND (!isset($dom[$key]['thead']) OR !$dom[$key]['thead']))
  16789. OR ($dom[$key]['tag'] AND (!$dom[$key]['opening']) AND ($dom[$key]['value'] == 'table'))) )) {
  16790. ++$key;
  16791. }
  16792. }
  16793. if ($dom[$key]['tag'] OR ($key == 0)) {
  16794. if ((($dom[$key]['value'] == 'table') OR ($dom[$key]['value'] == 'tr')) AND (isset($dom[$key]['align']))) {
  16795. $dom[$key]['align'] = ($this->rtl) ? 'R' : 'L';
  16796. }
  16797. // vertically align image in line
  16798. if ((!$this->newline) AND ($dom[$key]['value'] == 'img') AND (isset($dom[$key]['height'])) AND ($dom[$key]['height'] > 0)) {
  16799. // get image height
  16800. $imgh = $this->getHTMLUnitToUnits($dom[$key]['height'], ($dom[$key]['fontsize'] / $this->k), 'px');
  16801. $autolinebreak = false;
  16802. if (!empty($dom[$key]['width'])) {
  16803. $imgw = $this->getHTMLUnitToUnits($dom[$key]['width'], ($dom[$key]['fontsize'] / $this->k), 'px', false);
  16804. if (($imgw <= ($this->w - $this->lMargin - $this->rMargin - $this->cell_padding['L'] - $this->cell_padding['R']))
  16805. AND ((($this->rtl) AND (($this->x - $imgw) < ($this->lMargin + $this->cell_padding['L'])))
  16806. OR ((!$this->rtl) AND (($this->x + $imgw) > ($this->w - $this->rMargin - $this->cell_padding['R']))))) {
  16807. // add automatic line break
  16808. $autolinebreak = true;
  16809. $this->Ln('', $cell);
  16810. if ((!$dom[($key-1)]['tag']) AND ($dom[($key-1)]['value'] == ' ')) {
  16811. // go back to evaluate this line break
  16812. --$key;
  16813. }
  16814. }
  16815. }
  16816. if (!$autolinebreak) {
  16817. if ($this->inPageBody()) {
  16818. $pre_y = $this->y;
  16819. // check for page break
  16820. if ((!$this->checkPageBreak($imgh)) AND ($this->y < $pre_y)) {
  16821. // fix for multicolumn mode
  16822. $startliney = $this->y;
  16823. }
  16824. }
  16825. if ($this->page > $startlinepage) {
  16826. // fix line splitted over two pages
  16827. if (isset($this->footerlen[$startlinepage])) {
  16828. $curpos = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
  16829. }
  16830. // line to be moved one page forward
  16831. $pagebuff = $this->getPageBuffer($startlinepage);
  16832. $linebeg = substr($pagebuff, $startlinepos, ($curpos - $startlinepos));
  16833. $tstart = substr($pagebuff, 0, $startlinepos);
  16834. $tend = substr($this->getPageBuffer($startlinepage), $curpos);
  16835. // remove line from previous page
  16836. $this->setPageBuffer($startlinepage, $tstart.''.$tend);
  16837. $pagebuff = $this->getPageBuffer($this->page);
  16838. $tstart = substr($pagebuff, 0, $this->cntmrk[$this->page]);
  16839. $tend = substr($pagebuff, $this->cntmrk[$this->page]);
  16840. // add line start to current page
  16841. $yshift = ($minstartliney - $this->y);
  16842. if ($fontaligned) {
  16843. $yshift += ($curfontsize / $this->k);
  16844. }
  16845. $try = sprintf('1 0 0 1 0 %F cm', ($yshift * $this->k));
  16846. $this->setPageBuffer($this->page, $tstart."\nq\n".$try."\n".$linebeg."\nQ\n".$tend);
  16847. // shift the annotations and links
  16848. if (isset($this->PageAnnots[$this->page])) {
  16849. $next_pask = count($this->PageAnnots[$this->page]);
  16850. } else {
  16851. $next_pask = 0;
  16852. }
  16853. if (isset($this->PageAnnots[$startlinepage])) {
  16854. foreach ($this->PageAnnots[$startlinepage] as $pak => $pac) {
  16855. if ($pak >= $pask) {
  16856. $this->PageAnnots[$this->page][] = $pac;
  16857. unset($this->PageAnnots[$startlinepage][$pak]);
  16858. $npak = count($this->PageAnnots[$this->page]) - 1;
  16859. $this->PageAnnots[$this->page][$npak]['y'] -= $yshift;
  16860. }
  16861. }
  16862. }
  16863. $pask = $next_pask;
  16864. $startlinepos = $this->cntmrk[$this->page];
  16865. $startlinepage = $this->page;
  16866. $startliney = $this->y;
  16867. $this->newline = false;
  16868. }
  16869. $this->y += ($this->getCellHeight($curfontsize / $this->k) - ($curfontdescent * $this->cell_height_ratio) - $imgh);
  16870. $minstartliney = min($this->y, $minstartliney);
  16871. $maxbottomliney = ($startliney + $this->getCellHeight($curfontsize / $this->k));
  16872. }
  16873. } elseif (isset($dom[$key]['fontname']) OR isset($dom[$key]['fontstyle']) OR isset($dom[$key]['fontsize']) OR isset($dom[$key]['line-height'])) {
  16874. // account for different font size
  16875. $pfontname = $curfontname;
  16876. $pfontstyle = $curfontstyle;
  16877. $pfontsize = $curfontsize;
  16878. $fontname = (isset($dom[$key]['fontname']) ? $dom[$key]['fontname'] : $curfontname);
  16879. $fontstyle = (isset($dom[$key]['fontstyle']) ? $dom[$key]['fontstyle'] : $curfontstyle);
  16880. $fontsize = (isset($dom[$key]['fontsize']) ? $dom[$key]['fontsize'] : $curfontsize);
  16881. $fontascent = $this->getFontAscent($fontname, $fontstyle, $fontsize);
  16882. $fontdescent = $this->getFontDescent($fontname, $fontstyle, $fontsize);
  16883. if (($fontname != $curfontname) OR ($fontstyle != $curfontstyle) OR ($fontsize != $curfontsize)
  16884. OR ($this->cell_height_ratio != $dom[$key]['line-height'])
  16885. OR ($dom[$key]['tag'] AND $dom[$key]['opening'] AND ($dom[$key]['value'] == 'li')) ) {
  16886. if (($key < ($maxel - 1)) AND (
  16887. ($dom[$key]['tag'] AND $dom[$key]['opening'] AND ($dom[$key]['value'] == 'li'))
  16888. OR ($this->cell_height_ratio != $dom[$key]['line-height'])
  16889. OR (!$this->newline AND is_numeric($fontsize) AND is_numeric($curfontsize)
  16890. AND ($fontsize >= 0) AND ($curfontsize >= 0)
  16891. AND (($fontsize != $curfontsize) OR ($fontstyle != $curfontstyle) OR ($fontname != $curfontname)))
  16892. )) {
  16893. if ($this->page > $startlinepage) {
  16894. // fix lines splitted over two pages
  16895. if (isset($this->footerlen[$startlinepage])) {
  16896. $curpos = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
  16897. }
  16898. // line to be moved one page forward
  16899. $pagebuff = $this->getPageBuffer($startlinepage);
  16900. $linebeg = substr($pagebuff, $startlinepos, ($curpos - $startlinepos));
  16901. $tstart = substr($pagebuff, 0, $startlinepos);
  16902. $tend = substr($this->getPageBuffer($startlinepage), $curpos);
  16903. // remove line start from previous page
  16904. $this->setPageBuffer($startlinepage, $tstart.''.$tend);
  16905. $pagebuff = $this->getPageBuffer($this->page);
  16906. $tstart = substr($pagebuff, 0, $this->cntmrk[$this->page]);
  16907. $tend = substr($pagebuff, $this->cntmrk[$this->page]);
  16908. // add line start to current page
  16909. $yshift = ($minstartliney - $this->y);
  16910. $try = sprintf('1 0 0 1 0 %F cm', ($yshift * $this->k));
  16911. $this->setPageBuffer($this->page, $tstart."\nq\n".$try."\n".$linebeg."\nQ\n".$tend);
  16912. // shift the annotations and links
  16913. if (isset($this->PageAnnots[$this->page])) {
  16914. $next_pask = count($this->PageAnnots[$this->page]);
  16915. } else {
  16916. $next_pask = 0;
  16917. }
  16918. if (isset($this->PageAnnots[$startlinepage])) {
  16919. foreach ($this->PageAnnots[$startlinepage] as $pak => $pac) {
  16920. if ($pak >= $pask) {
  16921. $this->PageAnnots[$this->page][] = $pac;
  16922. unset($this->PageAnnots[$startlinepage][$pak]);
  16923. $npak = count($this->PageAnnots[$this->page]) - 1;
  16924. $this->PageAnnots[$this->page][$npak]['y'] -= $yshift;
  16925. }
  16926. }
  16927. }
  16928. $pask = $next_pask;
  16929. $startlinepos = $this->cntmrk[$this->page];
  16930. $startlinepage = $this->page;
  16931. $startliney = $this->y;
  16932. }
  16933. if (!isset($dom[$key]['line-height'])) {
  16934. $dom[$key]['line-height'] = $this->cell_height_ratio;
  16935. }
  16936. if (!$dom[$key]['block']) {
  16937. 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']))) {
  16938. $this->y += (((($curfontsize * $this->cell_height_ratio) - ($fontsize * $dom[$key]['line-height'])) / $this->k) + $curfontascent - $fontascent - $curfontdescent + $fontdescent) / 2;
  16939. }
  16940. if (($dom[$key]['value'] != 'sup') AND ($dom[$key]['value'] != 'sub')) {
  16941. $current_line_align_data = array($key, $minstartliney, $maxbottomliney);
  16942. 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)))) {
  16943. $minstartliney = min($this->y, $line_align_data[1]);
  16944. $maxbottomliney = max(($this->y + $this->getCellHeight($fontsize / $this->k)), $line_align_data[2]);
  16945. } else {
  16946. $minstartliney = min($this->y, $minstartliney);
  16947. $maxbottomliney = max(($this->y + $this->getCellHeight($fontsize / $this->k)), $maxbottomliney);
  16948. }
  16949. $line_align_data = $current_line_align_data;
  16950. }
  16951. }
  16952. $this->cell_height_ratio = $dom[$key]['line-height'];
  16953. $fontaligned = true;
  16954. }
  16955. $this->SetFont($fontname, $fontstyle, $fontsize);
  16956. // reset row height
  16957. $this->resetLastH();
  16958. $curfontname = $fontname;
  16959. $curfontstyle = $fontstyle;
  16960. $curfontsize = $fontsize;
  16961. $curfontascent = $fontascent;
  16962. $curfontdescent = $fontdescent;
  16963. }
  16964. }
  16965. // set text rendering mode
  16966. $textstroke = isset($dom[$key]['stroke']) ? $dom[$key]['stroke'] : $this->textstrokewidth;
  16967. $textfill = isset($dom[$key]['fill']) ? $dom[$key]['fill'] : (($this->textrendermode % 2) == 0);
  16968. $textclip = isset($dom[$key]['clip']) ? $dom[$key]['clip'] : ($this->textrendermode > 3);
  16969. $this->setTextRenderingMode($textstroke, $textfill, $textclip);
  16970. if (isset($dom[$key]['font-stretch']) AND ($dom[$key]['font-stretch'] !== false)) {
  16971. $this->setFontStretching($dom[$key]['font-stretch']);
  16972. }
  16973. if (isset($dom[$key]['letter-spacing']) AND ($dom[$key]['letter-spacing'] !== false)) {
  16974. $this->setFontSpacing($dom[$key]['letter-spacing']);
  16975. }
  16976. if (($plalign == 'J') AND $dom[$key]['block']) {
  16977. $plalign = '';
  16978. }
  16979. // get current position on page buffer
  16980. $curpos = $this->pagelen[$startlinepage];
  16981. if (isset($dom[$key]['bgcolor']) AND ($dom[$key]['bgcolor'] !== false)) {
  16982. $this->SetFillColorArray($dom[$key]['bgcolor']);
  16983. $wfill = true;
  16984. } else {
  16985. $wfill = $fill | false;
  16986. }
  16987. if (isset($dom[$key]['fgcolor']) AND ($dom[$key]['fgcolor'] !== false)) {
  16988. $this->SetTextColorArray($dom[$key]['fgcolor']);
  16989. }
  16990. if (isset($dom[$key]['strokecolor']) AND ($dom[$key]['strokecolor'] !== false)) {
  16991. $this->SetDrawColorArray($dom[$key]['strokecolor']);
  16992. }
  16993. if (isset($dom[$key]['align'])) {
  16994. $lalign = $dom[$key]['align'];
  16995. }
  16996. if (TCPDF_STATIC::empty_string($lalign)) {
  16997. $lalign = $align;
  16998. }
  16999. }
  17000. // align lines
  17001. if ($this->newline AND (strlen($dom[$key]['value']) > 0) AND ($dom[$key]['value'] != 'td') AND ($dom[$key]['value'] != 'th')) {
  17002. $newline = true;
  17003. $fontaligned = false;
  17004. // we are at the beginning of a new line
  17005. if (isset($startlinex)) {
  17006. $yshift = ($minstartliney - $startliney);
  17007. if (($yshift > 0) OR ($this->page > $startlinepage)) {
  17008. $yshift = 0;
  17009. }
  17010. $t_x = 0;
  17011. // the last line must be shifted to be aligned as requested
  17012. $linew = abs($this->endlinex - $startlinex);
  17013. if ($this->inxobj) {
  17014. // we are inside an XObject template
  17015. $pstart = substr($this->xobjects[$this->xobjid]['outdata'], 0, $startlinepos);
  17016. if (isset($opentagpos)) {
  17017. $midpos = $opentagpos;
  17018. } else {
  17019. $midpos = 0;
  17020. }
  17021. if ($midpos > 0) {
  17022. $pmid = substr($this->xobjects[$this->xobjid]['outdata'], $startlinepos, ($midpos - $startlinepos));
  17023. $pend = substr($this->xobjects[$this->xobjid]['outdata'], $midpos);
  17024. } else {
  17025. $pmid = substr($this->xobjects[$this->xobjid]['outdata'], $startlinepos);
  17026. $pend = '';
  17027. }
  17028. } else {
  17029. $pstart = substr($this->getPageBuffer($startlinepage), 0, $startlinepos);
  17030. if (isset($opentagpos) AND isset($this->footerlen[$startlinepage]) AND (!$this->InFooter)) {
  17031. $this->footerpos[$startlinepage] = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
  17032. $midpos = min($opentagpos, $this->footerpos[$startlinepage]);
  17033. } elseif (isset($opentagpos)) {
  17034. $midpos = $opentagpos;
  17035. } elseif (isset($this->footerlen[$startlinepage]) AND (!$this->InFooter)) {
  17036. $this->footerpos[$startlinepage] = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
  17037. $midpos = $this->footerpos[$startlinepage];
  17038. } else {
  17039. $midpos = 0;
  17040. }
  17041. if ($midpos > 0) {
  17042. $pmid = substr($this->getPageBuffer($startlinepage), $startlinepos, ($midpos - $startlinepos));
  17043. $pend = substr($this->getPageBuffer($startlinepage), $midpos);
  17044. } else {
  17045. $pmid = substr($this->getPageBuffer($startlinepage), $startlinepos);
  17046. $pend = '';
  17047. }
  17048. }
  17049. if ((isset($plalign) AND ((($plalign == 'C') OR ($plalign == 'J') OR (($plalign == 'R') AND (!$this->rtl)) OR (($plalign == 'L') AND ($this->rtl)))))) {
  17050. // calculate shifting amount
  17051. $tw = $w;
  17052. if (($plalign == 'J') AND $this->isRTLTextDir() AND ($this->num_columns > 1)) {
  17053. $tw += $this->cell_padding['R'];
  17054. }
  17055. if ($this->lMargin != $prevlMargin) {
  17056. $tw += ($prevlMargin - $this->lMargin);
  17057. }
  17058. if ($this->rMargin != $prevrMargin) {
  17059. $tw += ($prevrMargin - $this->rMargin);
  17060. }
  17061. $one_space_width = $this->GetStringWidth(chr(32));
  17062. $no = 0; // number of spaces on a line contained on a single block
  17063. if ($this->isRTLTextDir()) { // RTL
  17064. // remove left space if exist
  17065. $pos1 = TCPDF_STATIC::revstrpos($pmid, '[(');
  17066. if ($pos1 > 0) {
  17067. $pos1 = intval($pos1);
  17068. if ($this->isUnicodeFont()) {
  17069. $pos2 = intval(TCPDF_STATIC::revstrpos($pmid, '[('.chr(0).chr(32)));
  17070. $spacelen = 2;
  17071. } else {
  17072. $pos2 = intval(TCPDF_STATIC::revstrpos($pmid, '[('.chr(32)));
  17073. $spacelen = 1;
  17074. }
  17075. if ($pos1 == $pos2) {
  17076. $pmid = substr($pmid, 0, ($pos1 + 2)).substr($pmid, ($pos1 + 2 + $spacelen));
  17077. if (substr($pmid, $pos1, 4) == '[()]') {
  17078. $linew -= $one_space_width;
  17079. } elseif ($pos1 == strpos($pmid, '[(')) {
  17080. $no = 1;
  17081. }
  17082. }
  17083. }
  17084. } else { // LTR
  17085. // remove right space if exist
  17086. $pos1 = TCPDF_STATIC::revstrpos($pmid, ')]');
  17087. if ($pos1 > 0) {
  17088. $pos1 = intval($pos1);
  17089. if ($this->isUnicodeFont()) {
  17090. $pos2 = intval(TCPDF_STATIC::revstrpos($pmid, chr(0).chr(32).')]')) + 2;
  17091. $spacelen = 2;
  17092. } else {
  17093. $pos2 = intval(TCPDF_STATIC::revstrpos($pmid, chr(32).')]')) + 1;
  17094. $spacelen = 1;
  17095. }
  17096. if ($pos1 == $pos2) {
  17097. $pmid = substr($pmid, 0, ($pos1 - $spacelen)).substr($pmid, $pos1);
  17098. $linew -= $one_space_width;
  17099. }
  17100. }
  17101. }
  17102. $mdiff = ($tw - $linew);
  17103. if ($plalign == 'C') {
  17104. if ($this->rtl) {
  17105. $t_x = -($mdiff / 2);
  17106. } else {
  17107. $t_x = ($mdiff / 2);
  17108. }
  17109. } elseif ($plalign == 'R') {
  17110. // right alignment on LTR document
  17111. $t_x = $mdiff;
  17112. } elseif ($plalign == 'L') {
  17113. // left alignment on RTL document
  17114. $t_x = -$mdiff;
  17115. } elseif (($plalign == 'J') AND ($plalign == $lalign)) {
  17116. // Justification
  17117. if ($this->isRTLTextDir()) {
  17118. // align text on the left
  17119. $t_x = -$mdiff;
  17120. }
  17121. $ns = 0; // number of spaces
  17122. $pmidtemp = $pmid;
  17123. // escape special characters
  17124. $pmidtemp = preg_replace('/[\\\][\(]/x', '\\#!#OP#!#', $pmidtemp);
  17125. $pmidtemp = preg_replace('/[\\\][\)]/x', '\\#!#CP#!#', $pmidtemp);
  17126. // search spaces
  17127. if (preg_match_all('/\[\(([^\)]*)\)\]/x', $pmidtemp, $lnstring, PREG_PATTERN_ORDER)) {
  17128. $spacestr = $this->getSpaceString();
  17129. $maxkk = count($lnstring[1]) - 1;
  17130. for ($kk=0; $kk <= $maxkk; ++$kk) {
  17131. // restore special characters
  17132. $lnstring[1][$kk] = str_replace('#!#OP#!#', '(', $lnstring[1][$kk]);
  17133. $lnstring[1][$kk] = str_replace('#!#CP#!#', ')', $lnstring[1][$kk]);
  17134. // store number of spaces on the strings
  17135. $lnstring[2][$kk] = substr_count($lnstring[1][$kk], $spacestr);
  17136. // count total spaces on line
  17137. $ns += $lnstring[2][$kk];
  17138. $lnstring[3][$kk] = $ns;
  17139. }
  17140. if ($ns == 0) {
  17141. $ns = 1;
  17142. }
  17143. // calculate additional space to add to each existing space
  17144. $spacewidth = ($mdiff / ($ns - $no)) * $this->k;
  17145. if ($this->FontSize <= 0) {
  17146. $this->FontSize = 1;
  17147. }
  17148. $spacewidthu = -1000 * ($mdiff + (($ns + $no) * $one_space_width)) / $ns / $this->FontSize;
  17149. if ($this->font_spacing != 0) {
  17150. // fixed spacing mode
  17151. $osw = -1000 * $this->font_spacing / $this->FontSize;
  17152. $spacewidthu += $osw;
  17153. }
  17154. $nsmax = $ns;
  17155. $ns = 0;
  17156. reset($lnstring);
  17157. $offset = 0;
  17158. $strcount = 0;
  17159. $prev_epsposbeg = 0;
  17160. $textpos = 0;
  17161. if ($this->isRTLTextDir()) {
  17162. $textpos = $this->wPt;
  17163. }
  17164. while (preg_match('/([0-9\.\+\-]*)[\s](Td|cm|m|l|c|re)[\s]/x', $pmid, $strpiece, PREG_OFFSET_CAPTURE, $offset) == 1) {
  17165. // check if we are inside a string section '[( ... )]'
  17166. $stroffset = strpos($pmid, '[(', $offset);
  17167. if (($stroffset !== false) AND ($stroffset <= $strpiece[2][1])) {
  17168. // set offset to the end of string section
  17169. $offset = strpos($pmid, ')]', $stroffset);
  17170. while (($offset !== false) AND ($pmid[($offset - 1)] == '\\')) {
  17171. $offset = strpos($pmid, ')]', ($offset + 1));
  17172. }
  17173. if ($offset === false) {
  17174. $this->Error('HTML Justification: malformed PDF code.');
  17175. }
  17176. continue;
  17177. }
  17178. if ($this->isRTLTextDir()) {
  17179. $spacew = ($spacewidth * ($nsmax - $ns));
  17180. } else {
  17181. $spacew = ($spacewidth * $ns);
  17182. }
  17183. $offset = $strpiece[2][1] + strlen($strpiece[2][0]);
  17184. $epsposend = strpos($pmid, $this->epsmarker.'Q', $offset);
  17185. if ($epsposend !== null) {
  17186. $epsposend += strlen($this->epsmarker.'Q');
  17187. $epsposbeg = strpos($pmid, 'q'.$this->epsmarker, $offset);
  17188. if ($epsposbeg === null) {
  17189. $epsposbeg = strpos($pmid, 'q'.$this->epsmarker, ($prev_epsposbeg - 6));
  17190. $prev_epsposbeg = $epsposbeg;
  17191. }
  17192. if (($epsposbeg > 0) AND ($epsposend > 0) AND ($offset > $epsposbeg) AND ($offset < $epsposend)) {
  17193. // shift EPS images
  17194. $trx = sprintf('1 0 0 1 %F 0 cm', $spacew);
  17195. $pmid_b = substr($pmid, 0, $epsposbeg);
  17196. $pmid_m = substr($pmid, $epsposbeg, ($epsposend - $epsposbeg));
  17197. $pmid_e = substr($pmid, $epsposend);
  17198. $pmid = $pmid_b."\nq\n".$trx."\n".$pmid_m."\nQ\n".$pmid_e;
  17199. $offset = $epsposend;
  17200. continue;
  17201. }
  17202. }
  17203. $currentxpos = 0;
  17204. // shift blocks of code
  17205. switch ($strpiece[2][0]) {
  17206. case 'Td':
  17207. case 'cm':
  17208. case 'm':
  17209. case 'l': {
  17210. // get current X position
  17211. preg_match('/([0-9\.\+\-]*)[\s]('.$strpiece[1][0].')[\s]('.$strpiece[2][0].')([\s]*)/x', $pmid, $xmatches);
  17212. if (!isset($xmatches[1])) {
  17213. break;
  17214. }
  17215. $currentxpos = $xmatches[1];
  17216. $textpos = $currentxpos;
  17217. if (($strcount <= $maxkk) AND ($strpiece[2][0] == 'Td')) {
  17218. $ns = $lnstring[3][$strcount];
  17219. if ($this->isRTLTextDir()) {
  17220. $spacew = ($spacewidth * ($nsmax - $ns));
  17221. }
  17222. ++$strcount;
  17223. }
  17224. // justify block
  17225. if (preg_match('/([0-9\.\+\-]*)[\s]('.$strpiece[1][0].')[\s]('.$strpiece[2][0].')([\s]*)/x', $pmid, $pmatch) == 1) {
  17226. $newpmid = sprintf('%F',(floatval($pmatch[1]) + $spacew)).' '.$pmatch[2].' x*#!#*x'.$pmatch[3].$pmatch[4];
  17227. $pmid = str_replace($pmatch[0], $newpmid, $pmid);
  17228. unset($pmatch, $newpmid);
  17229. }
  17230. break;
  17231. }
  17232. case 're': {
  17233. // justify block
  17234. if (!TCPDF_STATIC::empty_string($this->lispacer)) {
  17235. $this->lispacer = '';
  17236. break;
  17237. }
  17238. preg_match('/([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]('.$strpiece[1][0].')[\s](re)([\s]*)/x', $pmid, $xmatches);
  17239. if (!isset($xmatches[1])) {
  17240. break;
  17241. }
  17242. $currentxpos = $xmatches[1];
  17243. $x_diff = 0;
  17244. $w_diff = 0;
  17245. if ($this->isRTLTextDir()) { // RTL
  17246. if ($currentxpos < $textpos) {
  17247. $x_diff = ($spacewidth * ($nsmax - $lnstring[3][$strcount]));
  17248. $w_diff = ($spacewidth * $lnstring[2][$strcount]);
  17249. } else {
  17250. if ($strcount > 0) {
  17251. $x_diff = ($spacewidth * ($nsmax - $lnstring[3][($strcount - 1)]));
  17252. $w_diff = ($spacewidth * $lnstring[2][($strcount - 1)]);
  17253. }
  17254. }
  17255. } else { // LTR
  17256. if ($currentxpos > $textpos) {
  17257. if ($strcount > 0) {
  17258. $x_diff = ($spacewidth * $lnstring[3][($strcount - 1)]);
  17259. }
  17260. $w_diff = ($spacewidth * $lnstring[2][$strcount]);
  17261. } else {
  17262. if ($strcount > 1) {
  17263. $x_diff = ($spacewidth * $lnstring[3][($strcount - 2)]);
  17264. }
  17265. if ($strcount > 0) {
  17266. $w_diff = ($spacewidth * $lnstring[2][($strcount - 1)]);
  17267. }
  17268. }
  17269. }
  17270. if (preg_match('/('.$xmatches[1].')[\s]('.$xmatches[2].')[\s]('.$xmatches[3].')[\s]('.$strpiece[1][0].')[\s](re)([\s]*)/x', $pmid, $pmatch) == 1) {
  17271. $newx = sprintf('%F',(floatval($pmatch[1]) + $x_diff));
  17272. $neww = sprintf('%F',(floatval($pmatch[3]) + $w_diff));
  17273. $newpmid = $newx.' '.$pmatch[2].' '.$neww.' '.$pmatch[4].' x*#!#*x'.$pmatch[5].$pmatch[6];
  17274. $pmid = str_replace($pmatch[0], $newpmid, $pmid);
  17275. unset($pmatch, $newpmid, $newx, $neww);
  17276. }
  17277. break;
  17278. }
  17279. case 'c': {
  17280. // get current X position
  17281. 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);
  17282. if (!isset($xmatches[1])) {
  17283. break;
  17284. }
  17285. $currentxpos = $xmatches[1];
  17286. // justify block
  17287. if (preg_match('/('.$xmatches[1].')[\s]('.$xmatches[2].')[\s]('.$xmatches[3].')[\s]('.$xmatches[4].')[\s]('.$xmatches[5].')[\s]('.$strpiece[1][0].')[\s](c)([\s]*)/x', $pmid, $pmatch) == 1) {
  17288. $newx1 = sprintf('%F',(floatval($pmatch[1]) + $spacew));
  17289. $newx2 = sprintf('%F',(floatval($pmatch[3]) + $spacew));
  17290. $newx3 = sprintf('%F',(floatval($pmatch[5]) + $spacew));
  17291. $newpmid = $newx1.' '.$pmatch[2].' '.$newx2.' '.$pmatch[4].' '.$newx3.' '.$pmatch[6].' x*#!#*x'.$pmatch[7].$pmatch[8];
  17292. $pmid = str_replace($pmatch[0], $newpmid, $pmid);
  17293. unset($pmatch, $newpmid, $newx1, $newx2, $newx3);
  17294. }
  17295. break;
  17296. }
  17297. }
  17298. // shift the annotations and links
  17299. $cxpos = ($currentxpos / $this->k);
  17300. $lmpos = ($this->lMargin + $this->cell_padding['L'] + $this->feps);
  17301. if ($this->inxobj) {
  17302. // we are inside an XObject template
  17303. foreach ($this->xobjects[$this->xobjid]['annotations'] as $pak => $pac) {
  17304. if (($pac['y'] >= $minstartliney) AND (($pac['x'] * $this->k) >= ($currentxpos - $this->feps)) AND (($pac['x'] * $this->k) <= ($currentxpos + $this->feps))) {
  17305. if ($cxpos > $lmpos) {
  17306. $this->xobjects[$this->xobjid]['annotations'][$pak]['x'] += ($spacew / $this->k);
  17307. $this->xobjects[$this->xobjid]['annotations'][$pak]['w'] += (($spacewidth * $pac['numspaces']) / $this->k);
  17308. } else {
  17309. $this->xobjects[$this->xobjid]['annotations'][$pak]['w'] += (($spacewidth * $pac['numspaces']) / $this->k);
  17310. }
  17311. break;
  17312. }
  17313. }
  17314. } elseif (isset($this->PageAnnots[$this->page])) {
  17315. foreach ($this->PageAnnots[$this->page] as $pak => $pac) {
  17316. if (($pac['y'] >= $minstartliney) AND (($pac['x'] * $this->k) >= ($currentxpos - $this->feps)) AND (($pac['x'] * $this->k) <= ($currentxpos + $this->feps))) {
  17317. if ($cxpos > $lmpos) {
  17318. $this->PageAnnots[$this->page][$pak]['x'] += ($spacew / $this->k);
  17319. $this->PageAnnots[$this->page][$pak]['w'] += (($spacewidth * $pac['numspaces']) / $this->k);
  17320. } else {
  17321. $this->PageAnnots[$this->page][$pak]['w'] += (($spacewidth * $pac['numspaces']) / $this->k);
  17322. }
  17323. break;
  17324. }
  17325. }
  17326. }
  17327. } // end of while
  17328. // remove markers
  17329. $pmid = str_replace('x*#!#*x', '', $pmid);
  17330. if ($this->isUnicodeFont()) {
  17331. // multibyte characters
  17332. $spacew = $spacewidthu;
  17333. if ($this->font_stretching != 100) {
  17334. // word spacing is affected by stretching
  17335. $spacew /= ($this->font_stretching / 100);
  17336. }
  17337. // escape special characters
  17338. $pos = 0;
  17339. $pmid = preg_replace('/[\\\][\(]/x', '\\#!#OP#!#', $pmid);
  17340. $pmid = preg_replace('/[\\\][\)]/x', '\\#!#CP#!#', $pmid);
  17341. if (preg_match_all('/\[\(([^\)]*)\)\]/x', $pmid, $pamatch) > 0) {
  17342. foreach($pamatch[0] as $pk => $pmatch) {
  17343. $replace = $pamatch[1][$pk];
  17344. $replace = str_replace('#!#OP#!#', '(', $replace);
  17345. $replace = str_replace('#!#CP#!#', ')', $replace);
  17346. $newpmid = '[('.str_replace(chr(0).chr(32), ') '.sprintf('%F', $spacew).' (', $replace).')]';
  17347. $pos = strpos($pmid, $pmatch, $pos);
  17348. if ($pos !== FALSE) {
  17349. $pmid = substr_replace($pmid, $newpmid, $pos, strlen($pmatch));
  17350. }
  17351. ++$pos;
  17352. }
  17353. unset($pamatch);
  17354. }
  17355. if ($this->inxobj) {
  17356. // we are inside an XObject template
  17357. $this->xobjects[$this->xobjid]['outdata'] = $pstart."\n".$pmid."\n".$pend;
  17358. } else {
  17359. $this->setPageBuffer($startlinepage, $pstart."\n".$pmid."\n".$pend);
  17360. }
  17361. $endlinepos = strlen($pstart."\n".$pmid."\n");
  17362. } else {
  17363. // non-unicode (single-byte characters)
  17364. if ($this->font_stretching != 100) {
  17365. // word spacing (Tw) is affected by stretching
  17366. $spacewidth /= ($this->font_stretching / 100);
  17367. }
  17368. $rs = sprintf('%F Tw', $spacewidth);
  17369. $pmid = preg_replace("/\[\(/x", $rs.' [(', $pmid);
  17370. if ($this->inxobj) {
  17371. // we are inside an XObject template
  17372. $this->xobjects[$this->xobjid]['outdata'] = $pstart."\n".$pmid."\nBT 0 Tw ET\n".$pend;
  17373. } else {
  17374. $this->setPageBuffer($startlinepage, $pstart."\n".$pmid."\nBT 0 Tw ET\n".$pend);
  17375. }
  17376. $endlinepos = strlen($pstart."\n".$pmid."\nBT 0 Tw ET\n");
  17377. }
  17378. }
  17379. } // end of J
  17380. } // end if $startlinex
  17381. if (($t_x != 0) OR ($yshift < 0)) {
  17382. // shift the line
  17383. $trx = sprintf('1 0 0 1 %F %F cm', ($t_x * $this->k), ($yshift * $this->k));
  17384. $pstart .= "\nq\n".$trx."\n".$pmid."\nQ\n";
  17385. $endlinepos = strlen($pstart);
  17386. if ($this->inxobj) {
  17387. // we are inside an XObject template
  17388. $this->xobjects[$this->xobjid]['outdata'] = $pstart.$pend;
  17389. foreach ($this->xobjects[$this->xobjid]['annotations'] as $pak => $pac) {
  17390. if ($pak >= $pask) {
  17391. $this->xobjects[$this->xobjid]['annotations'][$pak]['x'] += $t_x;
  17392. $this->xobjects[$this->xobjid]['annotations'][$pak]['y'] -= $yshift;
  17393. }
  17394. }
  17395. } else {
  17396. $this->setPageBuffer($startlinepage, $pstart.$pend);
  17397. // shift the annotations and links
  17398. if (isset($this->PageAnnots[$this->page])) {
  17399. foreach ($this->PageAnnots[$this->page] as $pak => $pac) {
  17400. if ($pak >= $pask) {
  17401. $this->PageAnnots[$this->page][$pak]['x'] += $t_x;
  17402. $this->PageAnnots[$this->page][$pak]['y'] -= $yshift;
  17403. }
  17404. }
  17405. }
  17406. }
  17407. $this->y -= $yshift;
  17408. }
  17409. }
  17410. $pbrk = $this->checkPageBreak($this->lasth);
  17411. $this->newline = false;
  17412. $startlinex = $this->x;
  17413. $startliney = $this->y;
  17414. if ($dom[$dom[$key]['parent']]['value'] == 'sup') {
  17415. $startliney -= ((0.3 * $this->FontSizePt) / $this->k);
  17416. } elseif ($dom[$dom[$key]['parent']]['value'] == 'sub') {
  17417. $startliney -= (($this->FontSizePt / 0.7) / $this->k);
  17418. } else {
  17419. $minstartliney = $startliney;
  17420. $maxbottomliney = ($this->y + $this->getCellHeight($fontsize / $this->k));
  17421. }
  17422. $startlinepage = $this->page;
  17423. if (isset($endlinepos) AND (!$pbrk)) {
  17424. $startlinepos = $endlinepos;
  17425. } else {
  17426. if ($this->inxobj) {
  17427. // we are inside an XObject template
  17428. $startlinepos = strlen($this->xobjects[$this->xobjid]['outdata']);
  17429. } elseif (!$this->InFooter) {
  17430. if (isset($this->footerlen[$this->page])) {
  17431. $this->footerpos[$this->page] = $this->pagelen[$this->page] - $this->footerlen[$this->page];
  17432. } else {
  17433. $this->footerpos[$this->page] = $this->pagelen[$this->page];
  17434. }
  17435. $startlinepos = $this->footerpos[$this->page];
  17436. } else {
  17437. $startlinepos = $this->pagelen[$this->page];
  17438. }
  17439. }
  17440. unset($endlinepos);
  17441. $plalign = $lalign;
  17442. if (isset($this->PageAnnots[$this->page])) {
  17443. $pask = count($this->PageAnnots[$this->page]);
  17444. } else {
  17445. $pask = 0;
  17446. }
  17447. if (!($dom[$key]['tag'] AND !$dom[$key]['opening'] AND ($dom[$key]['value'] == 'table')
  17448. AND (isset($this->emptypagemrk[$this->page]))
  17449. AND ($this->emptypagemrk[$this->page] == $this->pagelen[$this->page]))) {
  17450. $this->SetFont($fontname, $fontstyle, $fontsize);
  17451. if ($wfill) {
  17452. $this->SetFillColorArray($this->bgcolor);
  17453. }
  17454. }
  17455. } // end newline
  17456. if (isset($opentagpos)) {
  17457. unset($opentagpos);
  17458. }
  17459. if ($dom[$key]['tag']) {
  17460. if ($dom[$key]['opening']) {
  17461. // get text indentation (if any)
  17462. if (isset($dom[$key]['text-indent']) AND $dom[$key]['block']) {
  17463. $this->textindent = $dom[$key]['text-indent'];
  17464. $this->newline = true;
  17465. }
  17466. // table
  17467. if (($dom[$key]['value'] == 'table') AND isset($dom[$key]['cols']) AND ($dom[$key]['cols'] > 0)) {
  17468. // available page width
  17469. if ($this->rtl) {
  17470. $wtmp = $this->x - $this->lMargin;
  17471. } else {
  17472. $wtmp = $this->w - $this->rMargin - $this->x;
  17473. }
  17474. // get cell spacing
  17475. if (isset($dom[$key]['attribute']['cellspacing'])) {
  17476. $clsp = $this->getHTMLUnitToUnits($dom[$key]['attribute']['cellspacing'], 1, 'px');
  17477. $cellspacing = array('H' => $clsp, 'V' => $clsp);
  17478. } elseif (isset($dom[$key]['border-spacing'])) {
  17479. $cellspacing = $dom[$key]['border-spacing'];
  17480. } else {
  17481. $cellspacing = array('H' => 0, 'V' => 0);
  17482. }
  17483. // table width
  17484. if (isset($dom[$key]['width'])) {
  17485. $table_width = $this->getHTMLUnitToUnits($dom[$key]['width'], $wtmp, 'px');
  17486. } else {
  17487. $table_width = $wtmp;
  17488. }
  17489. $table_width -= (2 * $cellspacing['H']);
  17490. if (!$this->inthead) {
  17491. $this->y += $cellspacing['V'];
  17492. }
  17493. if ($this->rtl) {
  17494. $cellspacingx = -$cellspacing['H'];
  17495. } else {
  17496. $cellspacingx = $cellspacing['H'];
  17497. }
  17498. // total table width without cellspaces
  17499. $table_columns_width = ($table_width - ($cellspacing['H'] * ($dom[$key]['cols'] - 1)));
  17500. // minimum column width
  17501. $table_min_column_width = ($table_columns_width / $dom[$key]['cols']);
  17502. // array of custom column widths
  17503. $table_colwidths = array_fill(0, $dom[$key]['cols'], $table_min_column_width);
  17504. }
  17505. // table row
  17506. if ($dom[$key]['value'] == 'tr') {
  17507. // reset column counter
  17508. $colid = 0;
  17509. }
  17510. // table cell
  17511. if (($dom[$key]['value'] == 'td') OR ($dom[$key]['value'] == 'th')) {
  17512. $trid = $dom[$key]['parent'];
  17513. $table_el = $dom[$trid]['parent'];
  17514. if (!isset($dom[$table_el]['cols'])) {
  17515. $dom[$table_el]['cols'] = $dom[$trid]['cols'];
  17516. }
  17517. // store border info
  17518. $tdborder = 0;
  17519. if (isset($dom[$key]['border']) AND !empty($dom[$key]['border'])) {
  17520. $tdborder = $dom[$key]['border'];
  17521. }
  17522. $colspan = intval($dom[$key]['attribute']['colspan']);
  17523. if ($colspan <= 0) {
  17524. $colspan = 1;
  17525. }
  17526. $old_cell_padding = $this->cell_padding;
  17527. if (isset($dom[($dom[$trid]['parent'])]['attribute']['cellpadding'])) {
  17528. $crclpd = $this->getHTMLUnitToUnits($dom[($dom[$trid]['parent'])]['attribute']['cellpadding'], 1, 'px');
  17529. $current_cell_padding = array('L' => $crclpd, 'T' => $crclpd, 'R' => $crclpd, 'B' => $crclpd);
  17530. } elseif (isset($dom[($dom[$trid]['parent'])]['padding'])) {
  17531. $current_cell_padding = $dom[($dom[$trid]['parent'])]['padding'];
  17532. } else {
  17533. $current_cell_padding = array('L' => 0, 'T' => 0, 'R' => 0, 'B' => 0);
  17534. }
  17535. $this->cell_padding = $current_cell_padding;
  17536. if (isset($dom[$key]['height'])) {
  17537. // minimum cell height
  17538. $cellh = $this->getHTMLUnitToUnits($dom[$key]['height'], 0, 'px');
  17539. } else {
  17540. $cellh = 0;
  17541. }
  17542. if (isset($dom[$key]['content'])) {
  17543. $cell_content = $dom[$key]['content'];
  17544. } else {
  17545. $cell_content = '&nbsp;';
  17546. }
  17547. $tagtype = $dom[$key]['value'];
  17548. $parentid = $key;
  17549. while (($key < $maxel) AND (!(($dom[$key]['tag']) AND (!$dom[$key]['opening']) AND ($dom[$key]['value'] == $tagtype) AND ($dom[$key]['parent'] == $parentid)))) {
  17550. // move $key index forward
  17551. ++$key;
  17552. }
  17553. if (!isset($dom[$trid]['startpage'])) {
  17554. $dom[$trid]['startpage'] = $this->page;
  17555. } else {
  17556. $this->setPage($dom[$trid]['startpage']);
  17557. }
  17558. if (!isset($dom[$trid]['startcolumn'])) {
  17559. $dom[$trid]['startcolumn'] = $this->current_column;
  17560. } elseif ($this->current_column != $dom[$trid]['startcolumn']) {
  17561. $tmpx = $this->x;
  17562. $this->selectColumn($dom[$trid]['startcolumn']);
  17563. $this->x = $tmpx;
  17564. }
  17565. if (!isset($dom[$trid]['starty'])) {
  17566. $dom[$trid]['starty'] = $this->y;
  17567. } else {
  17568. $this->y = $dom[$trid]['starty'];
  17569. }
  17570. if (!isset($dom[$trid]['startx'])) {
  17571. $dom[$trid]['startx'] = $this->x;
  17572. $this->x += $cellspacingx;
  17573. } else {
  17574. $this->x += ($cellspacingx / 2);
  17575. }
  17576. if (isset($dom[$parentid]['attribute']['rowspan'])) {
  17577. $rowspan = intval($dom[$parentid]['attribute']['rowspan']);
  17578. } else {
  17579. $rowspan = 1;
  17580. }
  17581. // skip row-spanned cells started on the previous rows
  17582. if (isset($dom[$table_el]['rowspans'])) {
  17583. $rsk = 0;
  17584. $rskmax = count($dom[$table_el]['rowspans']);
  17585. while ($rsk < $rskmax) {
  17586. $trwsp = $dom[$table_el]['rowspans'][$rsk];
  17587. $rsstartx = $trwsp['startx'];
  17588. $rsendx = $trwsp['endx'];
  17589. // account for margin changes
  17590. if ($trwsp['startpage'] < $this->page) {
  17591. if (($this->rtl) AND ($this->pagedim[$this->page]['orm'] != $this->pagedim[$trwsp['startpage']]['orm'])) {
  17592. $dl = ($this->pagedim[$this->page]['orm'] - $this->pagedim[$trwsp['startpage']]['orm']);
  17593. $rsstartx -= $dl;
  17594. $rsendx -= $dl;
  17595. } elseif ((!$this->rtl) AND ($this->pagedim[$this->page]['olm'] != $this->pagedim[$trwsp['startpage']]['olm'])) {
  17596. $dl = ($this->pagedim[$this->page]['olm'] - $this->pagedim[$trwsp['startpage']]['olm']);
  17597. $rsstartx += $dl;
  17598. $rsendx += $dl;
  17599. }
  17600. }
  17601. if (($trwsp['rowspan'] > 0)
  17602. AND ($rsstartx > ($this->x - $cellspacing['H'] - $current_cell_padding['L'] - $this->feps))
  17603. AND ($rsstartx < ($this->x + $cellspacing['H'] + $current_cell_padding['R'] + $this->feps))
  17604. AND (($trwsp['starty'] < ($this->y - $this->feps)) OR ($trwsp['startpage'] < $this->page) OR ($trwsp['startcolumn'] < $this->current_column))) {
  17605. // set the starting X position of the current cell
  17606. $this->x = $rsendx + $cellspacingx;
  17607. // increment column indicator
  17608. $colid += $trwsp['colspan'];
  17609. if (($trwsp['rowspan'] == 1)
  17610. AND (isset($dom[$trid]['endy']))
  17611. AND (isset($dom[$trid]['endpage']))
  17612. AND (isset($dom[$trid]['endcolumn']))
  17613. AND ($trwsp['endpage'] == $dom[$trid]['endpage'])
  17614. AND ($trwsp['endcolumn'] == $dom[$trid]['endcolumn'])) {
  17615. // set ending Y position for row
  17616. $dom[$table_el]['rowspans'][$rsk]['endy'] = max($dom[$trid]['endy'], $trwsp['endy']);
  17617. $dom[$trid]['endy'] = $dom[$table_el]['rowspans'][$rsk]['endy'];
  17618. }
  17619. $rsk = 0;
  17620. } else {
  17621. ++$rsk;
  17622. }
  17623. }
  17624. }
  17625. if (isset($dom[$parentid]['width'])) {
  17626. // user specified width
  17627. $cellw = $this->getHTMLUnitToUnits($dom[$parentid]['width'], $table_columns_width, 'px');
  17628. $tmpcw = ($cellw / $colspan);
  17629. for ($i = 0; $i < $colspan; ++$i) {
  17630. $table_colwidths[($colid + $i)] = $tmpcw;
  17631. }
  17632. } else {
  17633. // inherit column width
  17634. $cellw = 0;
  17635. for ($i = 0; $i < $colspan; ++$i) {
  17636. $cellw += (isset($table_colwidths[($colid + $i)]) ? $table_colwidths[($colid + $i)] : 0);
  17637. }
  17638. }
  17639. $cellw += (($colspan - 1) * $cellspacing['H']);
  17640. // increment column indicator
  17641. $colid += $colspan;
  17642. // add rowspan information to table element
  17643. if ($rowspan > 1) {
  17644. $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));
  17645. }
  17646. $cellid = array_push($dom[$trid]['cellpos'], array('startx' => $this->x));
  17647. if ($rowspan > 1) {
  17648. $dom[$trid]['cellpos'][($cellid - 1)]['rowspanid'] = ($trsid - 1);
  17649. }
  17650. // push background colors
  17651. if (isset($dom[$parentid]['bgcolor']) AND ($dom[$parentid]['bgcolor'] !== false)) {
  17652. $dom[$trid]['cellpos'][($cellid - 1)]['bgcolor'] = $dom[$parentid]['bgcolor'];
  17653. }
  17654. // store border info
  17655. if (isset($tdborder) AND !empty($tdborder)) {
  17656. $dom[$trid]['cellpos'][($cellid - 1)]['border'] = $tdborder;
  17657. }
  17658. $prevLastH = $this->lasth;
  17659. // store some info for multicolumn mode
  17660. if ($this->rtl) {
  17661. $this->colxshift['x'] = $this->w - $this->x - $this->rMargin;
  17662. } else {
  17663. $this->colxshift['x'] = $this->x - $this->lMargin;
  17664. }
  17665. $this->colxshift['s'] = $cellspacing;
  17666. $this->colxshift['p'] = $current_cell_padding;
  17667. // ****** write the cell content ******
  17668. $this->MultiCell($cellw, $cellh, $cell_content, false, $lalign, false, 2, '', '', true, 0, true, true, 0, 'T', false);
  17669. // restore some values
  17670. $this->colxshift = array('x' => 0, 's' => array('H' => 0, 'V' => 0), 'p' => array('L' => 0, 'T' => 0, 'R' => 0, 'B' => 0));
  17671. $this->lasth = $prevLastH;
  17672. $this->cell_padding = $old_cell_padding;
  17673. $dom[$trid]['cellpos'][($cellid - 1)]['endx'] = $this->x;
  17674. // update the end of row position
  17675. if ($rowspan <= 1) {
  17676. if (isset($dom[$trid]['endy'])) {
  17677. if (($this->page == $dom[$trid]['endpage']) AND ($this->current_column == $dom[$trid]['endcolumn'])) {
  17678. $dom[$trid]['endy'] = max($this->y, $dom[$trid]['endy']);
  17679. } elseif (($this->page > $dom[$trid]['endpage']) OR ($this->current_column > $dom[$trid]['endcolumn'])) {
  17680. $dom[$trid]['endy'] = $this->y;
  17681. }
  17682. } else {
  17683. $dom[$trid]['endy'] = $this->y;
  17684. }
  17685. if (isset($dom[$trid]['endpage'])) {
  17686. $dom[$trid]['endpage'] = max($this->page, $dom[$trid]['endpage']);
  17687. } else {
  17688. $dom[$trid]['endpage'] = $this->page;
  17689. }
  17690. if (isset($dom[$trid]['endcolumn'])) {
  17691. $dom[$trid]['endcolumn'] = max($this->current_column, $dom[$trid]['endcolumn']);
  17692. } else {
  17693. $dom[$trid]['endcolumn'] = $this->current_column;
  17694. }
  17695. } else {
  17696. // account for row-spanned cells
  17697. $dom[$table_el]['rowspans'][($trsid - 1)]['endx'] = $this->x;
  17698. $dom[$table_el]['rowspans'][($trsid - 1)]['endy'] = $this->y;
  17699. $dom[$table_el]['rowspans'][($trsid - 1)]['endpage'] = $this->page;
  17700. $dom[$table_el]['rowspans'][($trsid - 1)]['endcolumn'] = $this->current_column;
  17701. }
  17702. if (isset($dom[$table_el]['rowspans'])) {
  17703. // update endy and endpage on rowspanned cells
  17704. foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
  17705. if ($trwsp['rowspan'] > 0) {
  17706. if (isset($dom[$trid]['endpage'])) {
  17707. if (($trwsp['endpage'] == $dom[$trid]['endpage']) AND ($trwsp['endcolumn'] == $dom[$trid]['endcolumn'])) {
  17708. $dom[$table_el]['rowspans'][$k]['endy'] = max($dom[$trid]['endy'], $trwsp['endy']);
  17709. } elseif (($trwsp['endpage'] < $dom[$trid]['endpage']) OR ($trwsp['endcolumn'] < $dom[$trid]['endcolumn'])) {
  17710. $dom[$table_el]['rowspans'][$k]['endy'] = $dom[$trid]['endy'];
  17711. $dom[$table_el]['rowspans'][$k]['endpage'] = $dom[$trid]['endpage'];
  17712. $dom[$table_el]['rowspans'][$k]['endcolumn'] = $dom[$trid]['endcolumn'];
  17713. } else {
  17714. $dom[$trid]['endy'] = $this->pagedim[$dom[$trid]['endpage']]['hk'] - $this->pagedim[$dom[$trid]['endpage']]['bm'];
  17715. }
  17716. }
  17717. }
  17718. }
  17719. }
  17720. $this->x += ($cellspacingx / 2);
  17721. } else {
  17722. // opening tag (or self-closing tag)
  17723. if (!isset($opentagpos)) {
  17724. if ($this->inxobj) {
  17725. // we are inside an XObject template
  17726. $opentagpos = strlen($this->xobjects[$this->xobjid]['outdata']);
  17727. } elseif (!$this->InFooter) {
  17728. if (isset($this->footerlen[$this->page])) {
  17729. $this->footerpos[$this->page] = $this->pagelen[$this->page] - $this->footerlen[$this->page];
  17730. } else {
  17731. $this->footerpos[$this->page] = $this->pagelen[$this->page];
  17732. }
  17733. $opentagpos = $this->footerpos[$this->page];
  17734. }
  17735. }
  17736. $dom = $this->openHTMLTagHandler($dom, $key, $cell);
  17737. }
  17738. } else { // closing tag
  17739. $prev_numpages = $this->numpages;
  17740. $old_bordermrk = $this->bordermrk[$this->page];
  17741. $dom = $this->closeHTMLTagHandler($dom, $key, $cell, $maxbottomliney);
  17742. if ($this->bordermrk[$this->page] > $old_bordermrk) {
  17743. $startlinepos += ($this->bordermrk[$this->page] - $old_bordermrk);
  17744. }
  17745. if ($prev_numpages > $this->numpages) {
  17746. $startlinepage = $this->page;
  17747. }
  17748. }
  17749. } elseif (strlen($dom[$key]['value']) > 0) {
  17750. // print list-item
  17751. if (!TCPDF_STATIC::empty_string($this->lispacer) AND ($this->lispacer != '^')) {
  17752. $this->SetFont($pfontname, $pfontstyle, $pfontsize);
  17753. $this->resetLastH();
  17754. $minstartliney = $this->y;
  17755. $maxbottomliney = ($startliney + $this->getCellHeight($this->FontSize));
  17756. if (is_numeric($pfontsize) AND ($pfontsize > 0)) {
  17757. $this->putHtmlListBullet($this->listnum, $this->lispacer, $pfontsize);
  17758. }
  17759. $this->SetFont($curfontname, $curfontstyle, $curfontsize);
  17760. $this->resetLastH();
  17761. if (is_numeric($pfontsize) AND ($pfontsize > 0) AND is_numeric($curfontsize) AND ($curfontsize > 0) AND ($pfontsize != $curfontsize)) {
  17762. $pfontascent = $this->getFontAscent($pfontname, $pfontstyle, $pfontsize);
  17763. $pfontdescent = $this->getFontDescent($pfontname, $pfontstyle, $pfontsize);
  17764. $this->y += ($this->getCellHeight(($pfontsize - $curfontsize) / $this->k) + $pfontascent - $curfontascent - $pfontdescent + $curfontdescent) / 2;
  17765. $minstartliney = min($this->y, $minstartliney);
  17766. $maxbottomliney = max(($this->y + $this->getCellHeight($pfontsize / $this->k)), $maxbottomliney);
  17767. }
  17768. }
  17769. // text
  17770. $this->htmlvspace = 0;
  17771. $isRTLString = preg_match(TCPDF_FONT_DATA::$uni_RE_PATTERN_RTL, $dom[$key]['value']) || preg_match(TCPDF_FONT_DATA::$uni_RE_PATTERN_ARABIC, $dom[$key]['value']);
  17772. if ((!$this->premode) AND $this->isRTLTextDir() AND !$isRTLString) {
  17773. // reverse spaces order
  17774. $lsp = ''; // left spaces
  17775. $rsp = ''; // right spaces
  17776. if (preg_match('/^('.$this->re_space['p'].'+)/'.$this->re_space['m'], $dom[$key]['value'], $matches)) {
  17777. $lsp = $matches[1];
  17778. }
  17779. if (preg_match('/('.$this->re_space['p'].'+)$/'.$this->re_space['m'], $dom[$key]['value'], $matches)) {
  17780. $rsp = $matches[1];
  17781. }
  17782. $dom[$key]['value'] = $rsp.$this->stringTrim($dom[$key]['value']).$lsp;
  17783. }
  17784. if ($newline) {
  17785. if (!$this->premode) {
  17786. $prelen = strlen($dom[$key]['value']);
  17787. if ($this->isRTLTextDir() AND !$isRTLString) {
  17788. // right trim except non-breaking space
  17789. $dom[$key]['value'] = $this->stringRightTrim($dom[$key]['value']);
  17790. } else {
  17791. // left trim except non-breaking space
  17792. $dom[$key]['value'] = $this->stringLeftTrim($dom[$key]['value']);
  17793. }
  17794. $postlen = strlen($dom[$key]['value']);
  17795. if (($postlen == 0) AND ($prelen > 0)) {
  17796. $dom[$key]['trimmed_space'] = true;
  17797. }
  17798. }
  17799. $newline = false;
  17800. $firstblock = true;
  17801. } else {
  17802. $firstblock = false;
  17803. // replace empty multiple spaces string with a single space
  17804. $dom[$key]['value'] = preg_replace('/^'.$this->re_space['p'].'+$/'.$this->re_space['m'], chr(32), $dom[$key]['value']);
  17805. }
  17806. $strrest = '';
  17807. if ($this->rtl) {
  17808. $this->x -= $this->textindent;
  17809. } else {
  17810. $this->x += $this->textindent;
  17811. }
  17812. if (!isset($dom[$key]['trimmed_space']) OR !$dom[$key]['trimmed_space']) {
  17813. $strlinelen = $this->GetStringWidth($dom[$key]['value']);
  17814. if (!empty($this->HREF) AND (isset($this->HREF['url']))) {
  17815. // HTML <a> Link
  17816. $hrefcolor = '';
  17817. if (isset($dom[($dom[$key]['parent'])]['fgcolor']) AND ($dom[($dom[$key]['parent'])]['fgcolor'] !== false)) {
  17818. $hrefcolor = $dom[($dom[$key]['parent'])]['fgcolor'];
  17819. }
  17820. $hrefstyle = -1;
  17821. if (isset($dom[($dom[$key]['parent'])]['fontstyle']) AND ($dom[($dom[$key]['parent'])]['fontstyle'] !== false)) {
  17822. $hrefstyle = $dom[($dom[$key]['parent'])]['fontstyle'];
  17823. }
  17824. $strrest = $this->addHtmlLink($this->HREF['url'], $dom[$key]['value'], $wfill, true, $hrefcolor, $hrefstyle, true);
  17825. } else {
  17826. $wadj = 0; // space to leave for block continuity
  17827. if ($this->rtl) {
  17828. $cwa = ($this->x - $this->lMargin);
  17829. } else {
  17830. $cwa = ($this->w - $this->rMargin - $this->x);
  17831. }
  17832. if (($strlinelen < $cwa) AND (isset($dom[($key + 1)])) AND ($dom[($key + 1)]['tag']) AND (!$dom[($key + 1)]['block'])) {
  17833. // check the next text blocks for continuity
  17834. $nkey = ($key + 1);
  17835. $write_block = true;
  17836. $same_textdir = true;
  17837. $tmp_fontname = $this->FontFamily;
  17838. $tmp_fontstyle = $this->FontStyle;
  17839. $tmp_fontsize = $this->FontSizePt;
  17840. while ($write_block AND isset($dom[$nkey])) {
  17841. if ($dom[$nkey]['tag']) {
  17842. if ($dom[$nkey]['block']) {
  17843. // end of block
  17844. $write_block = false;
  17845. }
  17846. $tmp_fontname = isset($dom[$nkey]['fontname']) ? $dom[$nkey]['fontname'] : $this->FontFamily;
  17847. $tmp_fontstyle = isset($dom[$nkey]['fontstyle']) ? $dom[$nkey]['fontstyle'] : $this->FontStyle;
  17848. $tmp_fontsize = isset($dom[$nkey]['fontsize']) ? $dom[$nkey]['fontsize'] : $this->FontSizePt;
  17849. $same_textdir = ($dom[$nkey]['dir'] == $dom[$key]['dir']);
  17850. } else {
  17851. $nextstr = TCPDF_STATIC::pregSplit('/'.$this->re_space['p'].'+/', $this->re_space['m'], $dom[$nkey]['value']);
  17852. if (isset($nextstr[0]) AND $same_textdir) {
  17853. $wadj += $this->GetStringWidth($nextstr[0], $tmp_fontname, $tmp_fontstyle, $tmp_fontsize);
  17854. if (isset($nextstr[1])) {
  17855. $write_block = false;
  17856. }
  17857. }
  17858. }
  17859. ++$nkey;
  17860. }
  17861. }
  17862. if (($wadj > 0) AND (($strlinelen + $wadj) >= $cwa)) {
  17863. $wadj = 0;
  17864. $nextstr = TCPDF_STATIC::pregSplit('/'.$this->re_space['p'].'/', $this->re_space['m'], $dom[$key]['value']);
  17865. $numblks = count($nextstr);
  17866. if ($numblks > 1) {
  17867. // try to split on blank spaces
  17868. $wadj = ($cwa - $strlinelen + $this->GetStringWidth($nextstr[($numblks - 1)]));
  17869. } else {
  17870. // set the entire block on new line
  17871. $wadj = $this->GetStringWidth($nextstr[0]);
  17872. }
  17873. }
  17874. // check for reversed text direction
  17875. if (($wadj > 0) AND (($this->rtl AND ($this->tmprtl === 'L')) OR (!$this->rtl AND ($this->tmprtl === 'R')))) {
  17876. // LTR text on RTL direction or RTL text on LTR direction
  17877. $reverse_dir = true;
  17878. $this->rtl = !$this->rtl;
  17879. $revshift = ($strlinelen + $wadj + 0.000001); // add little quantity for rounding problems
  17880. if ($this->rtl) {
  17881. $this->x += $revshift;
  17882. } else {
  17883. $this->x -= $revshift;
  17884. }
  17885. $xws = $this->x;
  17886. }
  17887. // ****** write only until the end of the line and get the rest ******
  17888. $strrest = $this->Write($this->lasth, $dom[$key]['value'], '', $wfill, '', false, 0, true, $firstblock, 0, $wadj);
  17889. // restore default direction
  17890. if ($reverse_dir AND ($wadj == 0)) {
  17891. $this->x = $xws;
  17892. $this->rtl = !$this->rtl;
  17893. $reverse_dir = false;
  17894. }
  17895. }
  17896. }
  17897. $this->textindent = 0;
  17898. if (strlen($strrest) > 0) {
  17899. // store the remaining string on the previous $key position
  17900. $this->newline = true;
  17901. if ($strrest == $dom[$key]['value']) {
  17902. // used to avoid infinite loop
  17903. ++$loop;
  17904. } else {
  17905. $loop = 0;
  17906. }
  17907. $dom[$key]['value'] = $strrest;
  17908. if ($cell) {
  17909. if ($this->rtl) {
  17910. $this->x -= $this->cell_padding['R'];
  17911. } else {
  17912. $this->x += $this->cell_padding['L'];
  17913. }
  17914. }
  17915. if ($loop < 3) {
  17916. --$key;
  17917. }
  17918. } else {
  17919. $loop = 0;
  17920. // add the positive font spacing of the last character (if any)
  17921. if ($this->font_spacing > 0) {
  17922. if ($this->rtl) {
  17923. $this->x -= $this->font_spacing;
  17924. } else {
  17925. $this->x += $this->font_spacing;
  17926. }
  17927. }
  17928. }
  17929. }
  17930. ++$key;
  17931. 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')) {
  17932. // check if we are on a new page or on a new column
  17933. if ((!$undo) AND (($this->y < $this->start_transaction_y) OR (($dom[$key]['value'] == 'tr') AND ($dom[($dom[$key]['parent'])]['endy'] < $this->start_transaction_y)))) {
  17934. // we are on a new page or on a new column and the total object height is less than the available vertical space.
  17935. // restore previous object
  17936. $this->rollbackTransaction(true);
  17937. // restore previous values
  17938. foreach ($this_method_vars as $vkey => $vval) {
  17939. $$vkey = $vval;
  17940. }
  17941. if (!empty($dom[$key]['thead'])) {
  17942. $this->inthead = true;
  17943. }
  17944. // add a page (or trig AcceptPageBreak() for multicolumn mode)
  17945. $pre_y = $this->y;
  17946. if ((!$this->checkPageBreak($this->PageBreakTrigger + 1)) AND ($this->y < $pre_y)) {
  17947. $startliney = $this->y;
  17948. }
  17949. $undo = true; // avoid infinite loop
  17950. } else {
  17951. $undo = false;
  17952. }
  17953. }
  17954. } // end for each $key
  17955. // align the last line
  17956. if (isset($startlinex)) {
  17957. $yshift = ($minstartliney - $startliney);
  17958. if (($yshift > 0) OR ($this->page > $startlinepage)) {
  17959. $yshift = 0;
  17960. }
  17961. $t_x = 0;
  17962. // the last line must be shifted to be aligned as requested
  17963. $linew = abs($this->endlinex - $startlinex);
  17964. if ($this->inxobj) {
  17965. // we are inside an XObject template
  17966. $pstart = substr($this->xobjects[$this->xobjid]['outdata'], 0, $startlinepos);
  17967. if (isset($opentagpos)) {
  17968. $midpos = $opentagpos;
  17969. } else {
  17970. $midpos = 0;
  17971. }
  17972. if ($midpos > 0) {
  17973. $pmid = substr($this->xobjects[$this->xobjid]['outdata'], $startlinepos, ($midpos - $startlinepos));
  17974. $pend = substr($this->xobjects[$this->xobjid]['outdata'], $midpos);
  17975. } else {
  17976. $pmid = substr($this->xobjects[$this->xobjid]['outdata'], $startlinepos);
  17977. $pend = '';
  17978. }
  17979. } else {
  17980. $pstart = substr($this->getPageBuffer($startlinepage), 0, $startlinepos);
  17981. if (isset($opentagpos) AND isset($this->footerlen[$startlinepage]) AND (!$this->InFooter)) {
  17982. $this->footerpos[$startlinepage] = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
  17983. $midpos = min($opentagpos, $this->footerpos[$startlinepage]);
  17984. } elseif (isset($opentagpos)) {
  17985. $midpos = $opentagpos;
  17986. } elseif (isset($this->footerlen[$startlinepage]) AND (!$this->InFooter)) {
  17987. $this->footerpos[$startlinepage] = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
  17988. $midpos = $this->footerpos[$startlinepage];
  17989. } else {
  17990. $midpos = 0;
  17991. }
  17992. if ($midpos > 0) {
  17993. $pmid = substr($this->getPageBuffer($startlinepage), $startlinepos, ($midpos - $startlinepos));
  17994. $pend = substr($this->getPageBuffer($startlinepage), $midpos);
  17995. } else {
  17996. $pmid = substr($this->getPageBuffer($startlinepage), $startlinepos);
  17997. $pend = '';
  17998. }
  17999. }
  18000. if ((isset($plalign) AND ((($plalign == 'C') OR (($plalign == 'R') AND (!$this->rtl)) OR (($plalign == 'L') AND ($this->rtl)))))) {
  18001. // calculate shifting amount
  18002. $tw = $w;
  18003. if ($this->lMargin != $prevlMargin) {
  18004. $tw += ($prevlMargin - $this->lMargin);
  18005. }
  18006. if ($this->rMargin != $prevrMargin) {
  18007. $tw += ($prevrMargin - $this->rMargin);
  18008. }
  18009. $one_space_width = $this->GetStringWidth(chr(32));
  18010. $no = 0; // number of spaces on a line contained on a single block
  18011. if ($this->isRTLTextDir()) { // RTL
  18012. // remove left space if exist
  18013. $pos1 = TCPDF_STATIC::revstrpos($pmid, '[(');
  18014. if ($pos1 > 0) {
  18015. $pos1 = intval($pos1);
  18016. if ($this->isUnicodeFont()) {
  18017. $pos2 = intval(TCPDF_STATIC::revstrpos($pmid, '[('.chr(0).chr(32)));
  18018. $spacelen = 2;
  18019. } else {
  18020. $pos2 = intval(TCPDF_STATIC::revstrpos($pmid, '[('.chr(32)));
  18021. $spacelen = 1;
  18022. }
  18023. if ($pos1 == $pos2) {
  18024. $pmid = substr($pmid, 0, ($pos1 + 2)).substr($pmid, ($pos1 + 2 + $spacelen));
  18025. if (substr($pmid, $pos1, 4) == '[()]') {
  18026. $linew -= $one_space_width;
  18027. } elseif ($pos1 == strpos($pmid, '[(')) {
  18028. $no = 1;
  18029. }
  18030. }
  18031. }
  18032. } else { // LTR
  18033. // remove right space if exist
  18034. $pos1 = TCPDF_STATIC::revstrpos($pmid, ')]');
  18035. if ($pos1 > 0) {
  18036. $pos1 = intval($pos1);
  18037. if ($this->isUnicodeFont()) {
  18038. $pos2 = intval(TCPDF_STATIC::revstrpos($pmid, chr(0).chr(32).')]')) + 2;
  18039. $spacelen = 2;
  18040. } else {
  18041. $pos2 = intval(TCPDF_STATIC::revstrpos($pmid, chr(32).')]')) + 1;
  18042. $spacelen = 1;
  18043. }
  18044. if ($pos1 == $pos2) {
  18045. $pmid = substr($pmid, 0, ($pos1 - $spacelen)).substr($pmid, $pos1);
  18046. $linew -= $one_space_width;
  18047. }
  18048. }
  18049. }
  18050. $mdiff = ($tw - $linew);
  18051. if ($plalign == 'C') {
  18052. if ($this->rtl) {
  18053. $t_x = -($mdiff / 2);
  18054. } else {
  18055. $t_x = ($mdiff / 2);
  18056. }
  18057. } elseif ($plalign == 'R') {
  18058. // right alignment on LTR document
  18059. $t_x = $mdiff;
  18060. } elseif ($plalign == 'L') {
  18061. // left alignment on RTL document
  18062. $t_x = -$mdiff;
  18063. }
  18064. } // end if startlinex
  18065. if (($t_x != 0) OR ($yshift < 0)) {
  18066. // shift the line
  18067. $trx = sprintf('1 0 0 1 %F %F cm', ($t_x * $this->k), ($yshift * $this->k));
  18068. $pstart .= "\nq\n".$trx."\n".$pmid."\nQ\n";
  18069. $endlinepos = strlen($pstart);
  18070. if ($this->inxobj) {
  18071. // we are inside an XObject template
  18072. $this->xobjects[$this->xobjid]['outdata'] = $pstart.$pend;
  18073. foreach ($this->xobjects[$this->xobjid]['annotations'] as $pak => $pac) {
  18074. if ($pak >= $pask) {
  18075. $this->xobjects[$this->xobjid]['annotations'][$pak]['x'] += $t_x;
  18076. $this->xobjects[$this->xobjid]['annotations'][$pak]['y'] -= $yshift;
  18077. }
  18078. }
  18079. } else {
  18080. $this->setPageBuffer($startlinepage, $pstart.$pend);
  18081. // shift the annotations and links
  18082. if (isset($this->PageAnnots[$this->page])) {
  18083. foreach ($this->PageAnnots[$this->page] as $pak => $pac) {
  18084. if ($pak >= $pask) {
  18085. $this->PageAnnots[$this->page][$pak]['x'] += $t_x;
  18086. $this->PageAnnots[$this->page][$pak]['y'] -= $yshift;
  18087. }
  18088. }
  18089. }
  18090. }
  18091. $this->y -= $yshift;
  18092. $yshift = 0;
  18093. }
  18094. }
  18095. // restore previous values
  18096. $this->setGraphicVars($gvars);
  18097. if ($this->num_columns > 1) {
  18098. $this->selectColumn();
  18099. } elseif ($this->page > $prevPage) {
  18100. $this->lMargin = $this->pagedim[$this->page]['olm'];
  18101. $this->rMargin = $this->pagedim[$this->page]['orm'];
  18102. }
  18103. // restore previous list state
  18104. $this->cell_height_ratio = $prev_cell_height_ratio;
  18105. $this->listnum = $prev_listnum;
  18106. $this->listordered = $prev_listordered;
  18107. $this->listcount = $prev_listcount;
  18108. $this->lispacer = $prev_lispacer;
  18109. if ($ln AND (!($cell AND ($dom[$key-1]['value'] == 'table')))) {
  18110. $this->Ln($this->lasth);
  18111. if (($this->y < $maxbottomliney) AND ($startlinepage == $this->page)) {
  18112. $this->y = $maxbottomliney;
  18113. }
  18114. }
  18115. unset($dom);
  18116. }
  18117. /**
  18118. * Process opening tags.
  18119. * @param $dom (array) html dom array
  18120. * @param $key (int) current element id
  18121. * @param $cell (boolean) if true add the default left (or right if RTL) padding to each new line (default false).
  18122. * @return $dom array
  18123. * @protected
  18124. */
  18125. protected function openHTMLTagHandler($dom, $key, $cell) {
  18126. $tag = $dom[$key];
  18127. $parent = $dom[($dom[$key]['parent'])];
  18128. $firsttag = ($key == 1);
  18129. // check for text direction attribute
  18130. if (isset($tag['dir'])) {
  18131. $this->setTempRTL($tag['dir']);
  18132. } else {
  18133. $this->tmprtl = false;
  18134. }
  18135. if ($tag['block']) {
  18136. $hbz = 0; // distance from y to line bottom
  18137. $hb = 0; // vertical space between block tags
  18138. // calculate vertical space for block tags
  18139. if (isset($this->tagvspaces[$tag['value']][0]['h']) && !empty($this->tagvspaces[$tag['value']][0]['h']) && ($this->tagvspaces[$tag['value']][0]['h'] >= 0)) {
  18140. $cur_h = $this->tagvspaces[$tag['value']][0]['h'];
  18141. } elseif (isset($tag['fontsize'])) {
  18142. $cur_h = $this->getCellHeight($tag['fontsize'] / $this->k);
  18143. } else {
  18144. $cur_h = $this->getCellHeight($this->FontSize);
  18145. }
  18146. if (isset($this->tagvspaces[$tag['value']][0]['n'])) {
  18147. $on = $this->tagvspaces[$tag['value']][0]['n'];
  18148. } elseif (preg_match('/[h][0-9]/', $tag['value']) > 0) {
  18149. $on = 0.6;
  18150. } else {
  18151. $on = 1;
  18152. }
  18153. if ((!isset($this->tagvspaces[$tag['value']])) AND (in_array($tag['value'], array('div', 'dt', 'dd', 'li', 'br', 'hr')))) {
  18154. $hb = 0;
  18155. } else {
  18156. $hb = ($on * $cur_h);
  18157. }
  18158. if (($this->htmlvspace <= 0) AND ($on > 0)) {
  18159. if (isset($parent['fontsize'])) {
  18160. $hbz = (($parent['fontsize'] / $this->k) * $this->cell_height_ratio);
  18161. } else {
  18162. $hbz = $this->getCellHeight($this->FontSize);
  18163. }
  18164. }
  18165. if (isset($dom[($key - 1)]) AND ($dom[($key - 1)]['value'] == 'table')) {
  18166. // fix vertical space after table
  18167. $hbz = 0;
  18168. }
  18169. // closing vertical space
  18170. $hbc = 0;
  18171. if (isset($this->tagvspaces[$tag['value']][1]['h']) && !empty($this->tagvspaces[$tag['value']][1]['h']) && ($this->tagvspaces[$tag['value']][1]['h'] >= 0)) {
  18172. $pre_h = $this->tagvspaces[$tag['value']][1]['h'];
  18173. } elseif (isset($parent['fontsize'])) {
  18174. $pre_h = $this->getCellHeight($parent['fontsize'] / $this->k);
  18175. } else {
  18176. $pre_h = $this->getCellHeight($this->FontSize);
  18177. }
  18178. if (isset($this->tagvspaces[$tag['value']][1]['n'])) {
  18179. $cn = $this->tagvspaces[$tag['value']][1]['n'];
  18180. } elseif (preg_match('/[h][0-9]/', $tag['value']) > 0) {
  18181. $cn = 0.6;
  18182. } else {
  18183. $cn = 1;
  18184. }
  18185. if (isset($this->tagvspaces[$tag['value']][1])) {
  18186. $hbc = ($cn * $pre_h);
  18187. }
  18188. }
  18189. // Opening tag
  18190. switch($tag['value']) {
  18191. case 'table': {
  18192. $cp = 0;
  18193. $cs = 0;
  18194. $dom[$key]['rowspans'] = array();
  18195. if (!isset($dom[$key]['attribute']['nested']) OR ($dom[$key]['attribute']['nested'] != 'true')) {
  18196. $this->htmlvspace = 0;
  18197. // set table header
  18198. if (!TCPDF_STATIC::empty_string($dom[$key]['thead'])) {
  18199. // set table header
  18200. $this->thead = $dom[$key]['thead'];
  18201. if (!isset($this->theadMargins) OR (empty($this->theadMargins))) {
  18202. $this->theadMargins = array();
  18203. $this->theadMargins['cell_padding'] = $this->cell_padding;
  18204. $this->theadMargins['lmargin'] = $this->lMargin;
  18205. $this->theadMargins['rmargin'] = $this->rMargin;
  18206. $this->theadMargins['page'] = $this->page;
  18207. $this->theadMargins['cell'] = $cell;
  18208. $this->theadMargins['gvars'] = $this->getGraphicVars();
  18209. }
  18210. }
  18211. }
  18212. // store current margins and page
  18213. $dom[$key]['old_cell_padding'] = $this->cell_padding;
  18214. if (isset($tag['attribute']['cellpadding'])) {
  18215. $pad = $this->getHTMLUnitToUnits($tag['attribute']['cellpadding'], 1, 'px');
  18216. $this->SetCellPadding($pad);
  18217. } elseif (isset($tag['padding'])) {
  18218. $this->cell_padding = $tag['padding'];
  18219. }
  18220. if (isset($tag['attribute']['cellspacing'])) {
  18221. $cs = $this->getHTMLUnitToUnits($tag['attribute']['cellspacing'], 1, 'px');
  18222. } elseif (isset($tag['border-spacing'])) {
  18223. $cs = $tag['border-spacing']['V'];
  18224. }
  18225. $prev_y = $this->y;
  18226. if ($this->checkPageBreak(((2 * $cp) + (2 * $cs) + $this->lasth), '', false) OR ($this->y < $prev_y)) {
  18227. $this->inthead = true;
  18228. // add a page (or trig AcceptPageBreak() for multicolumn mode)
  18229. $this->checkPageBreak($this->PageBreakTrigger + 1);
  18230. }
  18231. break;
  18232. }
  18233. case 'tr': {
  18234. // array of columns positions
  18235. $dom[$key]['cellpos'] = array();
  18236. break;
  18237. }
  18238. case 'hr': {
  18239. if ((isset($tag['height'])) AND ($tag['height'] != '')) {
  18240. $hrHeight = $this->getHTMLUnitToUnits($tag['height'], 1, 'px');
  18241. } else {
  18242. $hrHeight = $this->GetLineWidth();
  18243. }
  18244. $this->addHTMLVertSpace($hbz, max($hb, ($hrHeight / 2)), $cell, $firsttag);
  18245. $x = $this->GetX();
  18246. $y = $this->GetY();
  18247. $wtmp = $this->w - $this->lMargin - $this->rMargin;
  18248. if ($cell) {
  18249. $wtmp -= ($this->cell_padding['L'] + $this->cell_padding['R']);
  18250. }
  18251. if ((isset($tag['width'])) AND ($tag['width'] != '')) {
  18252. $hrWidth = $this->getHTMLUnitToUnits($tag['width'], $wtmp, 'px');
  18253. } else {
  18254. $hrWidth = $wtmp;
  18255. }
  18256. $prevlinewidth = $this->GetLineWidth();
  18257. $this->SetLineWidth($hrHeight);
  18258. $this->Line($x, $y, $x + $hrWidth, $y);
  18259. $this->SetLineWidth($prevlinewidth);
  18260. $this->addHTMLVertSpace(max($hbc, ($hrHeight / 2)), 0, $cell, !isset($dom[($key + 1)]));
  18261. break;
  18262. }
  18263. case 'a': {
  18264. if (array_key_exists('href', $tag['attribute'])) {
  18265. $this->HREF['url'] = $tag['attribute']['href'];
  18266. }
  18267. break;
  18268. }
  18269. case 'img': {
  18270. if (empty($tag['attribute']['src'])) {
  18271. break;
  18272. }
  18273. $imgsrc = $tag['attribute']['src'];
  18274. if ($imgsrc[0] === '@') {
  18275. // data stream
  18276. $imgsrc = '@'.base64_decode(substr($imgsrc, 1));
  18277. $type = '';
  18278. } else {
  18279. if (($imgsrc[0] === '/') AND !empty($_SERVER['DOCUMENT_ROOT']) AND ($_SERVER['DOCUMENT_ROOT'] != '/')) {
  18280. // fix image path
  18281. $findroot = strpos($imgsrc, $_SERVER['DOCUMENT_ROOT']);
  18282. if (($findroot === false) OR ($findroot > 1)) {
  18283. if (substr($_SERVER['DOCUMENT_ROOT'], -1) == '/') {
  18284. $imgsrc = substr($_SERVER['DOCUMENT_ROOT'], 0, -1).$imgsrc;
  18285. } else {
  18286. $imgsrc = $_SERVER['DOCUMENT_ROOT'].$imgsrc;
  18287. }
  18288. }
  18289. $imgsrc = urldecode($imgsrc);
  18290. $testscrtype = @parse_url($imgsrc);
  18291. if (empty($testscrtype['query'])) {
  18292. // convert URL to server path
  18293. $imgsrc = str_replace(K_PATH_URL, K_PATH_MAIN, $imgsrc);
  18294. } elseif (preg_match('|^https?://|', $imgsrc) !== 1) {
  18295. // convert URL to server path
  18296. $imgsrc = str_replace(K_PATH_MAIN, K_PATH_URL, $imgsrc);
  18297. }
  18298. }
  18299. // get image type
  18300. $type = TCPDF_IMAGES::getImageFileType($imgsrc);
  18301. }
  18302. if (!isset($tag['width'])) {
  18303. $tag['width'] = 0;
  18304. }
  18305. if (!isset($tag['height'])) {
  18306. $tag['height'] = 0;
  18307. }
  18308. //if (!isset($tag['attribute']['align'])) {
  18309. // the only alignment supported is "bottom"
  18310. // further development is required for other modes.
  18311. $tag['attribute']['align'] = 'bottom';
  18312. //}
  18313. switch($tag['attribute']['align']) {
  18314. case 'top': {
  18315. $align = 'T';
  18316. break;
  18317. }
  18318. case 'middle': {
  18319. $align = 'M';
  18320. break;
  18321. }
  18322. case 'bottom': {
  18323. $align = 'B';
  18324. break;
  18325. }
  18326. default: {
  18327. $align = 'B';
  18328. break;
  18329. }
  18330. }
  18331. $prevy = $this->y;
  18332. $xpos = $this->x;
  18333. $imglink = '';
  18334. if (isset($this->HREF['url']) AND !TCPDF_STATIC::empty_string($this->HREF['url'])) {
  18335. $imglink = $this->HREF['url'];
  18336. if ($imglink[0] == '#') {
  18337. // convert url to internal link
  18338. $lnkdata = explode(',', $imglink);
  18339. if (isset($lnkdata[0])) {
  18340. $page = intval(substr($lnkdata[0], 1));
  18341. if (empty($page) OR ($page <= 0)) {
  18342. $page = $this->page;
  18343. }
  18344. if (isset($lnkdata[1]) AND (strlen($lnkdata[1]) > 0)) {
  18345. $lnky = floatval($lnkdata[1]);
  18346. } else {
  18347. $lnky = 0;
  18348. }
  18349. $imglink = $this->AddLink();
  18350. $this->SetLink($imglink, $lnky, $page);
  18351. }
  18352. }
  18353. }
  18354. $border = 0;
  18355. if (isset($tag['border']) AND !empty($tag['border'])) {
  18356. // currently only support 1 (frame) or a combination of 'LTRB'
  18357. $border = $tag['border'];
  18358. }
  18359. $iw = '';
  18360. if (isset($tag['width'])) {
  18361. $iw = $this->getHTMLUnitToUnits($tag['width'], ($tag['fontsize'] / $this->k), 'px', false);
  18362. }
  18363. $ih = '';
  18364. if (isset($tag['height'])) {
  18365. $ih = $this->getHTMLUnitToUnits($tag['height'], ($tag['fontsize'] / $this->k), 'px', false);
  18366. }
  18367. if (($type == 'eps') OR ($type == 'ai')) {
  18368. $this->ImageEps($imgsrc, $xpos, $this->y, $iw, $ih, $imglink, true, $align, '', $border, true);
  18369. } elseif ($type == 'svg') {
  18370. $this->ImageSVG($imgsrc, $xpos, $this->y, $iw, $ih, $imglink, $align, '', $border, true);
  18371. } else {
  18372. $this->Image($imgsrc, $xpos, $this->y, $iw, $ih, '', $imglink, $align, false, 300, '', false, false, $border, false, false, true);
  18373. }
  18374. switch($align) {
  18375. case 'T': {
  18376. $this->y = $prevy;
  18377. break;
  18378. }
  18379. case 'M': {
  18380. $this->y = (($this->img_rb_y + $prevy - ($this->getCellHeight($tag['fontsize'] / $this->k))) / 2);
  18381. break;
  18382. }
  18383. case 'B': {
  18384. $this->y = $this->img_rb_y - ($this->getCellHeight($tag['fontsize'] / $this->k) - ($this->getFontDescent($tag['fontname'], $tag['fontstyle'], $tag['fontsize']) * $this->cell_height_ratio));
  18385. break;
  18386. }
  18387. }
  18388. break;
  18389. }
  18390. case 'dl': {
  18391. ++$this->listnum;
  18392. if ($this->listnum == 1) {
  18393. $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
  18394. } else {
  18395. $this->addHTMLVertSpace(0, 0, $cell, $firsttag);
  18396. }
  18397. break;
  18398. }
  18399. case 'dt': {
  18400. $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
  18401. break;
  18402. }
  18403. case 'dd': {
  18404. if ($this->rtl) {
  18405. $this->rMargin += $this->listindent;
  18406. } else {
  18407. $this->lMargin += $this->listindent;
  18408. }
  18409. ++$this->listindentlevel;
  18410. $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
  18411. break;
  18412. }
  18413. case 'ul':
  18414. case 'ol': {
  18415. ++$this->listnum;
  18416. if ($tag['value'] == 'ol') {
  18417. $this->listordered[$this->listnum] = true;
  18418. } else {
  18419. $this->listordered[$this->listnum] = false;
  18420. }
  18421. if (isset($tag['attribute']['start'])) {
  18422. $this->listcount[$this->listnum] = intval($tag['attribute']['start']) - 1;
  18423. } else {
  18424. $this->listcount[$this->listnum] = 0;
  18425. }
  18426. if ($this->rtl) {
  18427. $this->rMargin += $this->listindent;
  18428. $this->x -= $this->listindent;
  18429. } else {
  18430. $this->lMargin += $this->listindent;
  18431. $this->x += $this->listindent;
  18432. }
  18433. ++$this->listindentlevel;
  18434. if ($this->listnum == 1) {
  18435. if ($key > 1) {
  18436. $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
  18437. }
  18438. } else {
  18439. $this->addHTMLVertSpace(0, 0, $cell, $firsttag);
  18440. }
  18441. break;
  18442. }
  18443. case 'li': {
  18444. if ($key > 2) {
  18445. $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
  18446. }
  18447. if ($this->listordered[$this->listnum]) {
  18448. // ordered item
  18449. if (isset($parent['attribute']['type']) AND !TCPDF_STATIC::empty_string($parent['attribute']['type'])) {
  18450. $this->lispacer = $parent['attribute']['type'];
  18451. } elseif (isset($parent['listtype']) AND !TCPDF_STATIC::empty_string($parent['listtype'])) {
  18452. $this->lispacer = $parent['listtype'];
  18453. } elseif (isset($this->lisymbol) AND !TCPDF_STATIC::empty_string($this->lisymbol)) {
  18454. $this->lispacer = $this->lisymbol;
  18455. } else {
  18456. $this->lispacer = '#';
  18457. }
  18458. ++$this->listcount[$this->listnum];
  18459. if (isset($tag['attribute']['value'])) {
  18460. $this->listcount[$this->listnum] = intval($tag['attribute']['value']);
  18461. }
  18462. } else {
  18463. // unordered item
  18464. if (isset($parent['attribute']['type']) AND !TCPDF_STATIC::empty_string($parent['attribute']['type'])) {
  18465. $this->lispacer = $parent['attribute']['type'];
  18466. } elseif (isset($parent['listtype']) AND !TCPDF_STATIC::empty_string($parent['listtype'])) {
  18467. $this->lispacer = $parent['listtype'];
  18468. } elseif (isset($this->lisymbol) AND !TCPDF_STATIC::empty_string($this->lisymbol)) {
  18469. $this->lispacer = $this->lisymbol;
  18470. } else {
  18471. $this->lispacer = '!';
  18472. }
  18473. }
  18474. break;
  18475. }
  18476. case 'blockquote': {
  18477. if ($this->rtl) {
  18478. $this->rMargin += $this->listindent;
  18479. } else {
  18480. $this->lMargin += $this->listindent;
  18481. }
  18482. ++$this->listindentlevel;
  18483. $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
  18484. break;
  18485. }
  18486. case 'br': {
  18487. $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
  18488. break;
  18489. }
  18490. case 'div': {
  18491. $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
  18492. break;
  18493. }
  18494. case 'p': {
  18495. $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
  18496. break;
  18497. }
  18498. case 'pre': {
  18499. $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
  18500. $this->premode = true;
  18501. break;
  18502. }
  18503. case 'sup': {
  18504. $this->SetXY($this->GetX(), $this->GetY() - ((0.7 * $this->FontSizePt) / $this->k));
  18505. break;
  18506. }
  18507. case 'sub': {
  18508. $this->SetXY($this->GetX(), $this->GetY() + ((0.3 * $this->FontSizePt) / $this->k));
  18509. break;
  18510. }
  18511. case 'h1':
  18512. case 'h2':
  18513. case 'h3':
  18514. case 'h4':
  18515. case 'h5':
  18516. case 'h6': {
  18517. $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
  18518. break;
  18519. }
  18520. // Form fields (since 4.8.000 - 2009-09-07)
  18521. case 'form': {
  18522. if (isset($tag['attribute']['action'])) {
  18523. $this->form_action = $tag['attribute']['action'];
  18524. } else {
  18525. $this->Error('Please explicitly set action attribute path!');
  18526. }
  18527. if (isset($tag['attribute']['enctype'])) {
  18528. $this->form_enctype = $tag['attribute']['enctype'];
  18529. } else {
  18530. $this->form_enctype = 'application/x-www-form-urlencoded';
  18531. }
  18532. if (isset($tag['attribute']['method'])) {
  18533. $this->form_mode = $tag['attribute']['method'];
  18534. } else {
  18535. $this->form_mode = 'post';
  18536. }
  18537. break;
  18538. }
  18539. case 'input': {
  18540. if (isset($tag['attribute']['name']) AND !TCPDF_STATIC::empty_string($tag['attribute']['name'])) {
  18541. $name = $tag['attribute']['name'];
  18542. } else {
  18543. break;
  18544. }
  18545. $prop = array();
  18546. $opt = array();
  18547. if (isset($tag['attribute']['readonly']) AND !TCPDF_STATIC::empty_string($tag['attribute']['readonly'])) {
  18548. $prop['readonly'] = true;
  18549. }
  18550. if (isset($tag['attribute']['value']) AND !TCPDF_STATIC::empty_string($tag['attribute']['value'])) {
  18551. $value = $tag['attribute']['value'];
  18552. }
  18553. if (isset($tag['attribute']['maxlength']) AND !TCPDF_STATIC::empty_string($tag['attribute']['maxlength'])) {
  18554. $opt['maxlen'] = intval($tag['attribute']['maxlength']);
  18555. }
  18556. $h = $this->getCellHeight($this->FontSize);
  18557. if (isset($tag['attribute']['size']) AND !TCPDF_STATIC::empty_string($tag['attribute']['size'])) {
  18558. $w = intval($tag['attribute']['size']) * $this->GetStringWidth(chr(32)) * 2;
  18559. } else {
  18560. $w = $h;
  18561. }
  18562. if (isset($tag['attribute']['checked']) AND (($tag['attribute']['checked'] == 'checked') OR ($tag['attribute']['checked'] == 'true'))) {
  18563. $checked = true;
  18564. } else {
  18565. $checked = false;
  18566. }
  18567. if (isset($tag['align'])) {
  18568. switch ($tag['align']) {
  18569. case 'C': {
  18570. $opt['q'] = 1;
  18571. break;
  18572. }
  18573. case 'R': {
  18574. $opt['q'] = 2;
  18575. break;
  18576. }
  18577. case 'L':
  18578. default: {
  18579. break;
  18580. }
  18581. }
  18582. }
  18583. switch ($tag['attribute']['type']) {
  18584. case 'text': {
  18585. if (isset($value)) {
  18586. $opt['v'] = $value;
  18587. }
  18588. $this->TextField($name, $w, $h, $prop, $opt, '', '', false);
  18589. break;
  18590. }
  18591. case 'password': {
  18592. if (isset($value)) {
  18593. $opt['v'] = $value;
  18594. }
  18595. $prop['password'] = 'true';
  18596. $this->TextField($name, $w, $h, $prop, $opt, '', '', false);
  18597. break;
  18598. }
  18599. case 'checkbox': {
  18600. if (!isset($value)) {
  18601. break;
  18602. }
  18603. $this->CheckBox($name, $w, $checked, $prop, $opt, $value, '', '', false);
  18604. break;
  18605. }
  18606. case 'radio': {
  18607. if (!isset($value)) {
  18608. break;
  18609. }
  18610. $this->RadioButton($name, $w, $prop, $opt, $value, $checked, '', '', false);
  18611. break;
  18612. }
  18613. case 'submit': {
  18614. if (!isset($value)) {
  18615. $value = 'submit';
  18616. }
  18617. $w = $this->GetStringWidth($value) * 1.5;
  18618. $h *= 1.6;
  18619. $prop = array('lineWidth'=>1, 'borderStyle'=>'beveled', 'fillColor'=>array(196, 196, 196), 'strokeColor'=>array(255, 255, 255));
  18620. $action = array();
  18621. $action['S'] = 'SubmitForm';
  18622. $action['F'] = $this->form_action;
  18623. if ($this->form_enctype != 'FDF') {
  18624. $action['Flags'] = array('ExportFormat');
  18625. }
  18626. if ($this->form_mode == 'get') {
  18627. $action['Flags'] = array('GetMethod');
  18628. }
  18629. $this->Button($name, $w, $h, $value, $action, $prop, $opt, '', '', false);
  18630. break;
  18631. }
  18632. case 'reset': {
  18633. if (!isset($value)) {
  18634. $value = 'reset';
  18635. }
  18636. $w = $this->GetStringWidth($value) * 1.5;
  18637. $h *= 1.6;
  18638. $prop = array('lineWidth'=>1, 'borderStyle'=>'beveled', 'fillColor'=>array(196, 196, 196), 'strokeColor'=>array(255, 255, 255));
  18639. $this->Button($name, $w, $h, $value, array('S'=>'ResetForm'), $prop, $opt, '', '', false);
  18640. break;
  18641. }
  18642. case 'file': {
  18643. $prop['fileSelect'] = 'true';
  18644. $this->TextField($name, $w, $h, $prop, $opt, '', '', false);
  18645. if (!isset($value)) {
  18646. $value = '*';
  18647. }
  18648. $w = $this->GetStringWidth($value) * 2;
  18649. $h *= 1.2;
  18650. $prop = array('lineWidth'=>1, 'borderStyle'=>'beveled', 'fillColor'=>array(196, 196, 196), 'strokeColor'=>array(255, 255, 255));
  18651. $jsaction = 'var f=this.getField(\''.$name.'\'); f.browseForFileToSubmit();';
  18652. $this->Button('FB_'.$name, $w, $h, $value, $jsaction, $prop, $opt, '', '', false);
  18653. break;
  18654. }
  18655. case 'hidden': {
  18656. if (isset($value)) {
  18657. $opt['v'] = $value;
  18658. }
  18659. $opt['f'] = array('invisible', 'hidden');
  18660. $this->TextField($name, 0, 0, $prop, $opt, '', '', false);
  18661. break;
  18662. }
  18663. case 'image': {
  18664. // THIS TYPE MUST BE FIXED
  18665. if (isset($tag['attribute']['src']) AND !TCPDF_STATIC::empty_string($tag['attribute']['src'])) {
  18666. $img = $tag['attribute']['src'];
  18667. } else {
  18668. break;
  18669. }
  18670. $value = 'img';
  18671. //$opt['mk'] = array('i'=>$img, 'tp'=>1, 'if'=>array('sw'=>'A', 's'=>'A', 'fb'=>false));
  18672. if (isset($tag['attribute']['onclick']) AND !empty($tag['attribute']['onclick'])) {
  18673. $jsaction = $tag['attribute']['onclick'];
  18674. } else {
  18675. $jsaction = '';
  18676. }
  18677. $this->Button($name, $w, $h, $value, $jsaction, $prop, $opt, '', '', false);
  18678. break;
  18679. }
  18680. case 'button': {
  18681. if (!isset($value)) {
  18682. $value = ' ';
  18683. }
  18684. $w = $this->GetStringWidth($value) * 1.5;
  18685. $h *= 1.6;
  18686. $prop = array('lineWidth'=>1, 'borderStyle'=>'beveled', 'fillColor'=>array(196, 196, 196), 'strokeColor'=>array(255, 255, 255));
  18687. if (isset($tag['attribute']['onclick']) AND !empty($tag['attribute']['onclick'])) {
  18688. $jsaction = $tag['attribute']['onclick'];
  18689. } else {
  18690. $jsaction = '';
  18691. }
  18692. $this->Button($name, $w, $h, $value, $jsaction, $prop, $opt, '', '', false);
  18693. break;
  18694. }
  18695. }
  18696. break;
  18697. }
  18698. case 'textarea': {
  18699. $prop = array();
  18700. $opt = array();
  18701. if (isset($tag['attribute']['readonly']) AND !TCPDF_STATIC::empty_string($tag['attribute']['readonly'])) {
  18702. $prop['readonly'] = true;
  18703. }
  18704. if (isset($tag['attribute']['name']) AND !TCPDF_STATIC::empty_string($tag['attribute']['name'])) {
  18705. $name = $tag['attribute']['name'];
  18706. } else {
  18707. break;
  18708. }
  18709. if (isset($tag['attribute']['value']) AND !TCPDF_STATIC::empty_string($tag['attribute']['value'])) {
  18710. $opt['v'] = $tag['attribute']['value'];
  18711. }
  18712. if (isset($tag['attribute']['cols']) AND !TCPDF_STATIC::empty_string($tag['attribute']['cols'])) {
  18713. $w = intval($tag['attribute']['cols']) * $this->GetStringWidth(chr(32)) * 2;
  18714. } else {
  18715. $w = 40;
  18716. }
  18717. if (isset($tag['attribute']['rows']) AND !TCPDF_STATIC::empty_string($tag['attribute']['rows'])) {
  18718. $h = intval($tag['attribute']['rows']) * $this->getCellHeight($this->FontSize);
  18719. } else {
  18720. $h = 10;
  18721. }
  18722. $prop['multiline'] = 'true';
  18723. $this->TextField($name, $w, $h, $prop, $opt, '', '', false);
  18724. break;
  18725. }
  18726. case 'select': {
  18727. $h = $this->getCellHeight($this->FontSize);
  18728. if (isset($tag['attribute']['size']) AND !TCPDF_STATIC::empty_string($tag['attribute']['size'])) {
  18729. $h *= ($tag['attribute']['size'] + 1);
  18730. }
  18731. $prop = array();
  18732. $opt = array();
  18733. if (isset($tag['attribute']['name']) AND !TCPDF_STATIC::empty_string($tag['attribute']['name'])) {
  18734. $name = $tag['attribute']['name'];
  18735. } else {
  18736. break;
  18737. }
  18738. $w = 0;
  18739. if (isset($tag['attribute']['opt']) AND !TCPDF_STATIC::empty_string($tag['attribute']['opt'])) {
  18740. $options = explode('#!NwL!#', $tag['attribute']['opt']);
  18741. $values = array();
  18742. foreach ($options as $val) {
  18743. if (strpos($val, '#!TaB!#') !== false) {
  18744. $opts = explode('#!TaB!#', $val);
  18745. $values[] = $opts;
  18746. $w = max($w, $this->GetStringWidth($opts[1]));
  18747. } else {
  18748. $values[] = $val;
  18749. $w = max($w, $this->GetStringWidth($val));
  18750. }
  18751. }
  18752. } else {
  18753. break;
  18754. }
  18755. $w *= 2;
  18756. if (isset($tag['attribute']['multiple']) AND ($tag['attribute']['multiple']='multiple')) {
  18757. $prop['multipleSelection'] = 'true';
  18758. $this->ListBox($name, $w, $h, $values, $prop, $opt, '', '', false);
  18759. } else {
  18760. $this->ComboBox($name, $w, $h, $values, $prop, $opt, '', '', false);
  18761. }
  18762. break;
  18763. }
  18764. case 'tcpdf': {
  18765. if (defined('K_TCPDF_CALLS_IN_HTML') AND (K_TCPDF_CALLS_IN_HTML === true)) {
  18766. // Special tag used to call TCPDF methods
  18767. if (isset($tag['attribute']['method'])) {
  18768. $tcpdf_method = $tag['attribute']['method'];
  18769. if (method_exists($this, $tcpdf_method)) {
  18770. if (isset($tag['attribute']['params']) AND (!empty($tag['attribute']['params']))) {
  18771. $params = $this->unserializeTCPDFtagParameters($tag['attribute']['params']);
  18772. call_user_func_array(array($this, $tcpdf_method), $params);
  18773. } else {
  18774. $this->$tcpdf_method();
  18775. }
  18776. $this->newline = true;
  18777. }
  18778. }
  18779. }
  18780. break;
  18781. }
  18782. default: {
  18783. break;
  18784. }
  18785. }
  18786. // define tags that support borders and background colors
  18787. $bordertags = array('blockquote','br','dd','dl','div','dt','h1','h2','h3','h4','h5','h6','hr','li','ol','p','pre','ul','tcpdf','table');
  18788. if (in_array($tag['value'], $bordertags)) {
  18789. // set border
  18790. $dom[$key]['borderposition'] = $this->getBorderStartPosition();
  18791. }
  18792. if ($dom[$key]['self'] AND isset($dom[$key]['attribute']['pagebreakafter'])) {
  18793. $pba = $dom[$key]['attribute']['pagebreakafter'];
  18794. // check for pagebreak
  18795. if (($pba == 'true') OR ($pba == 'left') OR ($pba == 'right')) {
  18796. // add a page (or trig AcceptPageBreak() for multicolumn mode)
  18797. $this->checkPageBreak($this->PageBreakTrigger + 1);
  18798. }
  18799. if ((($pba == 'left') AND (((!$this->rtl) AND (($this->page % 2) == 0)) OR (($this->rtl) AND (($this->page % 2) != 0))))
  18800. OR (($pba == 'right') AND (((!$this->rtl) AND (($this->page % 2) != 0)) OR (($this->rtl) AND (($this->page % 2) == 0))))) {
  18801. // add a page (or trig AcceptPageBreak() for multicolumn mode)
  18802. $this->checkPageBreak($this->PageBreakTrigger + 1);
  18803. }
  18804. }
  18805. return $dom;
  18806. }
  18807. /**
  18808. * Process closing tags.
  18809. * @param $dom (array) html dom array
  18810. * @param $key (int) current element id
  18811. * @param $cell (boolean) if true add the default left (or right if RTL) padding to each new line (default false).
  18812. * @param $maxbottomliney (int) maximum y value of current line
  18813. * @return $dom array
  18814. * @protected
  18815. */
  18816. protected function closeHTMLTagHandler($dom, $key, $cell, $maxbottomliney=0) {
  18817. $tag = $dom[$key];
  18818. $parent = $dom[($dom[$key]['parent'])];
  18819. $lasttag = ((!isset($dom[($key + 1)])) OR ((!isset($dom[($key + 2)])) AND ($dom[($key + 1)]['value'] == 'marker')));
  18820. $in_table_head = false;
  18821. // maximum x position (used to draw borders)
  18822. if ($this->rtl) {
  18823. $xmax = $this->w;
  18824. } else {
  18825. $xmax = 0;
  18826. }
  18827. if ($tag['block']) {
  18828. $hbz = 0; // distance from y to line bottom
  18829. $hb = 0; // vertical space between block tags
  18830. // calculate vertical space for block tags
  18831. if (isset($this->tagvspaces[$tag['value']][1]['h']) && !empty($this->tagvspaces[$tag['value']][1]['h']) && ($this->tagvspaces[$tag['value']][1]['h'] >= 0)) {
  18832. $pre_h = $this->tagvspaces[$tag['value']][1]['h'];
  18833. } elseif (isset($parent['fontsize'])) {
  18834. $pre_h = $this->getCellHeight($parent['fontsize'] / $this->k);
  18835. } else {
  18836. $pre_h = $this->getCellHeight($this->FontSize);
  18837. }
  18838. if (isset($this->tagvspaces[$tag['value']][1]['n'])) {
  18839. $cn = $this->tagvspaces[$tag['value']][1]['n'];
  18840. } elseif (preg_match('/[h][0-9]/', $tag['value']) > 0) {
  18841. $cn = 0.6;
  18842. } else {
  18843. $cn = 1;
  18844. }
  18845. if ((!isset($this->tagvspaces[$tag['value']])) AND ($tag['value'] == 'div')) {
  18846. $hb = 0;
  18847. } else {
  18848. $hb = ($cn * $pre_h);
  18849. }
  18850. if ($maxbottomliney > $this->PageBreakTrigger) {
  18851. $hbz = $this->getCellHeight($this->FontSize);
  18852. } elseif ($this->y < $maxbottomliney) {
  18853. $hbz = ($maxbottomliney - $this->y);
  18854. }
  18855. }
  18856. // Closing tag
  18857. switch($tag['value']) {
  18858. case 'tr': {
  18859. $table_el = $dom[($dom[$key]['parent'])]['parent'];
  18860. if (!isset($parent['endy'])) {
  18861. $dom[($dom[$key]['parent'])]['endy'] = $this->y;
  18862. $parent['endy'] = $this->y;
  18863. }
  18864. if (!isset($parent['endpage'])) {
  18865. $dom[($dom[$key]['parent'])]['endpage'] = $this->page;
  18866. $parent['endpage'] = $this->page;
  18867. }
  18868. if (!isset($parent['endcolumn'])) {
  18869. $dom[($dom[$key]['parent'])]['endcolumn'] = $this->current_column;
  18870. $parent['endcolumn'] = $this->current_column;
  18871. }
  18872. // update row-spanned cells
  18873. if (isset($dom[$table_el]['rowspans'])) {
  18874. foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
  18875. $dom[$table_el]['rowspans'][$k]['rowspan'] -= 1;
  18876. if ($dom[$table_el]['rowspans'][$k]['rowspan'] == 0) {
  18877. if (($dom[$table_el]['rowspans'][$k]['endpage'] == $parent['endpage']) AND ($dom[$table_el]['rowspans'][$k]['endcolumn'] == $parent['endcolumn'])) {
  18878. $dom[($dom[$key]['parent'])]['endy'] = max($dom[$table_el]['rowspans'][$k]['endy'], $parent['endy']);
  18879. } elseif (($dom[$table_el]['rowspans'][$k]['endpage'] > $parent['endpage']) OR ($dom[$table_el]['rowspans'][$k]['endcolumn'] > $parent['endcolumn'])) {
  18880. $dom[($dom[$key]['parent'])]['endy'] = $dom[$table_el]['rowspans'][$k]['endy'];
  18881. $dom[($dom[$key]['parent'])]['endpage'] = $dom[$table_el]['rowspans'][$k]['endpage'];
  18882. $dom[($dom[$key]['parent'])]['endcolumn'] = $dom[$table_el]['rowspans'][$k]['endcolumn'];
  18883. }
  18884. }
  18885. }
  18886. // report new endy and endpage to the rowspanned cells
  18887. foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
  18888. if ($dom[$table_el]['rowspans'][$k]['rowspan'] == 0) {
  18889. $dom[$table_el]['rowspans'][$k]['endpage'] = max($dom[$table_el]['rowspans'][$k]['endpage'], $dom[($dom[$key]['parent'])]['endpage']);
  18890. $dom[($dom[$key]['parent'])]['endpage'] = $dom[$table_el]['rowspans'][$k]['endpage'];
  18891. $dom[$table_el]['rowspans'][$k]['endcolumn'] = max($dom[$table_el]['rowspans'][$k]['endcolumn'], $dom[($dom[$key]['parent'])]['endcolumn']);
  18892. $dom[($dom[$key]['parent'])]['endcolumn'] = $dom[$table_el]['rowspans'][$k]['endcolumn'];
  18893. $dom[$table_el]['rowspans'][$k]['endy'] = max($dom[$table_el]['rowspans'][$k]['endy'], $dom[($dom[$key]['parent'])]['endy']);
  18894. $dom[($dom[$key]['parent'])]['endy'] = $dom[$table_el]['rowspans'][$k]['endy'];
  18895. }
  18896. }
  18897. // update remaining rowspanned cells
  18898. foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
  18899. if ($dom[$table_el]['rowspans'][$k]['rowspan'] == 0) {
  18900. $dom[$table_el]['rowspans'][$k]['endpage'] = $dom[($dom[$key]['parent'])]['endpage'];
  18901. $dom[$table_el]['rowspans'][$k]['endcolumn'] = $dom[($dom[$key]['parent'])]['endcolumn'];
  18902. $dom[$table_el]['rowspans'][$k]['endy'] = $dom[($dom[$key]['parent'])]['endy'];
  18903. }
  18904. }
  18905. }
  18906. $prev_page = $this->page;
  18907. $this->setPage($dom[($dom[$key]['parent'])]['endpage']);
  18908. if ($this->num_columns > 1) {
  18909. if (($prev_page < $this->page)
  18910. AND ((($this->current_column == 0) AND ($dom[($dom[$key]['parent'])]['endcolumn'] == ($this->num_columns - 1)))
  18911. OR ($this->current_column == $dom[($dom[$key]['parent'])]['endcolumn']))) {
  18912. // page jump
  18913. $this->selectColumn(0);
  18914. $dom[($dom[$key]['parent'])]['endcolumn'] = 0;
  18915. $dom[($dom[$key]['parent'])]['endy'] = $this->y;
  18916. } else {
  18917. $this->selectColumn($dom[($dom[$key]['parent'])]['endcolumn']);
  18918. $this->y = $dom[($dom[$key]['parent'])]['endy'];
  18919. }
  18920. } else {
  18921. $this->y = $dom[($dom[$key]['parent'])]['endy'];
  18922. }
  18923. if (isset($dom[$table_el]['attribute']['cellspacing'])) {
  18924. $this->y += $this->getHTMLUnitToUnits($dom[$table_el]['attribute']['cellspacing'], 1, 'px');
  18925. } elseif (isset($dom[$table_el]['border-spacing'])) {
  18926. $this->y += $dom[$table_el]['border-spacing']['V'];
  18927. }
  18928. $this->Ln(0, $cell);
  18929. if ($this->current_column == $parent['startcolumn']) {
  18930. $this->x = $parent['startx'];
  18931. }
  18932. // account for booklet mode
  18933. if ($this->page > $parent['startpage']) {
  18934. if (($this->rtl) AND ($this->pagedim[$this->page]['orm'] != $this->pagedim[$parent['startpage']]['orm'])) {
  18935. $this->x -= ($this->pagedim[$this->page]['orm'] - $this->pagedim[$parent['startpage']]['orm']);
  18936. } elseif ((!$this->rtl) AND ($this->pagedim[$this->page]['olm'] != $this->pagedim[$parent['startpage']]['olm'])) {
  18937. $this->x += ($this->pagedim[$this->page]['olm'] - $this->pagedim[$parent['startpage']]['olm']);
  18938. }
  18939. }
  18940. break;
  18941. }
  18942. case 'tablehead':
  18943. // closing tag used for the thead part
  18944. $in_table_head = true;
  18945. $this->inthead = false;
  18946. case 'table': {
  18947. $table_el = $parent;
  18948. // set default border
  18949. if (isset($table_el['attribute']['border']) AND ($table_el['attribute']['border'] > 0)) {
  18950. // set default border
  18951. $border = array('LTRB' => array('width' => $this->getCSSBorderWidth($table_el['attribute']['border']), 'cap'=>'square', 'join'=>'miter', 'dash'=> 0, 'color'=>array(0,0,0)));
  18952. } else {
  18953. $border = 0;
  18954. }
  18955. $default_border = $border;
  18956. // fix bottom line alignment of last line before page break
  18957. foreach ($dom[($dom[$key]['parent'])]['trids'] as $j => $trkey) {
  18958. // update row-spanned cells
  18959. if (isset($dom[($dom[$key]['parent'])]['rowspans'])) {
  18960. foreach ($dom[($dom[$key]['parent'])]['rowspans'] as $k => $trwsp) {
  18961. if (isset($prevtrkey) AND ($trwsp['trid'] == $prevtrkey) AND ($trwsp['mrowspan'] > 0)) {
  18962. $dom[($dom[$key]['parent'])]['rowspans'][$k]['trid'] = $trkey;
  18963. }
  18964. if ($dom[($dom[$key]['parent'])]['rowspans'][$k]['trid'] == $trkey) {
  18965. $dom[($dom[$key]['parent'])]['rowspans'][$k]['mrowspan'] -= 1;
  18966. }
  18967. }
  18968. }
  18969. if (isset($prevtrkey) AND ($dom[$trkey]['startpage'] > $dom[$prevtrkey]['endpage'])) {
  18970. $pgendy = $this->pagedim[$dom[$prevtrkey]['endpage']]['hk'] - $this->pagedim[$dom[$prevtrkey]['endpage']]['bm'];
  18971. $dom[$prevtrkey]['endy'] = $pgendy;
  18972. // update row-spanned cells
  18973. if (isset($dom[($dom[$key]['parent'])]['rowspans'])) {
  18974. foreach ($dom[($dom[$key]['parent'])]['rowspans'] as $k => $trwsp) {
  18975. if (($trwsp['trid'] == $prevtrkey) AND ($trwsp['mrowspan'] >= 0) AND ($trwsp['endpage'] == $dom[$prevtrkey]['endpage'])) {
  18976. $dom[($dom[$key]['parent'])]['rowspans'][$k]['endy'] = $pgendy;
  18977. $dom[($dom[$key]['parent'])]['rowspans'][$k]['mrowspan'] = -1;
  18978. }
  18979. }
  18980. }
  18981. }
  18982. $prevtrkey = $trkey;
  18983. $table_el = $dom[($dom[$key]['parent'])];
  18984. }
  18985. // for each row
  18986. if (count($table_el['trids']) > 0) {
  18987. unset($xmax);
  18988. }
  18989. foreach ($table_el['trids'] as $j => $trkey) {
  18990. $parent = $dom[$trkey];
  18991. if (!isset($xmax)) {
  18992. $xmax = $parent['cellpos'][(count($parent['cellpos']) - 1)]['endx'];
  18993. }
  18994. // for each cell on the row
  18995. foreach ($parent['cellpos'] as $k => $cellpos) {
  18996. if (isset($cellpos['rowspanid']) AND ($cellpos['rowspanid'] >= 0)) {
  18997. $cellpos['startx'] = $table_el['rowspans'][($cellpos['rowspanid'])]['startx'];
  18998. $cellpos['endx'] = $table_el['rowspans'][($cellpos['rowspanid'])]['endx'];
  18999. $endy = $table_el['rowspans'][($cellpos['rowspanid'])]['endy'];
  19000. $startpage = $table_el['rowspans'][($cellpos['rowspanid'])]['startpage'];
  19001. $endpage = $table_el['rowspans'][($cellpos['rowspanid'])]['endpage'];
  19002. $startcolumn = $table_el['rowspans'][($cellpos['rowspanid'])]['startcolumn'];
  19003. $endcolumn = $table_el['rowspans'][($cellpos['rowspanid'])]['endcolumn'];
  19004. } else {
  19005. $endy = $parent['endy'];
  19006. $startpage = $parent['startpage'];
  19007. $endpage = $parent['endpage'];
  19008. $startcolumn = $parent['startcolumn'];
  19009. $endcolumn = $parent['endcolumn'];
  19010. }
  19011. if ($this->num_columns == 0) {
  19012. $this->num_columns = 1;
  19013. }
  19014. if (isset($cellpos['border'])) {
  19015. $border = $cellpos['border'];
  19016. }
  19017. if (isset($cellpos['bgcolor']) AND ($cellpos['bgcolor']) !== false) {
  19018. $this->SetFillColorArray($cellpos['bgcolor']);
  19019. $fill = true;
  19020. } else {
  19021. $fill = false;
  19022. }
  19023. $x = $cellpos['startx'];
  19024. $y = $parent['starty'];
  19025. $starty = $y;
  19026. $w = abs($cellpos['endx'] - $cellpos['startx']);
  19027. // get border modes
  19028. $border_start = TCPDF_STATIC::getBorderMode($border, $position='start', $this->opencell);
  19029. $border_end = TCPDF_STATIC::getBorderMode($border, $position='end', $this->opencell);
  19030. $border_middle = TCPDF_STATIC::getBorderMode($border, $position='middle', $this->opencell);
  19031. // design borders around HTML cells.
  19032. for ($page = $startpage; $page <= $endpage; ++$page) { // for each page
  19033. $ccode = '';
  19034. $this->setPage($page);
  19035. if ($this->num_columns < 2) {
  19036. // single-column mode
  19037. $this->x = $x;
  19038. $this->y = $this->tMargin;
  19039. }
  19040. // account for margin changes
  19041. if ($page > $startpage) {
  19042. if (($this->rtl) AND ($this->pagedim[$page]['orm'] != $this->pagedim[$startpage]['orm'])) {
  19043. $this->x -= ($this->pagedim[$page]['orm'] - $this->pagedim[$startpage]['orm']);
  19044. } elseif ((!$this->rtl) AND ($this->pagedim[$page]['olm'] != $this->pagedim[$startpage]['olm'])) {
  19045. $this->x += ($this->pagedim[$page]['olm'] - $this->pagedim[$startpage]['olm']);
  19046. }
  19047. }
  19048. if ($startpage == $endpage) { // single page
  19049. $deltacol = 0;
  19050. $deltath = 0;
  19051. for ($column = $startcolumn; $column <= $endcolumn; ++$column) { // for each column
  19052. $this->selectColumn($column);
  19053. if ($startcolumn == $endcolumn) { // single column
  19054. $cborder = $border;
  19055. $h = $endy - $parent['starty'];
  19056. $this->y = $y;
  19057. $this->x = $x;
  19058. } elseif ($column == $startcolumn) { // first column
  19059. $cborder = $border_start;
  19060. $this->y = $starty;
  19061. $this->x = $x;
  19062. $h = $this->h - $this->y - $this->bMargin;
  19063. if ($this->rtl) {
  19064. $deltacol = $this->x + $this->rMargin - $this->w;
  19065. } else {
  19066. $deltacol = $this->x - $this->lMargin;
  19067. }
  19068. } elseif ($column == $endcolumn) { // end column
  19069. $cborder = $border_end;
  19070. if (isset($this->columns[$column]['th']['\''.$page.'\''])) {
  19071. $this->y = $this->columns[$column]['th']['\''.$page.'\''];
  19072. }
  19073. $this->x += $deltacol;
  19074. $h = $endy - $this->y;
  19075. } else { // middle column
  19076. $cborder = $border_middle;
  19077. if (isset($this->columns[$column]['th']['\''.$page.'\''])) {
  19078. $this->y = $this->columns[$column]['th']['\''.$page.'\''];
  19079. }
  19080. $this->x += $deltacol;
  19081. $h = $this->h - $this->y - $this->bMargin;
  19082. }
  19083. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  19084. } // end for each column
  19085. } elseif ($page == $startpage) { // first page
  19086. $deltacol = 0;
  19087. $deltath = 0;
  19088. for ($column = $startcolumn; $column < $this->num_columns; ++$column) { // for each column
  19089. $this->selectColumn($column);
  19090. if ($column == $startcolumn) { // first column
  19091. $cborder = $border_start;
  19092. $this->y = $starty;
  19093. $this->x = $x;
  19094. $h = $this->h - $this->y - $this->bMargin;
  19095. if ($this->rtl) {
  19096. $deltacol = $this->x + $this->rMargin - $this->w;
  19097. } else {
  19098. $deltacol = $this->x - $this->lMargin;
  19099. }
  19100. } else { // middle column
  19101. $cborder = $border_middle;
  19102. if (isset($this->columns[$column]['th']['\''.$page.'\''])) {
  19103. $this->y = $this->columns[$column]['th']['\''.$page.'\''];
  19104. }
  19105. $this->x += $deltacol;
  19106. $h = $this->h - $this->y - $this->bMargin;
  19107. }
  19108. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  19109. } // end for each column
  19110. } elseif ($page == $endpage) { // last page
  19111. $deltacol = 0;
  19112. $deltath = 0;
  19113. for ($column = 0; $column <= $endcolumn; ++$column) { // for each column
  19114. $this->selectColumn($column);
  19115. if ($column == $endcolumn) { // end column
  19116. $cborder = $border_end;
  19117. if (isset($this->columns[$column]['th']['\''.$page.'\''])) {
  19118. $this->y = $this->columns[$column]['th']['\''.$page.'\''];
  19119. }
  19120. $this->x += $deltacol;
  19121. $h = $endy - $this->y;
  19122. } else { // middle column
  19123. $cborder = $border_middle;
  19124. if (isset($this->columns[$column]['th']['\''.$page.'\''])) {
  19125. $this->y = $this->columns[$column]['th']['\''.$page.'\''];
  19126. }
  19127. $this->x += $deltacol;
  19128. $h = $this->h - $this->y - $this->bMargin;
  19129. }
  19130. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  19131. } // end for each column
  19132. } else { // middle page
  19133. $deltacol = 0;
  19134. $deltath = 0;
  19135. for ($column = 0; $column < $this->num_columns; ++$column) { // for each column
  19136. $this->selectColumn($column);
  19137. $cborder = $border_middle;
  19138. if (isset($this->columns[$column]['th']['\''.$page.'\''])) {
  19139. $this->y = $this->columns[$column]['th']['\''.$page.'\''];
  19140. }
  19141. $this->x += $deltacol;
  19142. $h = $this->h - $this->y - $this->bMargin;
  19143. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  19144. } // end for each column
  19145. }
  19146. if (!empty($cborder) OR !empty($fill)) {
  19147. $offsetlen = strlen($ccode);
  19148. // draw border and fill
  19149. if ($this->inxobj) {
  19150. // we are inside an XObject template
  19151. if (end($this->xobjects[$this->xobjid]['transfmrk']) !== false) {
  19152. $pagemarkkey = key($this->xobjects[$this->xobjid]['transfmrk']);
  19153. $pagemark = $this->xobjects[$this->xobjid]['transfmrk'][$pagemarkkey];
  19154. $this->xobjects[$this->xobjid]['transfmrk'][$pagemarkkey] += $offsetlen;
  19155. } else {
  19156. $pagemark = $this->xobjects[$this->xobjid]['intmrk'];
  19157. $this->xobjects[$this->xobjid]['intmrk'] += $offsetlen;
  19158. }
  19159. $pagebuff = $this->xobjects[$this->xobjid]['outdata'];
  19160. $pstart = substr($pagebuff, 0, $pagemark);
  19161. $pend = substr($pagebuff, $pagemark);
  19162. $this->xobjects[$this->xobjid]['outdata'] = $pstart.$ccode.$pend;
  19163. } else {
  19164. // draw border and fill
  19165. if (end($this->transfmrk[$this->page]) !== false) {
  19166. $pagemarkkey = key($this->transfmrk[$this->page]);
  19167. $pagemark = $this->transfmrk[$this->page][$pagemarkkey];
  19168. } elseif ($this->InFooter) {
  19169. $pagemark = $this->footerpos[$this->page];
  19170. } else {
  19171. $pagemark = $this->intmrk[$this->page];
  19172. }
  19173. $pagebuff = $this->getPageBuffer($this->page);
  19174. $pstart = substr($pagebuff, 0, $pagemark);
  19175. $pend = substr($pagebuff, $pagemark);
  19176. $this->setPageBuffer($this->page, $pstart.$ccode.$pend);
  19177. }
  19178. }
  19179. } // end for each page
  19180. // restore default border
  19181. $border = $default_border;
  19182. } // end for each cell on the row
  19183. if (isset($table_el['attribute']['cellspacing'])) {
  19184. $this->y += $this->getHTMLUnitToUnits($table_el['attribute']['cellspacing'], 1, 'px');
  19185. } elseif (isset($table_el['border-spacing'])) {
  19186. $this->y += $table_el['border-spacing']['V'];
  19187. }
  19188. $this->Ln(0, $cell);
  19189. $this->x = $parent['startx'];
  19190. if ($endpage > $startpage) {
  19191. if (($this->rtl) AND ($this->pagedim[$endpage]['orm'] != $this->pagedim[$startpage]['orm'])) {
  19192. $this->x += ($this->pagedim[$endpage]['orm'] - $this->pagedim[$startpage]['orm']);
  19193. } elseif ((!$this->rtl) AND ($this->pagedim[$endpage]['olm'] != $this->pagedim[$startpage]['olm'])) {
  19194. $this->x += ($this->pagedim[$endpage]['olm'] - $this->pagedim[$startpage]['olm']);
  19195. }
  19196. }
  19197. }
  19198. if (!$in_table_head) { // we are not inside a thead section
  19199. $this->cell_padding = $table_el['old_cell_padding'];
  19200. // reset row height
  19201. $this->resetLastH();
  19202. if (($this->page == ($this->numpages - 1)) AND ($this->pageopen[$this->numpages])) {
  19203. $plendiff = ($this->pagelen[$this->numpages] - $this->emptypagemrk[$this->numpages]);
  19204. if (($plendiff > 0) AND ($plendiff < 60)) {
  19205. $pagediff = substr($this->getPageBuffer($this->numpages), $this->emptypagemrk[$this->numpages], $plendiff);
  19206. if (substr($pagediff, 0, 5) == 'BT /F') {
  19207. // the difference is only a font setting
  19208. $plendiff = 0;
  19209. }
  19210. }
  19211. if ($plendiff == 0) {
  19212. // remove last blank page
  19213. $this->deletePage($this->numpages);
  19214. }
  19215. }
  19216. if (isset($this->theadMargins['top'])) {
  19217. // restore top margin
  19218. $this->tMargin = $this->theadMargins['top'];
  19219. }
  19220. if (!isset($table_el['attribute']['nested']) OR ($table_el['attribute']['nested'] != 'true')) {
  19221. // reset main table header
  19222. $this->thead = '';
  19223. $this->theadMargins = array();
  19224. $this->pagedim[$this->page]['tm'] = $this->tMargin;
  19225. }
  19226. }
  19227. $parent = $table_el;
  19228. break;
  19229. }
  19230. case 'a': {
  19231. $this->HREF = array();
  19232. break;
  19233. }
  19234. case 'sup': {
  19235. $this->SetXY($this->GetX(), $this->GetY() + ((0.7 * $parent['fontsize']) / $this->k));
  19236. break;
  19237. }
  19238. case 'sub': {
  19239. $this->SetXY($this->GetX(), $this->GetY() - ((0.3 * $parent['fontsize']) / $this->k));
  19240. break;
  19241. }
  19242. case 'div': {
  19243. $this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
  19244. break;
  19245. }
  19246. case 'blockquote': {
  19247. if ($this->rtl) {
  19248. $this->rMargin -= $this->listindent;
  19249. } else {
  19250. $this->lMargin -= $this->listindent;
  19251. }
  19252. --$this->listindentlevel;
  19253. $this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
  19254. break;
  19255. }
  19256. case 'p': {
  19257. $this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
  19258. break;
  19259. }
  19260. case 'pre': {
  19261. $this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
  19262. $this->premode = false;
  19263. break;
  19264. }
  19265. case 'dl': {
  19266. --$this->listnum;
  19267. if ($this->listnum <= 0) {
  19268. $this->listnum = 0;
  19269. $this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
  19270. } else {
  19271. $this->addHTMLVertSpace(0, 0, $cell, false, $lasttag);
  19272. }
  19273. $this->resetLastH();
  19274. break;
  19275. }
  19276. case 'dt': {
  19277. $this->lispacer = '';
  19278. $this->addHTMLVertSpace(0, 0, $cell, false, $lasttag);
  19279. break;
  19280. }
  19281. case 'dd': {
  19282. $this->lispacer = '';
  19283. if ($this->rtl) {
  19284. $this->rMargin -= $this->listindent;
  19285. } else {
  19286. $this->lMargin -= $this->listindent;
  19287. }
  19288. --$this->listindentlevel;
  19289. $this->addHTMLVertSpace(0, 0, $cell, false, $lasttag);
  19290. break;
  19291. }
  19292. case 'ul':
  19293. case 'ol': {
  19294. --$this->listnum;
  19295. $this->lispacer = '';
  19296. if ($this->rtl) {
  19297. $this->rMargin -= $this->listindent;
  19298. } else {
  19299. $this->lMargin -= $this->listindent;
  19300. }
  19301. --$this->listindentlevel;
  19302. if ($this->listnum <= 0) {
  19303. $this->listnum = 0;
  19304. $this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
  19305. } else {
  19306. $this->addHTMLVertSpace(0, 0, $cell, false, $lasttag);
  19307. }
  19308. $this->resetLastH();
  19309. break;
  19310. }
  19311. case 'li': {
  19312. $this->lispacer = '';
  19313. $this->addHTMLVertSpace(0, 0, $cell, false, $lasttag);
  19314. break;
  19315. }
  19316. case 'h1':
  19317. case 'h2':
  19318. case 'h3':
  19319. case 'h4':
  19320. case 'h5':
  19321. case 'h6': {
  19322. $this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
  19323. break;
  19324. }
  19325. // Form fields (since 4.8.000 - 2009-09-07)
  19326. case 'form': {
  19327. $this->form_action = '';
  19328. $this->form_enctype = 'application/x-www-form-urlencoded';
  19329. break;
  19330. }
  19331. default : {
  19332. break;
  19333. }
  19334. }
  19335. // draw border and background (if any)
  19336. $this->drawHTMLTagBorder($parent, $xmax);
  19337. if (isset($dom[($dom[$key]['parent'])]['attribute']['pagebreakafter'])) {
  19338. $pba = $dom[($dom[$key]['parent'])]['attribute']['pagebreakafter'];
  19339. // check for pagebreak
  19340. if (($pba == 'true') OR ($pba == 'left') OR ($pba == 'right')) {
  19341. // add a page (or trig AcceptPageBreak() for multicolumn mode)
  19342. $this->checkPageBreak($this->PageBreakTrigger + 1);
  19343. }
  19344. if ((($pba == 'left') AND (((!$this->rtl) AND (($this->page % 2) == 0)) OR (($this->rtl) AND (($this->page % 2) != 0))))
  19345. OR (($pba == 'right') AND (((!$this->rtl) AND (($this->page % 2) != 0)) OR (($this->rtl) AND (($this->page % 2) == 0))))) {
  19346. // add a page (or trig AcceptPageBreak() for multicolumn mode)
  19347. $this->checkPageBreak($this->PageBreakTrigger + 1);
  19348. }
  19349. }
  19350. $this->tmprtl = false;
  19351. return $dom;
  19352. }
  19353. /**
  19354. * Add vertical spaces if needed.
  19355. * @param $hbz (string) Distance between current y and line bottom.
  19356. * @param $hb (string) The height of the break.
  19357. * @param $cell (boolean) if true add the default left (or right if RTL) padding to each new line (default false).
  19358. * @param $firsttag (boolean) set to true when the tag is the first.
  19359. * @param $lasttag (boolean) set to true when the tag is the last.
  19360. * @protected
  19361. */
  19362. protected function addHTMLVertSpace($hbz=0, $hb=0, $cell=false, $firsttag=false, $lasttag=false) {
  19363. if ($firsttag) {
  19364. $this->Ln(0, $cell);
  19365. $this->htmlvspace = 0;
  19366. return;
  19367. }
  19368. if ($lasttag) {
  19369. $this->Ln($hbz, $cell);
  19370. $this->htmlvspace = 0;
  19371. return;
  19372. }
  19373. if ($hb < $this->htmlvspace) {
  19374. $hd = 0;
  19375. } else {
  19376. $hd = $hb - $this->htmlvspace;
  19377. $this->htmlvspace = $hb;
  19378. }
  19379. $this->Ln(($hbz + $hd), $cell);
  19380. }
  19381. /**
  19382. * Return the starting coordinates to draw an html border
  19383. * @return array containing top-left border coordinates
  19384. * @protected
  19385. * @since 5.7.000 (2010-08-03)
  19386. */
  19387. protected function getBorderStartPosition() {
  19388. if ($this->rtl) {
  19389. $xmax = $this->lMargin;
  19390. } else {
  19391. $xmax = $this->w - $this->rMargin;
  19392. }
  19393. return array('page' => $this->page, 'column' => $this->current_column, 'x' => $this->x, 'y' => $this->y, 'xmax' => $xmax);
  19394. }
  19395. /**
  19396. * Draw an HTML block border and fill
  19397. * @param $tag (array) array of tag properties.
  19398. * @param $xmax (int) end X coordinate for border.
  19399. * @protected
  19400. * @since 5.7.000 (2010-08-03)
  19401. */
  19402. protected function drawHTMLTagBorder($tag, $xmax) {
  19403. if (!isset($tag['borderposition'])) {
  19404. // nothing to draw
  19405. return;
  19406. }
  19407. $prev_x = $this->x;
  19408. $prev_y = $this->y;
  19409. $prev_lasth = $this->lasth;
  19410. $border = 0;
  19411. $fill = false;
  19412. $this->lasth = 0;
  19413. if (isset($tag['border']) AND !empty($tag['border'])) {
  19414. // get border style
  19415. $border = $tag['border'];
  19416. if (!TCPDF_STATIC::empty_string($this->thead) AND (!$this->inthead)) {
  19417. // border for table header
  19418. $border = TCPDF_STATIC::getBorderMode($border, $position='middle', $this->opencell);
  19419. }
  19420. }
  19421. if (isset($tag['bgcolor']) AND ($tag['bgcolor'] !== false)) {
  19422. // get background color
  19423. $old_bgcolor = $this->bgcolor;
  19424. $this->SetFillColorArray($tag['bgcolor']);
  19425. $fill = true;
  19426. }
  19427. if (!$border AND !$fill) {
  19428. // nothing to draw
  19429. return;
  19430. }
  19431. if (isset($tag['attribute']['cellspacing'])) {
  19432. $clsp = $this->getHTMLUnitToUnits($tag['attribute']['cellspacing'], 1, 'px');
  19433. $cellspacing = array('H' => $clsp, 'V' => $clsp);
  19434. } elseif (isset($tag['border-spacing'])) {
  19435. $cellspacing = $tag['border-spacing'];
  19436. } else {
  19437. $cellspacing = array('H' => 0, 'V' => 0);
  19438. }
  19439. if (($tag['value'] != 'table') AND (is_array($border)) AND (!empty($border))) {
  19440. // draw the border externally respect the sqare edge.
  19441. $border['mode'] = 'ext';
  19442. }
  19443. if ($this->rtl) {
  19444. if ($xmax >= $tag['borderposition']['x']) {
  19445. $xmax = $tag['borderposition']['xmax'];
  19446. }
  19447. $w = ($tag['borderposition']['x'] - $xmax);
  19448. } else {
  19449. if ($xmax <= $tag['borderposition']['x']) {
  19450. $xmax = $tag['borderposition']['xmax'];
  19451. }
  19452. $w = ($xmax - $tag['borderposition']['x']);
  19453. }
  19454. if ($w <= 0) {
  19455. return;
  19456. }
  19457. $w += $cellspacing['H'];
  19458. $startpage = $tag['borderposition']['page'];
  19459. $startcolumn = $tag['borderposition']['column'];
  19460. $x = $tag['borderposition']['x'];
  19461. $y = $tag['borderposition']['y'];
  19462. $endpage = $this->page;
  19463. $starty = $tag['borderposition']['y'] - $cellspacing['V'];
  19464. $currentY = $this->y;
  19465. $this->x = $x;
  19466. // get latest column
  19467. $endcolumn = $this->current_column;
  19468. if ($this->num_columns == 0) {
  19469. $this->num_columns = 1;
  19470. }
  19471. // get border modes
  19472. $border_start = TCPDF_STATIC::getBorderMode($border, $position='start', $this->opencell);
  19473. $border_end = TCPDF_STATIC::getBorderMode($border, $position='end', $this->opencell);
  19474. $border_middle = TCPDF_STATIC::getBorderMode($border, $position='middle', $this->opencell);
  19475. // temporary disable page regions
  19476. $temp_page_regions = $this->page_regions;
  19477. $this->page_regions = array();
  19478. // design borders around HTML cells.
  19479. for ($page = $startpage; $page <= $endpage; ++$page) { // for each page
  19480. $ccode = '';
  19481. $this->setPage($page);
  19482. if ($this->num_columns < 2) {
  19483. // single-column mode
  19484. $this->x = $x;
  19485. $this->y = $this->tMargin;
  19486. }
  19487. // account for margin changes
  19488. if ($page > $startpage) {
  19489. if (($this->rtl) AND ($this->pagedim[$page]['orm'] != $this->pagedim[$startpage]['orm'])) {
  19490. $this->x -= ($this->pagedim[$page]['orm'] - $this->pagedim[$startpage]['orm']);
  19491. } elseif ((!$this->rtl) AND ($this->pagedim[$page]['olm'] != $this->pagedim[$startpage]['olm'])) {
  19492. $this->x += ($this->pagedim[$page]['olm'] - $this->pagedim[$startpage]['olm']);
  19493. }
  19494. }
  19495. if ($startpage == $endpage) {
  19496. // single page
  19497. for ($column = $startcolumn; $column <= $endcolumn; ++$column) { // for each column
  19498. $this->selectColumn($column);
  19499. if ($startcolumn == $endcolumn) { // single column
  19500. $cborder = $border;
  19501. $h = ($currentY - $y) + $cellspacing['V'];
  19502. $this->y = $starty;
  19503. } elseif ($column == $startcolumn) { // first column
  19504. $cborder = $border_start;
  19505. $this->y = $starty;
  19506. $h = $this->h - $this->y - $this->bMargin;
  19507. } elseif ($column == $endcolumn) { // end column
  19508. $cborder = $border_end;
  19509. $h = $currentY - $this->y;
  19510. } else { // middle column
  19511. $cborder = $border_middle;
  19512. $h = $this->h - $this->y - $this->bMargin;
  19513. }
  19514. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  19515. } // end for each column
  19516. } elseif ($page == $startpage) { // first page
  19517. for ($column = $startcolumn; $column < $this->num_columns; ++$column) { // for each column
  19518. $this->selectColumn($column);
  19519. if ($column == $startcolumn) { // first column
  19520. $cborder = $border_start;
  19521. $this->y = $starty;
  19522. $h = $this->h - $this->y - $this->bMargin;
  19523. } else { // middle column
  19524. $cborder = $border_middle;
  19525. $h = $this->h - $this->y - $this->bMargin;
  19526. }
  19527. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  19528. } // end for each column
  19529. } elseif ($page == $endpage) { // last page
  19530. for ($column = 0; $column <= $endcolumn; ++$column) { // for each column
  19531. $this->selectColumn($column);
  19532. if ($column == $endcolumn) {
  19533. // end column
  19534. $cborder = $border_end;
  19535. $h = $currentY - $this->y;
  19536. } else {
  19537. // middle column
  19538. $cborder = $border_middle;
  19539. $h = $this->h - $this->y - $this->bMargin;
  19540. }
  19541. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  19542. } // end for each column
  19543. } else { // middle page
  19544. for ($column = 0; $column < $this->num_columns; ++$column) { // for each column
  19545. $this->selectColumn($column);
  19546. $cborder = $border_middle;
  19547. $h = $this->h - $this->y - $this->bMargin;
  19548. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  19549. } // end for each column
  19550. }
  19551. if ($cborder OR $fill) {
  19552. $offsetlen = strlen($ccode);
  19553. // draw border and fill
  19554. if ($this->inxobj) {
  19555. // we are inside an XObject template
  19556. if (end($this->xobjects[$this->xobjid]['transfmrk']) !== false) {
  19557. $pagemarkkey = key($this->xobjects[$this->xobjid]['transfmrk']);
  19558. $pagemark = $this->xobjects[$this->xobjid]['transfmrk'][$pagemarkkey];
  19559. $this->xobjects[$this->xobjid]['transfmrk'][$pagemarkkey] += $offsetlen;
  19560. } else {
  19561. $pagemark = $this->xobjects[$this->xobjid]['intmrk'];
  19562. $this->xobjects[$this->xobjid]['intmrk'] += $offsetlen;
  19563. }
  19564. $pagebuff = $this->xobjects[$this->xobjid]['outdata'];
  19565. $pstart = substr($pagebuff, 0, $pagemark);
  19566. $pend = substr($pagebuff, $pagemark);
  19567. $this->xobjects[$this->xobjid]['outdata'] = $pstart.$ccode.$pend;
  19568. } else {
  19569. if (end($this->transfmrk[$this->page]) !== false) {
  19570. $pagemarkkey = key($this->transfmrk[$this->page]);
  19571. $pagemark = $this->transfmrk[$this->page][$pagemarkkey];
  19572. } elseif ($this->InFooter) {
  19573. $pagemark = $this->footerpos[$this->page];
  19574. } else {
  19575. $pagemark = $this->intmrk[$this->page];
  19576. }
  19577. $pagebuff = $this->getPageBuffer($this->page);
  19578. $pstart = substr($pagebuff, 0, $pagemark);
  19579. $pend = substr($pagebuff, $pagemark);
  19580. $this->setPageBuffer($this->page, $pstart.$ccode.$pend);
  19581. $this->bordermrk[$this->page] += $offsetlen;
  19582. $this->cntmrk[$this->page] += $offsetlen;
  19583. }
  19584. }
  19585. } // end for each page
  19586. // restore page regions
  19587. $this->page_regions = $temp_page_regions;
  19588. if (isset($old_bgcolor)) {
  19589. // restore background color
  19590. $this->SetFillColorArray($old_bgcolor);
  19591. }
  19592. // restore pointer position
  19593. $this->x = $prev_x;
  19594. $this->y = $prev_y;
  19595. $this->lasth = $prev_lasth;
  19596. }
  19597. /**
  19598. * Set the default bullet to be used as LI bullet symbol
  19599. * @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')
  19600. * @public
  19601. * @since 4.0.028 (2008-09-26)
  19602. */
  19603. public function setLIsymbol($symbol='!') {
  19604. // check for custom image symbol
  19605. if (substr($symbol, 0, 4) == 'img|') {
  19606. $this->lisymbol = $symbol;
  19607. return;
  19608. }
  19609. $symbol = strtolower($symbol);
  19610. $valid_symbols = array('!', '#', 'disc', 'circle', 'square', '1', 'decimal', 'decimal-leading-zero', 'i', 'lower-roman', 'I', 'upper-roman', 'a', 'lower-alpha', 'lower-latin', 'A', 'upper-alpha', 'upper-latin', 'lower-greek');
  19611. if (in_array($symbol, $valid_symbols)) {
  19612. $this->lisymbol = $symbol;
  19613. } else {
  19614. $this->lisymbol = '';
  19615. }
  19616. }
  19617. /**
  19618. * Set the booklet mode for double-sided pages.
  19619. * @param $booklet (boolean) true set the booklet mode on, false otherwise.
  19620. * @param $inner (float) Inner page margin.
  19621. * @param $outer (float) Outer page margin.
  19622. * @public
  19623. * @since 4.2.000 (2008-10-29)
  19624. */
  19625. public function SetBooklet($booklet=true, $inner=-1, $outer=-1) {
  19626. $this->booklet = $booklet;
  19627. if ($inner >= 0) {
  19628. $this->lMargin = $inner;
  19629. }
  19630. if ($outer >= 0) {
  19631. $this->rMargin = $outer;
  19632. }
  19633. }
  19634. /**
  19635. * Swap the left and right margins.
  19636. * @param $reverse (boolean) if true swap left and right margins.
  19637. * @protected
  19638. * @since 4.2.000 (2008-10-29)
  19639. */
  19640. protected function swapMargins($reverse=true) {
  19641. if ($reverse) {
  19642. // swap left and right margins
  19643. $mtemp = $this->original_lMargin;
  19644. $this->original_lMargin = $this->original_rMargin;
  19645. $this->original_rMargin = $mtemp;
  19646. $deltam = $this->original_lMargin - $this->original_rMargin;
  19647. $this->lMargin += $deltam;
  19648. $this->rMargin -= $deltam;
  19649. }
  19650. }
  19651. /**
  19652. * Set the vertical spaces for HTML tags.
  19653. * The array must have the following structure (example):
  19654. * $tagvs = array('h1' => array(0 => array('h' => '', 'n' => 2), 1 => array('h' => 1.3, 'n' => 1)));
  19655. * The first array level contains the tag names,
  19656. * the second level contains 0 for opening tags or 1 for closing tags,
  19657. * the third level contains the vertical space unit (h) and the number spaces to add (n).
  19658. * If the h parameter is not specified, default values are used.
  19659. * @param $tagvs (array) array of tags and relative vertical spaces.
  19660. * @public
  19661. * @since 4.2.001 (2008-10-30)
  19662. */
  19663. public function setHtmlVSpace($tagvs) {
  19664. $this->tagvspaces = $tagvs;
  19665. }
  19666. /**
  19667. * Set custom width for list indentation.
  19668. * @param $width (float) width of the indentation. Use negative value to disable it.
  19669. * @public
  19670. * @since 4.2.007 (2008-11-12)
  19671. */
  19672. public function setListIndentWidth($width) {
  19673. return $this->customlistindent = floatval($width);
  19674. }
  19675. /**
  19676. * Set the top/bottom cell sides to be open or closed when the cell cross the page.
  19677. * @param $isopen (boolean) if true keeps the top/bottom border open for the cell sides that cross the page.
  19678. * @public
  19679. * @since 4.2.010 (2008-11-14)
  19680. */
  19681. public function setOpenCell($isopen) {
  19682. $this->opencell = $isopen;
  19683. }
  19684. /**
  19685. * Set the color and font style for HTML links.
  19686. * @param $color (array) RGB array of colors
  19687. * @param $fontstyle (string) additional font styles to add
  19688. * @public
  19689. * @since 4.4.003 (2008-12-09)
  19690. */
  19691. public function setHtmlLinksStyle($color=array(0,0,255), $fontstyle='U') {
  19692. $this->htmlLinkColorArray = $color;
  19693. $this->htmlLinkFontStyle = $fontstyle;
  19694. }
  19695. /**
  19696. * Convert HTML string containing value and unit of measure to user's units or points.
  19697. * @param $htmlval (string) String containing values and unit.
  19698. * @param $refsize (string) Reference value in points.
  19699. * @param $defaultunit (string) Default unit (can be one of the following: %, em, ex, px, in, mm, pc, pt).
  19700. * @param $points (boolean) If true returns points, otherwise returns value in user's units.
  19701. * @return float value in user's unit or point if $points=true
  19702. * @public
  19703. * @since 4.4.004 (2008-12-10)
  19704. */
  19705. public function getHTMLUnitToUnits($htmlval, $refsize=1, $defaultunit='px', $points=false) {
  19706. $supportedunits = array('%', 'em', 'ex', 'px', 'in', 'cm', 'mm', 'pc', 'pt');
  19707. $retval = 0;
  19708. $value = 0;
  19709. $unit = 'px';
  19710. if ($points) {
  19711. $k = 1;
  19712. } else {
  19713. $k = $this->k;
  19714. }
  19715. if (in_array($defaultunit, $supportedunits)) {
  19716. $unit = $defaultunit;
  19717. }
  19718. if (is_numeric($htmlval)) {
  19719. $value = floatval($htmlval);
  19720. } elseif (preg_match('/([0-9\.\-\+]+)/', $htmlval, $mnum)) {
  19721. $value = floatval($mnum[1]);
  19722. if (preg_match('/([a-z%]+)/', $htmlval, $munit)) {
  19723. if (in_array($munit[1], $supportedunits)) {
  19724. $unit = $munit[1];
  19725. }
  19726. }
  19727. }
  19728. switch ($unit) {
  19729. // percentage
  19730. case '%': {
  19731. $retval = (($value * $refsize) / 100);
  19732. break;
  19733. }
  19734. // relative-size
  19735. case 'em': {
  19736. $retval = ($value * $refsize);
  19737. break;
  19738. }
  19739. // height of lower case 'x' (about half the font-size)
  19740. case 'ex': {
  19741. $retval = ($value * ($refsize / 2));
  19742. break;
  19743. }
  19744. // absolute-size
  19745. case 'in': {
  19746. $retval = (($value * $this->dpi) / $k);
  19747. break;
  19748. }
  19749. // centimeters
  19750. case 'cm': {
  19751. $retval = (($value / 2.54 * $this->dpi) / $k);
  19752. break;
  19753. }
  19754. // millimeters
  19755. case 'mm': {
  19756. $retval = (($value / 25.4 * $this->dpi) / $k);
  19757. break;
  19758. }
  19759. // one pica is 12 points
  19760. case 'pc': {
  19761. $retval = (($value * 12) / $k);
  19762. break;
  19763. }
  19764. // points
  19765. case 'pt': {
  19766. $retval = ($value / $k);
  19767. break;
  19768. }
  19769. // pixels
  19770. case 'px': {
  19771. $retval = $this->pixelsToUnits($value);
  19772. if ($points) {
  19773. $retval *= $this->k;
  19774. }
  19775. break;
  19776. }
  19777. }
  19778. return $retval;
  19779. }
  19780. /**
  19781. * Output an HTML list bullet or ordered item symbol
  19782. * @param $listdepth (int) list nesting level
  19783. * @param $listtype (string) type of list
  19784. * @param $size (float) current font size
  19785. * @protected
  19786. * @since 4.4.004 (2008-12-10)
  19787. */
  19788. protected function putHtmlListBullet($listdepth, $listtype='', $size=10) {
  19789. if ($this->state != 2) {
  19790. return;
  19791. }
  19792. $size /= $this->k;
  19793. $fill = '';
  19794. $bgcolor = $this->bgcolor;
  19795. $color = $this->fgcolor;
  19796. $strokecolor = $this->strokecolor;
  19797. $width = 0;
  19798. $textitem = '';
  19799. $tmpx = $this->x;
  19800. $lspace = $this->GetStringWidth(' ');
  19801. if ($listtype == '^') {
  19802. // special symbol used for avoid justification of rect bullet
  19803. $this->lispacer = '';
  19804. return;
  19805. } elseif ($listtype == '!') {
  19806. // set default list type for unordered list
  19807. $deftypes = array('disc', 'circle', 'square');
  19808. $listtype = $deftypes[($listdepth - 1) % 3];
  19809. } elseif ($listtype == '#') {
  19810. // set default list type for ordered list
  19811. $listtype = 'decimal';
  19812. } elseif (substr($listtype, 0, 4) == 'img|') {
  19813. // custom image type ('img|type|width|height|image.ext')
  19814. $img = explode('|', $listtype);
  19815. $listtype = 'img';
  19816. }
  19817. switch ($listtype) {
  19818. // unordered types
  19819. case 'none': {
  19820. break;
  19821. }
  19822. case 'disc': {
  19823. $r = $size / 6;
  19824. $lspace += (2 * $r);
  19825. if ($this->rtl) {
  19826. $this->x += $lspace;
  19827. } else {
  19828. $this->x -= $lspace;
  19829. }
  19830. $this->Circle(($this->x + $r), ($this->y + ($this->lasth / 2)), $r, 0, 360, 'F', array(), $color, 8);
  19831. break;
  19832. }
  19833. case 'circle': {
  19834. $r = $size / 6;
  19835. $lspace += (2 * $r);
  19836. if ($this->rtl) {
  19837. $this->x += $lspace;
  19838. } else {
  19839. $this->x -= $lspace;
  19840. }
  19841. $prev_line_style = $this->linestyleWidth.' '.$this->linestyleCap.' '.$this->linestyleJoin.' '.$this->linestyleDash.' '.$this->DrawColor;
  19842. $new_line_style = array('width' => ($r / 3), 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'phase' => 0, 'color'=>$color);
  19843. $this->Circle(($this->x + $r), ($this->y + ($this->lasth / 2)), ($r * (1 - (1/6))), 0, 360, 'D', $new_line_style, array(), 8);
  19844. $this->_out($prev_line_style); // restore line settings
  19845. break;
  19846. }
  19847. case 'square': {
  19848. $l = $size / 3;
  19849. $lspace += $l;
  19850. if ($this->rtl) {;
  19851. $this->x += $lspace;
  19852. } else {
  19853. $this->x -= $lspace;
  19854. }
  19855. $this->Rect($this->x, ($this->y + (($this->lasth - $l) / 2)), $l, $l, 'F', array(), $color);
  19856. break;
  19857. }
  19858. case 'img': {
  19859. // 1=>type, 2=>width, 3=>height, 4=>image.ext
  19860. $lspace += $img[2];
  19861. if ($this->rtl) {;
  19862. $this->x += $lspace;
  19863. } else {
  19864. $this->x -= $lspace;
  19865. }
  19866. $imgtype = strtolower($img[1]);
  19867. $prev_y = $this->y;
  19868. switch ($imgtype) {
  19869. case 'svg': {
  19870. $this->ImageSVG($img[4], $this->x, ($this->y + (($this->lasth - $img[3]) / 2)), $img[2], $img[3], '', 'T', '', 0, false);
  19871. break;
  19872. }
  19873. case 'ai':
  19874. case 'eps': {
  19875. $this->ImageEps($img[4], $this->x, ($this->y + (($this->lasth - $img[3]) / 2)), $img[2], $img[3], '', true, 'T', '', 0, false);
  19876. break;
  19877. }
  19878. default: {
  19879. $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);
  19880. break;
  19881. }
  19882. }
  19883. $this->y = $prev_y;
  19884. break;
  19885. }
  19886. // ordered types
  19887. // $this->listcount[$this->listnum];
  19888. // $textitem
  19889. case '1':
  19890. case 'decimal': {
  19891. $textitem = $this->listcount[$this->listnum];
  19892. break;
  19893. }
  19894. case 'decimal-leading-zero': {
  19895. $textitem = sprintf('%02d', $this->listcount[$this->listnum]);
  19896. break;
  19897. }
  19898. case 'i':
  19899. case 'lower-roman': {
  19900. $textitem = strtolower(TCPDF_STATIC::intToRoman($this->listcount[$this->listnum]));
  19901. break;
  19902. }
  19903. case 'I':
  19904. case 'upper-roman': {
  19905. $textitem = TCPDF_STATIC::intToRoman($this->listcount[$this->listnum]);
  19906. break;
  19907. }
  19908. case 'a':
  19909. case 'lower-alpha':
  19910. case 'lower-latin': {
  19911. $textitem = chr(97 + $this->listcount[$this->listnum] - 1);
  19912. break;
  19913. }
  19914. case 'A':
  19915. case 'upper-alpha':
  19916. case 'upper-latin': {
  19917. $textitem = chr(65 + $this->listcount[$this->listnum] - 1);
  19918. break;
  19919. }
  19920. case 'lower-greek': {
  19921. $textitem = TCPDF_FONTS::unichr((945 + $this->listcount[$this->listnum] - 1), $this->isunicode);
  19922. break;
  19923. }
  19924. /*
  19925. // Types to be implemented (special handling)
  19926. case 'hebrew': {
  19927. break;
  19928. }
  19929. case 'armenian': {
  19930. break;
  19931. }
  19932. case 'georgian': {
  19933. break;
  19934. }
  19935. case 'cjk-ideographic': {
  19936. break;
  19937. }
  19938. case 'hiragana': {
  19939. break;
  19940. }
  19941. case 'katakana': {
  19942. break;
  19943. }
  19944. case 'hiragana-iroha': {
  19945. break;
  19946. }
  19947. case 'katakana-iroha': {
  19948. break;
  19949. }
  19950. */
  19951. default: {
  19952. $textitem = $this->listcount[$this->listnum];
  19953. }
  19954. }
  19955. if (!TCPDF_STATIC::empty_string($textitem)) {
  19956. // Check whether we need a new page or new column
  19957. $prev_y = $this->y;
  19958. $h = $this->getCellHeight($this->FontSize);
  19959. if ($this->checkPageBreak($h) OR ($this->y < $prev_y)) {
  19960. $tmpx = $this->x;
  19961. }
  19962. // print ordered item
  19963. if ($this->rtl) {
  19964. $textitem = '.'.$textitem;
  19965. } else {
  19966. $textitem = $textitem.'.';
  19967. }
  19968. $lspace += $this->GetStringWidth($textitem);
  19969. if ($this->rtl) {
  19970. $this->x += $lspace;
  19971. } else {
  19972. $this->x -= $lspace;
  19973. }
  19974. $this->Write($this->lasth, $textitem, '', false, '', false, 0, false);
  19975. }
  19976. $this->x = $tmpx;
  19977. $this->lispacer = '^';
  19978. // restore colors
  19979. $this->SetFillColorArray($bgcolor);
  19980. $this->SetDrawColorArray($strokecolor);
  19981. $this->SettextColorArray($color);
  19982. }
  19983. /**
  19984. * Returns current graphic variables as array.
  19985. * @return array of graphic variables
  19986. * @protected
  19987. * @since 4.2.010 (2008-11-14)
  19988. */
  19989. protected function getGraphicVars() {
  19990. $grapvars = array(
  19991. 'FontFamily' => $this->FontFamily,
  19992. 'FontStyle' => $this->FontStyle,
  19993. 'FontSizePt' => $this->FontSizePt,
  19994. 'rMargin' => $this->rMargin,
  19995. 'lMargin' => $this->lMargin,
  19996. 'cell_padding' => $this->cell_padding,
  19997. 'cell_margin' => $this->cell_margin,
  19998. 'LineWidth' => $this->LineWidth,
  19999. 'linestyleWidth' => $this->linestyleWidth,
  20000. 'linestyleCap' => $this->linestyleCap,
  20001. 'linestyleJoin' => $this->linestyleJoin,
  20002. 'linestyleDash' => $this->linestyleDash,
  20003. 'textrendermode' => $this->textrendermode,
  20004. 'textstrokewidth' => $this->textstrokewidth,
  20005. 'DrawColor' => $this->DrawColor,
  20006. 'FillColor' => $this->FillColor,
  20007. 'TextColor' => $this->TextColor,
  20008. 'ColorFlag' => $this->ColorFlag,
  20009. 'bgcolor' => $this->bgcolor,
  20010. 'fgcolor' => $this->fgcolor,
  20011. 'htmlvspace' => $this->htmlvspace,
  20012. 'listindent' => $this->listindent,
  20013. 'listindentlevel' => $this->listindentlevel,
  20014. 'listnum' => $this->listnum,
  20015. 'listordered' => $this->listordered,
  20016. 'listcount' => $this->listcount,
  20017. 'lispacer' => $this->lispacer,
  20018. 'cell_height_ratio' => $this->cell_height_ratio,
  20019. 'font_stretching' => $this->font_stretching,
  20020. 'font_spacing' => $this->font_spacing,
  20021. 'alpha' => $this->alpha,
  20022. // extended
  20023. 'lasth' => $this->lasth,
  20024. 'tMargin' => $this->tMargin,
  20025. 'bMargin' => $this->bMargin,
  20026. 'AutoPageBreak' => $this->AutoPageBreak,
  20027. 'PageBreakTrigger' => $this->PageBreakTrigger,
  20028. 'x' => $this->x,
  20029. 'y' => $this->y,
  20030. 'w' => $this->w,
  20031. 'h' => $this->h,
  20032. 'wPt' => $this->wPt,
  20033. 'hPt' => $this->hPt,
  20034. 'fwPt' => $this->fwPt,
  20035. 'fhPt' => $this->fhPt,
  20036. 'page' => $this->page,
  20037. 'current_column' => $this->current_column,
  20038. 'num_columns' => $this->num_columns
  20039. );
  20040. return $grapvars;
  20041. }
  20042. /**
  20043. * Set graphic variables.
  20044. * @param $gvars (array) array of graphic variablesto restore
  20045. * @param $extended (boolean) if true restore extended graphic variables
  20046. * @protected
  20047. * @since 4.2.010 (2008-11-14)
  20048. */
  20049. protected function setGraphicVars($gvars, $extended=false) {
  20050. if ($this->state != 2) {
  20051. return;
  20052. }
  20053. $this->FontFamily = $gvars['FontFamily'];
  20054. $this->FontStyle = $gvars['FontStyle'];
  20055. $this->FontSizePt = $gvars['FontSizePt'];
  20056. $this->rMargin = $gvars['rMargin'];
  20057. $this->lMargin = $gvars['lMargin'];
  20058. $this->cell_padding = $gvars['cell_padding'];
  20059. $this->cell_margin = $gvars['cell_margin'];
  20060. $this->LineWidth = $gvars['LineWidth'];
  20061. $this->linestyleWidth = $gvars['linestyleWidth'];
  20062. $this->linestyleCap = $gvars['linestyleCap'];
  20063. $this->linestyleJoin = $gvars['linestyleJoin'];
  20064. $this->linestyleDash = $gvars['linestyleDash'];
  20065. $this->textrendermode = $gvars['textrendermode'];
  20066. $this->textstrokewidth = $gvars['textstrokewidth'];
  20067. $this->DrawColor = $gvars['DrawColor'];
  20068. $this->FillColor = $gvars['FillColor'];
  20069. $this->TextColor = $gvars['TextColor'];
  20070. $this->ColorFlag = $gvars['ColorFlag'];
  20071. $this->bgcolor = $gvars['bgcolor'];
  20072. $this->fgcolor = $gvars['fgcolor'];
  20073. $this->htmlvspace = $gvars['htmlvspace'];
  20074. $this->listindent = $gvars['listindent'];
  20075. $this->listindentlevel = $gvars['listindentlevel'];
  20076. $this->listnum = $gvars['listnum'];
  20077. $this->listordered = $gvars['listordered'];
  20078. $this->listcount = $gvars['listcount'];
  20079. $this->lispacer = $gvars['lispacer'];
  20080. $this->cell_height_ratio = $gvars['cell_height_ratio'];
  20081. $this->font_stretching = $gvars['font_stretching'];
  20082. $this->font_spacing = $gvars['font_spacing'];
  20083. $this->alpha = $gvars['alpha'];
  20084. if ($extended) {
  20085. // restore extended values
  20086. $this->lasth = $gvars['lasth'];
  20087. $this->tMargin = $gvars['tMargin'];
  20088. $this->bMargin = $gvars['bMargin'];
  20089. $this->AutoPageBreak = $gvars['AutoPageBreak'];
  20090. $this->PageBreakTrigger = $gvars['PageBreakTrigger'];
  20091. $this->x = $gvars['x'];
  20092. $this->y = $gvars['y'];
  20093. $this->w = $gvars['w'];
  20094. $this->h = $gvars['h'];
  20095. $this->wPt = $gvars['wPt'];
  20096. $this->hPt = $gvars['hPt'];
  20097. $this->fwPt = $gvars['fwPt'];
  20098. $this->fhPt = $gvars['fhPt'];
  20099. $this->page = $gvars['page'];
  20100. $this->current_column = $gvars['current_column'];
  20101. $this->num_columns = $gvars['num_columns'];
  20102. }
  20103. $this->_out(''.$this->linestyleWidth.' '.$this->linestyleCap.' '.$this->linestyleJoin.' '.$this->linestyleDash.' '.$this->DrawColor.' '.$this->FillColor.'');
  20104. if (!TCPDF_STATIC::empty_string($this->FontFamily)) {
  20105. $this->SetFont($this->FontFamily, $this->FontStyle, $this->FontSizePt);
  20106. }
  20107. }
  20108. /**
  20109. * Outputs the "save graphics state" operator 'q'
  20110. * @protected
  20111. */
  20112. protected function _outSaveGraphicsState() {
  20113. $this->_out('q');
  20114. }
  20115. /**
  20116. * Outputs the "restore graphics state" operator 'Q'
  20117. * @protected
  20118. */
  20119. protected function _outRestoreGraphicsState() {
  20120. $this->_out('Q');
  20121. }
  20122. /**
  20123. * Set buffer content (always append data).
  20124. * @param $data (string) data
  20125. * @protected
  20126. * @since 4.5.000 (2009-01-02)
  20127. */
  20128. protected function setBuffer($data) {
  20129. $this->bufferlen += strlen($data);
  20130. $this->buffer .= $data;
  20131. }
  20132. /**
  20133. * Replace the buffer content
  20134. * @param $data (string) data
  20135. * @protected
  20136. * @since 5.5.000 (2010-06-22)
  20137. */
  20138. protected function replaceBuffer($data) {
  20139. $this->bufferlen = strlen($data);
  20140. $this->buffer = $data;
  20141. }
  20142. /**
  20143. * Get buffer content.
  20144. * @return string buffer content
  20145. * @protected
  20146. * @since 4.5.000 (2009-01-02)
  20147. */
  20148. protected function getBuffer() {
  20149. return $this->buffer;
  20150. }
  20151. /**
  20152. * Set page buffer content.
  20153. * @param $page (int) page number
  20154. * @param $data (string) page data
  20155. * @param $append (boolean) if true append data, false replace.
  20156. * @protected
  20157. * @since 4.5.000 (2008-12-31)
  20158. */
  20159. protected function setPageBuffer($page, $data, $append=false) {
  20160. if ($append) {
  20161. $this->pages[$page] .= $data;
  20162. } else {
  20163. $this->pages[$page] = $data;
  20164. }
  20165. if ($append AND isset($this->pagelen[$page])) {
  20166. $this->pagelen[$page] += strlen($data);
  20167. } else {
  20168. $this->pagelen[$page] = strlen($data);
  20169. }
  20170. }
  20171. /**
  20172. * Get page buffer content.
  20173. * @param $page (int) page number
  20174. * @return string page buffer content or false in case of error
  20175. * @protected
  20176. * @since 4.5.000 (2008-12-31)
  20177. */
  20178. protected function getPageBuffer($page) {
  20179. if (isset($this->pages[$page])) {
  20180. return $this->pages[$page];
  20181. }
  20182. return false;
  20183. }
  20184. /**
  20185. * Set image buffer content.
  20186. * @param $image (string) image key
  20187. * @param $data (array) image data
  20188. * @return int image index number
  20189. * @protected
  20190. * @since 4.5.000 (2008-12-31)
  20191. */
  20192. protected function setImageBuffer($image, $data) {
  20193. if (($data['i'] = array_search($image, $this->imagekeys)) === FALSE) {
  20194. $this->imagekeys[$this->numimages] = $image;
  20195. $data['i'] = $this->numimages;
  20196. ++$this->numimages;
  20197. }
  20198. $this->images[$image] = $data;
  20199. return $data['i'];
  20200. }
  20201. /**
  20202. * Set image buffer content for a specified sub-key.
  20203. * @param $image (string) image key
  20204. * @param $key (string) image sub-key
  20205. * @param $data (array) image data
  20206. * @protected
  20207. * @since 4.5.000 (2008-12-31)
  20208. */
  20209. protected function setImageSubBuffer($image, $key, $data) {
  20210. if (!isset($this->images[$image])) {
  20211. $this->setImageBuffer($image, array());
  20212. }
  20213. $this->images[$image][$key] = $data;
  20214. }
  20215. /**
  20216. * Get image buffer content.
  20217. * @param $image (string) image key
  20218. * @return string image buffer content or false in case of error
  20219. * @protected
  20220. * @since 4.5.000 (2008-12-31)
  20221. */
  20222. protected function getImageBuffer($image) {
  20223. if (isset($this->images[$image])) {
  20224. return $this->images[$image];
  20225. }
  20226. return false;
  20227. }
  20228. /**
  20229. * Set font buffer content.
  20230. * @param $font (string) font key
  20231. * @param $data (array) font data
  20232. * @protected
  20233. * @since 4.5.000 (2009-01-02)
  20234. */
  20235. protected function setFontBuffer($font, $data) {
  20236. $this->fonts[$font] = $data;
  20237. if (!in_array($font, $this->fontkeys)) {
  20238. $this->fontkeys[] = $font;
  20239. // store object ID for current font
  20240. ++$this->n;
  20241. $this->font_obj_ids[$font] = $this->n;
  20242. $this->setFontSubBuffer($font, 'n', $this->n);
  20243. }
  20244. }
  20245. /**
  20246. * Set font buffer content.
  20247. * @param $font (string) font key
  20248. * @param $key (string) font sub-key
  20249. * @param $data (array) font data
  20250. * @protected
  20251. * @since 4.5.000 (2009-01-02)
  20252. */
  20253. protected function setFontSubBuffer($font, $key, $data) {
  20254. if (!isset($this->fonts[$font])) {
  20255. $this->setFontBuffer($font, array());
  20256. }
  20257. $this->fonts[$font][$key] = $data;
  20258. }
  20259. /**
  20260. * Get font buffer content.
  20261. * @param $font (string) font key
  20262. * @return string font buffer content or false in case of error
  20263. * @protected
  20264. * @since 4.5.000 (2009-01-02)
  20265. */
  20266. protected function getFontBuffer($font) {
  20267. if (isset($this->fonts[$font])) {
  20268. return $this->fonts[$font];
  20269. }
  20270. return false;
  20271. }
  20272. /**
  20273. * Move a page to a previous position.
  20274. * @param $frompage (int) number of the source page
  20275. * @param $topage (int) number of the destination page (must be less than $frompage)
  20276. * @return true in case of success, false in case of error.
  20277. * @public
  20278. * @since 4.5.000 (2009-01-02)
  20279. */
  20280. public function movePage($frompage, $topage) {
  20281. if (($frompage > $this->numpages) OR ($frompage <= $topage)) {
  20282. return false;
  20283. }
  20284. if ($frompage == $this->page) {
  20285. // close the page before moving it
  20286. $this->endPage();
  20287. }
  20288. // move all page-related states
  20289. $tmppage = $this->getPageBuffer($frompage);
  20290. $tmppagedim = $this->pagedim[$frompage];
  20291. $tmppagelen = $this->pagelen[$frompage];
  20292. $tmpintmrk = $this->intmrk[$frompage];
  20293. $tmpbordermrk = $this->bordermrk[$frompage];
  20294. $tmpcntmrk = $this->cntmrk[$frompage];
  20295. $tmppageobjects = $this->pageobjects[$frompage];
  20296. if (isset($this->footerpos[$frompage])) {
  20297. $tmpfooterpos = $this->footerpos[$frompage];
  20298. }
  20299. if (isset($this->footerlen[$frompage])) {
  20300. $tmpfooterlen = $this->footerlen[$frompage];
  20301. }
  20302. if (isset($this->transfmrk[$frompage])) {
  20303. $tmptransfmrk = $this->transfmrk[$frompage];
  20304. }
  20305. if (isset($this->PageAnnots[$frompage])) {
  20306. $tmpannots = $this->PageAnnots[$frompage];
  20307. }
  20308. if (isset($this->newpagegroup) AND !empty($this->newpagegroup)) {
  20309. for ($i = $frompage; $i > $topage; --$i) {
  20310. if (isset($this->newpagegroup[$i]) AND (($i + $this->pagegroups[$this->newpagegroup[$i]]) > $frompage)) {
  20311. --$this->pagegroups[$this->newpagegroup[$i]];
  20312. break;
  20313. }
  20314. }
  20315. for ($i = $topage; $i > 0; --$i) {
  20316. if (isset($this->newpagegroup[$i]) AND (($i + $this->pagegroups[$this->newpagegroup[$i]]) > $topage)) {
  20317. ++$this->pagegroups[$this->newpagegroup[$i]];
  20318. break;
  20319. }
  20320. }
  20321. }
  20322. for ($i = $frompage; $i > $topage; --$i) {
  20323. $j = $i - 1;
  20324. // shift pages down
  20325. $this->setPageBuffer($i, $this->getPageBuffer($j));
  20326. $this->pagedim[$i] = $this->pagedim[$j];
  20327. $this->pagelen[$i] = $this->pagelen[$j];
  20328. $this->intmrk[$i] = $this->intmrk[$j];
  20329. $this->bordermrk[$i] = $this->bordermrk[$j];
  20330. $this->cntmrk[$i] = $this->cntmrk[$j];
  20331. $this->pageobjects[$i] = $this->pageobjects[$j];
  20332. if (isset($this->footerpos[$j])) {
  20333. $this->footerpos[$i] = $this->footerpos[$j];
  20334. } elseif (isset($this->footerpos[$i])) {
  20335. unset($this->footerpos[$i]);
  20336. }
  20337. if (isset($this->footerlen[$j])) {
  20338. $this->footerlen[$i] = $this->footerlen[$j];
  20339. } elseif (isset($this->footerlen[$i])) {
  20340. unset($this->footerlen[$i]);
  20341. }
  20342. if (isset($this->transfmrk[$j])) {
  20343. $this->transfmrk[$i] = $this->transfmrk[$j];
  20344. } elseif (isset($this->transfmrk[$i])) {
  20345. unset($this->transfmrk[$i]);
  20346. }
  20347. if (isset($this->PageAnnots[$j])) {
  20348. $this->PageAnnots[$i] = $this->PageAnnots[$j];
  20349. } elseif (isset($this->PageAnnots[$i])) {
  20350. unset($this->PageAnnots[$i]);
  20351. }
  20352. if (isset($this->newpagegroup[$j])) {
  20353. $this->newpagegroup[$i] = $this->newpagegroup[$j];
  20354. unset($this->newpagegroup[$j]);
  20355. }
  20356. if ($this->currpagegroup == $j) {
  20357. $this->currpagegroup = $i;
  20358. }
  20359. }
  20360. $this->setPageBuffer($topage, $tmppage);
  20361. $this->pagedim[$topage] = $tmppagedim;
  20362. $this->pagelen[$topage] = $tmppagelen;
  20363. $this->intmrk[$topage] = $tmpintmrk;
  20364. $this->bordermrk[$topage] = $tmpbordermrk;
  20365. $this->cntmrk[$topage] = $tmpcntmrk;
  20366. $this->pageobjects[$topage] = $tmppageobjects;
  20367. if (isset($tmpfooterpos)) {
  20368. $this->footerpos[$topage] = $tmpfooterpos;
  20369. } elseif (isset($this->footerpos[$topage])) {
  20370. unset($this->footerpos[$topage]);
  20371. }
  20372. if (isset($tmpfooterlen)) {
  20373. $this->footerlen[$topage] = $tmpfooterlen;
  20374. } elseif (isset($this->footerlen[$topage])) {
  20375. unset($this->footerlen[$topage]);
  20376. }
  20377. if (isset($tmptransfmrk)) {
  20378. $this->transfmrk[$topage] = $tmptransfmrk;
  20379. } elseif (isset($this->transfmrk[$topage])) {
  20380. unset($this->transfmrk[$topage]);
  20381. }
  20382. if (isset($tmpannots)) {
  20383. $this->PageAnnots[$topage] = $tmpannots;
  20384. } elseif (isset($this->PageAnnots[$topage])) {
  20385. unset($this->PageAnnots[$topage]);
  20386. }
  20387. // adjust outlines
  20388. $tmpoutlines = $this->outlines;
  20389. foreach ($tmpoutlines as $key => $outline) {
  20390. if (!$outline['f']) {
  20391. if (($outline['p'] >= $topage) AND ($outline['p'] < $frompage)) {
  20392. $this->outlines[$key]['p'] = ($outline['p'] + 1);
  20393. } elseif ($outline['p'] == $frompage) {
  20394. $this->outlines[$key]['p'] = $topage;
  20395. }
  20396. }
  20397. }
  20398. // adjust dests
  20399. $tmpdests = $this->dests;
  20400. foreach ($tmpdests as $key => $dest) {
  20401. if (!$dest['f']) {
  20402. if (($dest['p'] >= $topage) AND ($dest['p'] < $frompage)) {
  20403. $this->dests[$key]['p'] = ($dest['p'] + 1);
  20404. } elseif ($dest['p'] == $frompage) {
  20405. $this->dests[$key]['p'] = $topage;
  20406. }
  20407. }
  20408. }
  20409. // adjust links
  20410. $tmplinks = $this->links;
  20411. foreach ($tmplinks as $key => $link) {
  20412. if (!$link['f']) {
  20413. if (($link['p'] >= $topage) AND ($link['p'] < $frompage)) {
  20414. $this->links[$key]['p'] = ($link['p'] + 1);
  20415. } elseif ($link['p'] == $frompage) {
  20416. $this->links[$key]['p'] = $topage;
  20417. }
  20418. }
  20419. }
  20420. // adjust javascript
  20421. $jfrompage = $frompage;
  20422. $jtopage = $topage;
  20423. if (preg_match_all('/this\.addField\(\'([^\']*)\',\'([^\']*)\',([0-9]+)/', $this->javascript, $pamatch) > 0) {
  20424. foreach($pamatch[0] as $pk => $pmatch) {
  20425. $pagenum = intval($pamatch[3][$pk]) + 1;
  20426. if (($pagenum >= $jtopage) AND ($pagenum < $jfrompage)) {
  20427. $newpage = ($pagenum + 1);
  20428. } elseif ($pagenum == $jfrompage) {
  20429. $newpage = $jtopage;
  20430. } else {
  20431. $newpage = $pagenum;
  20432. }
  20433. --$newpage;
  20434. $newjs = "this.addField(\'".$pamatch[1][$pk]."\',\'".$pamatch[2][$pk]."\',".$newpage;
  20435. $this->javascript = str_replace($pmatch, $newjs, $this->javascript);
  20436. }
  20437. unset($pamatch);
  20438. }
  20439. // return to last page
  20440. $this->lastPage(true);
  20441. return true;
  20442. }
  20443. /**
  20444. * Remove the specified page.
  20445. * @param $page (int) page to remove
  20446. * @return true in case of success, false in case of error.
  20447. * @public
  20448. * @since 4.6.004 (2009-04-23)
  20449. */
  20450. public function deletePage($page) {
  20451. if (($page < 1) OR ($page > $this->numpages)) {
  20452. return false;
  20453. }
  20454. // delete current page
  20455. unset($this->pages[$page]);
  20456. unset($this->pagedim[$page]);
  20457. unset($this->pagelen[$page]);
  20458. unset($this->intmrk[$page]);
  20459. unset($this->bordermrk[$page]);
  20460. unset($this->cntmrk[$page]);
  20461. foreach ($this->pageobjects[$page] as $oid) {
  20462. if (isset($this->offsets[$oid])){
  20463. unset($this->offsets[$oid]);
  20464. }
  20465. }
  20466. unset($this->pageobjects[$page]);
  20467. if (isset($this->footerpos[$page])) {
  20468. unset($this->footerpos[$page]);
  20469. }
  20470. if (isset($this->footerlen[$page])) {
  20471. unset($this->footerlen[$page]);
  20472. }
  20473. if (isset($this->transfmrk[$page])) {
  20474. unset($this->transfmrk[$page]);
  20475. }
  20476. if (isset($this->PageAnnots[$page])) {
  20477. unset($this->PageAnnots[$page]);
  20478. }
  20479. if (isset($this->newpagegroup) AND !empty($this->newpagegroup)) {
  20480. for ($i = $page; $i > 0; --$i) {
  20481. if (isset($this->newpagegroup[$i]) AND (($i + $this->pagegroups[$this->newpagegroup[$i]]) > $page)) {
  20482. --$this->pagegroups[$this->newpagegroup[$i]];
  20483. break;
  20484. }
  20485. }
  20486. }
  20487. if (isset($this->pageopen[$page])) {
  20488. unset($this->pageopen[$page]);
  20489. }
  20490. if ($page < $this->numpages) {
  20491. // update remaining pages
  20492. for ($i = $page; $i < $this->numpages; ++$i) {
  20493. $j = $i + 1;
  20494. // shift pages
  20495. $this->setPageBuffer($i, $this->getPageBuffer($j));
  20496. $this->pagedim[$i] = $this->pagedim[$j];
  20497. $this->pagelen[$i] = $this->pagelen[$j];
  20498. $this->intmrk[$i] = $this->intmrk[$j];
  20499. $this->bordermrk[$i] = $this->bordermrk[$j];
  20500. $this->cntmrk[$i] = $this->cntmrk[$j];
  20501. $this->pageobjects[$i] = $this->pageobjects[$j];
  20502. if (isset($this->footerpos[$j])) {
  20503. $this->footerpos[$i] = $this->footerpos[$j];
  20504. } elseif (isset($this->footerpos[$i])) {
  20505. unset($this->footerpos[$i]);
  20506. }
  20507. if (isset($this->footerlen[$j])) {
  20508. $this->footerlen[$i] = $this->footerlen[$j];
  20509. } elseif (isset($this->footerlen[$i])) {
  20510. unset($this->footerlen[$i]);
  20511. }
  20512. if (isset($this->transfmrk[$j])) {
  20513. $this->transfmrk[$i] = $this->transfmrk[$j];
  20514. } elseif (isset($this->transfmrk[$i])) {
  20515. unset($this->transfmrk[$i]);
  20516. }
  20517. if (isset($this->PageAnnots[$j])) {
  20518. $this->PageAnnots[$i] = $this->PageAnnots[$j];
  20519. } elseif (isset($this->PageAnnots[$i])) {
  20520. unset($this->PageAnnots[$i]);
  20521. }
  20522. if (isset($this->newpagegroup[$j])) {
  20523. $this->newpagegroup[$i] = $this->newpagegroup[$j];
  20524. unset($this->newpagegroup[$j]);
  20525. }
  20526. if ($this->currpagegroup == $j) {
  20527. $this->currpagegroup = $i;
  20528. }
  20529. if (isset($this->pageopen[$j])) {
  20530. $this->pageopen[$i] = $this->pageopen[$j];
  20531. } elseif (isset($this->pageopen[$i])) {
  20532. unset($this->pageopen[$i]);
  20533. }
  20534. }
  20535. // remove last page
  20536. unset($this->pages[$this->numpages]);
  20537. unset($this->pagedim[$this->numpages]);
  20538. unset($this->pagelen[$this->numpages]);
  20539. unset($this->intmrk[$this->numpages]);
  20540. unset($this->bordermrk[$this->numpages]);
  20541. unset($this->cntmrk[$this->numpages]);
  20542. foreach ($this->pageobjects[$this->numpages] as $oid) {
  20543. if (isset($this->offsets[$oid])){
  20544. unset($this->offsets[$oid]);
  20545. }
  20546. }
  20547. unset($this->pageobjects[$this->numpages]);
  20548. if (isset($this->footerpos[$this->numpages])) {
  20549. unset($this->footerpos[$this->numpages]);
  20550. }
  20551. if (isset($this->footerlen[$this->numpages])) {
  20552. unset($this->footerlen[$this->numpages]);
  20553. }
  20554. if (isset($this->transfmrk[$this->numpages])) {
  20555. unset($this->transfmrk[$this->numpages]);
  20556. }
  20557. if (isset($this->PageAnnots[$this->numpages])) {
  20558. unset($this->PageAnnots[$this->numpages]);
  20559. }
  20560. if (isset($this->newpagegroup[$this->numpages])) {
  20561. unset($this->newpagegroup[$this->numpages]);
  20562. }
  20563. if ($this->currpagegroup == $this->numpages) {
  20564. $this->currpagegroup = ($this->numpages - 1);
  20565. }
  20566. if (isset($this->pagegroups[$this->numpages])) {
  20567. unset($this->pagegroups[$this->numpages]);
  20568. }
  20569. if (isset($this->pageopen[$this->numpages])) {
  20570. unset($this->pageopen[$this->numpages]);
  20571. }
  20572. }
  20573. --$this->numpages;
  20574. $this->page = $this->numpages;
  20575. // adjust outlines
  20576. $tmpoutlines = $this->outlines;
  20577. foreach ($tmpoutlines as $key => $outline) {
  20578. if (!$outline['f']) {
  20579. if ($outline['p'] > $page) {
  20580. $this->outlines[$key]['p'] = $outline['p'] - 1;
  20581. } elseif ($outline['p'] == $page) {
  20582. unset($this->outlines[$key]);
  20583. }
  20584. }
  20585. }
  20586. // adjust dests
  20587. $tmpdests = $this->dests;
  20588. foreach ($tmpdests as $key => $dest) {
  20589. if (!$dest['f']) {
  20590. if ($dest['p'] > $page) {
  20591. $this->dests[$key]['p'] = $dest['p'] - 1;
  20592. } elseif ($dest['p'] == $page) {
  20593. unset($this->dests[$key]);
  20594. }
  20595. }
  20596. }
  20597. // adjust links
  20598. $tmplinks = $this->links;
  20599. foreach ($tmplinks as $key => $link) {
  20600. if (!$link['f']) {
  20601. if ($link['p'] > $page) {
  20602. $this->links[$key]['p'] = $link['p'] - 1;
  20603. } elseif ($link['p'] == $page) {
  20604. unset($this->links[$key]);
  20605. }
  20606. }
  20607. }
  20608. // adjust javascript
  20609. $jpage = $page;
  20610. if (preg_match_all('/this\.addField\(\'([^\']*)\',\'([^\']*)\',([0-9]+)/', $this->javascript, $pamatch) > 0) {
  20611. foreach($pamatch[0] as $pk => $pmatch) {
  20612. $pagenum = intval($pamatch[3][$pk]) + 1;
  20613. if ($pagenum >= $jpage) {
  20614. $newpage = ($pagenum - 1);
  20615. } elseif ($pagenum == $jpage) {
  20616. $newpage = 1;
  20617. } else {
  20618. $newpage = $pagenum;
  20619. }
  20620. --$newpage;
  20621. $newjs = "this.addField(\'".$pamatch[1][$pk]."\',\'".$pamatch[2][$pk]."\',".$newpage;
  20622. $this->javascript = str_replace($pmatch, $newjs, $this->javascript);
  20623. }
  20624. unset($pamatch);
  20625. }
  20626. // return to last page
  20627. if ($this->numpages > 0) {
  20628. $this->lastPage(true);
  20629. }
  20630. return true;
  20631. }
  20632. /**
  20633. * Clone the specified page to a new page.
  20634. * @param $page (int) number of page to copy (0 = current page)
  20635. * @return true in case of success, false in case of error.
  20636. * @public
  20637. * @since 4.9.015 (2010-04-20)
  20638. */
  20639. public function copyPage($page=0) {
  20640. if ($page == 0) {
  20641. // default value
  20642. $page = $this->page;
  20643. }
  20644. if (($page < 1) OR ($page > $this->numpages)) {
  20645. return false;
  20646. }
  20647. // close the last page
  20648. $this->endPage();
  20649. // copy all page-related states
  20650. ++$this->numpages;
  20651. $this->page = $this->numpages;
  20652. $this->setPageBuffer($this->page, $this->getPageBuffer($page));
  20653. $this->pagedim[$this->page] = $this->pagedim[$page];
  20654. $this->pagelen[$this->page] = $this->pagelen[$page];
  20655. $this->intmrk[$this->page] = $this->intmrk[$page];
  20656. $this->bordermrk[$this->page] = $this->bordermrk[$page];
  20657. $this->cntmrk[$this->page] = $this->cntmrk[$page];
  20658. $this->pageobjects[$this->page] = $this->pageobjects[$page];
  20659. $this->pageopen[$this->page] = false;
  20660. if (isset($this->footerpos[$page])) {
  20661. $this->footerpos[$this->page] = $this->footerpos[$page];
  20662. }
  20663. if (isset($this->footerlen[$page])) {
  20664. $this->footerlen[$this->page] = $this->footerlen[$page];
  20665. }
  20666. if (isset($this->transfmrk[$page])) {
  20667. $this->transfmrk[$this->page] = $this->transfmrk[$page];
  20668. }
  20669. if (isset($this->PageAnnots[$page])) {
  20670. $this->PageAnnots[$this->page] = $this->PageAnnots[$page];
  20671. }
  20672. if (isset($this->newpagegroup[$page])) {
  20673. // start a new group
  20674. $this->newpagegroup[$this->page] = sizeof($this->newpagegroup) + 1;
  20675. $this->currpagegroup = $this->newpagegroup[$this->page];
  20676. $this->pagegroups[$this->currpagegroup] = 1;
  20677. } elseif (isset($this->currpagegroup) AND ($this->currpagegroup > 0)) {
  20678. ++$this->pagegroups[$this->currpagegroup];
  20679. }
  20680. // copy outlines
  20681. $tmpoutlines = $this->outlines;
  20682. foreach ($tmpoutlines as $key => $outline) {
  20683. if ($outline['p'] == $page) {
  20684. $this->outlines[] = array('t' => $outline['t'], 'l' => $outline['l'], 'x' => $outline['x'], 'y' => $outline['y'], 'p' => $this->page, 'f' => $outline['f'], 's' => $outline['s'], 'c' => $outline['c']);
  20685. }
  20686. }
  20687. // copy links
  20688. $tmplinks = $this->links;
  20689. foreach ($tmplinks as $key => $link) {
  20690. if ($link['p'] == $page) {
  20691. $this->links[] = array('p' => $this->page, 'y' => $link['y'], 'f' => $link['f']);
  20692. }
  20693. }
  20694. // return to last page
  20695. $this->lastPage(true);
  20696. return true;
  20697. }
  20698. /**
  20699. * Output a Table of Content Index (TOC).
  20700. * This method must be called after all Bookmarks were set.
  20701. * Before calling this method you have to open the page using the addTOCPage() method.
  20702. * After calling this method you have to call endTOCPage() to close the TOC page.
  20703. * You can override this method to achieve different styles.
  20704. * @param $page (int) page number where this TOC should be inserted (leave empty for current page).
  20705. * @param $numbersfont (string) set the font for page numbers (please use monospaced font for better alignment).
  20706. * @param $filler (string) string used to fill the space between text and page number.
  20707. * @param $toc_name (string) name to use for TOC bookmark.
  20708. * @param $style (string) Font style for title: B = Bold, I = Italic, BI = Bold + Italic.
  20709. * @param $color (array) RGB color array for bookmark title (values from 0 to 255).
  20710. * @public
  20711. * @author Nicola Asuni
  20712. * @since 4.5.000 (2009-01-02)
  20713. * @see addTOCPage(), endTOCPage(), addHTMLTOC()
  20714. */
  20715. public function addTOC($page='', $numbersfont='', $filler='.', $toc_name='TOC', $style='', $color=array(0,0,0)) {
  20716. $fontsize = $this->FontSizePt;
  20717. $fontfamily = $this->FontFamily;
  20718. $fontstyle = $this->FontStyle;
  20719. $w = $this->w - $this->lMargin - $this->rMargin;
  20720. $spacer = $this->GetStringWidth(chr(32)) * 4;
  20721. $lmargin = $this->lMargin;
  20722. $rmargin = $this->rMargin;
  20723. $x_start = $this->GetX();
  20724. $page_first = $this->page;
  20725. $current_page = $this->page;
  20726. $page_fill_start = false;
  20727. $page_fill_end = false;
  20728. $current_column = $this->current_column;
  20729. if (TCPDF_STATIC::empty_string($numbersfont)) {
  20730. $numbersfont = $this->default_monospaced_font;
  20731. }
  20732. if (TCPDF_STATIC::empty_string($filler)) {
  20733. $filler = ' ';
  20734. }
  20735. if (TCPDF_STATIC::empty_string($page)) {
  20736. $gap = ' ';
  20737. } else {
  20738. $gap = '';
  20739. if ($page < 1) {
  20740. $page = 1;
  20741. }
  20742. }
  20743. $this->SetFont($numbersfont, $fontstyle, $fontsize);
  20744. $numwidth = $this->GetStringWidth('00000');
  20745. $maxpage = 0; //used for pages on attached documents
  20746. foreach ($this->outlines as $key => $outline) {
  20747. // check for extra pages (used for attachments)
  20748. if (($this->page > $page_first) AND ($outline['p'] >= $this->numpages)) {
  20749. $outline['p'] += ($this->page - $page_first);
  20750. }
  20751. if ($this->rtl) {
  20752. $aligntext = 'R';
  20753. $alignnum = 'L';
  20754. } else {
  20755. $aligntext = 'L';
  20756. $alignnum = 'R';
  20757. }
  20758. if ($outline['l'] == 0) {
  20759. $this->SetFont($fontfamily, $outline['s'].'B', $fontsize);
  20760. } else {
  20761. $this->SetFont($fontfamily, $outline['s'], $fontsize - $outline['l']);
  20762. }
  20763. $this->SetTextColorArray($outline['c']);
  20764. // check for page break
  20765. $this->checkPageBreak(2 * $this->getCellHeight($this->FontSize));
  20766. // set margins and X position
  20767. if (($this->page == $current_page) AND ($this->current_column == $current_column)) {
  20768. $this->lMargin = $lmargin;
  20769. $this->rMargin = $rmargin;
  20770. } else {
  20771. if ($this->current_column != $current_column) {
  20772. if ($this->rtl) {
  20773. $x_start = $this->w - $this->columns[$this->current_column]['x'];
  20774. } else {
  20775. $x_start = $this->columns[$this->current_column]['x'];
  20776. }
  20777. }
  20778. $lmargin = $this->lMargin;
  20779. $rmargin = $this->rMargin;
  20780. $current_page = $this->page;
  20781. $current_column = $this->current_column;
  20782. }
  20783. $this->SetX($x_start);
  20784. $indent = ($spacer * $outline['l']);
  20785. if ($this->rtl) {
  20786. $this->x -= $indent;
  20787. $this->rMargin = $this->w - $this->x;
  20788. } else {
  20789. $this->x += $indent;
  20790. $this->lMargin = $this->x;
  20791. }
  20792. $link = $this->AddLink();
  20793. $this->SetLink($link, $outline['y'], $outline['p']);
  20794. // write the text
  20795. if ($this->rtl) {
  20796. $txt = ' '.$outline['t'];
  20797. } else {
  20798. $txt = $outline['t'].' ';
  20799. }
  20800. $this->Write(0, $txt, $link, false, $aligntext, false, 0, false, false, 0, $numwidth, '');
  20801. if ($this->rtl) {
  20802. $tw = $this->x - $this->lMargin;
  20803. } else {
  20804. $tw = $this->w - $this->rMargin - $this->x;
  20805. }
  20806. $this->SetFont($numbersfont, $fontstyle, $fontsize);
  20807. if (TCPDF_STATIC::empty_string($page)) {
  20808. $pagenum = $outline['p'];
  20809. } else {
  20810. // placemark to be replaced with the correct number
  20811. $pagenum = '{#'.($outline['p']).'}';
  20812. if ($this->isUnicodeFont()) {
  20813. $pagenum = '{'.$pagenum.'}';
  20814. }
  20815. $maxpage = max($maxpage, $outline['p']);
  20816. }
  20817. $fw = ($tw - $this->GetStringWidth($pagenum.$filler));
  20818. $wfiller = $this->GetStringWidth($filler);
  20819. if ($wfiller > 0) {
  20820. $numfills = floor($fw / $wfiller);
  20821. } else {
  20822. $numfills = 0;
  20823. }
  20824. if ($numfills > 0) {
  20825. $rowfill = str_repeat($filler, $numfills);
  20826. } else {
  20827. $rowfill = '';
  20828. }
  20829. if ($this->rtl) {
  20830. $pagenum = $pagenum.$gap.$rowfill;
  20831. } else {
  20832. $pagenum = $rowfill.$gap.$pagenum;
  20833. }
  20834. // write the number
  20835. $this->Cell($tw, 0, $pagenum, 0, 1, $alignnum, 0, $link, 0);
  20836. }
  20837. $page_last = $this->getPage();
  20838. $numpages = ($page_last - $page_first + 1);
  20839. // account for booklet mode
  20840. if ($this->booklet) {
  20841. // check if a blank page is required before TOC
  20842. $page_fill_start = ((($page_first % 2) == 0) XOR (($page % 2) == 0));
  20843. $page_fill_end = (!((($numpages % 2) == 0) XOR ($page_fill_start)));
  20844. if ($page_fill_start) {
  20845. // add a page at the end (to be moved before TOC)
  20846. $this->addPage();
  20847. ++$page_last;
  20848. ++$numpages;
  20849. }
  20850. if ($page_fill_end) {
  20851. // add a page at the end
  20852. $this->addPage();
  20853. ++$page_last;
  20854. ++$numpages;
  20855. }
  20856. }
  20857. $maxpage = max($maxpage, $page_last);
  20858. if (!TCPDF_STATIC::empty_string($page)) {
  20859. for ($p = $page_first; $p <= $page_last; ++$p) {
  20860. // get page data
  20861. $temppage = $this->getPageBuffer($p);
  20862. for ($n = 1; $n <= $maxpage; ++$n) {
  20863. // update page numbers
  20864. $a = '{#'.$n.'}';
  20865. // get page number aliases
  20866. $pnalias = $this->getInternalPageNumberAliases($a);
  20867. // calculate replacement number
  20868. if (($n >= $page) AND ($n <= $this->numpages)) {
  20869. $np = $n + $numpages;
  20870. } else {
  20871. $np = $n;
  20872. }
  20873. $na = TCPDF_STATIC::formatTOCPageNumber(($this->starting_page_number + $np - 1));
  20874. $nu = TCPDF_FONTS::UTF8ToUTF16BE($na, false, $this->isunicode, $this->CurrentFont);
  20875. // replace aliases with numbers
  20876. foreach ($pnalias['u'] as $u) {
  20877. $sfill = str_repeat($filler, max(0, (strlen($u) - strlen($nu.' '))));
  20878. if ($this->rtl) {
  20879. $nr = $nu.TCPDF_FONTS::UTF8ToUTF16BE(' '.$sfill, false, $this->isunicode, $this->CurrentFont);
  20880. } else {
  20881. $nr = TCPDF_FONTS::UTF8ToUTF16BE($sfill.' ', false, $this->isunicode, $this->CurrentFont).$nu;
  20882. }
  20883. $temppage = str_replace($u, $nr, $temppage);
  20884. }
  20885. foreach ($pnalias['a'] as $a) {
  20886. $sfill = str_repeat($filler, max(0, (strlen($a) - strlen($na.' '))));
  20887. if ($this->rtl) {
  20888. $nr = $na.' '.$sfill;
  20889. } else {
  20890. $nr = $sfill.' '.$na;
  20891. }
  20892. $temppage = str_replace($a, $nr, $temppage);
  20893. }
  20894. }
  20895. // save changes
  20896. $this->setPageBuffer($p, $temppage);
  20897. }
  20898. // move pages
  20899. $this->Bookmark($toc_name, 0, 0, $page_first, $style, $color);
  20900. if ($page_fill_start) {
  20901. $this->movePage($page_last, $page_first);
  20902. }
  20903. for ($i = 0; $i < $numpages; ++$i) {
  20904. $this->movePage($page_last, $page);
  20905. }
  20906. }
  20907. }
  20908. /**
  20909. * Output a Table Of Content Index (TOC) using HTML templates.
  20910. * This method must be called after all Bookmarks were set.
  20911. * Before calling this method you have to open the page using the addTOCPage() method.
  20912. * After calling this method you have to call endTOCPage() to close the TOC page.
  20913. * @param $page (int) page number where this TOC should be inserted (leave empty for current page).
  20914. * @param $toc_name (string) name to use for TOC bookmark.
  20915. * @param $templates (array) array of html templates. Use: "#TOC_DESCRIPTION#" for bookmark title, "#TOC_PAGE_NUMBER#" for page number.
  20916. * @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)
  20917. * @param $style (string) Font style for title: B = Bold, I = Italic, BI = Bold + Italic.
  20918. * @param $color (array) RGB color array for title (values from 0 to 255).
  20919. * @public
  20920. * @author Nicola Asuni
  20921. * @since 5.0.001 (2010-05-06)
  20922. * @see addTOCPage(), endTOCPage(), addTOC()
  20923. */
  20924. public function addHTMLTOC($page='', $toc_name='TOC', $templates=array(), $correct_align=true, $style='', $color=array(0,0,0)) {
  20925. $filler = ' ';
  20926. $prev_htmlLinkColorArray = $this->htmlLinkColorArray;
  20927. $prev_htmlLinkFontStyle = $this->htmlLinkFontStyle;
  20928. // set new style for link
  20929. $this->htmlLinkColorArray = array();
  20930. $this->htmlLinkFontStyle = '';
  20931. $page_first = $this->getPage();
  20932. $page_fill_start = false;
  20933. $page_fill_end = false;
  20934. // get the font type used for numbers in each template
  20935. $current_font = $this->FontFamily;
  20936. foreach ($templates as $level => $html) {
  20937. $dom = $this->getHtmlDomArray($html);
  20938. foreach ($dom as $key => $value) {
  20939. if ($value['value'] == '#TOC_PAGE_NUMBER#') {
  20940. $this->SetFont($dom[($key - 1)]['fontname']);
  20941. $templates['F'.$level] = $this->isUnicodeFont();
  20942. }
  20943. }
  20944. }
  20945. $this->SetFont($current_font);
  20946. $maxpage = 0; //used for pages on attached documents
  20947. foreach ($this->outlines as $key => $outline) {
  20948. // get HTML template
  20949. $row = $templates[$outline['l']];
  20950. if (TCPDF_STATIC::empty_string($page)) {
  20951. $pagenum = $outline['p'];
  20952. } else {
  20953. // placemark to be replaced with the correct number
  20954. $pagenum = '{#'.($outline['p']).'}';
  20955. if (isset($templates['F'.$outline['l']]) && $templates['F'.$outline['l']]) {
  20956. $pagenum = '{'.$pagenum.'}';
  20957. }
  20958. $maxpage = max($maxpage, $outline['p']);
  20959. }
  20960. // replace templates with current values
  20961. $row = str_replace('#TOC_DESCRIPTION#', $outline['t'], $row);
  20962. $row = str_replace('#TOC_PAGE_NUMBER#', $pagenum, $row);
  20963. // add link to page
  20964. $row = '<a href="#'.$outline['p'].','.$outline['y'].'">'.$row.'</a>';
  20965. // write bookmark entry
  20966. $this->writeHTML($row, false, false, true, false, '');
  20967. }
  20968. // restore link styles
  20969. $this->htmlLinkColorArray = $prev_htmlLinkColorArray;
  20970. $this->htmlLinkFontStyle = $prev_htmlLinkFontStyle;
  20971. // move TOC page and replace numbers
  20972. $page_last = $this->getPage();
  20973. $numpages = ($page_last - $page_first + 1);
  20974. // account for booklet mode
  20975. if ($this->booklet) {
  20976. // check if a blank page is required before TOC
  20977. $page_fill_start = ((($page_first % 2) == 0) XOR (($page % 2) == 0));
  20978. $page_fill_end = (!((($numpages % 2) == 0) XOR ($page_fill_start)));
  20979. if ($page_fill_start) {
  20980. // add a page at the end (to be moved before TOC)
  20981. $this->addPage();
  20982. ++$page_last;
  20983. ++$numpages;
  20984. }
  20985. if ($page_fill_end) {
  20986. // add a page at the end
  20987. $this->addPage();
  20988. ++$page_last;
  20989. ++$numpages;
  20990. }
  20991. }
  20992. $maxpage = max($maxpage, $page_last);
  20993. if (!TCPDF_STATIC::empty_string($page)) {
  20994. for ($p = $page_first; $p <= $page_last; ++$p) {
  20995. // get page data
  20996. $temppage = $this->getPageBuffer($p);
  20997. for ($n = 1; $n <= $maxpage; ++$n) {
  20998. // update page numbers
  20999. $a = '{#'.$n.'}';
  21000. // get page number aliases
  21001. $pnalias = $this->getInternalPageNumberAliases($a);
  21002. // calculate replacement number
  21003. if ($n >= $page) {
  21004. $np = $n + $numpages;
  21005. } else {
  21006. $np = $n;
  21007. }
  21008. $na = TCPDF_STATIC::formatTOCPageNumber(($this->starting_page_number + $np - 1));
  21009. $nu = TCPDF_FONTS::UTF8ToUTF16BE($na, false, $this->isunicode, $this->CurrentFont);
  21010. // replace aliases with numbers
  21011. foreach ($pnalias['u'] as $u) {
  21012. if ($correct_align) {
  21013. $sfill = str_repeat($filler, (strlen($u) - strlen($nu.' ')));
  21014. if ($this->rtl) {
  21015. $nr = $nu.TCPDF_FONTS::UTF8ToUTF16BE(' '.$sfill, false, $this->isunicode, $this->CurrentFont);
  21016. } else {
  21017. $nr = TCPDF_FONTS::UTF8ToUTF16BE($sfill.' ', false, $this->isunicode, $this->CurrentFont).$nu;
  21018. }
  21019. } else {
  21020. $nr = $nu;
  21021. }
  21022. $temppage = str_replace($u, $nr, $temppage);
  21023. }
  21024. foreach ($pnalias['a'] as $a) {
  21025. if ($correct_align) {
  21026. $sfill = str_repeat($filler, (strlen($a) - strlen($na.' ')));
  21027. if ($this->rtl) {
  21028. $nr = $na.' '.$sfill;
  21029. } else {
  21030. $nr = $sfill.' '.$na;
  21031. }
  21032. } else {
  21033. $nr = $na;
  21034. }
  21035. $temppage = str_replace($a, $nr, $temppage);
  21036. }
  21037. }
  21038. // save changes
  21039. $this->setPageBuffer($p, $temppage);
  21040. }
  21041. // move pages
  21042. $this->Bookmark($toc_name, 0, 0, $page_first, $style, $color);
  21043. if ($page_fill_start) {
  21044. $this->movePage($page_last, $page_first);
  21045. }
  21046. for ($i = 0; $i < $numpages; ++$i) {
  21047. $this->movePage($page_last, $page);
  21048. }
  21049. }
  21050. }
  21051. /**
  21052. * Stores a copy of the current TCPDF object used for undo operation.
  21053. * @public
  21054. * @since 4.5.029 (2009-03-19)
  21055. */
  21056. public function startTransaction() {
  21057. if (isset($this->objcopy)) {
  21058. // remove previous copy
  21059. $this->commitTransaction();
  21060. }
  21061. // record current page number and Y position
  21062. $this->start_transaction_page = $this->page;
  21063. $this->start_transaction_y = $this->y;
  21064. // clone current object
  21065. $this->objcopy = TCPDF_STATIC::objclone($this);
  21066. }
  21067. /**
  21068. * Delete the copy of the current TCPDF object used for undo operation.
  21069. * @public
  21070. * @since 4.5.029 (2009-03-19)
  21071. */
  21072. public function commitTransaction() {
  21073. if (isset($this->objcopy)) {
  21074. $this->objcopy->_destroy(true, true);
  21075. unset($this->objcopy);
  21076. }
  21077. }
  21078. /**
  21079. * This method allows to undo the latest transaction by returning the latest saved TCPDF object with startTransaction().
  21080. * @param $self (boolean) if true restores current class object to previous state without the need of reassignment via the returned value.
  21081. * @return TCPDF object.
  21082. * @public
  21083. * @since 4.5.029 (2009-03-19)
  21084. */
  21085. public function rollbackTransaction($self=false) {
  21086. if (isset($this->objcopy)) {
  21087. $this->_destroy(true, true);
  21088. if ($self) {
  21089. $objvars = get_object_vars($this->objcopy);
  21090. foreach ($objvars as $key => $value) {
  21091. $this->$key = $value;
  21092. }
  21093. }
  21094. return $this->objcopy;
  21095. }
  21096. return $this;
  21097. }
  21098. // --- MULTI COLUMNS METHODS -----------------------
  21099. /**
  21100. * Set multiple columns of the same size
  21101. * @param $numcols (int) number of columns (set to zero to disable columns mode)
  21102. * @param $width (int) column width
  21103. * @param $y (int) column starting Y position (leave empty for current Y position)
  21104. * @public
  21105. * @since 4.9.001 (2010-03-28)
  21106. */
  21107. public function setEqualColumns($numcols=0, $width=0, $y='') {
  21108. $this->columns = array();
  21109. if ($numcols < 2) {
  21110. $numcols = 0;
  21111. $this->columns = array();
  21112. } else {
  21113. // maximum column width
  21114. $maxwidth = ($this->w - $this->original_lMargin - $this->original_rMargin) / $numcols;
  21115. if (($width == 0) OR ($width > $maxwidth)) {
  21116. $width = $maxwidth;
  21117. }
  21118. if (TCPDF_STATIC::empty_string($y)) {
  21119. $y = $this->y;
  21120. }
  21121. // space between columns
  21122. $space = (($this->w - $this->original_lMargin - $this->original_rMargin - ($numcols * $width)) / ($numcols - 1));
  21123. // fill the columns array (with, space, starting Y position)
  21124. for ($i = 0; $i < $numcols; ++$i) {
  21125. $this->columns[$i] = array('w' => $width, 's' => $space, 'y' => $y);
  21126. }
  21127. }
  21128. $this->num_columns = $numcols;
  21129. $this->current_column = 0;
  21130. $this->column_start_page = $this->page;
  21131. $this->selectColumn(0);
  21132. }
  21133. /**
  21134. * Remove columns and reset page margins.
  21135. * @public
  21136. * @since 5.9.072 (2011-04-26)
  21137. */
  21138. public function resetColumns() {
  21139. $this->lMargin = $this->original_lMargin;
  21140. $this->rMargin = $this->original_rMargin;
  21141. $this->setEqualColumns();
  21142. }
  21143. /**
  21144. * Set columns array.
  21145. * Each column is represented by an array of arrays with the following keys: (w = width, s = space between columns, y = column top position).
  21146. * @param $columns (array)
  21147. * @public
  21148. * @since 4.9.001 (2010-03-28)
  21149. */
  21150. public function setColumnsArray($columns) {
  21151. $this->columns = $columns;
  21152. $this->num_columns = count($columns);
  21153. $this->current_column = 0;
  21154. $this->column_start_page = $this->page;
  21155. $this->selectColumn(0);
  21156. }
  21157. /**
  21158. * Set position at a given column
  21159. * @param $col (int) column number (from 0 to getNumberOfColumns()-1); empty string = current column.
  21160. * @public
  21161. * @since 4.9.001 (2010-03-28)
  21162. */
  21163. public function selectColumn($col='') {
  21164. if (is_string($col)) {
  21165. $col = $this->current_column;
  21166. } elseif ($col >= $this->num_columns) {
  21167. $col = 0;
  21168. }
  21169. $xshift = array('x' => 0, 's' => array('H' => 0, 'V' => 0), 'p' => array('L' => 0, 'T' => 0, 'R' => 0, 'B' => 0));
  21170. $enable_thead = false;
  21171. if ($this->num_columns > 1) {
  21172. if ($col != $this->current_column) {
  21173. // move Y pointer at the top of the column
  21174. if ($this->column_start_page == $this->page) {
  21175. $this->y = $this->columns[$col]['y'];
  21176. } else {
  21177. $this->y = $this->tMargin;
  21178. }
  21179. // Avoid to write table headers more than once
  21180. if (($this->page > $this->maxselcol['page']) OR (($this->page == $this->maxselcol['page']) AND ($col > $this->maxselcol['column']))) {
  21181. $enable_thead = true;
  21182. $this->maxselcol['page'] = $this->page;
  21183. $this->maxselcol['column'] = $col;
  21184. }
  21185. }
  21186. $xshift = $this->colxshift;
  21187. // set X position of the current column by case
  21188. $listindent = ($this->listindentlevel * $this->listindent);
  21189. // calculate column X position
  21190. $colpos = 0;
  21191. for ($i = 0; $i < $col; ++$i) {
  21192. $colpos += ($this->columns[$i]['w'] + $this->columns[$i]['s']);
  21193. }
  21194. if ($this->rtl) {
  21195. $x = $this->w - $this->original_rMargin - $colpos;
  21196. $this->rMargin = ($this->w - $x + $listindent);
  21197. $this->lMargin = ($x - $this->columns[$col]['w']);
  21198. $this->x = $x - $listindent;
  21199. } else {
  21200. $x = $this->original_lMargin + $colpos;
  21201. $this->lMargin = ($x + $listindent);
  21202. $this->rMargin = ($this->w - $x - $this->columns[$col]['w']);
  21203. $this->x = $x + $listindent;
  21204. }
  21205. $this->columns[$col]['x'] = $x;
  21206. }
  21207. $this->current_column = $col;
  21208. // fix for HTML mode
  21209. $this->newline = true;
  21210. // print HTML table header (if any)
  21211. if ((!TCPDF_STATIC::empty_string($this->thead)) AND (!$this->inthead)) {
  21212. if ($enable_thead) {
  21213. // print table header
  21214. $this->writeHTML($this->thead, false, false, false, false, '');
  21215. $this->y += $xshift['s']['V'];
  21216. // store end of header position
  21217. if (!isset($this->columns[$col]['th'])) {
  21218. $this->columns[$col]['th'] = array();
  21219. }
  21220. $this->columns[$col]['th']['\''.$this->page.'\''] = $this->y;
  21221. $this->lasth = 0;
  21222. } elseif (isset($this->columns[$col]['th']['\''.$this->page.'\''])) {
  21223. $this->y = $this->columns[$col]['th']['\''.$this->page.'\''];
  21224. }
  21225. }
  21226. // account for an html table cell over multiple columns
  21227. if ($this->rtl) {
  21228. $this->rMargin += $xshift['x'];
  21229. $this->x -= ($xshift['x'] + $xshift['p']['R']);
  21230. } else {
  21231. $this->lMargin += $xshift['x'];
  21232. $this->x += $xshift['x'] + $xshift['p']['L'];
  21233. }
  21234. }
  21235. /**
  21236. * Return the current column number
  21237. * @return int current column number
  21238. * @public
  21239. * @since 5.5.011 (2010-07-08)
  21240. */
  21241. public function getColumn() {
  21242. return $this->current_column;
  21243. }
  21244. /**
  21245. * Return the current number of columns.
  21246. * @return int number of columns
  21247. * @public
  21248. * @since 5.8.018 (2010-08-25)
  21249. */
  21250. public function getNumberOfColumns() {
  21251. return $this->num_columns;
  21252. }
  21253. /**
  21254. * Set Text rendering mode.
  21255. * @param $stroke (int) outline size in user units (0 = disable).
  21256. * @param $fill (boolean) if true fills the text (default).
  21257. * @param $clip (boolean) if true activate clipping mode
  21258. * @public
  21259. * @since 4.9.008 (2009-04-02)
  21260. */
  21261. public function setTextRenderingMode($stroke=0, $fill=true, $clip=false) {
  21262. // Ref.: PDF 32000-1:2008 - 9.3.6 Text Rendering Mode
  21263. // convert text rendering parameters
  21264. if ($stroke < 0) {
  21265. $stroke = 0;
  21266. }
  21267. if ($fill === true) {
  21268. if ($stroke > 0) {
  21269. if ($clip === true) {
  21270. // Fill, then stroke text and add to path for clipping
  21271. $textrendermode = 6;
  21272. } else {
  21273. // Fill, then stroke text
  21274. $textrendermode = 2;
  21275. }
  21276. $textstrokewidth = $stroke;
  21277. } else {
  21278. if ($clip === true) {
  21279. // Fill text and add to path for clipping
  21280. $textrendermode = 4;
  21281. } else {
  21282. // Fill text
  21283. $textrendermode = 0;
  21284. }
  21285. }
  21286. } else {
  21287. if ($stroke > 0) {
  21288. if ($clip === true) {
  21289. // Stroke text and add to path for clipping
  21290. $textrendermode = 5;
  21291. } else {
  21292. // Stroke text
  21293. $textrendermode = 1;
  21294. }
  21295. $textstrokewidth = $stroke;
  21296. } else {
  21297. if ($clip === true) {
  21298. // Add text to path for clipping
  21299. $textrendermode = 7;
  21300. } else {
  21301. // Neither fill nor stroke text (invisible)
  21302. $textrendermode = 3;
  21303. }
  21304. }
  21305. }
  21306. $this->textrendermode = $textrendermode;
  21307. $this->textstrokewidth = $stroke;
  21308. }
  21309. /**
  21310. * Set parameters for drop shadow effect for text.
  21311. * @param $params (array) Array of parameters: enabled (boolean) set to true to enable shadow; depth_w (float) shadow width in user units; depth_h (float) shadow height in user units; color (array) shadow color or false to use the stroke color; opacity (float) Alpha value: real value from 0 (transparent) to 1 (opaque); blend_mode (string) blend mode, one of the following: Normal, Multiply, Screen, Overlay, Darken, Lighten, ColorDodge, ColorBurn, HardLight, SoftLight, Difference, Exclusion, Hue, Saturation, Color, Luminosity.
  21312. * @since 5.9.174 (2012-07-25)
  21313. * @public
  21314. */
  21315. public function setTextShadow($params=array('enabled'=>false, 'depth_w'=>0, 'depth_h'=>0, 'color'=>false, 'opacity'=>1, 'blend_mode'=>'Normal')) {
  21316. if (isset($params['enabled'])) {
  21317. $this->txtshadow['enabled'] = $params['enabled']?true:false;
  21318. } else {
  21319. $this->txtshadow['enabled'] = false;
  21320. }
  21321. if (isset($params['depth_w'])) {
  21322. $this->txtshadow['depth_w'] = floatval($params['depth_w']);
  21323. } else {
  21324. $this->txtshadow['depth_w'] = 0;
  21325. }
  21326. if (isset($params['depth_h'])) {
  21327. $this->txtshadow['depth_h'] = floatval($params['depth_h']);
  21328. } else {
  21329. $this->txtshadow['depth_h'] = 0;
  21330. }
  21331. if (isset($params['color']) AND ($params['color'] !== false) AND is_array($params['color'])) {
  21332. $this->txtshadow['color'] = $params['color'];
  21333. } else {
  21334. $this->txtshadow['color'] = $this->strokecolor;
  21335. }
  21336. if (isset($params['opacity'])) {
  21337. $this->txtshadow['opacity'] = min(1, max(0, floatval($params['opacity'])));
  21338. } else {
  21339. $this->txtshadow['opacity'] = 1;
  21340. }
  21341. if (isset($params['blend_mode']) AND in_array($params['blend_mode'], array('Normal', 'Multiply', 'Screen', 'Overlay', 'Darken', 'Lighten', 'ColorDodge', 'ColorBurn', 'HardLight', 'SoftLight', 'Difference', 'Exclusion', 'Hue', 'Saturation', 'Color', 'Luminosity'))) {
  21342. $this->txtshadow['blend_mode'] = $params['blend_mode'];
  21343. } else {
  21344. $this->txtshadow['blend_mode'] = 'Normal';
  21345. }
  21346. if ((($this->txtshadow['depth_w'] == 0) AND ($this->txtshadow['depth_h'] == 0)) OR ($this->txtshadow['opacity'] == 0)) {
  21347. $this->txtshadow['enabled'] = false;
  21348. }
  21349. }
  21350. /**
  21351. * Return the text shadow parameters array.
  21352. * @return Array of parameters.
  21353. * @since 5.9.174 (2012-07-25)
  21354. * @public
  21355. */
  21356. public function getTextShadow() {
  21357. return $this->txtshadow;
  21358. }
  21359. /**
  21360. * Returns an array of chars containing soft hyphens.
  21361. * @param $word (array) array of chars
  21362. * @param $patterns (array) Array of hypenation patterns.
  21363. * @param $dictionary (array) Array of words to be returned without applying the hyphenation algorithm.
  21364. * @param $leftmin (int) Minimum number of character to leave on the left of the word without applying the hyphens.
  21365. * @param $rightmin (int) Minimum number of character to leave on the right of the word without applying the hyphens.
  21366. * @param $charmin (int) Minimum word length to apply the hyphenation algorithm.
  21367. * @param $charmax (int) Maximum length of broken piece of word.
  21368. * @return array text with soft hyphens
  21369. * @author Nicola Asuni
  21370. * @since 4.9.012 (2010-04-12)
  21371. * @protected
  21372. */
  21373. protected function hyphenateWord($word, $patterns, $dictionary=array(), $leftmin=1, $rightmin=2, $charmin=1, $charmax=8) {
  21374. $hyphenword = array(); // hyphens positions
  21375. $numchars = count($word);
  21376. if ($numchars <= $charmin) {
  21377. return $word;
  21378. }
  21379. $word_string = TCPDF_FONTS::UTF8ArrSubString($word, '', '', $this->isunicode);
  21380. // some words will be returned as-is
  21381. $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})(\]?)$/';
  21382. if (preg_match($pattern, $word_string) > 0) {
  21383. // email
  21384. return $word;
  21385. }
  21386. $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})(\]?)$/';
  21387. if (preg_match($pattern, $word_string) > 0) {
  21388. // URL
  21389. return $word;
  21390. }
  21391. if (isset($dictionary[$word_string])) {
  21392. return TCPDF_FONTS::UTF8StringToArray($dictionary[$word_string], $this->isunicode, $this->CurrentFont);
  21393. }
  21394. // surround word with '_' characters
  21395. $tmpword = array_merge(array(46), $word, array(46));
  21396. $tmpnumchars = $numchars + 2;
  21397. $maxpos = $tmpnumchars - 1;
  21398. for ($pos = 0; $pos < $maxpos; ++$pos) {
  21399. $imax = min(($tmpnumchars - $pos), $charmax);
  21400. for ($i = 1; $i <= $imax; ++$i) {
  21401. $subword = strtolower(TCPDF_FONTS::UTF8ArrSubString($tmpword, $pos, ($pos + $i), $this->isunicode));
  21402. if (isset($patterns[$subword])) {
  21403. $pattern = TCPDF_FONTS::UTF8StringToArray($patterns[$subword], $this->isunicode, $this->CurrentFont);
  21404. $pattern_length = count($pattern);
  21405. $digits = 1;
  21406. for ($j = 0; $j < $pattern_length; ++$j) {
  21407. // check if $pattern[$j] is a number = hyphenation level (only numbers from 1 to 5 are valid)
  21408. if (($pattern[$j] >= 48) AND ($pattern[$j] <= 57)) {
  21409. if ($j == 0) {
  21410. $zero = $pos - 1;
  21411. } else {
  21412. $zero = $pos + $j - $digits;
  21413. }
  21414. // get hyphenation level
  21415. $level = ($pattern[$j] - 48);
  21416. // if two levels from two different patterns match at the same point, the higher one is selected.
  21417. if (!isset($hyphenword[$zero]) OR ($hyphenword[$zero] < $level)) {
  21418. $hyphenword[$zero] = $level;
  21419. }
  21420. ++$digits;
  21421. }
  21422. }
  21423. }
  21424. }
  21425. }
  21426. $inserted = 0;
  21427. $maxpos = $numchars - $rightmin;
  21428. for ($i = $leftmin; $i <= $maxpos; ++$i) {
  21429. // only odd levels indicate allowed hyphenation points
  21430. if (isset($hyphenword[$i]) AND (($hyphenword[$i] % 2) != 0)) {
  21431. // 173 = soft hyphen character
  21432. array_splice($word, $i + $inserted, 0, 173);
  21433. ++$inserted;
  21434. }
  21435. }
  21436. return $word;
  21437. }
  21438. /**
  21439. * Returns text with soft hyphens.
  21440. * @param $text (string) text to process
  21441. * @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/
  21442. * @param $dictionary (array) Array of words to be returned without applying the hyphenation algorithm.
  21443. * @param $leftmin (int) Minimum number of character to leave on the left of the word without applying the hyphens.
  21444. * @param $rightmin (int) Minimum number of character to leave on the right of the word without applying the hyphens.
  21445. * @param $charmin (int) Minimum word length to apply the hyphenation algorithm.
  21446. * @param $charmax (int) Maximum length of broken piece of word.
  21447. * @return array text with soft hyphens
  21448. * @author Nicola Asuni
  21449. * @since 4.9.012 (2010-04-12)
  21450. * @public
  21451. */
  21452. public function hyphenateText($text, $patterns, $dictionary=array(), $leftmin=1, $rightmin=2, $charmin=1, $charmax=8) {
  21453. $text = $this->unhtmlentities($text);
  21454. $word = array(); // last word
  21455. $txtarr = array(); // text to be returned
  21456. $intag = false; // true if we are inside an HTML tag
  21457. $skip = false; // true to skip hyphenation
  21458. if (!is_array($patterns)) {
  21459. $patterns = TCPDF_STATIC::getHyphenPatternsFromTEX($patterns);
  21460. }
  21461. // get array of characters
  21462. $unichars = TCPDF_FONTS::UTF8StringToArray($text, $this->isunicode, $this->CurrentFont);
  21463. // for each char
  21464. foreach ($unichars as $char) {
  21465. if ((!$intag) AND (!$skip) AND TCPDF_FONT_DATA::$uni_type[$char] == 'L') {
  21466. // letter character
  21467. $word[] = $char;
  21468. } else {
  21469. // other type of character
  21470. if (!TCPDF_STATIC::empty_string($word)) {
  21471. // hypenate the word
  21472. $txtarr = array_merge($txtarr, $this->hyphenateWord($word, $patterns, $dictionary, $leftmin, $rightmin, $charmin, $charmax));
  21473. $word = array();
  21474. }
  21475. $txtarr[] = $char;
  21476. if (chr($char) == '<') {
  21477. // we are inside an HTML tag
  21478. $intag = true;
  21479. } elseif ($intag AND (chr($char) == '>')) {
  21480. // end of HTML tag
  21481. $intag = false;
  21482. // check for style tag
  21483. $expected = array(115, 116, 121, 108, 101); // = 'style'
  21484. $current = array_slice($txtarr, -6, 5); // last 5 chars
  21485. $compare = array_diff($expected, $current);
  21486. if (empty($compare)) {
  21487. // check if it is a closing tag
  21488. $expected = array(47); // = '/'
  21489. $current = array_slice($txtarr, -7, 1);
  21490. $compare = array_diff($expected, $current);
  21491. if (empty($compare)) {
  21492. // closing style tag
  21493. $skip = false;
  21494. } else {
  21495. // opening style tag
  21496. $skip = true;
  21497. }
  21498. }
  21499. }
  21500. }
  21501. }
  21502. if (!TCPDF_STATIC::empty_string($word)) {
  21503. // hypenate the word
  21504. $txtarr = array_merge($txtarr, $this->hyphenateWord($word, $patterns, $dictionary, $leftmin, $rightmin, $charmin, $charmax));
  21505. }
  21506. // convert char array to string and return
  21507. return TCPDF_FONTS::UTF8ArrSubString($txtarr, '', '', $this->isunicode);
  21508. }
  21509. /**
  21510. * Enable/disable rasterization of vector images using ImageMagick library.
  21511. * @param $mode (boolean) if true enable rasterization, false otherwise.
  21512. * @public
  21513. * @since 5.0.000 (2010-04-27)
  21514. */
  21515. public function setRasterizeVectorImages($mode) {
  21516. $this->rasterize_vector_images = $mode;
  21517. }
  21518. /**
  21519. * Enable or disable default option for font subsetting.
  21520. * @param $enable (boolean) if true enable font subsetting by default.
  21521. * @author Nicola Asuni
  21522. * @public
  21523. * @since 5.3.002 (2010-06-07)
  21524. */
  21525. public function setFontSubsetting($enable=true) {
  21526. if ($this->pdfa_mode) {
  21527. $this->font_subsetting = false;
  21528. } else {
  21529. $this->font_subsetting = $enable ? true : false;
  21530. }
  21531. }
  21532. /**
  21533. * Return the default option for font subsetting.
  21534. * @return boolean default font subsetting state.
  21535. * @author Nicola Asuni
  21536. * @public
  21537. * @since 5.3.002 (2010-06-07)
  21538. */
  21539. public function getFontSubsetting() {
  21540. return $this->font_subsetting;
  21541. }
  21542. /**
  21543. * Left trim the input string
  21544. * @param $str (string) string to trim
  21545. * @param $replace (string) string that replace spaces.
  21546. * @return left trimmed string
  21547. * @author Nicola Asuni
  21548. * @public
  21549. * @since 5.8.000 (2010-08-11)
  21550. */
  21551. public function stringLeftTrim($str, $replace='') {
  21552. return preg_replace('/^'.$this->re_space['p'].'+/'.$this->re_space['m'], $replace, $str);
  21553. }
  21554. /**
  21555. * Right trim the input string
  21556. * @param $str (string) string to trim
  21557. * @param $replace (string) string that replace spaces.
  21558. * @return right trimmed string
  21559. * @author Nicola Asuni
  21560. * @public
  21561. * @since 5.8.000 (2010-08-11)
  21562. */
  21563. public function stringRightTrim($str, $replace='') {
  21564. return preg_replace('/'.$this->re_space['p'].'+$/'.$this->re_space['m'], $replace, $str);
  21565. }
  21566. /**
  21567. * Trim the input string
  21568. * @param $str (string) string to trim
  21569. * @param $replace (string) string that replace spaces.
  21570. * @return trimmed string
  21571. * @author Nicola Asuni
  21572. * @public
  21573. * @since 5.8.000 (2010-08-11)
  21574. */
  21575. public function stringTrim($str, $replace='') {
  21576. $str = $this->stringLeftTrim($str, $replace);
  21577. $str = $this->stringRightTrim($str, $replace);
  21578. return $str;
  21579. }
  21580. /**
  21581. * Return true if the current font is unicode type.
  21582. * @return true for unicode font, false otherwise.
  21583. * @author Nicola Asuni
  21584. * @public
  21585. * @since 5.8.002 (2010-08-14)
  21586. */
  21587. public function isUnicodeFont() {
  21588. return (($this->CurrentFont['type'] == 'TrueTypeUnicode') OR ($this->CurrentFont['type'] == 'cidfont0'));
  21589. }
  21590. /**
  21591. * Return normalized font name
  21592. * @param $fontfamily (string) property string containing font family names
  21593. * @return string normalized font name
  21594. * @author Nicola Asuni
  21595. * @public
  21596. * @since 5.8.004 (2010-08-17)
  21597. */
  21598. public function getFontFamilyName($fontfamily) {
  21599. // remove spaces and symbols
  21600. $fontfamily = preg_replace('/[^a-z0-9_\,]/', '', strtolower($fontfamily));
  21601. // extract all font names
  21602. $fontslist = preg_split('/[,]/', $fontfamily);
  21603. // find first valid font name
  21604. foreach ($fontslist as $font) {
  21605. // replace font variations
  21606. $font = preg_replace('/regular$/', '', $font);
  21607. $font = preg_replace('/italic$/', 'I', $font);
  21608. $font = preg_replace('/oblique$/', 'I', $font);
  21609. $font = preg_replace('/bold([I]?)$/', 'B\\1', $font);
  21610. // replace common family names and core fonts
  21611. $pattern = array();
  21612. $replacement = array();
  21613. $pattern[] = '/^serif|^cursive|^fantasy|^timesnewroman/';
  21614. $replacement[] = 'times';
  21615. $pattern[] = '/^sansserif/';
  21616. $replacement[] = 'helvetica';
  21617. $pattern[] = '/^monospace/';
  21618. $replacement[] = 'courier';
  21619. $font = preg_replace($pattern, $replacement, $font);
  21620. if (in_array(strtolower($font), $this->fontlist) OR in_array($font, $this->fontkeys)) {
  21621. return $font;
  21622. }
  21623. }
  21624. // return current font as default
  21625. return $this->CurrentFont['fontkey'];
  21626. }
  21627. /**
  21628. * Start a new XObject Template.
  21629. * 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).
  21630. * 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.
  21631. * Note: X,Y coordinates will be reset to 0,0.
  21632. * @param $w (int) Template width in user units (empty string or zero = page width less margins).
  21633. * @param $h (int) Template height in user units (empty string or zero = page height less margins).
  21634. * @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).
  21635. * @return int the XObject Template ID in case of success or false in case of error.
  21636. * @author Nicola Asuni
  21637. * @public
  21638. * @since 5.8.017 (2010-08-24)
  21639. * @see endTemplate(), printTemplate()
  21640. */
  21641. public function startTemplate($w=0, $h=0, $group=false) {
  21642. if ($this->inxobj) {
  21643. // we are already inside an XObject template
  21644. return false;
  21645. }
  21646. $this->inxobj = true;
  21647. ++$this->n;
  21648. // XObject ID
  21649. $this->xobjid = 'XT'.$this->n;
  21650. // object ID
  21651. $this->xobjects[$this->xobjid] = array('n' => $this->n);
  21652. // store current graphic state
  21653. $this->xobjects[$this->xobjid]['gvars'] = $this->getGraphicVars();
  21654. // initialize data
  21655. $this->xobjects[$this->xobjid]['intmrk'] = 0;
  21656. $this->xobjects[$this->xobjid]['transfmrk'] = array();
  21657. $this->xobjects[$this->xobjid]['outdata'] = '';
  21658. $this->xobjects[$this->xobjid]['xobjects'] = array();
  21659. $this->xobjects[$this->xobjid]['images'] = array();
  21660. $this->xobjects[$this->xobjid]['fonts'] = array();
  21661. $this->xobjects[$this->xobjid]['annotations'] = array();
  21662. $this->xobjects[$this->xobjid]['extgstates'] = array();
  21663. $this->xobjects[$this->xobjid]['gradients'] = array();
  21664. $this->xobjects[$this->xobjid]['spot_colors'] = array();
  21665. // set new environment
  21666. $this->num_columns = 1;
  21667. $this->current_column = 0;
  21668. $this->SetAutoPageBreak(false);
  21669. if (($w === '') OR ($w <= 0)) {
  21670. $w = $this->w - $this->lMargin - $this->rMargin;
  21671. }
  21672. if (($h === '') OR ($h <= 0)) {
  21673. $h = $this->h - $this->tMargin - $this->bMargin;
  21674. }
  21675. $this->xobjects[$this->xobjid]['x'] = 0;
  21676. $this->xobjects[$this->xobjid]['y'] = 0;
  21677. $this->xobjects[$this->xobjid]['w'] = $w;
  21678. $this->xobjects[$this->xobjid]['h'] = $h;
  21679. $this->w = $w;
  21680. $this->h = $h;
  21681. $this->wPt = $this->w * $this->k;
  21682. $this->hPt = $this->h * $this->k;
  21683. $this->fwPt = $this->wPt;
  21684. $this->fhPt = $this->hPt;
  21685. $this->x = 0;
  21686. $this->y = 0;
  21687. $this->lMargin = 0;
  21688. $this->rMargin = 0;
  21689. $this->tMargin = 0;
  21690. $this->bMargin = 0;
  21691. // set group mode
  21692. $this->xobjects[$this->xobjid]['group'] = $group;
  21693. return $this->xobjid;
  21694. }
  21695. /**
  21696. * End the current XObject Template started with startTemplate() and restore the previous graphic state.
  21697. * 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).
  21698. * 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.
  21699. * @return int the XObject Template ID in case of success or false in case of error.
  21700. * @author Nicola Asuni
  21701. * @public
  21702. * @since 5.8.017 (2010-08-24)
  21703. * @see startTemplate(), printTemplate()
  21704. */
  21705. public function endTemplate() {
  21706. if (!$this->inxobj) {
  21707. // we are not inside a template
  21708. return false;
  21709. }
  21710. $this->inxobj = false;
  21711. // restore previous graphic state
  21712. $this->setGraphicVars($this->xobjects[$this->xobjid]['gvars'], true);
  21713. return $this->xobjid;
  21714. }
  21715. /**
  21716. * Print an XObject Template.
  21717. * You can print an XObject Template inside the currently opened Template.
  21718. * 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).
  21719. * 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.
  21720. * @param $id (string) The ID of XObject Template to print.
  21721. * @param $x (int) X position in user units (empty string = current x position)
  21722. * @param $y (int) Y position in user units (empty string = current y position)
  21723. * @param $w (int) Width in user units (zero = remaining page width)
  21724. * @param $h (int) Height in user units (zero = remaining page height)
  21725. * @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>
  21726. * @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>
  21727. * @param $fitonpage (boolean) If true the template is resized to not exceed page dimensions.
  21728. * @author Nicola Asuni
  21729. * @public
  21730. * @since 5.8.017 (2010-08-24)
  21731. * @see startTemplate(), endTemplate()
  21732. */
  21733. public function printTemplate($id, $x='', $y='', $w=0, $h=0, $align='', $palign='', $fitonpage=false) {
  21734. if ($this->state != 2) {
  21735. return;
  21736. }
  21737. if (!isset($this->xobjects[$id])) {
  21738. $this->Error('The XObject Template \''.$id.'\' doesn\'t exist!');
  21739. }
  21740. if ($this->inxobj) {
  21741. if ($id == $this->xobjid) {
  21742. // close current template
  21743. $this->endTemplate();
  21744. } else {
  21745. // use the template as resource for the template currently opened
  21746. $this->xobjects[$this->xobjid]['xobjects'][$id] = $this->xobjects[$id];
  21747. }
  21748. }
  21749. // set default values
  21750. if ($x === '') {
  21751. $x = $this->x;
  21752. }
  21753. if ($y === '') {
  21754. $y = $this->y;
  21755. }
  21756. // check page for no-write regions and adapt page margins if necessary
  21757. list($x, $y) = $this->checkPageRegions($h, $x, $y);
  21758. $ow = $this->xobjects[$id]['w'];
  21759. if ($ow <= 0) {
  21760. $ow = 1;
  21761. }
  21762. $oh = $this->xobjects[$id]['h'];
  21763. if ($oh <= 0) {
  21764. $oh = 1;
  21765. }
  21766. // calculate template width and height on document
  21767. if (($w <= 0) AND ($h <= 0)) {
  21768. $w = $ow;
  21769. $h = $oh;
  21770. } elseif ($w <= 0) {
  21771. $w = $h * $ow / $oh;
  21772. } elseif ($h <= 0) {
  21773. $h = $w * $oh / $ow;
  21774. }
  21775. // fit the template on available space
  21776. list($w, $h, $x, $y) = $this->fitBlock($w, $h, $x, $y, $fitonpage);
  21777. // set page alignment
  21778. $rb_y = $y + $h;
  21779. // set alignment
  21780. if ($this->rtl) {
  21781. if ($palign == 'L') {
  21782. $xt = $this->lMargin;
  21783. } elseif ($palign == 'C') {
  21784. $xt = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
  21785. } elseif ($palign == 'R') {
  21786. $xt = $this->w - $this->rMargin - $w;
  21787. } else {
  21788. $xt = $x - $w;
  21789. }
  21790. $rb_x = $xt;
  21791. } else {
  21792. if ($palign == 'L') {
  21793. $xt = $this->lMargin;
  21794. } elseif ($palign == 'C') {
  21795. $xt = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
  21796. } elseif ($palign == 'R') {
  21797. $xt = $this->w - $this->rMargin - $w;
  21798. } else {
  21799. $xt = $x;
  21800. }
  21801. $rb_x = $xt + $w;
  21802. }
  21803. // print XObject Template + Transformation matrix
  21804. $this->StartTransform();
  21805. // translate and scale
  21806. $sx = ($w / $ow);
  21807. $sy = ($h / $oh);
  21808. $tm = array();
  21809. $tm[0] = $sx;
  21810. $tm[1] = 0;
  21811. $tm[2] = 0;
  21812. $tm[3] = $sy;
  21813. $tm[4] = $xt * $this->k;
  21814. $tm[5] = ($this->h - $h - $y) * $this->k;
  21815. $this->Transform($tm);
  21816. // set object
  21817. $this->_out('/'.$id.' Do');
  21818. $this->StopTransform();
  21819. // add annotations
  21820. if (!empty($this->xobjects[$id]['annotations'])) {
  21821. foreach ($this->xobjects[$id]['annotations'] as $annot) {
  21822. // transform original coordinates
  21823. $coordlt = TCPDF_STATIC::getTransformationMatrixProduct($tm, array(1, 0, 0, 1, ($annot['x'] * $this->k), (-$annot['y'] * $this->k)));
  21824. $ax = ($coordlt[4] / $this->k);
  21825. $ay = ($this->h - $h - ($coordlt[5] / $this->k));
  21826. $coordrb = TCPDF_STATIC::getTransformationMatrixProduct($tm, array(1, 0, 0, 1, (($annot['x'] + $annot['w']) * $this->k), ((-$annot['y'] - $annot['h']) * $this->k)));
  21827. $aw = ($coordrb[4] / $this->k) - $ax;
  21828. $ah = ($this->h - $h - ($coordrb[5] / $this->k)) - $ay;
  21829. $this->Annotation($ax, $ay, $aw, $ah, $annot['text'], $annot['opt'], $annot['spaces']);
  21830. }
  21831. }
  21832. // set pointer to align the next text/objects
  21833. switch($align) {
  21834. case 'T': {
  21835. $this->y = $y;
  21836. $this->x = $rb_x;
  21837. break;
  21838. }
  21839. case 'M': {
  21840. $this->y = $y + round($h/2);
  21841. $this->x = $rb_x;
  21842. break;
  21843. }
  21844. case 'B': {
  21845. $this->y = $rb_y;
  21846. $this->x = $rb_x;
  21847. break;
  21848. }
  21849. case 'N': {
  21850. $this->SetY($rb_y);
  21851. break;
  21852. }
  21853. default:{
  21854. break;
  21855. }
  21856. }
  21857. }
  21858. /**
  21859. * Set the percentage of character stretching.
  21860. * @param $perc (int) percentage of stretching (100 = no stretching)
  21861. * @author Nicola Asuni
  21862. * @public
  21863. * @since 5.9.000 (2010-09-29)
  21864. */
  21865. public function setFontStretching($perc=100) {
  21866. $this->font_stretching = $perc;
  21867. }
  21868. /**
  21869. * Get the percentage of character stretching.
  21870. * @return float stretching value
  21871. * @author Nicola Asuni
  21872. * @public
  21873. * @since 5.9.000 (2010-09-29)
  21874. */
  21875. public function getFontStretching() {
  21876. return $this->font_stretching;
  21877. }
  21878. /**
  21879. * Set the amount to increase or decrease the space between characters in a text.
  21880. * @param $spacing (float) amount to increase or decrease the space between characters in a text (0 = default spacing)
  21881. * @author Nicola Asuni
  21882. * @public
  21883. * @since 5.9.000 (2010-09-29)
  21884. */
  21885. public function setFontSpacing($spacing=0) {
  21886. $this->font_spacing = $spacing;
  21887. }
  21888. /**
  21889. * Get the amount to increase or decrease the space between characters in a text.
  21890. * @return int font spacing (tracking) value
  21891. * @author Nicola Asuni
  21892. * @public
  21893. * @since 5.9.000 (2010-09-29)
  21894. */
  21895. public function getFontSpacing() {
  21896. return $this->font_spacing;
  21897. }
  21898. /**
  21899. * Return an array of no-write page regions
  21900. * @return array of no-write page regions
  21901. * @author Nicola Asuni
  21902. * @public
  21903. * @since 5.9.003 (2010-10-13)
  21904. * @see setPageRegions(), addPageRegion()
  21905. */
  21906. public function getPageRegions() {
  21907. return $this->page_regions;
  21908. }
  21909. /**
  21910. * Set no-write regions on page.
  21911. * 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.
  21912. * A region is always aligned on the left or right side of the page ad is defined using a vertical segment.
  21913. * You can set multiple regions for the same page.
  21914. * @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.
  21915. * @author Nicola Asuni
  21916. * @public
  21917. * @since 5.9.003 (2010-10-13)
  21918. * @see addPageRegion(), getPageRegions()
  21919. */
  21920. public function setPageRegions($regions=array()) {
  21921. // empty current regions array
  21922. $this->page_regions = array();
  21923. // add regions
  21924. foreach ($regions as $data) {
  21925. $this->addPageRegion($data);
  21926. }
  21927. }
  21928. /**
  21929. * Add a single no-write region on selected page.
  21930. * 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.
  21931. * A region is always aligned on the left or right side of the page ad is defined using a vertical segment.
  21932. * You can set multiple regions for the same page.
  21933. * @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).
  21934. * @author Nicola Asuni
  21935. * @public
  21936. * @since 5.9.003 (2010-10-13)
  21937. * @see setPageRegions(), getPageRegions()
  21938. */
  21939. public function addPageRegion($region) {
  21940. if (!isset($region['page']) OR empty($region['page'])) {
  21941. $region['page'] = $this->page;
  21942. }
  21943. if (isset($region['xt']) AND isset($region['xb']) AND ($region['xt'] > 0) AND ($region['xb'] > 0)
  21944. AND isset($region['yt']) AND isset($region['yb']) AND ($region['yt'] >= 0) AND ($region['yt'] < $region['yb'])
  21945. AND isset($region['side']) AND (($region['side'] == 'L') OR ($region['side'] == 'R'))) {
  21946. $this->page_regions[] = $region;
  21947. }
  21948. }
  21949. /**
  21950. * Remove a single no-write region.
  21951. * @param $key (int) region key
  21952. * @author Nicola Asuni
  21953. * @public
  21954. * @since 5.9.003 (2010-10-13)
  21955. * @see setPageRegions(), getPageRegions()
  21956. */
  21957. public function removePageRegion($key) {
  21958. if (isset($this->page_regions[$key])) {
  21959. unset($this->page_regions[$key]);
  21960. }
  21961. }
  21962. /**
  21963. * Check page for no-write regions and adapt current coordinates and page margins if necessary.
  21964. * 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.
  21965. * A region is always aligned on the left or right side of the page ad is defined using a vertical segment.
  21966. * @param $h (float) height of the text/image/object to print in user units
  21967. * @param $x (float) current X coordinate in user units
  21968. * @param $y (float) current Y coordinate in user units
  21969. * @return array($x, $y)
  21970. * @author Nicola Asuni
  21971. * @protected
  21972. * @since 5.9.003 (2010-10-13)
  21973. */
  21974. protected function checkPageRegions($h, $x, $y) {
  21975. // set default values
  21976. if ($x === '') {
  21977. $x = $this->x;
  21978. }
  21979. if ($y === '') {
  21980. $y = $this->y;
  21981. }
  21982. if (!$this->check_page_regions OR empty($this->page_regions)) {
  21983. // no page regions defined
  21984. return array($x, $y);
  21985. }
  21986. if (empty($h)) {
  21987. $h = $this->getCellHeight($this->FontSize);
  21988. }
  21989. // check for page break
  21990. if ($this->checkPageBreak($h, $y)) {
  21991. // the content will be printed on a new page
  21992. $x = $this->x;
  21993. $y = $this->y;
  21994. }
  21995. if ($this->num_columns > 1) {
  21996. if ($this->rtl) {
  21997. $this->lMargin = ($this->columns[$this->current_column]['x'] - $this->columns[$this->current_column]['w']);
  21998. } else {
  21999. $this->rMargin = ($this->w - $this->columns[$this->current_column]['x'] - $this->columns[$this->current_column]['w']);
  22000. }
  22001. } else {
  22002. if ($this->rtl) {
  22003. $this->lMargin = max($this->clMargin, $this->original_lMargin);
  22004. } else {
  22005. $this->rMargin = max($this->crMargin, $this->original_rMargin);
  22006. }
  22007. }
  22008. // adjust coordinates and page margins
  22009. foreach ($this->page_regions as $regid => $regdata) {
  22010. if ($regdata['page'] == $this->page) {
  22011. // check region boundaries
  22012. if (($y > ($regdata['yt'] - $h)) AND ($y <= $regdata['yb'])) {
  22013. // Y is inside the region
  22014. $minv = ($regdata['xb'] - $regdata['xt']) / ($regdata['yb'] - $regdata['yt']); // inverse of angular coefficient
  22015. $yt = max($y, $regdata['yt']);
  22016. $yb = min(($yt + $h), $regdata['yb']);
  22017. $xt = (($yt - $regdata['yt']) * $minv) + $regdata['xt'];
  22018. $xb = (($yb - $regdata['yt']) * $minv) + $regdata['xt'];
  22019. if ($regdata['side'] == 'L') { // left side
  22020. $new_margin = max($xt, $xb);
  22021. if ($this->lMargin < $new_margin) {
  22022. if ($this->rtl) {
  22023. // adjust left page margin
  22024. $this->lMargin = max(0, $new_margin);
  22025. }
  22026. if ($x < $new_margin) {
  22027. // adjust x position
  22028. $x = $new_margin;
  22029. if ($new_margin > ($this->w - $this->rMargin)) {
  22030. // adjust y position
  22031. $y = $regdata['yb'] - $h;
  22032. }
  22033. }
  22034. }
  22035. } elseif ($regdata['side'] == 'R') { // right side
  22036. $new_margin = min($xt, $xb);
  22037. if (($this->w - $this->rMargin) > $new_margin) {
  22038. if (!$this->rtl) {
  22039. // adjust right page margin
  22040. $this->rMargin = max(0, ($this->w - $new_margin));
  22041. }
  22042. if ($x > $new_margin) {
  22043. // adjust x position
  22044. $x = $new_margin;
  22045. if ($new_margin > $this->lMargin) {
  22046. // adjust y position
  22047. $y = $regdata['yb'] - $h;
  22048. }
  22049. }
  22050. }
  22051. }
  22052. }
  22053. }
  22054. }
  22055. return array($x, $y);
  22056. }
  22057. // --- SVG METHODS ---------------------------------------------------------
  22058. /**
  22059. * Embedd a Scalable Vector Graphics (SVG) image.
  22060. * NOTE: SVG standard is not yet fully implemented, use the setRasterizeVectorImages() method to enable/disable rasterization of vector images using ImageMagick library.
  22061. * @param $file (string) Name of the SVG file or a '@' character followed by the SVG data string.
  22062. * @param $x (float) Abscissa of the upper-left corner.
  22063. * @param $y (float) Ordinate of the upper-left corner.
  22064. * @param $w (float) Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
  22065. * @param $h (float) Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
  22066. * @param $link (mixed) URL or identifier returned by AddLink().
  22067. * @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.
  22068. * @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>
  22069. * @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)))
  22070. * @param $fitonpage (boolean) if true the image is resized to not exceed page dimensions.
  22071. * @author Nicola Asuni
  22072. * @since 5.0.000 (2010-05-02)
  22073. * @public
  22074. */
  22075. public function ImageSVG($file, $x='', $y='', $w=0, $h=0, $link='', $align='', $palign='', $border=0, $fitonpage=false) {
  22076. if ($this->state != 2) {
  22077. return;
  22078. }
  22079. // reset SVG vars
  22080. $this->svggradients = array();
  22081. $this->svggradientid = 0;
  22082. $this->svgdefsmode = false;
  22083. $this->svgdefs = array();
  22084. $this->svgclipmode = false;
  22085. $this->svgclippaths = array();
  22086. $this->svgcliptm = array();
  22087. $this->svgclipid = 0;
  22088. $this->svgtext = '';
  22089. $this->svgtextmode = array();
  22090. if ($this->rasterize_vector_images AND ($w > 0) AND ($h > 0)) {
  22091. // convert SVG to raster image using GD or ImageMagick libraries
  22092. return $this->Image($file, $x, $y, $w, $h, 'SVG', $link, $align, true, 300, $palign, false, false, $border, false, false, false);
  22093. }
  22094. if ($file[0] === '@') { // image from string
  22095. $this->svgdir = '';
  22096. $svgdata = substr($file, 1);
  22097. } else { // SVG file
  22098. $this->svgdir = dirname($file);
  22099. $svgdata = TCPDF_STATIC::fileGetContents($file);
  22100. }
  22101. if ($svgdata === FALSE) {
  22102. $this->Error('SVG file not found: '.$file);
  22103. }
  22104. if ($x === '') {
  22105. $x = $this->x;
  22106. }
  22107. if ($y === '') {
  22108. $y = $this->y;
  22109. }
  22110. // check page for no-write regions and adapt page margins if necessary
  22111. list($x, $y) = $this->checkPageRegions($h, $x, $y);
  22112. $k = $this->k;
  22113. $ox = 0;
  22114. $oy = 0;
  22115. $ow = $w;
  22116. $oh = $h;
  22117. $aspect_ratio_align = 'xMidYMid';
  22118. $aspect_ratio_ms = 'meet';
  22119. $regs = array();
  22120. // get original image width and height
  22121. preg_match('/<svg([^\>]*)>/si', $svgdata, $regs);
  22122. if (isset($regs[1]) AND !empty($regs[1])) {
  22123. $tmp = array();
  22124. if (preg_match('/[\s]+x[\s]*=[\s]*"([^"]*)"/si', $regs[1], $tmp)) {
  22125. $ox = $this->getHTMLUnitToUnits($tmp[1], 0, $this->svgunit, false);
  22126. }
  22127. $tmp = array();
  22128. if (preg_match('/[\s]+y[\s]*=[\s]*"([^"]*)"/si', $regs[1], $tmp)) {
  22129. $oy = $this->getHTMLUnitToUnits($tmp[1], 0, $this->svgunit, false);
  22130. }
  22131. $tmp = array();
  22132. if (preg_match('/[\s]+width[\s]*=[\s]*"([^"]*)"/si', $regs[1], $tmp)) {
  22133. $ow = $this->getHTMLUnitToUnits($tmp[1], 1, $this->svgunit, false);
  22134. }
  22135. $tmp = array();
  22136. if (preg_match('/[\s]+height[\s]*=[\s]*"([^"]*)"/si', $regs[1], $tmp)) {
  22137. $oh = $this->getHTMLUnitToUnits($tmp[1], 1, $this->svgunit, false);
  22138. }
  22139. $tmp = array();
  22140. $view_box = array();
  22141. if (preg_match('/[\s]+viewBox[\s]*=[\s]*"[\s]*([0-9\.\-]+)[\s]+([0-9\.\-]+)[\s]+([0-9\.]+)[\s]+([0-9\.]+)[\s]*"/si', $regs[1], $tmp)) {
  22142. if (count($tmp) == 5) {
  22143. array_shift($tmp);
  22144. foreach ($tmp as $key => $val) {
  22145. $view_box[$key] = $this->getHTMLUnitToUnits($val, 0, $this->svgunit, false);
  22146. }
  22147. $ox = $view_box[0];
  22148. $oy = $view_box[1];
  22149. }
  22150. // get aspect ratio
  22151. $tmp = array();
  22152. if (preg_match('/[\s]+preserveAspectRatio[\s]*=[\s]*"([^"]*)"/si', $regs[1], $tmp)) {
  22153. $aspect_ratio = preg_split('/[\s]+/si', $tmp[1]);
  22154. switch (count($aspect_ratio)) {
  22155. case 3: {
  22156. $aspect_ratio_align = $aspect_ratio[1];
  22157. $aspect_ratio_ms = $aspect_ratio[2];
  22158. break;
  22159. }
  22160. case 2: {
  22161. $aspect_ratio_align = $aspect_ratio[0];
  22162. $aspect_ratio_ms = $aspect_ratio[1];
  22163. break;
  22164. }
  22165. case 1: {
  22166. $aspect_ratio_align = $aspect_ratio[0];
  22167. $aspect_ratio_ms = 'meet';
  22168. break;
  22169. }
  22170. }
  22171. }
  22172. }
  22173. }
  22174. if ($ow <= 0) {
  22175. $ow = 1;
  22176. }
  22177. if ($oh <= 0) {
  22178. $oh = 1;
  22179. }
  22180. // calculate image width and height on document
  22181. if (($w <= 0) AND ($h <= 0)) {
  22182. // convert image size to document unit
  22183. $w = $ow;
  22184. $h = $oh;
  22185. } elseif ($w <= 0) {
  22186. $w = $h * $ow / $oh;
  22187. } elseif ($h <= 0) {
  22188. $h = $w * $oh / $ow;
  22189. }
  22190. // fit the image on available space
  22191. list($w, $h, $x, $y) = $this->fitBlock($w, $h, $x, $y, $fitonpage);
  22192. if ($this->rasterize_vector_images) {
  22193. // convert SVG to raster image using GD or ImageMagick libraries
  22194. return $this->Image($file, $x, $y, $w, $h, 'SVG', $link, $align, true, 300, $palign, false, false, $border, false, false, false);
  22195. }
  22196. // set alignment
  22197. $this->img_rb_y = $y + $h;
  22198. // set alignment
  22199. if ($this->rtl) {
  22200. if ($palign == 'L') {
  22201. $ximg = $this->lMargin;
  22202. } elseif ($palign == 'C') {
  22203. $ximg = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
  22204. } elseif ($palign == 'R') {
  22205. $ximg = $this->w - $this->rMargin - $w;
  22206. } else {
  22207. $ximg = $x - $w;
  22208. }
  22209. $this->img_rb_x = $ximg;
  22210. } else {
  22211. if ($palign == 'L') {
  22212. $ximg = $this->lMargin;
  22213. } elseif ($palign == 'C') {
  22214. $ximg = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
  22215. } elseif ($palign == 'R') {
  22216. $ximg = $this->w - $this->rMargin - $w;
  22217. } else {
  22218. $ximg = $x;
  22219. }
  22220. $this->img_rb_x = $ximg + $w;
  22221. }
  22222. // store current graphic vars
  22223. $gvars = $this->getGraphicVars();
  22224. // store SVG position and scale factors
  22225. $svgoffset_x = ($ximg - $ox) * $this->k;
  22226. $svgoffset_y = -($y - $oy) * $this->k;
  22227. if (isset($view_box[2]) AND ($view_box[2] > 0) AND ($view_box[3] > 0)) {
  22228. $ow = $view_box[2];
  22229. $oh = $view_box[3];
  22230. } else {
  22231. if ($ow <= 0) {
  22232. $ow = $w;
  22233. }
  22234. if ($oh <= 0) {
  22235. $oh = $h;
  22236. }
  22237. }
  22238. $svgscale_x = $w / $ow;
  22239. $svgscale_y = $h / $oh;
  22240. // scaling and alignment
  22241. if ($aspect_ratio_align != 'none') {
  22242. // store current scaling values
  22243. $svgscale_old_x = $svgscale_x;
  22244. $svgscale_old_y = $svgscale_y;
  22245. // force uniform scaling
  22246. if ($aspect_ratio_ms == 'slice') {
  22247. // the entire viewport is covered by the viewBox
  22248. if ($svgscale_x > $svgscale_y) {
  22249. $svgscale_y = $svgscale_x;
  22250. } elseif ($svgscale_x < $svgscale_y) {
  22251. $svgscale_x = $svgscale_y;
  22252. }
  22253. } else { // meet
  22254. // the entire viewBox is visible within the viewport
  22255. if ($svgscale_x < $svgscale_y) {
  22256. $svgscale_y = $svgscale_x;
  22257. } elseif ($svgscale_x > $svgscale_y) {
  22258. $svgscale_x = $svgscale_y;
  22259. }
  22260. }
  22261. // correct X alignment
  22262. switch (substr($aspect_ratio_align, 1, 3)) {
  22263. case 'Min': {
  22264. // do nothing
  22265. break;
  22266. }
  22267. case 'Max': {
  22268. $svgoffset_x += (($w * $this->k) - ($ow * $this->k * $svgscale_x));
  22269. break;
  22270. }
  22271. default:
  22272. case 'Mid': {
  22273. $svgoffset_x += ((($w * $this->k) - ($ow * $this->k * $svgscale_x)) / 2);
  22274. break;
  22275. }
  22276. }
  22277. // correct Y alignment
  22278. switch (substr($aspect_ratio_align, 5)) {
  22279. case 'Min': {
  22280. // do nothing
  22281. break;
  22282. }
  22283. case 'Max': {
  22284. $svgoffset_y -= (($h * $this->k) - ($oh * $this->k * $svgscale_y));
  22285. break;
  22286. }
  22287. default:
  22288. case 'Mid': {
  22289. $svgoffset_y -= ((($h * $this->k) - ($oh * $this->k * $svgscale_y)) / 2);
  22290. break;
  22291. }
  22292. }
  22293. }
  22294. // store current page break mode
  22295. $page_break_mode = $this->AutoPageBreak;
  22296. $page_break_margin = $this->getBreakMargin();
  22297. $cell_padding = $this->cell_padding;
  22298. $this->SetCellPadding(0);
  22299. $this->SetAutoPageBreak(false);
  22300. // save the current graphic state
  22301. $this->_out('q'.$this->epsmarker);
  22302. // set initial clipping mask
  22303. $this->Rect($ximg, $y, $w, $h, 'CNZ', array(), array());
  22304. // scale and translate
  22305. $e = $ox * $this->k * (1 - $svgscale_x);
  22306. $f = ($this->h - $oy) * $this->k * (1 - $svgscale_y);
  22307. $this->_out(sprintf('%F %F %F %F %F %F cm', $svgscale_x, 0, 0, $svgscale_y, ($e + $svgoffset_x), ($f + $svgoffset_y)));
  22308. // creates a new XML parser to be used by the other XML functions
  22309. $this->parser = xml_parser_create('UTF-8');
  22310. // the following function allows to use parser inside object
  22311. xml_set_object($this->parser, $this);
  22312. // disable case-folding for this XML parser
  22313. xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0);
  22314. // sets the element handler functions for the XML parser
  22315. xml_set_element_handler($this->parser, 'startSVGElementHandler', 'endSVGElementHandler');
  22316. // sets the character data handler function for the XML parser
  22317. xml_set_character_data_handler($this->parser, 'segSVGContentHandler');
  22318. // start parsing an XML document
  22319. if (!xml_parse($this->parser, $svgdata)) {
  22320. $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));
  22321. $this->Error($error_message);
  22322. }
  22323. // free this XML parser
  22324. xml_parser_free($this->parser);
  22325. // restore previous graphic state
  22326. $this->_out($this->epsmarker.'Q');
  22327. // restore graphic vars
  22328. $this->setGraphicVars($gvars);
  22329. $this->lasth = $gvars['lasth'];
  22330. if (!empty($border)) {
  22331. $bx = $this->x;
  22332. $by = $this->y;
  22333. $this->x = $ximg;
  22334. if ($this->rtl) {
  22335. $this->x += $w;
  22336. }
  22337. $this->y = $y;
  22338. $this->Cell($w, $h, '', $border, 0, '', 0, '', 0, true);
  22339. $this->x = $bx;
  22340. $this->y = $by;
  22341. }
  22342. if ($link) {
  22343. $this->Link($ximg, $y, $w, $h, $link, 0);
  22344. }
  22345. // set pointer to align the next text/objects
  22346. switch($align) {
  22347. case 'T':{
  22348. $this->y = $y;
  22349. $this->x = $this->img_rb_x;
  22350. break;
  22351. }
  22352. case 'M':{
  22353. $this->y = $y + round($h/2);
  22354. $this->x = $this->img_rb_x;
  22355. break;
  22356. }
  22357. case 'B':{
  22358. $this->y = $this->img_rb_y;
  22359. $this->x = $this->img_rb_x;
  22360. break;
  22361. }
  22362. case 'N':{
  22363. $this->SetY($this->img_rb_y);
  22364. break;
  22365. }
  22366. default:{
  22367. // restore pointer to starting position
  22368. $this->x = $gvars['x'];
  22369. $this->y = $gvars['y'];
  22370. $this->page = $gvars['page'];
  22371. $this->current_column = $gvars['current_column'];
  22372. $this->tMargin = $gvars['tMargin'];
  22373. $this->bMargin = $gvars['bMargin'];
  22374. $this->w = $gvars['w'];
  22375. $this->h = $gvars['h'];
  22376. $this->wPt = $gvars['wPt'];
  22377. $this->hPt = $gvars['hPt'];
  22378. $this->fwPt = $gvars['fwPt'];
  22379. $this->fhPt = $gvars['fhPt'];
  22380. break;
  22381. }
  22382. }
  22383. $this->endlinex = $this->img_rb_x;
  22384. // restore page break
  22385. $this->SetAutoPageBreak($page_break_mode, $page_break_margin);
  22386. $this->cell_padding = $cell_padding;
  22387. }
  22388. /**
  22389. * Convert SVG transformation matrix to PDF.
  22390. * @param $tm (array) original SVG transformation matrix
  22391. * @return array transformation matrix
  22392. * @protected
  22393. * @since 5.0.000 (2010-05-02)
  22394. */
  22395. protected function convertSVGtMatrix($tm) {
  22396. $a = $tm[0];
  22397. $b = -$tm[1];
  22398. $c = -$tm[2];
  22399. $d = $tm[3];
  22400. $e = $this->getHTMLUnitToUnits($tm[4], 1, $this->svgunit, false) * $this->k;
  22401. $f = -$this->getHTMLUnitToUnits($tm[5], 1, $this->svgunit, false) * $this->k;
  22402. $x = 0;
  22403. $y = $this->h * $this->k;
  22404. $e = ($x * (1 - $a)) - ($y * $c) + $e;
  22405. $f = ($y * (1 - $d)) - ($x * $b) + $f;
  22406. return array($a, $b, $c, $d, $e, $f);
  22407. }
  22408. /**
  22409. * Apply SVG graphic transformation matrix.
  22410. * @param $tm (array) original SVG transformation matrix
  22411. * @protected
  22412. * @since 5.0.000 (2010-05-02)
  22413. */
  22414. protected function SVGTransform($tm) {
  22415. $this->Transform($this->convertSVGtMatrix($tm));
  22416. }
  22417. /**
  22418. * Apply the requested SVG styles (*** TO BE COMPLETED ***)
  22419. * @param $svgstyle (array) array of SVG styles to apply
  22420. * @param $prevsvgstyle (array) array of previous SVG style
  22421. * @param $x (int) X origin of the bounding box
  22422. * @param $y (int) Y origin of the bounding box
  22423. * @param $w (int) width of the bounding box
  22424. * @param $h (int) height of the bounding box
  22425. * @param $clip_function (string) clip function
  22426. * @param $clip_params (array) array of parameters for clipping function
  22427. * @return object style
  22428. * @author Nicola Asuni
  22429. * @since 5.0.000 (2010-05-02)
  22430. * @protected
  22431. */
  22432. protected function setSVGStyles($svgstyle, $prevsvgstyle, $x=0, $y=0, $w=1, $h=1, $clip_function='', $clip_params=array()) {
  22433. if ($this->state != 2) {
  22434. return;
  22435. }
  22436. $objstyle = '';
  22437. $minlen = (0.01 / $this->k); // minimum acceptable length
  22438. if (!isset($svgstyle['opacity'])) {
  22439. return $objstyle;
  22440. }
  22441. // clip-path
  22442. $regs = array();
  22443. if (preg_match('/url\([\s]*\#([^\)]*)\)/si', $svgstyle['clip-path'], $regs)) {
  22444. $clip_path = $this->svgclippaths[$regs[1]];
  22445. foreach ($clip_path as $cp) {
  22446. $this->startSVGElementHandler('clip-path', $cp['name'], $cp['attribs'], $cp['tm']);
  22447. }
  22448. }
  22449. // opacity
  22450. if ($svgstyle['opacity'] != 1) {
  22451. $this->setAlpha($svgstyle['opacity'], 'Normal', $svgstyle['opacity'], false);
  22452. }
  22453. // color
  22454. $fill_color = TCPDF_COLORS::convertHTMLColorToDec($svgstyle['color'], $this->spot_colors);
  22455. $this->SetFillColorArray($fill_color);
  22456. // text color
  22457. $text_color = TCPDF_COLORS::convertHTMLColorToDec($svgstyle['text-color'], $this->spot_colors);
  22458. $this->SetTextColorArray($text_color);
  22459. // clip
  22460. if (preg_match('/rect\(([a-z0-9\-\.]*)[\s]*([a-z0-9\-\.]*)[\s]*([a-z0-9\-\.]*)[\s]*([a-z0-9\-\.]*)\)/si', $svgstyle['clip'], $regs)) {
  22461. $top = (isset($regs[1])?$this->getHTMLUnitToUnits($regs[1], 0, $this->svgunit, false):0);
  22462. $right = (isset($regs[2])?$this->getHTMLUnitToUnits($regs[2], 0, $this->svgunit, false):0);
  22463. $bottom = (isset($regs[3])?$this->getHTMLUnitToUnits($regs[3], 0, $this->svgunit, false):0);
  22464. $left = (isset($regs[4])?$this->getHTMLUnitToUnits($regs[4], 0, $this->svgunit, false):0);
  22465. $cx = $x + $left;
  22466. $cy = $y + $top;
  22467. $cw = $w - $left - $right;
  22468. $ch = $h - $top - $bottom;
  22469. if ($svgstyle['clip-rule'] == 'evenodd') {
  22470. $clip_rule = 'CNZ';
  22471. } else {
  22472. $clip_rule = 'CEO';
  22473. }
  22474. $this->Rect($cx, $cy, $cw, $ch, $clip_rule, array(), array());
  22475. }
  22476. // fill
  22477. $regs = array();
  22478. if (preg_match('/url\([\s]*\#([^\)]*)\)/si', $svgstyle['fill'], $regs)) {
  22479. // gradient
  22480. $gradient = $this->svggradients[$regs[1]];
  22481. if (isset($gradient['xref'])) {
  22482. // reference to another gradient definition
  22483. $newgradient = $this->svggradients[$gradient['xref']];
  22484. $newgradient['coords'] = $gradient['coords'];
  22485. $newgradient['mode'] = $gradient['mode'];
  22486. $newgradient['type'] = $gradient['type'];
  22487. $newgradient['gradientUnits'] = $gradient['gradientUnits'];
  22488. if (isset($gradient['gradientTransform'])) {
  22489. $newgradient['gradientTransform'] = $gradient['gradientTransform'];
  22490. }
  22491. $gradient = $newgradient;
  22492. }
  22493. //save current Graphic State
  22494. $this->_outSaveGraphicsState();
  22495. //set clipping area
  22496. if (!empty($clip_function) AND method_exists($this, $clip_function)) {
  22497. $bbox = call_user_func_array(array($this, $clip_function), $clip_params);
  22498. if ((!isset($gradient['type']) OR ($gradient['type'] != 3)) AND is_array($bbox) AND (count($bbox) == 4)) {
  22499. list($x, $y, $w, $h) = $bbox;
  22500. }
  22501. }
  22502. if ($gradient['mode'] == 'measure') {
  22503. if (!isset($gradient['coords'][4])) {
  22504. $gradient['coords'][4] = 0.5;
  22505. }
  22506. if (isset($gradient['gradientTransform']) AND !empty($gradient['gradientTransform'])) {
  22507. $gtm = $gradient['gradientTransform'];
  22508. // apply transformation matrix
  22509. $xa = ($gtm[0] * $gradient['coords'][0]) + ($gtm[2] * $gradient['coords'][1]) + $gtm[4];
  22510. $ya = ($gtm[1] * $gradient['coords'][0]) + ($gtm[3] * $gradient['coords'][1]) + $gtm[5];
  22511. $xb = ($gtm[0] * $gradient['coords'][2]) + ($gtm[2] * $gradient['coords'][3]) + $gtm[4];
  22512. $yb = ($gtm[1] * $gradient['coords'][2]) + ($gtm[3] * $gradient['coords'][3]) + $gtm[5];
  22513. $r = sqrt(pow(($gtm[0] * $gradient['coords'][4]), 2) + pow(($gtm[1] * $gradient['coords'][4]), 2));
  22514. $gradient['coords'][0] = $xa;
  22515. $gradient['coords'][1] = $ya;
  22516. $gradient['coords'][2] = $xb;
  22517. $gradient['coords'][3] = $yb;
  22518. $gradient['coords'][4] = $r;
  22519. }
  22520. // convert SVG coordinates to user units
  22521. $gradient['coords'][0] = $this->getHTMLUnitToUnits($gradient['coords'][0], 0, $this->svgunit, false);
  22522. $gradient['coords'][1] = $this->getHTMLUnitToUnits($gradient['coords'][1], 0, $this->svgunit, false);
  22523. $gradient['coords'][2] = $this->getHTMLUnitToUnits($gradient['coords'][2], 0, $this->svgunit, false);
  22524. $gradient['coords'][3] = $this->getHTMLUnitToUnits($gradient['coords'][3], 0, $this->svgunit, false);
  22525. $gradient['coords'][4] = $this->getHTMLUnitToUnits($gradient['coords'][4], 0, $this->svgunit, false);
  22526. if ($w <= $minlen) {
  22527. $w = $minlen;
  22528. }
  22529. if ($h <= $minlen) {
  22530. $h = $minlen;
  22531. }
  22532. // shift units
  22533. if ($gradient['gradientUnits'] == 'objectBoundingBox') {
  22534. // convert to SVG coordinate system
  22535. $gradient['coords'][0] += $x;
  22536. $gradient['coords'][1] += $y;
  22537. $gradient['coords'][2] += $x;
  22538. $gradient['coords'][3] += $y;
  22539. }
  22540. // calculate percentages
  22541. $gradient['coords'][0] = (($gradient['coords'][0] - $x) / $w);
  22542. $gradient['coords'][1] = (($gradient['coords'][1] - $y) / $h);
  22543. $gradient['coords'][2] = (($gradient['coords'][2] - $x) / $w);
  22544. $gradient['coords'][3] = (($gradient['coords'][3] - $y) / $h);
  22545. $gradient['coords'][4] /= $w;
  22546. } elseif ($gradient['mode'] == 'percentage') {
  22547. foreach($gradient['coords'] as $key => $val) {
  22548. $gradient['coords'][$key] = (intval($val) / 100);
  22549. if ($val < 0) {
  22550. $gradient['coords'][$key] = 0;
  22551. } elseif ($val > 1) {
  22552. $gradient['coords'][$key] = 1;
  22553. }
  22554. }
  22555. }
  22556. if (($gradient['type'] == 2) AND ($gradient['coords'][0] == $gradient['coords'][2]) AND ($gradient['coords'][1] == $gradient['coords'][3])) {
  22557. // single color (no shading)
  22558. $gradient['coords'][0] = 1;
  22559. $gradient['coords'][1] = 0;
  22560. $gradient['coords'][2] = 0.999;
  22561. $gradient['coords'][3] = 0;
  22562. }
  22563. // swap Y coordinates
  22564. $tmp = $gradient['coords'][1];
  22565. $gradient['coords'][1] = $gradient['coords'][3];
  22566. $gradient['coords'][3] = $tmp;
  22567. // set transformation map for gradient
  22568. $cy = ($this->h - $y);
  22569. if ($gradient['type'] == 3) {
  22570. // circular gradient
  22571. $cy -= ($gradient['coords'][1] * ($w + $h));
  22572. $h = $w = max($w, $h);
  22573. } else {
  22574. $cy -= $h;
  22575. }
  22576. $this->_out(sprintf('%F 0 0 %F %F %F cm', ($w * $this->k), ($h * $this->k), ($x * $this->k), ($cy * $this->k)));
  22577. if (count($gradient['stops']) > 1) {
  22578. $this->Gradient($gradient['type'], $gradient['coords'], $gradient['stops'], array(), false);
  22579. }
  22580. } elseif ($svgstyle['fill'] != 'none') {
  22581. $fill_color = TCPDF_COLORS::convertHTMLColorToDec($svgstyle['fill'], $this->spot_colors);
  22582. if ($svgstyle['fill-opacity'] != 1) {
  22583. $this->setAlpha($this->alpha['CA'], 'Normal', $svgstyle['fill-opacity'], false);
  22584. }
  22585. $this->SetFillColorArray($fill_color);
  22586. if ($svgstyle['fill-rule'] == 'evenodd') {
  22587. $objstyle .= 'F*';
  22588. } else {
  22589. $objstyle .= 'F';
  22590. }
  22591. }
  22592. // stroke
  22593. if ($svgstyle['stroke'] != 'none') {
  22594. if ($svgstyle['stroke-opacity'] != 1) {
  22595. $this->setAlpha($svgstyle['stroke-opacity'], 'Normal', $this->alpha['ca'], false);
  22596. } elseif (preg_match('/rgba\(\d+%?,\s*\d+%?,\s*\d+%?,\s*(\d+(?:\.\d+)?)\)/i', $svgstyle['stroke'], $rgba_matches)) {
  22597. $this->setAlpha($rgba_matches[1], 'Normal', $this->alpha['ca'], false);
  22598. }
  22599. $stroke_style = array(
  22600. 'color' => TCPDF_COLORS::convertHTMLColorToDec($svgstyle['stroke'], $this->spot_colors),
  22601. 'width' => $this->getHTMLUnitToUnits($svgstyle['stroke-width'], 0, $this->svgunit, false),
  22602. 'cap' => $svgstyle['stroke-linecap'],
  22603. 'join' => $svgstyle['stroke-linejoin']
  22604. );
  22605. if (isset($svgstyle['stroke-dasharray']) AND !empty($svgstyle['stroke-dasharray']) AND ($svgstyle['stroke-dasharray'] != 'none')) {
  22606. $stroke_style['dash'] = $svgstyle['stroke-dasharray'];
  22607. }
  22608. $this->SetLineStyle($stroke_style);
  22609. $objstyle .= 'D';
  22610. }
  22611. // font
  22612. $regs = array();
  22613. if (!empty($svgstyle['font'])) {
  22614. if (preg_match('/font-family[\s]*:[\s]*([^\;\"]*)/si', $svgstyle['font'], $regs)) {
  22615. $font_family = $this->getFontFamilyName($regs[1]);
  22616. } else {
  22617. $font_family = $svgstyle['font-family'];
  22618. }
  22619. if (preg_match('/font-size[\s]*:[\s]*([^\s\;\"]*)/si', $svgstyle['font'], $regs)) {
  22620. $font_size = trim($regs[1]);
  22621. } else {
  22622. $font_size = $svgstyle['font-size'];
  22623. }
  22624. if (preg_match('/font-style[\s]*:[\s]*([^\s\;\"]*)/si', $svgstyle['font'], $regs)) {
  22625. $font_style = trim($regs[1]);
  22626. } else {
  22627. $font_style = $svgstyle['font-style'];
  22628. }
  22629. if (preg_match('/font-weight[\s]*:[\s]*([^\s\;\"]*)/si', $svgstyle['font'], $regs)) {
  22630. $font_weight = trim($regs[1]);
  22631. } else {
  22632. $font_weight = $svgstyle['font-weight'];
  22633. }
  22634. if (preg_match('/font-stretch[\s]*:[\s]*([^\s\;\"]*)/si', $svgstyle['font'], $regs)) {
  22635. $font_stretch = trim($regs[1]);
  22636. } else {
  22637. $font_stretch = $svgstyle['font-stretch'];
  22638. }
  22639. if (preg_match('/letter-spacing[\s]*:[\s]*([^\s\;\"]*)/si', $svgstyle['font'], $regs)) {
  22640. $font_spacing = trim($regs[1]);
  22641. } else {
  22642. $font_spacing = $svgstyle['letter-spacing'];
  22643. }
  22644. } else {
  22645. $font_family = $this->getFontFamilyName($svgstyle['font-family']);
  22646. $font_size = $svgstyle['font-size'];
  22647. $font_style = $svgstyle['font-style'];
  22648. $font_weight = $svgstyle['font-weight'];
  22649. $font_stretch = $svgstyle['font-stretch'];
  22650. $font_spacing = $svgstyle['letter-spacing'];
  22651. }
  22652. $font_size = $this->getHTMLFontUnits($font_size, $this->svgstyles[0]['font-size'], $prevsvgstyle['font-size'], $this->svgunit);
  22653. $font_stretch = $this->getCSSFontStretching($font_stretch, $svgstyle['font-stretch']);
  22654. $font_spacing = $this->getCSSFontSpacing($font_spacing, $svgstyle['letter-spacing']);
  22655. switch ($font_style) {
  22656. case 'italic': {
  22657. $font_style = 'I';
  22658. break;
  22659. }
  22660. case 'oblique': {
  22661. $font_style = 'I';
  22662. break;
  22663. }
  22664. default:
  22665. case 'normal': {
  22666. $font_style = '';
  22667. break;
  22668. }
  22669. }
  22670. switch ($font_weight) {
  22671. case 'bold':
  22672. case 'bolder': {
  22673. $font_style .= 'B';
  22674. break;
  22675. }
  22676. case 'normal': {
  22677. if ((substr($font_family, -1) == 'I') AND (substr($font_family, -2, 1) == 'B')) {
  22678. $font_family = substr($font_family, 0, -2).'I';
  22679. } elseif (substr($font_family, -1) == 'B') {
  22680. $font_family = substr($font_family, 0, -1);
  22681. }
  22682. break;
  22683. }
  22684. }
  22685. switch ($svgstyle['text-decoration']) {
  22686. case 'underline': {
  22687. $font_style .= 'U';
  22688. break;
  22689. }
  22690. case 'overline': {
  22691. $font_style .= 'O';
  22692. break;
  22693. }
  22694. case 'line-through': {
  22695. $font_style .= 'D';
  22696. break;
  22697. }
  22698. default:
  22699. case 'none': {
  22700. break;
  22701. }
  22702. }
  22703. $this->SetFont($font_family, $font_style, $font_size);
  22704. $this->setFontStretching($font_stretch);
  22705. $this->setFontSpacing($font_spacing);
  22706. return $objstyle;
  22707. }
  22708. /**
  22709. * Draws an SVG path
  22710. * @param $d (string) attribute d of the path SVG element
  22711. * @param $style (string) Style of rendering. Possible values are:
  22712. * <ul>
  22713. * <li>D or empty string: Draw (default).</li>
  22714. * <li>F: Fill.</li>
  22715. * <li>F*: Fill using the even-odd rule to determine which regions lie inside the clipping path.</li>
  22716. * <li>DF or FD: Draw and fill.</li>
  22717. * <li>DF* or FD*: Draw and fill using the even-odd rule to determine which regions lie inside the clipping path.</li>
  22718. * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
  22719. * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
  22720. * </ul>
  22721. * @return array of container box measures (x, y, w, h)
  22722. * @author Nicola Asuni
  22723. * @since 5.0.000 (2010-05-02)
  22724. * @protected
  22725. */
  22726. protected function SVGPath($d, $style='') {
  22727. if ($this->state != 2) {
  22728. return;
  22729. }
  22730. // set fill/stroke style
  22731. $op = TCPDF_STATIC::getPathPaintOperator($style, '');
  22732. if (empty($op)) {
  22733. return;
  22734. }
  22735. $paths = array();
  22736. $d = preg_replace('/([0-9ACHLMQSTVZ])([\-\+])/si', '\\1 \\2', $d);
  22737. preg_match_all('/([ACHLMQSTVZ])[\s]*([^ACHLMQSTVZ\"]*)/si', $d, $paths, PREG_SET_ORDER);
  22738. $x = 0;
  22739. $y = 0;
  22740. $x1 = 0;
  22741. $y1 = 0;
  22742. $x2 = 0;
  22743. $y2 = 0;
  22744. $xmin = 2147483647;
  22745. $xmax = 0;
  22746. $ymin = 2147483647;
  22747. $ymax = 0;
  22748. $relcoord = false;
  22749. $minlen = (0.01 / $this->k); // minimum acceptable length (3 point)
  22750. $firstcmd = true; // used to print first point
  22751. // draw curve pieces
  22752. foreach ($paths as $key => $val) {
  22753. // get curve type
  22754. $cmd = trim($val[1]);
  22755. if (strtolower($cmd) == $cmd) {
  22756. // use relative coordinated instead of absolute
  22757. $relcoord = true;
  22758. $xoffset = $x;
  22759. $yoffset = $y;
  22760. } else {
  22761. $relcoord = false;
  22762. $xoffset = 0;
  22763. $yoffset = 0;
  22764. }
  22765. $params = array();
  22766. if (isset($val[2])) {
  22767. // get curve parameters
  22768. $rawparams = preg_split('/([\,\s]+)/si', trim($val[2]));
  22769. $params = array();
  22770. foreach ($rawparams as $ck => $cp) {
  22771. $params[$ck] = $this->getHTMLUnitToUnits($cp, 0, $this->svgunit, false);
  22772. if (abs($params[$ck]) < $minlen) {
  22773. // approximate little values to zero
  22774. $params[$ck] = 0;
  22775. }
  22776. }
  22777. }
  22778. // store current origin point
  22779. $x0 = $x;
  22780. $y0 = $y;
  22781. switch (strtoupper($cmd)) {
  22782. case 'M': { // moveto
  22783. foreach ($params as $ck => $cp) {
  22784. if (($ck % 2) == 0) {
  22785. $x = $cp + $xoffset;
  22786. } else {
  22787. $y = $cp + $yoffset;
  22788. if ($firstcmd OR (abs($x0 - $x) >= $minlen) OR (abs($y0 - $y) >= $minlen)) {
  22789. if ($ck == 1) {
  22790. $this->_outPoint($x, $y);
  22791. $firstcmd = false;
  22792. } else {
  22793. $this->_outLine($x, $y);
  22794. }
  22795. $x0 = $x;
  22796. $y0 = $y;
  22797. }
  22798. $xmin = min($xmin, $x);
  22799. $ymin = min($ymin, $y);
  22800. $xmax = max($xmax, $x);
  22801. $ymax = max($ymax, $y);
  22802. if ($relcoord) {
  22803. $xoffset = $x;
  22804. $yoffset = $y;
  22805. }
  22806. }
  22807. }
  22808. break;
  22809. }
  22810. case 'L': { // lineto
  22811. foreach ($params as $ck => $cp) {
  22812. if (($ck % 2) == 0) {
  22813. $x = $cp + $xoffset;
  22814. } else {
  22815. $y = $cp + $yoffset;
  22816. if ((abs($x0 - $x) >= $minlen) OR (abs($y0 - $y) >= $minlen)) {
  22817. $this->_outLine($x, $y);
  22818. $x0 = $x;
  22819. $y0 = $y;
  22820. }
  22821. $xmin = min($xmin, $x);
  22822. $ymin = min($ymin, $y);
  22823. $xmax = max($xmax, $x);
  22824. $ymax = max($ymax, $y);
  22825. if ($relcoord) {
  22826. $xoffset = $x;
  22827. $yoffset = $y;
  22828. }
  22829. }
  22830. }
  22831. break;
  22832. }
  22833. case 'H': { // horizontal lineto
  22834. foreach ($params as $ck => $cp) {
  22835. $x = $cp + $xoffset;
  22836. if ((abs($x0 - $x) >= $minlen) OR (abs($y0 - $y) >= $minlen)) {
  22837. $this->_outLine($x, $y);
  22838. $x0 = $x;
  22839. $y0 = $y;
  22840. }
  22841. $xmin = min($xmin, $x);
  22842. $xmax = max($xmax, $x);
  22843. if ($relcoord) {
  22844. $xoffset = $x;
  22845. }
  22846. }
  22847. break;
  22848. }
  22849. case 'V': { // vertical lineto
  22850. foreach ($params as $ck => $cp) {
  22851. $y = $cp + $yoffset;
  22852. if ((abs($x0 - $x) >= $minlen) OR (abs($y0 - $y) >= $minlen)) {
  22853. $this->_outLine($x, $y);
  22854. $x0 = $x;
  22855. $y0 = $y;
  22856. }
  22857. $ymin = min($ymin, $y);
  22858. $ymax = max($ymax, $y);
  22859. if ($relcoord) {
  22860. $yoffset = $y;
  22861. }
  22862. }
  22863. break;
  22864. }
  22865. case 'C': { // curveto
  22866. foreach ($params as $ck => $cp) {
  22867. $params[$ck] = $cp;
  22868. if ((($ck + 1) % 6) == 0) {
  22869. $x1 = $params[($ck - 5)] + $xoffset;
  22870. $y1 = $params[($ck - 4)] + $yoffset;
  22871. $x2 = $params[($ck - 3)] + $xoffset;
  22872. $y2 = $params[($ck - 2)] + $yoffset;
  22873. $x = $params[($ck - 1)] + $xoffset;
  22874. $y = $params[($ck)] + $yoffset;
  22875. $this->_outCurve($x1, $y1, $x2, $y2, $x, $y);
  22876. $xmin = min($xmin, $x, $x1, $x2);
  22877. $ymin = min($ymin, $y, $y1, $y2);
  22878. $xmax = max($xmax, $x, $x1, $x2);
  22879. $ymax = max($ymax, $y, $y1, $y2);
  22880. if ($relcoord) {
  22881. $xoffset = $x;
  22882. $yoffset = $y;
  22883. }
  22884. }
  22885. }
  22886. break;
  22887. }
  22888. case 'S': { // shorthand/smooth curveto
  22889. foreach ($params as $ck => $cp) {
  22890. $params[$ck] = $cp;
  22891. if ((($ck + 1) % 4) == 0) {
  22892. if (($key > 0) AND ((strtoupper($paths[($key - 1)][1]) == 'C') OR (strtoupper($paths[($key - 1)][1]) == 'S'))) {
  22893. $x1 = (2 * $x) - $x2;
  22894. $y1 = (2 * $y) - $y2;
  22895. } else {
  22896. $x1 = $x;
  22897. $y1 = $y;
  22898. }
  22899. $x2 = $params[($ck - 3)] + $xoffset;
  22900. $y2 = $params[($ck - 2)] + $yoffset;
  22901. $x = $params[($ck - 1)] + $xoffset;
  22902. $y = $params[($ck)] + $yoffset;
  22903. $this->_outCurve($x1, $y1, $x2, $y2, $x, $y);
  22904. $xmin = min($xmin, $x, $x1, $x2);
  22905. $ymin = min($ymin, $y, $y1, $y2);
  22906. $xmax = max($xmax, $x, $x1, $x2);
  22907. $ymax = max($ymax, $y, $y1, $y2);
  22908. if ($relcoord) {
  22909. $xoffset = $x;
  22910. $yoffset = $y;
  22911. }
  22912. }
  22913. }
  22914. break;
  22915. }
  22916. case 'Q': { // quadratic Bezier curveto
  22917. foreach ($params as $ck => $cp) {
  22918. $params[$ck] = $cp;
  22919. if ((($ck + 1) % 4) == 0) {
  22920. // convert quadratic points to cubic points
  22921. $x1 = $params[($ck - 3)] + $xoffset;
  22922. $y1 = $params[($ck - 2)] + $yoffset;
  22923. $xa = ($x + (2 * $x1)) / 3;
  22924. $ya = ($y + (2 * $y1)) / 3;
  22925. $x = $params[($ck - 1)] + $xoffset;
  22926. $y = $params[($ck)] + $yoffset;
  22927. $xb = ($x + (2 * $x1)) / 3;
  22928. $yb = ($y + (2 * $y1)) / 3;
  22929. $this->_outCurve($xa, $ya, $xb, $yb, $x, $y);
  22930. $xmin = min($xmin, $x, $xa, $xb);
  22931. $ymin = min($ymin, $y, $ya, $yb);
  22932. $xmax = max($xmax, $x, $xa, $xb);
  22933. $ymax = max($ymax, $y, $ya, $yb);
  22934. if ($relcoord) {
  22935. $xoffset = $x;
  22936. $yoffset = $y;
  22937. }
  22938. }
  22939. }
  22940. break;
  22941. }
  22942. case 'T': { // shorthand/smooth quadratic Bezier curveto
  22943. foreach ($params as $ck => $cp) {
  22944. $params[$ck] = $cp;
  22945. if (($ck % 2) != 0) {
  22946. if (($key > 0) AND ((strtoupper($paths[($key - 1)][1]) == 'Q') OR (strtoupper($paths[($key - 1)][1]) == 'T'))) {
  22947. $x1 = (2 * $x) - $x1;
  22948. $y1 = (2 * $y) - $y1;
  22949. } else {
  22950. $x1 = $x;
  22951. $y1 = $y;
  22952. }
  22953. // convert quadratic points to cubic points
  22954. $xa = ($x + (2 * $x1)) / 3;
  22955. $ya = ($y + (2 * $y1)) / 3;
  22956. $x = $params[($ck - 1)] + $xoffset;
  22957. $y = $params[($ck)] + $yoffset;
  22958. $xb = ($x + (2 * $x1)) / 3;
  22959. $yb = ($y + (2 * $y1)) / 3;
  22960. $this->_outCurve($xa, $ya, $xb, $yb, $x, $y);
  22961. $xmin = min($xmin, $x, $xa, $xb);
  22962. $ymin = min($ymin, $y, $ya, $yb);
  22963. $xmax = max($xmax, $x, $xa, $xb);
  22964. $ymax = max($ymax, $y, $ya, $yb);
  22965. if ($relcoord) {
  22966. $xoffset = $x;
  22967. $yoffset = $y;
  22968. }
  22969. }
  22970. }
  22971. break;
  22972. }
  22973. case 'A': { // elliptical arc
  22974. foreach ($params as $ck => $cp) {
  22975. $params[$ck] = $cp;
  22976. if ((($ck + 1) % 7) == 0) {
  22977. $x0 = $x;
  22978. $y0 = $y;
  22979. $rx = abs($params[($ck - 6)]);
  22980. $ry = abs($params[($ck - 5)]);
  22981. $ang = -$rawparams[($ck - 4)];
  22982. $angle = deg2rad($ang);
  22983. $fa = $rawparams[($ck - 3)]; // large-arc-flag
  22984. $fs = $rawparams[($ck - 2)]; // sweep-flag
  22985. $x = $params[($ck - 1)] + $xoffset;
  22986. $y = $params[$ck] + $yoffset;
  22987. if ((abs($x0 - $x) < $minlen) AND (abs($y0 - $y) < $minlen)) {
  22988. // endpoints are almost identical
  22989. $xmin = min($xmin, $x);
  22990. $ymin = min($ymin, $y);
  22991. $xmax = max($xmax, $x);
  22992. $ymax = max($ymax, $y);
  22993. } else {
  22994. $cos_ang = cos($angle);
  22995. $sin_ang = sin($angle);
  22996. $a = (($x0 - $x) / 2);
  22997. $b = (($y0 - $y) / 2);
  22998. $xa = ($a * $cos_ang) - ($b * $sin_ang);
  22999. $ya = ($a * $sin_ang) + ($b * $cos_ang);
  23000. $rx2 = $rx * $rx;
  23001. $ry2 = $ry * $ry;
  23002. $xa2 = $xa * $xa;
  23003. $ya2 = $ya * $ya;
  23004. $delta = ($xa2 / $rx2) + ($ya2 / $ry2);
  23005. if ($delta > 1) {
  23006. $rx *= sqrt($delta);
  23007. $ry *= sqrt($delta);
  23008. $rx2 = $rx * $rx;
  23009. $ry2 = $ry * $ry;
  23010. }
  23011. $numerator = (($rx2 * $ry2) - ($rx2 * $ya2) - ($ry2 * $xa2));
  23012. if ($numerator < 0) {
  23013. $root = 0;
  23014. } else {
  23015. $root = sqrt($numerator / (($rx2 * $ya2) + ($ry2 * $xa2)));
  23016. }
  23017. if ($fa == $fs){
  23018. $root *= -1;
  23019. }
  23020. $cax = $root * (($rx * $ya) / $ry);
  23021. $cay = -$root * (($ry * $xa) / $rx);
  23022. // coordinates of ellipse center
  23023. $cx = ($cax * $cos_ang) - ($cay * $sin_ang) + (($x0 + $x) / 2);
  23024. $cy = ($cax * $sin_ang) + ($cay * $cos_ang) + (($y0 + $y) / 2);
  23025. // get angles
  23026. $angs = TCPDF_STATIC::getVectorsAngle(1, 0, (($xa - $cax) / $rx), (($cay - $ya) / $ry));
  23027. $dang = TCPDF_STATIC::getVectorsAngle((($xa - $cax) / $rx), (($ya - $cay) / $ry), ((-$xa - $cax) / $rx), ((-$ya - $cay) / $ry));
  23028. if (($fs == 0) AND ($dang > 0)) {
  23029. $dang -= (2 * M_PI);
  23030. } elseif (($fs == 1) AND ($dang < 0)) {
  23031. $dang += (2 * M_PI);
  23032. }
  23033. $angf = $angs - $dang;
  23034. if ((($fs == 0) AND ($angs > $angf)) OR (($fs == 1) AND ($angs < $angf))) {
  23035. // reverse angles
  23036. $tmp = $angs;
  23037. $angs = $angf;
  23038. $angf = $tmp;
  23039. }
  23040. $angs = round(rad2deg($angs), 6);
  23041. $angf = round(rad2deg($angf), 6);
  23042. // covent angles to positive values
  23043. if (($angs < 0) AND ($angf < 0)) {
  23044. $angs += 360;
  23045. $angf += 360;
  23046. }
  23047. $pie = false;
  23048. if (($key == 0) AND (isset($paths[($key + 1)][1])) AND (trim($paths[($key + 1)][1]) == 'z')) {
  23049. $pie = true;
  23050. }
  23051. list($axmin, $aymin, $axmax, $aymax) = $this->_outellipticalarc($cx, $cy, $rx, $ry, $ang, $angs, $angf, $pie, 2, false, ($fs == 0), true);
  23052. $xmin = min($xmin, $x, $axmin);
  23053. $ymin = min($ymin, $y, $aymin);
  23054. $xmax = max($xmax, $x, $axmax);
  23055. $ymax = max($ymax, $y, $aymax);
  23056. }
  23057. if ($relcoord) {
  23058. $xoffset = $x;
  23059. $yoffset = $y;
  23060. }
  23061. }
  23062. }
  23063. break;
  23064. }
  23065. case 'Z': {
  23066. $this->_out('h');
  23067. break;
  23068. }
  23069. }
  23070. $firstcmd = false;
  23071. } // end foreach
  23072. if (!empty($op)) {
  23073. $this->_out($op);
  23074. }
  23075. return array($xmin, $ymin, ($xmax - $xmin), ($ymax - $ymin));
  23076. }
  23077. /**
  23078. * Return the tag name without the namespace
  23079. * @param $name (string) Tag name
  23080. * @protected
  23081. */
  23082. protected function removeTagNamespace($name) {
  23083. if(strpos($name, ':') !== false) {
  23084. $parts = explode(':', $name);
  23085. return $parts[(sizeof($parts) - 1)];
  23086. }
  23087. return $name;
  23088. }
  23089. /**
  23090. * Sets the opening SVG element handler function for the XML parser. (*** TO BE COMPLETED ***)
  23091. * @param $parser (resource) The first parameter, parser, is a reference to the XML parser calling the handler.
  23092. * @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.
  23093. * @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.
  23094. * @param $ctm (array) tranformation matrix for clipping mode (starting transformation matrix).
  23095. * @author Nicola Asuni
  23096. * @since 5.0.000 (2010-05-02)
  23097. * @protected
  23098. */
  23099. protected function startSVGElementHandler($parser, $name, $attribs, $ctm=array()) {
  23100. $name = $this->removeTagNamespace($name);
  23101. // check if we are in clip mode
  23102. if ($this->svgclipmode) {
  23103. $this->svgclippaths[$this->svgclipid][] = array('name' => $name, 'attribs' => $attribs, 'tm' => $this->svgcliptm[$this->svgclipid]);
  23104. return;
  23105. }
  23106. if ($this->svgdefsmode AND !in_array($name, array('clipPath', 'linearGradient', 'radialGradient', 'stop'))) {
  23107. if (isset($attribs['id'])) {
  23108. $attribs['child_elements'] = array();
  23109. $this->svgdefs[$attribs['id']] = array('name' => $name, 'attribs' => $attribs);
  23110. return;
  23111. }
  23112. if (end($this->svgdefs) !== FALSE) {
  23113. $last_svgdefs_id = key($this->svgdefs);
  23114. if (isset($this->svgdefs[$last_svgdefs_id]['attribs']['child_elements'])) {
  23115. $attribs['id'] = 'DF_'.(count($this->svgdefs[$last_svgdefs_id]['attribs']['child_elements']) + 1);
  23116. $this->svgdefs[$last_svgdefs_id]['attribs']['child_elements'][$attribs['id']] = array('name' => $name, 'attribs' => $attribs);
  23117. return;
  23118. }
  23119. }
  23120. return;
  23121. }
  23122. $clipping = false;
  23123. if ($parser == 'clip-path') {
  23124. // set clipping mode
  23125. $clipping = true;
  23126. }
  23127. // get styling properties
  23128. $prev_svgstyle = $this->svgstyles[max(0,(count($this->svgstyles) - 1))]; // previous style
  23129. $svgstyle = $this->svgstyles[0]; // set default style
  23130. if ($clipping AND !isset($attribs['fill']) AND (!isset($attribs['style']) OR (!preg_match('/[;\"\s]{1}fill[\s]*:[\s]*([^;\"]*)/si', $attribs['style'], $attrval)))) {
  23131. // default fill attribute for clipping
  23132. $attribs['fill'] = 'none';
  23133. }
  23134. if (isset($attribs['style']) AND !TCPDF_STATIC::empty_string($attribs['style']) AND ($attribs['style'][0] != ';')) {
  23135. // fix style for regular expression
  23136. $attribs['style'] = ';'.$attribs['style'];
  23137. }
  23138. foreach ($prev_svgstyle as $key => $val) {
  23139. if (in_array($key, TCPDF_IMAGES::$svginheritprop)) {
  23140. // inherit previous value
  23141. $svgstyle[$key] = $val;
  23142. }
  23143. if (isset($attribs[$key]) AND !TCPDF_STATIC::empty_string($attribs[$key])) {
  23144. // specific attribute settings
  23145. if ($attribs[$key] == 'inherit') {
  23146. $svgstyle[$key] = $val;
  23147. } else {
  23148. $svgstyle[$key] = $attribs[$key];
  23149. }
  23150. } elseif (isset($attribs['style']) AND !TCPDF_STATIC::empty_string($attribs['style'])) {
  23151. // CSS style syntax
  23152. $attrval = array();
  23153. if (preg_match('/[;\"\s]{1}'.$key.'[\s]*:[\s]*([^;\"]*)/si', $attribs['style'], $attrval) AND isset($attrval[1])) {
  23154. if ($attrval[1] == 'inherit') {
  23155. $svgstyle[$key] = $val;
  23156. } else {
  23157. $svgstyle[$key] = $attrval[1];
  23158. }
  23159. }
  23160. }
  23161. }
  23162. // transformation matrix
  23163. if (!empty($ctm)) {
  23164. $tm = $ctm;
  23165. } else {
  23166. $tm = array(1,0,0,1,0,0);
  23167. }
  23168. if (isset($attribs['transform']) AND !empty($attribs['transform'])) {
  23169. $tm = TCPDF_STATIC::getTransformationMatrixProduct($tm, TCPDF_STATIC::getSVGTransformMatrix($attribs['transform']));
  23170. }
  23171. $svgstyle['transfmatrix'] = $tm;
  23172. $invisible = false;
  23173. if (($svgstyle['visibility'] == 'hidden') OR ($svgstyle['visibility'] == 'collapse') OR ($svgstyle['display'] == 'none')) {
  23174. // the current graphics element is invisible (nothing is painted)
  23175. $invisible = true;
  23176. }
  23177. // process tag
  23178. switch($name) {
  23179. case 'defs': {
  23180. $this->svgdefsmode = true;
  23181. break;
  23182. }
  23183. // clipPath
  23184. case 'clipPath': {
  23185. if ($invisible) {
  23186. break;
  23187. }
  23188. $this->svgclipmode = true;
  23189. if (!isset($attribs['id'])) {
  23190. $attribs['id'] = 'CP_'.(count($this->svgcliptm) + 1);
  23191. }
  23192. $this->svgclipid = $attribs['id'];
  23193. $this->svgclippaths[$this->svgclipid] = array();
  23194. $this->svgcliptm[$this->svgclipid] = $tm;
  23195. break;
  23196. }
  23197. case 'svg': {
  23198. // start of SVG object
  23199. if(++$this->svg_tag_depth <= 1) {
  23200. break;
  23201. }
  23202. // inner SVG
  23203. array_push($this->svgstyles, $svgstyle);
  23204. $this->StartTransform();
  23205. $svgX = (isset($attribs['x'])?$attribs['x']:0);
  23206. $svgY = (isset($attribs['y'])?$attribs['y']:0);
  23207. $svgW = (isset($attribs['width'])?$attribs['width']:0);
  23208. $svgH = (isset($attribs['height'])?$attribs['height']:0);
  23209. // set x, y position using transform matrix
  23210. $tm = TCPDF_STATIC::getTransformationMatrixProduct($tm, array( 1, 0, 0, 1, $svgX, $svgY));
  23211. $this->SVGTransform($tm);
  23212. // set clipping for width and height
  23213. $x = 0;
  23214. $y = 0;
  23215. $w = (isset($attribs['width'])?$this->getHTMLUnitToUnits($attribs['width'], 0, $this->svgunit, false):$this->w);
  23216. $h = (isset($attribs['height'])?$this->getHTMLUnitToUnits($attribs['height'], 0, $this->svgunit, false):$this->h);
  23217. // draw clipping rect
  23218. $this->Rect($x, $y, $w, $h, 'CNZ', array(), array());
  23219. // parse viewbox, calculate extra transformation matrix
  23220. if (isset($attribs['viewBox'])) {
  23221. $tmp = array();
  23222. preg_match_all("/[0-9]+/", $attribs['viewBox'], $tmp);
  23223. $tmp = $tmp[0];
  23224. if (sizeof($tmp) == 4) {
  23225. $vx = $tmp[0];
  23226. $vy = $tmp[1];
  23227. $vw = $tmp[2];
  23228. $vh = $tmp[3];
  23229. // get aspect ratio
  23230. $tmp = array();
  23231. $aspectX = 'xMid';
  23232. $aspectY = 'YMid';
  23233. $fit = 'meet';
  23234. if (isset($attribs['preserveAspectRatio'])) {
  23235. if($attribs['preserveAspectRatio'] == 'none') {
  23236. $fit = 'none';
  23237. } else {
  23238. preg_match_all('/[a-zA-Z]+/', $attribs['preserveAspectRatio'], $tmp);
  23239. $tmp = $tmp[0];
  23240. if ((sizeof($tmp) == 2) AND (strlen($tmp[0]) == 8) AND (in_array($tmp[1], array('meet', 'slice', 'none')))) {
  23241. $aspectX = substr($tmp[0], 0, 4);
  23242. $aspectY = substr($tmp[0], 4, 4);
  23243. $fit = $tmp[1];
  23244. }
  23245. }
  23246. }
  23247. $wr = ($svgW / $vw);
  23248. $hr = ($svgH / $vh);
  23249. $ax = $ay = 0;
  23250. if ((($fit == 'meet') AND ($hr < $wr)) OR (($fit == 'slice') AND ($hr > $wr))) {
  23251. if ($aspectX == 'xMax') {
  23252. $ax = (($vw * ($wr / $hr)) - $vw);
  23253. }
  23254. if ($aspectX == 'xMid') {
  23255. $ax = ((($vw * ($wr / $hr)) - $vw) / 2);
  23256. }
  23257. $wr = $hr;
  23258. } elseif ((($fit == 'meet') AND ($hr > $wr)) OR (($fit == 'slice') AND ($hr < $wr))) {
  23259. if ($aspectY == 'YMax') {
  23260. $ay = (($vh * ($hr / $wr)) - $vh);
  23261. }
  23262. if ($aspectY == 'YMid') {
  23263. $ay = ((($vh * ($hr / $wr)) - $vh) / 2);
  23264. }
  23265. $hr = $wr;
  23266. }
  23267. $newtm = array($wr, 0, 0, $hr, (($wr * ($ax - $vx)) - $svgX), (($hr * ($ay - $vy)) - $svgY));
  23268. $tm = TCPDF_STATIC::getTransformationMatrixProduct($tm, $newtm);
  23269. $this->SVGTransform($tm);
  23270. }
  23271. }
  23272. $this->setSVGStyles($svgstyle, $prev_svgstyle);
  23273. break;
  23274. }
  23275. case 'g': {
  23276. // group together related graphics elements
  23277. array_push($this->svgstyles, $svgstyle);
  23278. $this->StartTransform();
  23279. $x = (isset($attribs['x'])?$attribs['x']:0);
  23280. $y = (isset($attribs['y'])?$attribs['y']:0);
  23281. $w = 1;//(isset($attribs['width'])?$attribs['width']:1);
  23282. $h = 1;//(isset($attribs['height'])?$attribs['height']:1);
  23283. $tm = TCPDF_STATIC::getTransformationMatrixProduct($tm, array($w, 0, 0, $h, $x, $y));
  23284. $this->SVGTransform($tm);
  23285. $this->setSVGStyles($svgstyle, $prev_svgstyle);
  23286. break;
  23287. }
  23288. case 'linearGradient': {
  23289. if ($this->pdfa_mode) {
  23290. break;
  23291. }
  23292. if (!isset($attribs['id'])) {
  23293. $attribs['id'] = 'GR_'.(count($this->svggradients) + 1);
  23294. }
  23295. $this->svggradientid = $attribs['id'];
  23296. $this->svggradients[$this->svggradientid] = array();
  23297. $this->svggradients[$this->svggradientid]['type'] = 2;
  23298. $this->svggradients[$this->svggradientid]['stops'] = array();
  23299. if (isset($attribs['gradientUnits'])) {
  23300. $this->svggradients[$this->svggradientid]['gradientUnits'] = $attribs['gradientUnits'];
  23301. } else {
  23302. $this->svggradients[$this->svggradientid]['gradientUnits'] = 'objectBoundingBox';
  23303. }
  23304. //$attribs['spreadMethod']
  23305. if (((!isset($attribs['x1'])) AND (!isset($attribs['y1'])) AND (!isset($attribs['x2'])) AND (!isset($attribs['y2'])))
  23306. OR ((isset($attribs['x1']) AND (substr($attribs['x1'], -1) == '%'))
  23307. OR (isset($attribs['y1']) AND (substr($attribs['y1'], -1) == '%'))
  23308. OR (isset($attribs['x2']) AND (substr($attribs['x2'], -1) == '%'))
  23309. OR (isset($attribs['y2']) AND (substr($attribs['y2'], -1) == '%')))) {
  23310. $this->svggradients[$this->svggradientid]['mode'] = 'percentage';
  23311. } else {
  23312. $this->svggradients[$this->svggradientid]['mode'] = 'measure';
  23313. }
  23314. $x1 = (isset($attribs['x1'])?$attribs['x1']:'0');
  23315. $y1 = (isset($attribs['y1'])?$attribs['y1']:'0');
  23316. $x2 = (isset($attribs['x2'])?$attribs['x2']:'100');
  23317. $y2 = (isset($attribs['y2'])?$attribs['y2']:'0');
  23318. if (isset($attribs['gradientTransform'])) {
  23319. $this->svggradients[$this->svggradientid]['gradientTransform'] = TCPDF_STATIC::getSVGTransformMatrix($attribs['gradientTransform']);
  23320. }
  23321. $this->svggradients[$this->svggradientid]['coords'] = array($x1, $y1, $x2, $y2);
  23322. if (isset($attribs['xlink:href']) AND !empty($attribs['xlink:href'])) {
  23323. // gradient is defined on another place
  23324. $this->svggradients[$this->svggradientid]['xref'] = substr($attribs['xlink:href'], 1);
  23325. }
  23326. break;
  23327. }
  23328. case 'radialGradient': {
  23329. if ($this->pdfa_mode) {
  23330. break;
  23331. }
  23332. if (!isset($attribs['id'])) {
  23333. $attribs['id'] = 'GR_'.(count($this->svggradients) + 1);
  23334. }
  23335. $this->svggradientid = $attribs['id'];
  23336. $this->svggradients[$this->svggradientid] = array();
  23337. $this->svggradients[$this->svggradientid]['type'] = 3;
  23338. $this->svggradients[$this->svggradientid]['stops'] = array();
  23339. if (isset($attribs['gradientUnits'])) {
  23340. $this->svggradients[$this->svggradientid]['gradientUnits'] = $attribs['gradientUnits'];
  23341. } else {
  23342. $this->svggradients[$this->svggradientid]['gradientUnits'] = 'objectBoundingBox';
  23343. }
  23344. //$attribs['spreadMethod']
  23345. if (((!isset($attribs['cx'])) AND (!isset($attribs['cy'])))
  23346. OR ((isset($attribs['cx']) AND (substr($attribs['cx'], -1) == '%'))
  23347. OR (isset($attribs['cy']) AND (substr($attribs['cy'], -1) == '%')))) {
  23348. $this->svggradients[$this->svggradientid]['mode'] = 'percentage';
  23349. } elseif (isset($attribs['r']) AND is_numeric($attribs['r']) AND ($attribs['r']) <= 1) {
  23350. $this->svggradients[$this->svggradientid]['mode'] = 'ratio';
  23351. } else {
  23352. $this->svggradients[$this->svggradientid]['mode'] = 'measure';
  23353. }
  23354. $cx = (isset($attribs['cx']) ? $attribs['cx'] : 0.5);
  23355. $cy = (isset($attribs['cy']) ? $attribs['cy'] : 0.5);
  23356. $fx = (isset($attribs['fx']) ? $attribs['fx'] : $cx);
  23357. $fy = (isset($attribs['fy']) ? $attribs['fy'] : $cy);
  23358. $r = (isset($attribs['r']) ? $attribs['r'] : 0.5);
  23359. if (isset($attribs['gradientTransform'])) {
  23360. $this->svggradients[$this->svggradientid]['gradientTransform'] = TCPDF_STATIC::getSVGTransformMatrix($attribs['gradientTransform']);
  23361. }
  23362. $this->svggradients[$this->svggradientid]['coords'] = array($cx, $cy, $fx, $fy, $r);
  23363. if (isset($attribs['xlink:href']) AND !empty($attribs['xlink:href'])) {
  23364. // gradient is defined on another place
  23365. $this->svggradients[$this->svggradientid]['xref'] = substr($attribs['xlink:href'], 1);
  23366. }
  23367. break;
  23368. }
  23369. case 'stop': {
  23370. // gradient stops
  23371. if (substr($attribs['offset'], -1) == '%') {
  23372. $offset = floatval(substr($attribs['offset'], 0, -1)) / 100;
  23373. } else {
  23374. $offset = floatval($attribs['offset']);
  23375. if ($offset > 1) {
  23376. $offset /= 100;
  23377. }
  23378. }
  23379. $stop_color = isset($svgstyle['stop-color'])?TCPDF_COLORS::convertHTMLColorToDec($svgstyle['stop-color'], $this->spot_colors):'black';
  23380. $opacity = isset($svgstyle['stop-opacity'])?$svgstyle['stop-opacity']:1;
  23381. $this->svggradients[$this->svggradientid]['stops'][] = array('offset' => $offset, 'color' => $stop_color, 'opacity' => $opacity);
  23382. break;
  23383. }
  23384. // paths
  23385. case 'path': {
  23386. if ($invisible) {
  23387. break;
  23388. }
  23389. if (isset($attribs['d'])) {
  23390. $d = trim($attribs['d']);
  23391. if (!empty($d)) {
  23392. $x = (isset($attribs['x'])?$attribs['x']:0);
  23393. $y = (isset($attribs['y'])?$attribs['y']:0);
  23394. $w = (isset($attribs['width'])?$attribs['width']:1);
  23395. $h = (isset($attribs['height'])?$attribs['height']:1);
  23396. $tm = TCPDF_STATIC::getTransformationMatrixProduct($tm, array($w, 0, 0, $h, $x, $y));
  23397. if ($clipping) {
  23398. $this->SVGTransform($tm);
  23399. $this->SVGPath($d, 'CNZ');
  23400. } else {
  23401. $this->StartTransform();
  23402. $this->SVGTransform($tm);
  23403. $obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h, 'SVGPath', array($d, 'CNZ'));
  23404. if (!empty($obstyle)) {
  23405. $this->SVGPath($d, $obstyle);
  23406. }
  23407. $this->StopTransform();
  23408. }
  23409. }
  23410. }
  23411. break;
  23412. }
  23413. // shapes
  23414. case 'rect': {
  23415. if ($invisible) {
  23416. break;
  23417. }
  23418. $x = (isset($attribs['x'])?$this->getHTMLUnitToUnits($attribs['x'], 0, $this->svgunit, false):0);
  23419. $y = (isset($attribs['y'])?$this->getHTMLUnitToUnits($attribs['y'], 0, $this->svgunit, false):0);
  23420. $w = (isset($attribs['width'])?$this->getHTMLUnitToUnits($attribs['width'], 0, $this->svgunit, false):0);
  23421. $h = (isset($attribs['height'])?$this->getHTMLUnitToUnits($attribs['height'], 0, $this->svgunit, false):0);
  23422. $rx = (isset($attribs['rx'])?$this->getHTMLUnitToUnits($attribs['rx'], 0, $this->svgunit, false):0);
  23423. $ry = (isset($attribs['ry'])?$this->getHTMLUnitToUnits($attribs['ry'], 0, $this->svgunit, false):$rx);
  23424. if ($clipping) {
  23425. $this->SVGTransform($tm);
  23426. $this->RoundedRectXY($x, $y, $w, $h, $rx, $ry, '1111', 'CNZ', array(), array());
  23427. } else {
  23428. $this->StartTransform();
  23429. $this->SVGTransform($tm);
  23430. $obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h, 'RoundedRectXY', array($x, $y, $w, $h, $rx, $ry, '1111', 'CNZ'));
  23431. if (!empty($obstyle)) {
  23432. $this->RoundedRectXY($x, $y, $w, $h, $rx, $ry, '1111', $obstyle, array(), array());
  23433. }
  23434. $this->StopTransform();
  23435. }
  23436. break;
  23437. }
  23438. case 'circle': {
  23439. if ($invisible) {
  23440. break;
  23441. }
  23442. $r = (isset($attribs['r']) ? $this->getHTMLUnitToUnits($attribs['r'], 0, $this->svgunit, false) : 0);
  23443. $cx = (isset($attribs['cx']) ? $this->getHTMLUnitToUnits($attribs['cx'], 0, $this->svgunit, false) : (isset($attribs['x']) ? $this->getHTMLUnitToUnits($attribs['x'], 0, $this->svgunit, false) : 0));
  23444. $cy = (isset($attribs['cy']) ? $this->getHTMLUnitToUnits($attribs['cy'], 0, $this->svgunit, false) : (isset($attribs['y']) ? $this->getHTMLUnitToUnits($attribs['y'], 0, $this->svgunit, false) : 0));
  23445. $x = ($cx - $r);
  23446. $y = ($cy - $r);
  23447. $w = (2 * $r);
  23448. $h = $w;
  23449. if ($clipping) {
  23450. $this->SVGTransform($tm);
  23451. $this->Circle($cx, $cy, $r, 0, 360, 'CNZ', array(), array(), 8);
  23452. } else {
  23453. $this->StartTransform();
  23454. $this->SVGTransform($tm);
  23455. $obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h, 'Circle', array($cx, $cy, $r, 0, 360, 'CNZ'));
  23456. if (!empty($obstyle)) {
  23457. $this->Circle($cx, $cy, $r, 0, 360, $obstyle, array(), array(), 8);
  23458. }
  23459. $this->StopTransform();
  23460. }
  23461. break;
  23462. }
  23463. case 'ellipse': {
  23464. if ($invisible) {
  23465. break;
  23466. }
  23467. $rx = (isset($attribs['rx']) ? $this->getHTMLUnitToUnits($attribs['rx'], 0, $this->svgunit, false) : 0);
  23468. $ry = (isset($attribs['ry']) ? $this->getHTMLUnitToUnits($attribs['ry'], 0, $this->svgunit, false) : 0);
  23469. $cx = (isset($attribs['cx']) ? $this->getHTMLUnitToUnits($attribs['cx'], 0, $this->svgunit, false) : (isset($attribs['x']) ? $this->getHTMLUnitToUnits($attribs['x'], 0, $this->svgunit, false) : 0));
  23470. $cy = (isset($attribs['cy']) ? $this->getHTMLUnitToUnits($attribs['cy'], 0, $this->svgunit, false) : (isset($attribs['y']) ? $this->getHTMLUnitToUnits($attribs['y'], 0, $this->svgunit, false) : 0));
  23471. $x = ($cx - $rx);
  23472. $y = ($cy - $ry);
  23473. $w = (2 * $rx);
  23474. $h = (2 * $ry);
  23475. if ($clipping) {
  23476. $this->SVGTransform($tm);
  23477. $this->Ellipse($cx, $cy, $rx, $ry, 0, 0, 360, 'CNZ', array(), array(), 8);
  23478. } else {
  23479. $this->StartTransform();
  23480. $this->SVGTransform($tm);
  23481. $obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h, 'Ellipse', array($cx, $cy, $rx, $ry, 0, 0, 360, 'CNZ'));
  23482. if (!empty($obstyle)) {
  23483. $this->Ellipse($cx, $cy, $rx, $ry, 0, 0, 360, $obstyle, array(), array(), 8);
  23484. }
  23485. $this->StopTransform();
  23486. }
  23487. break;
  23488. }
  23489. case 'line': {
  23490. if ($invisible) {
  23491. break;
  23492. }
  23493. $x1 = (isset($attribs['x1'])?$this->getHTMLUnitToUnits($attribs['x1'], 0, $this->svgunit, false):0);
  23494. $y1 = (isset($attribs['y1'])?$this->getHTMLUnitToUnits($attribs['y1'], 0, $this->svgunit, false):0);
  23495. $x2 = (isset($attribs['x2'])?$this->getHTMLUnitToUnits($attribs['x2'], 0, $this->svgunit, false):0);
  23496. $y2 = (isset($attribs['y2'])?$this->getHTMLUnitToUnits($attribs['y2'], 0, $this->svgunit, false):0);
  23497. $x = $x1;
  23498. $y = $y1;
  23499. $w = abs($x2 - $x1);
  23500. $h = abs($y2 - $y1);
  23501. if (!$clipping) {
  23502. $this->StartTransform();
  23503. $this->SVGTransform($tm);
  23504. $obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h, 'Line', array($x1, $y1, $x2, $y2));
  23505. $this->Line($x1, $y1, $x2, $y2);
  23506. $this->StopTransform();
  23507. }
  23508. break;
  23509. }
  23510. case 'polyline':
  23511. case 'polygon': {
  23512. if ($invisible) {
  23513. break;
  23514. }
  23515. $points = (isset($attribs['points'])?$attribs['points']:'0 0');
  23516. $points = trim($points);
  23517. // note that point may use a complex syntax not covered here
  23518. $points = preg_split('/[\,\s]+/si', $points);
  23519. if (count($points) < 4) {
  23520. break;
  23521. }
  23522. $p = array();
  23523. $xmin = 2147483647;
  23524. $xmax = 0;
  23525. $ymin = 2147483647;
  23526. $ymax = 0;
  23527. foreach ($points as $key => $val) {
  23528. $p[$key] = $this->getHTMLUnitToUnits($val, 0, $this->svgunit, false);
  23529. if (($key % 2) == 0) {
  23530. // X coordinate
  23531. $xmin = min($xmin, $p[$key]);
  23532. $xmax = max($xmax, $p[$key]);
  23533. } else {
  23534. // Y coordinate
  23535. $ymin = min($ymin, $p[$key]);
  23536. $ymax = max($ymax, $p[$key]);
  23537. }
  23538. }
  23539. $x = $xmin;
  23540. $y = $ymin;
  23541. $w = ($xmax - $xmin);
  23542. $h = ($ymax - $ymin);
  23543. if ($name == 'polyline') {
  23544. $this->StartTransform();
  23545. $this->SVGTransform($tm);
  23546. $obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h, 'PolyLine', array($p, 'CNZ'));
  23547. if (!empty($obstyle)) {
  23548. $this->PolyLine($p, $obstyle, array(), array());
  23549. }
  23550. $this->StopTransform();
  23551. } else { // polygon
  23552. if ($clipping) {
  23553. $this->SVGTransform($tm);
  23554. $this->Polygon($p, 'CNZ', array(), array(), true);
  23555. } else {
  23556. $this->StartTransform();
  23557. $this->SVGTransform($tm);
  23558. $obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h, 'Polygon', array($p, 'CNZ'));
  23559. if (!empty($obstyle)) {
  23560. $this->Polygon($p, $obstyle, array(), array(), true);
  23561. }
  23562. $this->StopTransform();
  23563. }
  23564. }
  23565. break;
  23566. }
  23567. // image
  23568. case 'image': {
  23569. if ($invisible) {
  23570. break;
  23571. }
  23572. if (!isset($attribs['xlink:href']) OR empty($attribs['xlink:href'])) {
  23573. break;
  23574. }
  23575. $x = (isset($attribs['x'])?$this->getHTMLUnitToUnits($attribs['x'], 0, $this->svgunit, false):0);
  23576. $y = (isset($attribs['y'])?$this->getHTMLUnitToUnits($attribs['y'], 0, $this->svgunit, false):0);
  23577. $w = (isset($attribs['width'])?$this->getHTMLUnitToUnits($attribs['width'], 0, $this->svgunit, false):0);
  23578. $h = (isset($attribs['height'])?$this->getHTMLUnitToUnits($attribs['height'], 0, $this->svgunit, false):0);
  23579. $img = $attribs['xlink:href'];
  23580. if (!$clipping) {
  23581. $this->StartTransform();
  23582. $this->SVGTransform($tm);
  23583. $obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h);
  23584. if (preg_match('/^data:image\/[^;]+;base64,/', $img, $m) > 0) {
  23585. // embedded image encoded as base64
  23586. $img = '@'.base64_decode(substr($img, strlen($m[0])));
  23587. } else {
  23588. // fix image path
  23589. if (!TCPDF_STATIC::empty_string($this->svgdir) AND (($img[0] == '.') OR (basename($img) == $img))) {
  23590. // replace relative path with full server path
  23591. $img = $this->svgdir.'/'.$img;
  23592. }
  23593. if (($img[0] == '/') AND !empty($_SERVER['DOCUMENT_ROOT']) AND ($_SERVER['DOCUMENT_ROOT'] != '/')) {
  23594. $findroot = strpos($img, $_SERVER['DOCUMENT_ROOT']);
  23595. if (($findroot === false) OR ($findroot > 1)) {
  23596. if (substr($_SERVER['DOCUMENT_ROOT'], -1) == '/') {
  23597. $img = substr($_SERVER['DOCUMENT_ROOT'], 0, -1).$img;
  23598. } else {
  23599. $img = $_SERVER['DOCUMENT_ROOT'].$img;
  23600. }
  23601. }
  23602. }
  23603. $img = urldecode($img);
  23604. $testscrtype = @parse_url($img);
  23605. if (empty($testscrtype['query'])) {
  23606. // convert URL to server path
  23607. $img = str_replace(K_PATH_URL, K_PATH_MAIN, $img);
  23608. } elseif (preg_match('|^https?://|', $img) !== 1) {
  23609. // convert server path to URL
  23610. $img = str_replace(K_PATH_MAIN, K_PATH_URL, $img);
  23611. }
  23612. }
  23613. // get image type
  23614. $imgtype = TCPDF_IMAGES::getImageFileType($img);
  23615. if (($imgtype == 'eps') OR ($imgtype == 'ai')) {
  23616. $this->ImageEps($img, $x, $y, $w, $h);
  23617. } elseif ($imgtype == 'svg') {
  23618. // store SVG vars
  23619. $svggradients = $this->svggradients;
  23620. $svggradientid = $this->svggradientid;
  23621. $svgdefsmode = $this->svgdefsmode;
  23622. $svgdefs = $this->svgdefs;
  23623. $svgclipmode = $this->svgclipmode;
  23624. $svgclippaths = $this->svgclippaths;
  23625. $svgcliptm = $this->svgcliptm;
  23626. $svgclipid = $this->svgclipid;
  23627. $svgtext = $this->svgtext;
  23628. $svgtextmode = $this->svgtextmode;
  23629. $this->ImageSVG($img, $x, $y, $w, $h);
  23630. // restore SVG vars
  23631. $this->svggradients = $svggradients;
  23632. $this->svggradientid = $svggradientid;
  23633. $this->svgdefsmode = $svgdefsmode;
  23634. $this->svgdefs = $svgdefs;
  23635. $this->svgclipmode = $svgclipmode;
  23636. $this->svgclippaths = $svgclippaths;
  23637. $this->svgcliptm = $svgcliptm;
  23638. $this->svgclipid = $svgclipid;
  23639. $this->svgtext = $svgtext;
  23640. $this->svgtextmode = $svgtextmode;
  23641. } else {
  23642. $this->Image($img, $x, $y, $w, $h);
  23643. }
  23644. $this->StopTransform();
  23645. }
  23646. break;
  23647. }
  23648. // text
  23649. case 'text':
  23650. case 'tspan': {
  23651. if (isset($this->svgtextmode['text-anchor']) AND !empty($this->svgtext)) {
  23652. // @TODO: unsupported feature
  23653. }
  23654. // only basic support - advanced features must be implemented
  23655. $this->svgtextmode['invisible'] = $invisible;
  23656. if ($invisible) {
  23657. break;
  23658. }
  23659. array_push($this->svgstyles, $svgstyle);
  23660. if (isset($attribs['x'])) {
  23661. $x = $this->getHTMLUnitToUnits($attribs['x'], 0, $this->svgunit, false);
  23662. } elseif ($name == 'tspan') {
  23663. $x = $this->x;
  23664. } else {
  23665. $x = 0;
  23666. }
  23667. if (isset($attribs['dx'])) {
  23668. $x += $this->getHTMLUnitToUnits($attribs['dx'], 0, $this->svgunit, false);
  23669. }
  23670. if (isset($attribs['y'])) {
  23671. $y = $this->getHTMLUnitToUnits($attribs['y'], 0, $this->svgunit, false);
  23672. } elseif ($name == 'tspan') {
  23673. $y = $this->y;
  23674. } else {
  23675. $y = 0;
  23676. }
  23677. if (isset($attribs['dy'])) {
  23678. $y += $this->getHTMLUnitToUnits($attribs['dy'], 0, $this->svgunit, false);
  23679. }
  23680. $svgstyle['text-color'] = $svgstyle['fill'];
  23681. $this->svgtext = '';
  23682. if (isset($svgstyle['text-anchor'])) {
  23683. $this->svgtextmode['text-anchor'] = $svgstyle['text-anchor'];
  23684. } else {
  23685. $this->svgtextmode['text-anchor'] = 'start';
  23686. }
  23687. if (isset($svgstyle['direction'])) {
  23688. if ($svgstyle['direction'] == 'rtl') {
  23689. $this->svgtextmode['rtl'] = true;
  23690. } else {
  23691. $this->svgtextmode['rtl'] = false;
  23692. }
  23693. } else {
  23694. $this->svgtextmode['rtl'] = false;
  23695. }
  23696. if (isset($svgstyle['stroke']) AND ($svgstyle['stroke'] != 'none') AND isset($svgstyle['stroke-width']) AND ($svgstyle['stroke-width'] > 0)) {
  23697. $this->svgtextmode['stroke'] = $this->getHTMLUnitToUnits($svgstyle['stroke-width'], 0, $this->svgunit, false);
  23698. } else {
  23699. $this->svgtextmode['stroke'] = false;
  23700. }
  23701. $this->StartTransform();
  23702. $this->SVGTransform($tm);
  23703. $obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, 1, 1);
  23704. $this->x = $x;
  23705. $this->y = $y;
  23706. break;
  23707. }
  23708. // use
  23709. case 'use': {
  23710. if (isset($attribs['xlink:href']) AND !empty($attribs['xlink:href'])) {
  23711. $svgdefid = substr($attribs['xlink:href'], 1);
  23712. if (isset($this->svgdefs[$svgdefid])) {
  23713. $use = $this->svgdefs[$svgdefid];
  23714. if (isset($attribs['xlink:href'])) {
  23715. unset($attribs['xlink:href']);
  23716. }
  23717. if (isset($attribs['id'])) {
  23718. unset($attribs['id']);
  23719. }
  23720. if (isset($use['attribs']['x']) AND isset($attribs['x'])) {
  23721. $attribs['x'] += $use['attribs']['x'];
  23722. }
  23723. if (isset($use['attribs']['y']) AND isset($attribs['y'])) {
  23724. $attribs['y'] += $use['attribs']['y'];
  23725. }
  23726. if (empty($attribs['style'])) {
  23727. $attribs['style'] = '';
  23728. }
  23729. if (!empty($use['attribs']['style'])) {
  23730. // merge styles
  23731. $attribs['style'] = str_replace(';;',';',';'.$use['attribs']['style'].$attribs['style']);
  23732. }
  23733. $attribs = array_merge($use['attribs'], $attribs);
  23734. $this->startSVGElementHandler($parser, $use['name'], $attribs);
  23735. return;
  23736. }
  23737. }
  23738. break;
  23739. }
  23740. default: {
  23741. break;
  23742. }
  23743. } // end of switch
  23744. // process child elements
  23745. if (!empty($attribs['child_elements'])) {
  23746. $child_elements = $attribs['child_elements'];
  23747. unset($attribs['child_elements']);
  23748. foreach($child_elements as $child_element) {
  23749. if (empty($child_element['attribs']['closing_tag'])) {
  23750. $this->startSVGElementHandler('child-tag', $child_element['name'], $child_element['attribs']);
  23751. } else {
  23752. if (isset($child_element['attribs']['content'])) {
  23753. $this->svgtext = $child_element['attribs']['content'];
  23754. }
  23755. $this->endSVGElementHandler('child-tag', $child_element['name']);
  23756. }
  23757. }
  23758. }
  23759. }
  23760. /**
  23761. * Sets the closing SVG element handler function for the XML parser.
  23762. * @param $parser (resource) The first parameter, parser, is a reference to the XML parser calling the handler.
  23763. * @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.
  23764. * @author Nicola Asuni
  23765. * @since 5.0.000 (2010-05-02)
  23766. * @protected
  23767. */
  23768. protected function endSVGElementHandler($parser, $name) {
  23769. $name = $this->removeTagNamespace($name);
  23770. if ($this->svgdefsmode AND !in_array($name, array('defs', 'clipPath', 'linearGradient', 'radialGradient', 'stop'))) {;
  23771. if (end($this->svgdefs) !== FALSE) {
  23772. $last_svgdefs_id = key($this->svgdefs);
  23773. if (isset($this->svgdefs[$last_svgdefs_id]['attribs']['child_elements'])) {
  23774. foreach($this->svgdefs[$last_svgdefs_id]['attribs']['child_elements'] as $child_element) {
  23775. if (isset($child_element['attribs']['id']) AND ($child_element['name'] == $name)) {
  23776. $this->svgdefs[$last_svgdefs_id]['attribs']['child_elements'][$child_element['attribs']['id'].'_CLOSE'] = array('name' => $name, 'attribs' => array('closing_tag' => TRUE, 'content' => $this->svgtext));
  23777. return;
  23778. }
  23779. }
  23780. if ($this->svgdefs[$last_svgdefs_id]['name'] == $name) {
  23781. $this->svgdefs[$last_svgdefs_id]['attribs']['child_elements'][$last_svgdefs_id.'_CLOSE'] = array('name' => $name, 'attribs' => array('closing_tag' => TRUE, 'content' => $this->svgtext));
  23782. return;
  23783. }
  23784. }
  23785. }
  23786. return;
  23787. }
  23788. switch($name) {
  23789. case 'defs': {
  23790. $this->svgdefsmode = false;
  23791. break;
  23792. }
  23793. // clipPath
  23794. case 'clipPath': {
  23795. $this->svgclipmode = false;
  23796. break;
  23797. }
  23798. case 'svg': {
  23799. if (--$this->svg_tag_depth <= 0) {
  23800. break;
  23801. }
  23802. }
  23803. case 'g': {
  23804. // ungroup: remove last style from array
  23805. array_pop($this->svgstyles);
  23806. $this->StopTransform();
  23807. break;
  23808. }
  23809. case 'text':
  23810. case 'tspan': {
  23811. if ($this->svgtextmode['invisible']) {
  23812. // This implementation must be fixed to following the rule:
  23813. // 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.
  23814. break;
  23815. }
  23816. // print text
  23817. $text = $this->svgtext;
  23818. //$text = $this->stringTrim($text);
  23819. $textlen = $this->GetStringWidth($text);
  23820. if ($this->svgtextmode['text-anchor'] != 'start') {
  23821. // check if string is RTL text
  23822. if ($this->svgtextmode['text-anchor'] == 'end') {
  23823. if ($this->svgtextmode['rtl']) {
  23824. $this->x += $textlen;
  23825. } else {
  23826. $this->x -= $textlen;
  23827. }
  23828. } elseif ($this->svgtextmode['text-anchor'] == 'middle') {
  23829. if ($this->svgtextmode['rtl']) {
  23830. $this->x += ($textlen / 2);
  23831. } else {
  23832. $this->x -= ($textlen / 2);
  23833. }
  23834. }
  23835. }
  23836. $textrendermode = $this->textrendermode;
  23837. $textstrokewidth = $this->textstrokewidth;
  23838. $this->setTextRenderingMode($this->svgtextmode['stroke'], true, false);
  23839. if ($name == 'text') {
  23840. // store current coordinates
  23841. $tmpx = $this->x;
  23842. $tmpy = $this->y;
  23843. }
  23844. // print the text
  23845. $this->Cell($textlen, 0, $text, 0, 0, '', false, '', 0, false, 'L', 'T');
  23846. if ($name == 'text') {
  23847. // restore coordinates
  23848. $this->x = $tmpx;
  23849. $this->y = $tmpy;
  23850. }
  23851. // restore previous rendering mode
  23852. $this->textrendermode = $textrendermode;
  23853. $this->textstrokewidth = $textstrokewidth;
  23854. $this->svgtext = '';
  23855. $this->StopTransform();
  23856. if (!$this->svgdefsmode) {
  23857. array_pop($this->svgstyles);
  23858. }
  23859. break;
  23860. }
  23861. default: {
  23862. break;
  23863. }
  23864. }
  23865. }
  23866. /**
  23867. * Sets the character data handler function for the XML parser.
  23868. * @param $parser (resource) The first parameter, parser, is a reference to the XML parser calling the handler.
  23869. * @param $data (string) The second parameter, data, contains the character data as a string.
  23870. * @author Nicola Asuni
  23871. * @since 5.0.000 (2010-05-02)
  23872. * @protected
  23873. */
  23874. protected function segSVGContentHandler($parser, $data) {
  23875. $this->svgtext .= $data;
  23876. }
  23877. // --- END SVG METHODS -----------------------------------------------------
  23878. } // END OF TCPDF CLASS
  23879. //============================================================+
  23880. // END OF FILE
  23881. //============================================================+