/lib/tcpdf/tcpdf.php

https://bitbucket.org/moodle/moodle · PHP · 24688 lines · 17109 code · 707 blank · 6872 comment · 3856 complexity · 144aa32f4e30fd69d49d1f832331ce62 MD5 · raw file

  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. * Boolean flag to indicate if the document language is Right-To-Left.
  669. * @protected
  670. * @since 2.0.000
  671. */
  672. protected $rtl = false;
  673. /**
  674. * Boolean flag used to force RTL or LTR string direction.
  675. * @protected
  676. * @since 2.0.000
  677. */
  678. protected $tmprtl = false;
  679. // --- Variables used for document encryption:
  680. /**
  681. * IBoolean flag indicating whether document is protected.
  682. * @protected
  683. * @since 2.0.000 (2008-01-02)
  684. */
  685. protected $encrypted;
  686. /**
  687. * Array containing encryption settings.
  688. * @protected
  689. * @since 5.0.005 (2010-05-11)
  690. */
  691. protected $encryptdata = array();
  692. /**
  693. * Last RC4 key encrypted (cached for optimisation).
  694. * @protected
  695. * @since 2.0.000 (2008-01-02)
  696. */
  697. protected $last_enc_key;
  698. /**
  699. * Last RC4 computed key.
  700. * @protected
  701. * @since 2.0.000 (2008-01-02)
  702. */
  703. protected $last_enc_key_c;
  704. /**
  705. * File ID (used on document trailer).
  706. * @protected
  707. * @since 5.0.005 (2010-05-12)
  708. */
  709. protected $file_id;
  710. // --- bookmark ---
  711. /**
  712. * Outlines for bookmark.
  713. * @protected
  714. * @since 2.1.002 (2008-02-12)
  715. */
  716. protected $outlines = array();
  717. /**
  718. * Outline root for bookmark.
  719. * @protected
  720. * @since 2.1.002 (2008-02-12)
  721. */
  722. protected $OutlineRoot;
  723. // --- javascript and form ---
  724. /**
  725. * Javascript code.
  726. * @protected
  727. * @since 2.1.002 (2008-02-12)
  728. */
  729. protected $javascript = '';
  730. /**
  731. * Javascript counter.
  732. * @protected
  733. * @since 2.1.002 (2008-02-12)
  734. */
  735. protected $n_js;
  736. /**
  737. * line through state
  738. * @protected
  739. * @since 2.8.000 (2008-03-19)
  740. */
  741. protected $linethrough;
  742. /**
  743. * Array with additional document-wide usage rights for the document.
  744. * @protected
  745. * @since 5.8.014 (2010-08-23)
  746. */
  747. protected $ur = array();
  748. /**
  749. * DPI (Dot Per Inch) Document Resolution (do not change).
  750. * @protected
  751. * @since 3.0.000 (2008-03-27)
  752. */
  753. protected $dpi = 72;
  754. /**
  755. * Array of page numbers were a new page group was started (the page numbers are the keys of the array).
  756. * @protected
  757. * @since 3.0.000 (2008-03-27)
  758. */
  759. protected $newpagegroup = array();
  760. /**
  761. * Array that contains the number of pages in each page group.
  762. * @protected
  763. * @since 3.0.000 (2008-03-27)
  764. */
  765. protected $pagegroups = array();
  766. /**
  767. * Current page group number.
  768. * @protected
  769. * @since 3.0.000 (2008-03-27)
  770. */
  771. protected $currpagegroup = 0;
  772. /**
  773. * Array of transparency objects and parameters.
  774. * @protected
  775. * @since 3.0.000 (2008-03-27)
  776. */
  777. protected $extgstates;
  778. /**
  779. * Set the default JPEG compression quality (1-100).
  780. * @protected
  781. * @since 3.0.000 (2008-03-27)
  782. */
  783. protected $jpeg_quality;
  784. /**
  785. * Default cell height ratio.
  786. * @protected
  787. * @since 3.0.014 (2008-05-23)
  788. */
  789. protected $cell_height_ratio = K_CELL_HEIGHT_RATIO;
  790. /**
  791. * PDF viewer preferences.
  792. * @protected
  793. * @since 3.1.000 (2008-06-09)
  794. */
  795. protected $viewer_preferences;
  796. /**
  797. * A name object specifying how the document should be displayed when opened.
  798. * @protected
  799. * @since 3.1.000 (2008-06-09)
  800. */
  801. protected $PageMode;
  802. /**
  803. * Array for storing gradient information.
  804. * @protected
  805. * @since 3.1.000 (2008-06-09)
  806. */
  807. protected $gradients = array();
  808. /**
  809. * Array used to store positions inside the pages buffer (keys are the page numbers).
  810. * @protected
  811. * @since 3.2.000 (2008-06-26)
  812. */
  813. protected $intmrk = array();
  814. /**
  815. * Array used to store positions inside the pages buffer (keys are the page numbers).
  816. * @protected
  817. * @since 5.7.000 (2010-08-03)
  818. */
  819. protected $bordermrk = array();
  820. /**
  821. * Array used to store page positions to track empty pages (keys are the page numbers).
  822. * @protected
  823. * @since 5.8.007 (2010-08-18)
  824. */
  825. protected $emptypagemrk = array();
  826. /**
  827. * Array used to store content positions inside the pages buffer (keys are the page numbers).
  828. * @protected
  829. * @since 4.6.021 (2009-07-20)
  830. */
  831. protected $cntmrk = array();
  832. /**
  833. * Array used to store footer positions of each page.
  834. * @protected
  835. * @since 3.2.000 (2008-07-01)
  836. */
  837. protected $footerpos = array();
  838. /**
  839. * Array used to store footer length of each page.
  840. * @protected
  841. * @since 4.0.014 (2008-07-29)
  842. */
  843. protected $footerlen = array();
  844. /**
  845. * Boolean flag to indicate if a new line is created.
  846. * @protected
  847. * @since 3.2.000 (2008-07-01)
  848. */
  849. protected $newline = true;
  850. /**
  851. * End position of the latest inserted line.
  852. * @protected
  853. * @since 3.2.000 (2008-07-01)
  854. */
  855. protected $endlinex = 0;
  856. /**
  857. * PDF string for width value of the last line.
  858. * @protected
  859. * @since 4.0.006 (2008-07-16)
  860. */
  861. protected $linestyleWidth = '';
  862. /**
  863. * PDF string for CAP value of the last line.
  864. * @protected
  865. * @since 4.0.006 (2008-07-16)
  866. */
  867. protected $linestyleCap = '0 J';
  868. /**
  869. * PDF string for join value of the last line.
  870. * @protected
  871. * @since 4.0.006 (2008-07-16)
  872. */
  873. protected $linestyleJoin = '0 j';
  874. /**
  875. * PDF string for dash value of the last line.
  876. * @protected
  877. * @since 4.0.006 (2008-07-16)
  878. */
  879. protected $linestyleDash = '[] 0 d';
  880. /**
  881. * Boolean flag to indicate if marked-content sequence is open.
  882. * @protected
  883. * @since 4.0.013 (2008-07-28)
  884. */
  885. protected $openMarkedContent = false;
  886. /**
  887. * Count the latest inserted vertical spaces on HTML.
  888. * @protected
  889. * @since 4.0.021 (2008-08-24)
  890. */
  891. protected $htmlvspace = 0;
  892. /**
  893. * Array of Spot colors.
  894. * @protected
  895. * @since 4.0.024 (2008-09-12)
  896. */
  897. protected $spot_colors = array();
  898. /**
  899. * Symbol used for HTML unordered list items.
  900. * @protected
  901. * @since 4.0.028 (2008-09-26)
  902. */
  903. protected $lisymbol = '';
  904. /**
  905. * String used to mark the beginning and end of EPS image blocks.
  906. * @protected
  907. * @since 4.1.000 (2008-10-18)
  908. */
  909. protected $epsmarker = 'x#!#EPS#!#x';
  910. /**
  911. * Array of transformation matrix.
  912. * @protected
  913. * @since 4.2.000 (2008-10-29)
  914. */
  915. protected $transfmatrix = array();
  916. /**
  917. * Current key for transformation matrix.
  918. * @protected
  919. * @since 4.8.005 (2009-09-17)
  920. */
  921. protected $transfmatrix_key = 0;
  922. /**
  923. * Booklet mode for double-sided pages.
  924. * @protected
  925. * @since 4.2.000 (2008-10-29)
  926. */
  927. protected $booklet = false;
  928. /**
  929. * Epsilon value used for float calculations.
  930. * @protected
  931. * @since 4.2.000 (2008-10-29)
  932. */
  933. protected $feps = 0.005;
  934. /**
  935. * Array used for custom vertical spaces for HTML tags.
  936. * @protected
  937. * @since 4.2.001 (2008-10-30)
  938. */
  939. protected $tagvspaces = array();
  940. /**
  941. * HTML PARSER: custom indent amount for lists. Negative value means disabled.
  942. * @protected
  943. * @since 4.2.007 (2008-11-12)
  944. */
  945. protected $customlistindent = -1;
  946. /**
  947. * Boolean flag to indicate if the border of the cell sides that cross the page should be removed.
  948. * @protected
  949. * @since 4.2.010 (2008-11-14)
  950. */
  951. protected $opencell = true;
  952. /**
  953. * Array of files to embedd.
  954. * @protected
  955. * @since 4.4.000 (2008-12-07)
  956. */
  957. protected $embeddedfiles = array();
  958. /**
  959. * Boolean flag to indicate if we are inside a PRE tag.
  960. * @protected
  961. * @since 4.4.001 (2008-12-08)
  962. */
  963. protected $premode = false;
  964. /**
  965. * Array used to store positions of graphics transformation blocks inside the page buffer.
  966. * keys are the page numbers
  967. * @protected
  968. * @since 4.4.002 (2008-12-09)
  969. */
  970. protected $transfmrk = array();
  971. /**
  972. * Default color for html links.
  973. * @protected
  974. * @since 4.4.003 (2008-12-09)
  975. */
  976. protected $htmlLinkColorArray = array(0, 0, 255);
  977. /**
  978. * Default font style to add to html links.
  979. * @protected
  980. * @since 4.4.003 (2008-12-09)
  981. */
  982. protected $htmlLinkFontStyle = 'U';
  983. /**
  984. * Counts the number of pages.
  985. * @protected
  986. * @since 4.5.000 (2008-12-31)
  987. */
  988. protected $numpages = 0;
  989. /**
  990. * Array containing page lengths in bytes.
  991. * @protected
  992. * @since 4.5.000 (2008-12-31)
  993. */
  994. protected $pagelen = array();
  995. /**
  996. * Counts the number of pages.
  997. * @protected
  998. * @since 4.5.000 (2008-12-31)
  999. */
  1000. protected $numimages = 0;
  1001. /**
  1002. * Store the image keys.
  1003. * @protected
  1004. * @since 4.5.000 (2008-12-31)
  1005. */
  1006. protected $imagekeys = array();
  1007. /**
  1008. * Length of the buffer in bytes.
  1009. * @protected
  1010. * @since 4.5.000 (2008-12-31)
  1011. */
  1012. protected $bufferlen = 0;
  1013. /**
  1014. * Counts the number of fonts.
  1015. * @protected
  1016. * @since 4.5.000 (2009-01-02)
  1017. */
  1018. protected $numfonts = 0;
  1019. /**
  1020. * Store the font keys.
  1021. * @protected
  1022. * @since 4.5.000 (2009-01-02)
  1023. */
  1024. protected $fontkeys = array();
  1025. /**
  1026. * Store the font object IDs.
  1027. * @protected
  1028. * @since 4.8.001 (2009-09-09)
  1029. */
  1030. protected $font_obj_ids = array();
  1031. /**
  1032. * Store the fage status (true when opened, false when closed).
  1033. * @protected
  1034. * @since 4.5.000 (2009-01-02)
  1035. */
  1036. protected $pageopen = array();
  1037. /**
  1038. * Default monospace font.
  1039. * @protected
  1040. * @since 4.5.025 (2009-03-10)
  1041. */
  1042. protected $default_monospaced_font = 'courier';
  1043. /**
  1044. * Cloned copy of the current class object.
  1045. * @protected
  1046. * @since 4.5.029 (2009-03-19)
  1047. */
  1048. protected $objcopy;
  1049. /**
  1050. * Array used to store the lengths of cache files.
  1051. * @protected
  1052. * @since 4.5.029 (2009-03-19)
  1053. */
  1054. protected $cache_file_length = array();
  1055. /**
  1056. * Table header content to be repeated on each new page.
  1057. * @protected
  1058. * @since 4.5.030 (2009-03-20)
  1059. */
  1060. protected $thead = '';
  1061. /**
  1062. * Margins used for table header.
  1063. * @protected
  1064. * @since 4.5.030 (2009-03-20)
  1065. */
  1066. protected $theadMargins = array();
  1067. /**
  1068. * Boolean flag to enable document digital signature.
  1069. * @protected
  1070. * @since 4.6.005 (2009-04-24)
  1071. */
  1072. protected $sign = false;
  1073. /**
  1074. * Digital signature data.
  1075. * @protected
  1076. * @since 4.6.005 (2009-04-24)
  1077. */
  1078. protected $signature_data = array();
  1079. /**
  1080. * Digital signature max length.
  1081. * @protected
  1082. * @since 4.6.005 (2009-04-24)
  1083. */
  1084. protected $signature_max_length = 11742;
  1085. /**
  1086. * Data for digital signature appearance.
  1087. * @protected
  1088. * @since 5.3.011 (2010-06-16)
  1089. */
  1090. protected $signature_appearance = array('page' => 1, 'rect' => '0 0 0 0');
  1091. /**
  1092. * Array of empty digital signature appearances.
  1093. * @protected
  1094. * @since 5.9.101 (2011-07-06)
  1095. */
  1096. protected $empty_signature_appearance = array();
  1097. /**
  1098. * Boolean flag to enable document timestamping with TSA.
  1099. * @protected
  1100. * @since 6.0.085 (2014-06-19)
  1101. */
  1102. protected $tsa_timestamp = false;
  1103. /**
  1104. * Timestamping data.
  1105. * @protected
  1106. * @since 6.0.085 (2014-06-19)
  1107. */
  1108. protected $tsa_data = array();
  1109. /**
  1110. * Regular expression used to find blank characters (required for word-wrapping).
  1111. * @protected
  1112. * @since 4.6.006 (2009-04-28)
  1113. */
  1114. protected $re_spaces = '/[^\S\xa0]/';
  1115. /**
  1116. * Array of $re_spaces parts.
  1117. * @protected
  1118. * @since 5.5.011 (2010-07-09)
  1119. */
  1120. protected $re_space = array('p' => '[^\S\xa0]', 'm' => '');
  1121. /**
  1122. * Digital signature object ID.
  1123. * @protected
  1124. * @since 4.6.022 (2009-06-23)
  1125. */
  1126. protected $sig_obj_id = 0;
  1127. /**
  1128. * ID of page objects.
  1129. * @protected
  1130. * @since 4.7.000 (2009-08-29)
  1131. */
  1132. protected $page_obj_id = array();
  1133. /**
  1134. * List of form annotations IDs.
  1135. * @protected
  1136. * @since 4.8.000 (2009-09-07)
  1137. */
  1138. protected $form_obj_id = array();
  1139. /**
  1140. * 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.
  1141. * @protected
  1142. * @since 4.8.000 (2009-09-07)
  1143. */
  1144. protected $default_form_prop = array('lineWidth'=>1, 'borderStyle'=>'solid', 'fillColor'=>array(255, 255, 255), 'strokeColor'=>array(128, 128, 128));
  1145. /**
  1146. * Javascript objects array.
  1147. * @protected
  1148. * @since 4.8.000 (2009-09-07)
  1149. */
  1150. protected $js_objects = array();
  1151. /**
  1152. * Current form action (used during XHTML rendering).
  1153. * @protected
  1154. * @since 4.8.000 (2009-09-07)
  1155. */
  1156. protected $form_action = '';
  1157. /**
  1158. * Current form encryption type (used during XHTML rendering).
  1159. * @protected
  1160. * @since 4.8.000 (2009-09-07)
  1161. */
  1162. protected $form_enctype = 'application/x-www-form-urlencoded';
  1163. /**
  1164. * Current method to submit forms.
  1165. * @protected
  1166. * @since 4.8.000 (2009-09-07)
  1167. */
  1168. protected $form_mode = 'post';
  1169. /**
  1170. * List of fonts used on form fields (fontname => fontkey).
  1171. * @protected
  1172. * @since 4.8.001 (2009-09-09)
  1173. */
  1174. protected $annotation_fonts = array();
  1175. /**
  1176. * List of radio buttons parent objects.
  1177. * @protected
  1178. * @since 4.8.001 (2009-09-09)
  1179. */
  1180. protected $radiobutton_groups = array();
  1181. /**
  1182. * List of radio group objects IDs.
  1183. * @protected
  1184. * @since 4.8.001 (2009-09-09)
  1185. */
  1186. protected $radio_groups = array();
  1187. /**
  1188. * Text indentation value (used for text-indent CSS attribute).
  1189. * @protected
  1190. * @since 4.8.006 (2009-09-23)
  1191. */
  1192. protected $textindent = 0;
  1193. /**
  1194. * Store page number when startTransaction() is called.
  1195. * @protected
  1196. * @since 4.8.006 (2009-09-23)
  1197. */
  1198. protected $start_transaction_page = 0;
  1199. /**
  1200. * Store Y position when startTransaction() is called.
  1201. * @protected
  1202. * @since 4.9.001 (2010-03-28)
  1203. */
  1204. protected $start_transaction_y = 0;
  1205. /**
  1206. * True when we are printing the thead section on a new page.
  1207. * @protected
  1208. * @since 4.8.027 (2010-01-25)
  1209. */
  1210. protected $inthead = false;
  1211. /**
  1212. * Array of column measures (width, space, starting Y position).
  1213. * @protected
  1214. * @since 4.9.001 (2010-03-28)
  1215. */
  1216. protected $columns = array();
  1217. /**
  1218. * Number of colums.
  1219. * @protected
  1220. * @since 4.9.001 (2010-03-28)
  1221. */
  1222. protected $num_columns = 1;
  1223. /**
  1224. * Current column number.
  1225. * @protected
  1226. * @since 4.9.001 (2010-03-28)
  1227. */
  1228. protected $current_column = 0;
  1229. /**
  1230. * Starting page for columns.
  1231. * @protected
  1232. * @since 4.9.001 (2010-03-28)
  1233. */
  1234. protected $column_start_page = 0;
  1235. /**
  1236. * Maximum page and column selected.
  1237. * @protected
  1238. * @since 5.8.000 (2010-08-11)
  1239. */
  1240. protected $maxselcol = array('page' => 0, 'column' => 0);
  1241. /**
  1242. * Array of: X difference between table cell x start and starting page margin, cellspacing, cellpadding.
  1243. * @protected
  1244. * @since 5.8.000 (2010-08-11)
  1245. */
  1246. protected $colxshift = array('x' => 0, 's' => array('H' => 0, 'V' => 0), 'p' => array('L' => 0, 'T' => 0, 'R' => 0, 'B' => 0));
  1247. /**
  1248. * 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.
  1249. * @protected
  1250. * @since 4.9.008 (2010-04-03)
  1251. */
  1252. protected $textrendermode = 0;
  1253. /**
  1254. * Text stroke width in doc units.
  1255. * @protected
  1256. * @since 4.9.008 (2010-04-03)
  1257. */
  1258. protected $textstrokewidth = 0;
  1259. /**
  1260. * Current stroke color.
  1261. * @protected
  1262. * @since 4.9.008 (2010-04-03)
  1263. */
  1264. protected $strokecolor;
  1265. /**
  1266. * Default unit of measure for document.
  1267. * @protected
  1268. * @since 5.0.000 (2010-04-22)
  1269. */
  1270. protected $pdfunit = 'mm';
  1271. /**
  1272. * Boolean flag true when we are on TOC (Table Of Content) page.
  1273. * @protected
  1274. */
  1275. protected $tocpage = false;
  1276. /**
  1277. * Boolean flag: if true convert vector images (SVG, EPS) to raster image using GD or ImageMagick library.
  1278. * @protected
  1279. * @since 5.0.000 (2010-04-26)
  1280. */
  1281. protected $rasterize_vector_images = false;
  1282. /**
  1283. * Boolean flag: if true enables font subsetting by default.
  1284. * @protected
  1285. * @since 5.3.002 (2010-06-07)
  1286. */
  1287. protected $font_subsetting = true;
  1288. /**
  1289. * Array of default graphic settings.
  1290. * @protected
  1291. * @since 5.5.008 (2010-07-02)
  1292. */
  1293. protected $default_graphic_vars = array();
  1294. /**
  1295. * Array of XObjects.
  1296. * @protected
  1297. * @since 5.8.014 (2010-08-23)
  1298. */
  1299. protected $xobjects = array();
  1300. /**
  1301. * Boolean value true when we are inside an XObject.
  1302. * @protected
  1303. * @since 5.8.017 (2010-08-24)
  1304. */
  1305. protected $inxobj = false;
  1306. /**
  1307. * Current XObject ID.
  1308. * @protected
  1309. * @since 5.8.017 (2010-08-24)
  1310. */
  1311. protected $xobjid = '';
  1312. /**
  1313. * Percentage of character stretching.
  1314. * @protected
  1315. * @since 5.9.000 (2010-09-29)
  1316. */
  1317. protected $font_stretching = 100;
  1318. /**
  1319. * Increases or decreases the space between characters in a text by the specified amount (tracking).
  1320. * @protected
  1321. * @since 5.9.000 (2010-09-29)
  1322. */
  1323. protected $font_spacing = 0;
  1324. /**
  1325. * Array of no-write regions.
  1326. * ('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)
  1327. * @protected
  1328. * @since 5.9.003 (2010-10-14)
  1329. */
  1330. protected $page_regions = array();
  1331. /**
  1332. * Boolean value true when page region check is active.
  1333. * @protected
  1334. */
  1335. protected $check_page_regions = true;
  1336. /**
  1337. * Array of PDF layers data.
  1338. * @protected
  1339. * @since 5.9.102 (2011-07-13)
  1340. */
  1341. protected $pdflayers = array();
  1342. /**
  1343. * A dictionary of names and corresponding destinations (Dests key on document Catalog).
  1344. * @protected
  1345. * @since 5.9.097 (2011-06-23)
  1346. */
  1347. protected $dests = array();
  1348. /**
  1349. * Object ID for Named Destinations
  1350. * @protected
  1351. * @since 5.9.097 (2011-06-23)
  1352. */
  1353. protected $n_dests;
  1354. /**
  1355. * Embedded Files Names
  1356. * @protected
  1357. * @since 5.9.204 (2013-01-23)
  1358. */
  1359. protected $efnames = array();
  1360. /**
  1361. * Directory used for the last SVG image.
  1362. * @protected
  1363. * @since 5.0.000 (2010-05-05)
  1364. */
  1365. protected $svgdir = '';
  1366. /**
  1367. * Deafult unit of measure for SVG.
  1368. * @protected
  1369. * @since 5.0.000 (2010-05-02)
  1370. */
  1371. protected $svgunit = 'px';
  1372. /**
  1373. * Array of SVG gradients.
  1374. * @protected
  1375. * @since 5.0.000 (2010-05-02)
  1376. */
  1377. protected $svggradients = array();
  1378. /**
  1379. * ID of last SVG gradient.
  1380. * @protected
  1381. * @since 5.0.000 (2010-05-02)
  1382. */
  1383. protected $svggradientid = 0;
  1384. /**
  1385. * Boolean value true when in SVG defs group.
  1386. * @protected
  1387. * @since 5.0.000 (2010-05-02)
  1388. */
  1389. protected $svgdefsmode = false;
  1390. /**
  1391. * Array of SVG defs.
  1392. * @protected
  1393. * @since 5.0.000 (2010-05-02)
  1394. */
  1395. protected $svgdefs = array();
  1396. /**
  1397. * Boolean value true when in SVG clipPath tag.
  1398. * @protected
  1399. * @since 5.0.000 (2010-04-26)
  1400. */
  1401. protected $svgclipmode = false;
  1402. /**
  1403. * Array of SVG clipPath commands.
  1404. * @protected
  1405. * @since 5.0.000 (2010-05-02)
  1406. */
  1407. protected $svgclippaths = array();
  1408. /**
  1409. * Array of SVG clipPath tranformation matrix.
  1410. * @protected
  1411. * @since 5.8.022 (2010-08-31)
  1412. */
  1413. protected $svgcliptm = array();
  1414. /**
  1415. * ID of last SVG clipPath.
  1416. * @protected
  1417. * @since 5.0.000 (2010-05-02)
  1418. */
  1419. protected $svgclipid = 0;
  1420. /**
  1421. * SVG text.
  1422. * @protected
  1423. * @since 5.0.000 (2010-05-02)
  1424. */
  1425. protected $svgtext = '';
  1426. /**
  1427. * SVG text properties.
  1428. * @protected
  1429. * @since 5.8.013 (2010-08-23)
  1430. */
  1431. protected $svgtextmode = array();
  1432. /**
  1433. * Array of SVG properties.
  1434. * @protected
  1435. * @since 5.0.000 (2010-05-02)
  1436. */
  1437. protected $svgstyles = array(array(
  1438. 'alignment-baseline' => 'auto',
  1439. 'baseline-shift' => 'baseline',
  1440. 'clip' => 'auto',
  1441. 'clip-path' => 'none',
  1442. 'clip-rule' => 'nonzero',
  1443. 'color' => 'black',
  1444. 'color-interpolation' => 'sRGB',
  1445. 'color-interpolation-filters' => 'linearRGB',
  1446. 'color-profile' => 'auto',
  1447. 'color-rendering' => 'auto',
  1448. 'cursor' => 'auto',
  1449. 'direction' => 'ltr',
  1450. 'display' => 'inline',
  1451. 'dominant-baseline' => 'auto',
  1452. 'enable-background' => 'accumulate',
  1453. 'fill' => 'black',
  1454. 'fill-opacity' => 1,
  1455. 'fill-rule' => 'nonzero',
  1456. 'filter' => 'none',
  1457. 'flood-color' => 'black',
  1458. 'flood-opacity' => 1,
  1459. 'font' => '',
  1460. 'font-family' => 'helvetica',
  1461. 'font-size' => 'medium',
  1462. 'font-size-adjust' => 'none',
  1463. 'font-stretch' => 'normal',
  1464. 'font-style' => 'normal',
  1465. 'font-variant' => 'normal',
  1466. 'font-weight' => 'normal',
  1467. 'glyph-orientation-horizontal' => '0deg',
  1468. 'glyph-orientation-vertical' => 'auto',
  1469. 'image-rendering' => 'auto',
  1470. 'kerning' => 'auto',
  1471. 'letter-spacing' => 'normal',
  1472. 'lighting-color' => 'white',
  1473. 'marker' => '',
  1474. 'marker-end' => 'none',
  1475. 'marker-mid' => 'none',
  1476. 'marker-start' => 'none',
  1477. 'mask' => 'none',
  1478. 'opacity' => 1,
  1479. 'overflow' => 'auto',
  1480. 'pointer-events' => 'visiblePainted',
  1481. 'shape-rendering' => 'auto',
  1482. 'stop-color' => 'black',
  1483. 'stop-opacity' => 1,
  1484. 'stroke' => 'none',
  1485. 'stroke-dasharray' => 'none',
  1486. 'stroke-dashoffset' => 0,
  1487. 'stroke-linecap' => 'butt',
  1488. 'stroke-linejoin' => 'miter',
  1489. 'stroke-miterlimit' => 4,
  1490. 'stroke-opacity' => 1,
  1491. 'stroke-width' => 1,
  1492. 'text-anchor' => 'start',
  1493. 'text-decoration' => 'none',
  1494. 'text-rendering' => 'auto',
  1495. 'unicode-bidi' => 'normal',
  1496. 'visibility' => 'visible',
  1497. 'word-spacing' => 'normal',
  1498. 'writing-mode' => 'lr-tb',
  1499. 'text-color' => 'black',
  1500. 'transfmatrix' => array(1, 0, 0, 1, 0, 0)
  1501. ));
  1502. /**
  1503. * If true force sRGB color profile for all document.
  1504. * @protected
  1505. * @since 5.9.121 (2011-09-28)
  1506. */
  1507. protected $force_srgb = false;
  1508. /**
  1509. * If true set the document to PDF/A mode.
  1510. * @protected
  1511. * @since 5.9.121 (2011-09-27)
  1512. */
  1513. protected $pdfa_mode = false;
  1514. /**
  1515. * version of PDF/A mode (1 - 3).
  1516. * @protected
  1517. * @since 6.2.26 (2019-03-12)
  1518. */
  1519. protected $pdfa_version = 1;
  1520. /**
  1521. * Document creation date-time
  1522. * @protected
  1523. * @since 5.9.152 (2012-03-22)
  1524. */
  1525. protected $doc_creation_timestamp;
  1526. /**
  1527. * Document modification date-time
  1528. * @protected
  1529. * @since 5.9.152 (2012-03-22)
  1530. */
  1531. protected $doc_modification_timestamp;
  1532. /**
  1533. * Custom XMP data.
  1534. * @protected
  1535. * @since 5.9.128 (2011-10-06)
  1536. */
  1537. protected $custom_xmp = '';
  1538. /**
  1539. * Custom XMP RDF data.
  1540. * @protected
  1541. * @since 6.3.0 (2019-09-19)
  1542. */
  1543. protected $custom_xmp_rdf = '';
  1544. /**
  1545. * Overprint mode array.
  1546. * (Check the "Entries in a Graphics State Parameter Dictionary" on PDF 32000-1:2008).
  1547. * @protected
  1548. * @since 5.9.152 (2012-03-23)
  1549. */
  1550. protected $overprint = array('OP' => false, 'op' => false, 'OPM' => 0);
  1551. /**
  1552. * Alpha mode array.
  1553. * (Check the "Entries in a Graphics State Parameter Dictionary" on PDF 32000-1:2008).
  1554. * @protected
  1555. * @since 5.9.152 (2012-03-23)
  1556. */
  1557. protected $alpha = array('CA' => 1, 'ca' => 1, 'BM' => '/Normal', 'AIS' => false);
  1558. /**
  1559. * Define the page boundaries boxes to be set on document.
  1560. * @protected
  1561. * @since 5.9.152 (2012-03-23)
  1562. */
  1563. protected $page_boxes = array('MediaBox', 'CropBox', 'BleedBox', 'TrimBox', 'ArtBox');
  1564. /**
  1565. * If true print TCPDF meta link.
  1566. * @protected
  1567. * @since 5.9.152 (2012-03-23)
  1568. */
  1569. protected $tcpdflink = true;
  1570. /**
  1571. * Cache array for computed GD gamma values.
  1572. * @protected
  1573. * @since 5.9.1632 (2012-06-05)
  1574. */
  1575. protected $gdgammacache = array();
  1576. /**
  1577. * Cache array for file content
  1578. * @protected
  1579. * @var array
  1580. * @sinde 6.3.5 (2020-09-28)
  1581. */
  1582. protected $fileContentCache = array();
  1583. /**
  1584. * Whether to allow local file path in image html tags, when prefixed with file://
  1585. *
  1586. * @var bool
  1587. * @protected
  1588. * @since 6.4 (2020-07-23)
  1589. */
  1590. protected $allowLocalFiles = false;
  1591. //------------------------------------------------------------
  1592. // METHODS
  1593. //------------------------------------------------------------
  1594. /**
  1595. * This is the class constructor.
  1596. * It allows to set up the page format, the orientation and the measure unit used in all the methods (except for the font sizes).
  1597. *
  1598. * @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>
  1599. * @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.
  1600. * @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().
  1601. * @param $unicode (boolean) TRUE means that the input text is unicode (default = true)
  1602. * @param $encoding (string) Charset encoding (used only when converting back html entities); default is UTF-8.
  1603. * @param $diskcache (boolean) DEPRECATED FEATURE
  1604. * @param $pdfa (integer) If not false, set the document to PDF/A mode and the good version (1 or 3).
  1605. * @public
  1606. * @see getPageSizeFromFormat(), setPageFormat()
  1607. */
  1608. public function __construct($orientation='P', $unit='mm', $format='A4', $unicode=true, $encoding='UTF-8', $diskcache=false, $pdfa=false) {
  1609. // set file ID for trailer
  1610. $serformat = (is_array($format) ? json_encode($format) : $format);
  1611. $this->file_id = md5(TCPDF_STATIC::getRandomSeed('TCPDF'.$orientation.$unit.$serformat.$encoding));
  1612. $this->font_obj_ids = array();
  1613. $this->page_obj_id = array();
  1614. $this->form_obj_id = array();
  1615. // set pdf/a mode
  1616. if ($pdfa != false) {
  1617. $this->pdfa_mode = true;
  1618. $this->pdfa_version = $pdfa; // 1 or 3
  1619. } else
  1620. $this->pdfa_mode = false;
  1621. $this->force_srgb = false;
  1622. // set language direction
  1623. $this->rtl = false;
  1624. $this->tmprtl = false;
  1625. // some checks
  1626. $this->_dochecks();
  1627. // initialization of properties
  1628. $this->isunicode = $unicode;
  1629. $this->page = 0;
  1630. $this->transfmrk[0] = array();
  1631. $this->pagedim = array();
  1632. $this->n = 2;
  1633. $this->buffer = '';
  1634. $this->pages = array();
  1635. $this->state = 0;
  1636. $this->fonts = array();
  1637. $this->FontFiles = array();
  1638. $this->diffs = array();
  1639. $this->images = array();
  1640. $this->links = array();
  1641. $this->gradients = array();
  1642. $this->InFooter = false;
  1643. $this->lasth = 0;
  1644. $this->FontFamily = defined('PDF_FONT_NAME_MAIN')?PDF_FONT_NAME_MAIN:'helvetica';
  1645. $this->FontStyle = '';
  1646. $this->FontSizePt = 12;
  1647. $this->underline = false;
  1648. $this->overline = false;
  1649. $this->linethrough = false;
  1650. $this->DrawColor = '0 G';
  1651. $this->FillColor = '0 g';
  1652. $this->TextColor = '0 g';
  1653. $this->ColorFlag = false;
  1654. $this->pdflayers = array();
  1655. // encryption values
  1656. $this->encrypted = false;
  1657. $this->last_enc_key = '';
  1658. // standard Unicode fonts
  1659. $this->CoreFonts = array(
  1660. 'courier'=>'Courier',
  1661. 'courierB'=>'Courier-Bold',
  1662. 'courierI'=>'Courier-Oblique',
  1663. 'courierBI'=>'Courier-BoldOblique',
  1664. 'helvetica'=>'Helvetica',
  1665. 'helveticaB'=>'Helvetica-Bold',
  1666. 'helveticaI'=>'Helvetica-Oblique',
  1667. 'helveticaBI'=>'Helvetica-BoldOblique',
  1668. 'times'=>'Times-Roman',
  1669. 'timesB'=>'Times-Bold',
  1670. 'timesI'=>'Times-Italic',
  1671. 'timesBI'=>'Times-BoldItalic',
  1672. 'symbol'=>'Symbol',
  1673. 'zapfdingbats'=>'ZapfDingbats'
  1674. );
  1675. // set scale factor
  1676. $this->setPageUnit($unit);
  1677. // set page format and orientation
  1678. $this->setPageFormat($format, $orientation);
  1679. // page margins (1 cm)
  1680. $margin = 28.35 / $this->k;
  1681. $this->SetMargins($margin, $margin);
  1682. $this->clMargin = $this->lMargin;
  1683. $this->crMargin = $this->rMargin;
  1684. // internal cell padding
  1685. $cpadding = $margin / 10;
  1686. $this->setCellPaddings($cpadding, 0, $cpadding, 0);
  1687. // cell margins
  1688. $this->setCellMargins(0, 0, 0, 0);
  1689. // line width (0.2 mm)
  1690. $this->LineWidth = 0.57 / $this->k;
  1691. $this->linestyleWidth = sprintf('%F w', ($this->LineWidth * $this->k));
  1692. $this->linestyleCap = '0 J';
  1693. $this->linestyleJoin = '0 j';
  1694. $this->linestyleDash = '[] 0 d';
  1695. // automatic page break
  1696. $this->SetAutoPageBreak(true, (2 * $margin));
  1697. // full width display mode
  1698. $this->SetDisplayMode('fullwidth');
  1699. // compression
  1700. $this->SetCompression();
  1701. // set default PDF version number
  1702. $this->setPDFVersion();
  1703. $this->tcpdflink = true;
  1704. $this->encoding = $encoding;
  1705. $this->HREF = array();
  1706. $this->getFontsList();
  1707. $this->fgcolor = array('R' => 0, 'G' => 0, 'B' => 0);
  1708. $this->strokecolor = array('R' => 0, 'G' => 0, 'B' => 0);
  1709. $this->bgcolor = array('R' => 255, 'G' => 255, 'B' => 255);
  1710. $this->extgstates = array();
  1711. $this->setTextShadow();
  1712. // signature
  1713. $this->sign = false;
  1714. $this->tsa_timestamp = false;
  1715. $this->tsa_data = array();
  1716. $this->signature_appearance = array('page' => 1, 'rect' => '0 0 0 0', 'name' => 'Signature');
  1717. $this->empty_signature_appearance = array();
  1718. // user's rights
  1719. $this->ur['enabled'] = false;
  1720. $this->ur['document'] = '/FullSave';
  1721. $this->ur['annots'] = '/Create/Delete/Modify/Copy/Import/Export';
  1722. $this->ur['form'] = '/Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate';
  1723. $this->ur['signature'] = '/Modify';
  1724. $this->ur['ef'] = '/Create/Delete/Modify/Import';
  1725. $this->ur['formex'] = '';
  1726. // set default JPEG quality
  1727. $this->jpeg_quality = 75;
  1728. // initialize some settings
  1729. TCPDF_FONTS::utf8Bidi(array(), '', false, $this->isunicode, $this->CurrentFont);
  1730. // set default font
  1731. $this->SetFont($this->FontFamily, $this->FontStyle, $this->FontSizePt);
  1732. $this->setHeaderFont(array($this->FontFamily, $this->FontStyle, $this->FontSizePt));
  1733. $this->setFooterFont(array($this->FontFamily, $this->FontStyle, $this->FontSizePt));
  1734. // check if PCRE Unicode support is enabled
  1735. if ($this->isunicode AND (@preg_match('/\pL/u', 'a') == 1)) {
  1736. // PCRE unicode support is turned ON
  1737. // \s : any whitespace character
  1738. // \p{Z} : any separator
  1739. // \p{Lo} : Unicode letter or ideograph that does not have lowercase and uppercase variants. Is used to chunk chinese words.
  1740. // \xa0 : Unicode Character 'NO-BREAK SPACE' (U+00A0)
  1741. //$this->setSpacesRE('/(?!\xa0)[\s\p{Z}\p{Lo}]/u');
  1742. $this->setSpacesRE('/(?!\xa0)[\s\p{Z}]/u');
  1743. } else {
  1744. // PCRE unicode support is turned OFF
  1745. $this->setSpacesRE('/[^\S\xa0]/');
  1746. }
  1747. $this->default_form_prop = array('lineWidth'=>1, 'borderStyle'=>'solid', 'fillColor'=>array(255, 255, 255), 'strokeColor'=>array(128, 128, 128));
  1748. // set document creation and modification timestamp
  1749. $this->doc_creation_timestamp = time();
  1750. $this->doc_modification_timestamp = $this->doc_creation_timestamp;
  1751. // get default graphic vars
  1752. $this->default_graphic_vars = $this->getGraphicVars();
  1753. $this->header_xobj_autoreset = false;
  1754. $this->custom_xmp = '';
  1755. $this->custom_xmp_rdf = '';
  1756. // Call cleanup method after script execution finishes or exit() is called.
  1757. // NOTE: This will not be executed if the process is killed with a SIGTERM or SIGKILL signal.
  1758. register_shutdown_function(array($this, '_destroy'), true);
  1759. }
  1760. /**
  1761. * Default destructor.
  1762. * @public
  1763. * @since 1.53.0.TC016
  1764. */
  1765. public function __destruct() {
  1766. // cleanup
  1767. $this->_destroy(true);
  1768. }
  1769. /**
  1770. * Set the units of measure for the document.
  1771. * @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.
  1772. * @public
  1773. * @since 3.0.015 (2008-06-06)
  1774. */
  1775. public function setPageUnit($unit) {
  1776. $unit = strtolower($unit);
  1777. //Set scale factor
  1778. switch ($unit) {
  1779. // points
  1780. case 'px':
  1781. case 'pt': {
  1782. $this->k = 1;
  1783. break;
  1784. }
  1785. // millimeters
  1786. case 'mm': {
  1787. $this->k = $this->dpi / 25.4;
  1788. break;
  1789. }
  1790. // centimeters
  1791. case 'cm': {
  1792. $this->k = $this->dpi / 2.54;
  1793. break;
  1794. }
  1795. // inches
  1796. case 'in': {
  1797. $this->k = $this->dpi;
  1798. break;
  1799. }
  1800. // unsupported unit
  1801. default : {
  1802. $this->Error('Incorrect unit: '.$unit);
  1803. break;
  1804. }
  1805. }
  1806. $this->pdfunit = $unit;
  1807. if (isset($this->CurOrientation)) {
  1808. $this->setPageOrientation($this->CurOrientation);
  1809. }
  1810. }
  1811. /**
  1812. * Change the format of the current page
  1813. * @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>
  1814. * <li>['format'] = page format name (one of the above);</li>
  1815. * <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>
  1816. * <li>['PZ'] : The page's preferred zoom (magnification) factor.</li>
  1817. * <li>['MediaBox'] : the boundaries of the physical medium on which the page shall be displayed or printed:</li>
  1818. * <li>['MediaBox']['llx'] : lower-left x coordinate</li>
  1819. * <li>['MediaBox']['lly'] : lower-left y coordinate</li>
  1820. * <li>['MediaBox']['urx'] : upper-right x coordinate</li>
  1821. * <li>['MediaBox']['ury'] : upper-right y coordinate</li>
  1822. * <li>['CropBox'] : the visible region of default user space:</li>
  1823. * <li>['CropBox']['llx'] : lower-left x coordinate</li>
  1824. * <li>['CropBox']['lly'] : lower-left y coordinate</li>
  1825. * <li>['CropBox']['urx'] : upper-right x coordinate</li>
  1826. * <li>['CropBox']['ury'] : upper-right y coordinate</li>
  1827. * <li>['BleedBox'] : the region to which the contents of the page shall be clipped when output in a production environment:</li>
  1828. * <li>['BleedBox']['llx'] : lower-left x coordinate</li>
  1829. * <li>['BleedBox']['lly'] : lower-left y coordinate</li>
  1830. * <li>['BleedBox']['urx'] : upper-right x coordinate</li>
  1831. * <li>['BleedBox']['ury'] : upper-right y coordinate</li>
  1832. * <li>['TrimBox'] : the intended dimensions of the finished page after trimming:</li>
  1833. * <li>['TrimBox']['llx'] : lower-left x coordinate</li>
  1834. * <li>['TrimBox']['lly'] : lower-left y coordinate</li>
  1835. * <li>['TrimBox']['urx'] : upper-right x coordinate</li>
  1836. * <li>['TrimBox']['ury'] : upper-right y coordinate</li>
  1837. * <li>['ArtBox'] : the extent of the page's meaningful content:</li>
  1838. * <li>['ArtBox']['llx'] : lower-left x coordinate</li>
  1839. * <li>['ArtBox']['lly'] : lower-left y coordinate</li>
  1840. * <li>['ArtBox']['urx'] : upper-right x coordinate</li>
  1841. * <li>['ArtBox']['ury'] : upper-right y coordinate</li>
  1842. * <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>
  1843. * <li>['BoxColorInfo'][BOXTYPE]['C'] : an array of three numbers in the range 0-255, representing the components in the DeviceRGB colour space.</li>
  1844. * <li>['BoxColorInfo'][BOXTYPE]['W'] : the guideline width in default user units</li>
  1845. * <li>['BoxColorInfo'][BOXTYPE]['S'] : the guideline style: S = Solid; D = Dashed</li>
  1846. * <li>['BoxColorInfo'][BOXTYPE]['D'] : dash array defining a pattern of dashes and gaps to be used in drawing dashed guidelines</li>
  1847. * <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>
  1848. * <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>
  1849. * <li>['trans']['S'] : transition style : Split, Blinds, Box, Wipe, Dissolve, Glitter, R, Fly, Push, Cover, Uncover, Fade</li>
  1850. * <li>['trans']['D'] : The duration of the transition effect, in seconds.</li>
  1851. * <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>
  1852. * <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>
  1853. * <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>
  1854. * <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>
  1855. * <li>['trans']['B'] : (Fly transition style only) If true, the area that shall be flown in is rectangular and opaque. Default: false.</li>
  1856. * </ul>
  1857. * @param $orientation (string) page orientation. Possible values are (case insensitive):<ul>
  1858. * <li>P or Portrait (default)</li>
  1859. * <li>L or Landscape</li>
  1860. * <li>'' (empty string) for automatic orientation</li>
  1861. * </ul>
  1862. * @protected
  1863. * @since 3.0.015 (2008-06-06)
  1864. * @see getPageSizeFromFormat()
  1865. */
  1866. protected function setPageFormat($format, $orientation='P') {
  1867. if (!empty($format) AND isset($this->pagedim[$this->page])) {
  1868. // remove inherited values
  1869. unset($this->pagedim[$this->page]);
  1870. }
  1871. if (is_string($format)) {
  1872. // get page measures from format name
  1873. $pf = TCPDF_STATIC::getPageSizeFromFormat($format);
  1874. $this->fwPt = $pf[0];
  1875. $this->fhPt = $pf[1];
  1876. } else {
  1877. // the boundaries of the physical medium on which the page shall be displayed or printed
  1878. if (isset($format['MediaBox'])) {
  1879. $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);
  1880. $this->fwPt = (($format['MediaBox']['urx'] - $format['MediaBox']['llx']) * $this->k);
  1881. $this->fhPt = (($format['MediaBox']['ury'] - $format['MediaBox']['lly']) * $this->k);
  1882. } else {
  1883. if (isset($format[0]) AND is_numeric($format[0]) AND isset($format[1]) AND is_numeric($format[1])) {
  1884. $pf = array(($format[0] * $this->k), ($format[1] * $this->k));
  1885. } else {
  1886. if (!isset($format['format'])) {
  1887. // default value
  1888. $format['format'] = 'A4';
  1889. }
  1890. $pf = TCPDF_STATIC::getPageSizeFromFormat($format['format']);
  1891. }
  1892. $this->fwPt = $pf[0];
  1893. $this->fhPt = $pf[1];
  1894. $this->pagedim = TCPDF_STATIC::setPageBoxes($this->page, 'MediaBox', 0, 0, $this->fwPt, $this->fhPt, true, $this->k, $this->pagedim);
  1895. }
  1896. // the visible region of default user space
  1897. if (isset($format['CropBox'])) {
  1898. $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);
  1899. }
  1900. // the region to which the contents of the page shall be clipped when output in a production environment
  1901. if (isset($format['BleedBox'])) {
  1902. $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);
  1903. }
  1904. // the intended dimensions of the finished page after trimming
  1905. if (isset($format['TrimBox'])) {
  1906. $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);
  1907. }
  1908. // the page's meaningful content (including potential white space)
  1909. if (isset($format['ArtBox'])) {
  1910. $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);
  1911. }
  1912. // specify the colours and other visual characteristics that should be used in displaying guidelines on the screen for the various page boundaries
  1913. if (isset($format['BoxColorInfo'])) {
  1914. $this->pagedim[$this->page]['BoxColorInfo'] = $format['BoxColorInfo'];
  1915. }
  1916. if (isset($format['Rotate']) AND (($format['Rotate'] % 90) == 0)) {
  1917. // The number of degrees by which the page shall be rotated clockwise when displayed or printed. The value shall be a multiple of 90.
  1918. $this->pagedim[$this->page]['Rotate'] = intval($format['Rotate']);
  1919. }
  1920. if (isset($format['PZ'])) {
  1921. // The page's preferred zoom (magnification) factor
  1922. $this->pagedim[$this->page]['PZ'] = floatval($format['PZ']);
  1923. }
  1924. if (isset($format['trans'])) {
  1925. // The style and duration of the visual transition to use when moving from another page to the given page during a presentation
  1926. if (isset($format['trans']['Dur'])) {
  1927. // The page's display duration
  1928. $this->pagedim[$this->page]['trans']['Dur'] = floatval($format['trans']['Dur']);
  1929. }
  1930. $stansition_styles = array('Split', 'Blinds', 'Box', 'Wipe', 'Dissolve', 'Glitter', 'R', 'Fly', 'Push', 'Cover', 'Uncover', 'Fade');
  1931. if (isset($format['trans']['S']) AND in_array($format['trans']['S'], $stansition_styles)) {
  1932. // The transition style that shall be used when moving to this page from another during a presentation
  1933. $this->pagedim[$this->page]['trans']['S'] = $format['trans']['S'];
  1934. $valid_effect = array('Split', 'Blinds');
  1935. $valid_vals = array('H', 'V');
  1936. if (isset($format['trans']['Dm']) AND in_array($format['trans']['S'], $valid_effect) AND in_array($format['trans']['Dm'], $valid_vals)) {
  1937. $this->pagedim[$this->page]['trans']['Dm'] = $format['trans']['Dm'];
  1938. }
  1939. $valid_effect = array('Split', 'Box', 'Fly');
  1940. $valid_vals = array('I', 'O');
  1941. if (isset($format['trans']['M']) AND in_array($format['trans']['S'], $valid_effect) AND in_array($format['trans']['M'], $valid_vals)) {
  1942. $this->pagedim[$this->page]['trans']['M'] = $format['trans']['M'];
  1943. }
  1944. $valid_effect = array('Wipe', 'Glitter', 'Fly', 'Cover', 'Uncover', 'Push');
  1945. if (isset($format['trans']['Di']) AND in_array($format['trans']['S'], $valid_effect)) {
  1946. if (((($format['trans']['Di'] == 90) OR ($format['trans']['Di'] == 180)) AND ($format['trans']['S'] == 'Wipe'))
  1947. OR (($format['trans']['Di'] == 315) AND ($format['trans']['S'] == 'Glitter'))
  1948. OR (($format['trans']['Di'] == 0) OR ($format['trans']['Di'] == 270))) {
  1949. $this->pagedim[$this->page]['trans']['Di'] = intval($format['trans']['Di']);
  1950. }
  1951. }
  1952. if (isset($format['trans']['SS']) AND ($format['trans']['S'] == 'Fly')) {
  1953. $this->pagedim[$this->page]['trans']['SS'] = floatval($format['trans']['SS']);
  1954. }
  1955. if (isset($format['trans']['B']) AND ($format['trans']['B'] === true) AND ($format['trans']['S'] == 'Fly')) {
  1956. $this->pagedim[$this->page]['trans']['B'] = 'true';
  1957. }
  1958. } else {
  1959. $this->pagedim[$this->page]['trans']['S'] = 'R';
  1960. }
  1961. if (isset($format['trans']['D'])) {
  1962. // The duration of the transition effect, in seconds
  1963. $this->pagedim[$this->page]['trans']['D'] = floatval($format['trans']['D']);
  1964. } else {
  1965. $this->pagedim[$this->page]['trans']['D'] = 1;
  1966. }
  1967. }
  1968. }
  1969. $this->setPageOrientation($orientation);
  1970. }
  1971. /**
  1972. * Set page orientation.
  1973. * @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>
  1974. * @param $autopagebreak (boolean) Boolean indicating if auto-page-break mode should be on or off.
  1975. * @param $bottommargin (float) bottom margin of the page.
  1976. * @public
  1977. * @since 3.0.015 (2008-06-06)
  1978. */
  1979. public function setPageOrientation($orientation, $autopagebreak='', $bottommargin='') {
  1980. if (!isset($this->pagedim[$this->page]['MediaBox'])) {
  1981. // the boundaries of the physical medium on which the page shall be displayed or printed
  1982. $this->pagedim = TCPDF_STATIC::setPageBoxes($this->page, 'MediaBox', 0, 0, $this->fwPt, $this->fhPt, true, $this->k, $this->pagedim);
  1983. }
  1984. if (!isset($this->pagedim[$this->page]['CropBox'])) {
  1985. // the visible region of default user space
  1986. $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);
  1987. }
  1988. if (!isset($this->pagedim[$this->page]['BleedBox'])) {
  1989. // the region to which the contents of the page shall be clipped when output in a production environment
  1990. $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);
  1991. }
  1992. if (!isset($this->pagedim[$this->page]['TrimBox'])) {
  1993. // the intended dimensions of the finished page after trimming
  1994. $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);
  1995. }
  1996. if (!isset($this->pagedim[$this->page]['ArtBox'])) {
  1997. // the page's meaningful content (including potential white space)
  1998. $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);
  1999. }
  2000. if (!isset($this->pagedim[$this->page]['Rotate'])) {
  2001. // The number of degrees by which the page shall be rotated clockwise when displayed or printed. The value shall be a multiple of 90.
  2002. $this->pagedim[$this->page]['Rotate'] = 0;
  2003. }
  2004. if (!isset($this->pagedim[$this->page]['PZ'])) {
  2005. // The page's preferred zoom (magnification) factor
  2006. $this->pagedim[$this->page]['PZ'] = 1;
  2007. }
  2008. if ($this->fwPt > $this->fhPt) {
  2009. // landscape
  2010. $default_orientation = 'L';
  2011. } else {
  2012. // portrait
  2013. $default_orientation = 'P';
  2014. }
  2015. $valid_orientations = array('P', 'L');
  2016. if (empty($orientation)) {
  2017. $orientation = $default_orientation;
  2018. } else {
  2019. $orientation = strtoupper($orientation[0]);
  2020. }
  2021. if (in_array($orientation, $valid_orientations) AND ($orientation != $default_orientation)) {
  2022. $this->CurOrientation = $orientation;
  2023. $this->wPt = $this->fhPt;
  2024. $this->hPt = $this->fwPt;
  2025. } else {
  2026. $this->CurOrientation = $default_orientation;
  2027. $this->wPt = $this->fwPt;
  2028. $this->hPt = $this->fhPt;
  2029. }
  2030. if ((abs($this->pagedim[$this->page]['MediaBox']['urx'] - $this->hPt) < $this->feps) AND (abs($this->pagedim[$this->page]['MediaBox']['ury'] - $this->wPt) < $this->feps)){
  2031. // swap X and Y coordinates (change page orientation)
  2032. $this->pagedim = TCPDF_STATIC::swapPageBoxCoordinates($this->page, $this->pagedim);
  2033. }
  2034. $this->w = ($this->wPt / $this->k);
  2035. $this->h = ($this->hPt / $this->k);
  2036. if (TCPDF_STATIC::empty_string($autopagebreak)) {
  2037. if (isset($this->AutoPageBreak)) {
  2038. $autopagebreak = $this->AutoPageBreak;
  2039. } else {
  2040. $autopagebreak = true;
  2041. }
  2042. }
  2043. if (TCPDF_STATIC::empty_string($bottommargin)) {
  2044. if (isset($this->bMargin)) {
  2045. $bottommargin = $this->bMargin;
  2046. } else {
  2047. // default value = 2 cm
  2048. $bottommargin = 2 * 28.35 / $this->k;
  2049. }
  2050. }
  2051. $this->SetAutoPageBreak($autopagebreak, $bottommargin);
  2052. // store page dimensions
  2053. $this->pagedim[$this->page]['w'] = $this->wPt;
  2054. $this->pagedim[$this->page]['h'] = $this->hPt;
  2055. $this->pagedim[$this->page]['wk'] = $this->w;
  2056. $this->pagedim[$this->page]['hk'] = $this->h;
  2057. $this->pagedim[$this->page]['tm'] = $this->tMargin;
  2058. $this->pagedim[$this->page]['bm'] = $bottommargin;
  2059. $this->pagedim[$this->page]['lm'] = $this->lMargin;
  2060. $this->pagedim[$this->page]['rm'] = $this->rMargin;
  2061. $this->pagedim[$this->page]['pb'] = $autopagebreak;
  2062. $this->pagedim[$this->page]['or'] = $this->CurOrientation;
  2063. $this->pagedim[$this->page]['olm'] = $this->original_lMargin;
  2064. $this->pagedim[$this->page]['orm'] = $this->original_rMargin;
  2065. }
  2066. /**
  2067. * Set regular expression to detect withespaces or word separators.
  2068. * The pattern delimiter must be the forward-slash character "/".
  2069. * Some example patterns are:
  2070. * <pre>
  2071. * Non-Unicode or missing PCRE unicode support: "/[^\S\xa0]/"
  2072. * Unicode and PCRE unicode support: "/(?!\xa0)[\s\p{Z}]/u"
  2073. * Unicode and PCRE unicode support in Chinese mode: "/(?!\xa0)[\s\p{Z}\p{Lo}]/u"
  2074. * if PCRE unicode support is turned ON ("\P" is the negate class of "\p"):
  2075. * \s : any whitespace character
  2076. * \p{Z} : any separator
  2077. * \p{Lo} : Unicode letter or ideograph that does not have lowercase and uppercase variants. Is used to chunk chinese words.
  2078. * \xa0 : Unicode Character 'NO-BREAK SPACE' (U+00A0)
  2079. * </pre>
  2080. * @param $re (string) regular expression (leave empty for default).
  2081. * @public
  2082. * @since 4.6.016 (2009-06-15)
  2083. */
  2084. public function setSpacesRE($re='/[^\S\xa0]/') {
  2085. $this->re_spaces = $re;
  2086. $re_parts = explode('/', $re);
  2087. // get pattern parts
  2088. $this->re_space = array();
  2089. if (isset($re_parts[1]) AND !empty($re_parts[1])) {
  2090. $this->re_space['p'] = $re_parts[1];
  2091. } else {
  2092. $this->re_space['p'] = '[\s]';
  2093. }
  2094. // set pattern modifiers
  2095. if (isset($re_parts[2]) AND !empty($re_parts[2])) {
  2096. $this->re_space['m'] = $re_parts[2];
  2097. } else {
  2098. $this->re_space['m'] = '';
  2099. }
  2100. }
  2101. /**
  2102. * Enable or disable Right-To-Left language mode
  2103. * @param $enable (Boolean) if true enable Right-To-Left language mode.
  2104. * @param $resetx (Boolean) if true reset the X position on direction change.
  2105. * @public
  2106. * @since 2.0.000 (2008-01-03)
  2107. */
  2108. public function setRTL($enable, $resetx=true) {
  2109. $enable = $enable ? true : false;
  2110. $resetx = ($resetx AND ($enable != $this->rtl));
  2111. $this->rtl = $enable;
  2112. $this->tmprtl = false;
  2113. if ($resetx) {
  2114. $this->Ln(0);
  2115. }
  2116. }
  2117. /**
  2118. * Return the RTL status
  2119. * @return boolean
  2120. * @public
  2121. * @since 4.0.012 (2008-07-24)
  2122. */
  2123. public function getRTL() {
  2124. return $this->rtl;
  2125. }
  2126. /**
  2127. * Force temporary RTL language direction
  2128. * @param $mode (mixed) can be false, 'L' for LTR or 'R' for RTL
  2129. * @public
  2130. * @since 2.1.000 (2008-01-09)
  2131. */
  2132. public function setTempRTL($mode) {
  2133. $newmode = false;
  2134. switch (strtoupper($mode)) {
  2135. case 'LTR':
  2136. case 'L': {
  2137. if ($this->rtl) {
  2138. $newmode = 'L';
  2139. }
  2140. break;
  2141. }
  2142. case 'RTL':
  2143. case 'R': {
  2144. if (!$this->rtl) {
  2145. $newmode = 'R';
  2146. }
  2147. break;
  2148. }
  2149. case false:
  2150. default: {
  2151. $newmode = false;
  2152. break;
  2153. }
  2154. }
  2155. $this->tmprtl = $newmode;
  2156. }
  2157. /**
  2158. * Return the current temporary RTL status
  2159. * @return boolean
  2160. * @public
  2161. * @since 4.8.014 (2009-11-04)
  2162. */
  2163. public function isRTLTextDir() {
  2164. return ($this->rtl OR ($this->tmprtl == 'R'));
  2165. }
  2166. /**
  2167. * Set the last cell height.
  2168. * @param $h (float) cell height.
  2169. * @author Nicola Asuni
  2170. * @public
  2171. * @since 1.53.0.TC034
  2172. */
  2173. public function setLastH($h) {
  2174. $this->lasth = $h;
  2175. }
  2176. /**
  2177. * Return the cell height
  2178. * @param $fontsize (int) Font size in internal units
  2179. * @param $padding (boolean) If true add cell padding
  2180. * @public
  2181. */
  2182. public function getCellHeight($fontsize, $padding=TRUE) {
  2183. $height = ($fontsize * $this->cell_height_ratio);
  2184. if ($padding) {
  2185. $height += ($this->cell_padding['T'] + $this->cell_padding['B']);
  2186. }
  2187. return round($height, 6);
  2188. }
  2189. /**
  2190. * Reset the last cell height.
  2191. * @public
  2192. * @since 5.9.000 (2010-10-03)
  2193. */
  2194. public function resetLastH() {
  2195. $this->lasth = $this->getCellHeight($this->FontSize);
  2196. }
  2197. /**
  2198. * Get the last cell height.
  2199. * @return last cell height
  2200. * @public
  2201. * @since 4.0.017 (2008-08-05)
  2202. */
  2203. public function getLastH() {
  2204. return $this->lasth;
  2205. }
  2206. /**
  2207. * Set the adjusting factor to convert pixels to user units.
  2208. * @param $scale (float) adjusting factor to convert pixels to user units.
  2209. * @author Nicola Asuni
  2210. * @public
  2211. * @since 1.5.2
  2212. */
  2213. public function setImageScale($scale) {
  2214. $this->imgscale = $scale;
  2215. }
  2216. /**
  2217. * Returns the adjusting factor to convert pixels to user units.
  2218. * @return float adjusting factor to convert pixels to user units.
  2219. * @author Nicola Asuni
  2220. * @public
  2221. * @since 1.5.2
  2222. */
  2223. public function getImageScale() {
  2224. return $this->imgscale;
  2225. }
  2226. /**
  2227. * Returns an array of page dimensions:
  2228. * <ul><li>$this->pagedim[$this->page]['w'] = page width in points</li><li>$this->pagedim[$this->page]['h'] = height in points</li><li>$this->pagedim[$this->page]['wk'] = page width in user units</li><li>$this->pagedim[$this->page]['hk'] = page height in user units</li><li>$this->pagedim[$this->page]['tm'] = top margin</li><li>$this->pagedim[$this->page]['bm'] = bottom margin</li><li>$this->pagedim[$this->page]['lm'] = left margin</li><li>$this->pagedim[$this->page]['rm'] = right margin</li><li>$this->pagedim[$this->page]['pb'] = auto page break</li><li>$this->pagedim[$this->page]['or'] = page orientation</li><li>$this->pagedim[$this->page]['olm'] = original left margin</li><li>$this->pagedim[$this->page]['orm'] = original right margin</li><li>$this->pagedim[$this->page]['Rotate'] = The number of degrees by which the page shall be rotated clockwise when displayed or printed. The value shall be a multiple of 90.</li><li>$this->pagedim[$this->page]['PZ'] = The page's preferred zoom (magnification) factor.</li><li>$this->pagedim[$this->page]['trans'] : the style and duration of the visual transition to use when moving from another page to the given page during a presentation<ul><li>$this->pagedim[$this->page]['trans']['Dur'] = The page's display duration (also called its advance timing): the maximum length of time, in seconds, that the page shall be displayed during presentations before the viewer application shall automatically advance to the next page.</li><li>$this->pagedim[$this->page]['trans']['S'] = transition style : Split, Blinds, Box, Wipe, Dissolve, Glitter, R, Fly, Push, Cover, Uncover, Fade</li><li>$this->pagedim[$this->page]['trans']['D'] = The duration of the transition effect, in seconds.</li><li>$this->pagedim[$this->page]['trans']['Dm'] = (Split and Blinds transition styles only) The dimension in which the specified transition effect shall occur: H = Horizontal, V = Vertical. Default value: H.</li><li>$this->pagedim[$this->page]['trans']['M'] = (Split, Box and Fly transition styles only) The direction of motion for the specified transition effect: I = Inward from the edges of the page, O = Outward from the center of the pageDefault value: I.</li><li>$this->pagedim[$this->page]['trans']['Di'] = (Wipe, Glitter, Fly, Cover, Uncover and Push transition styles only) The direction in which the specified transition effect shall moves, expressed in degrees counterclockwise starting from a left-to-right direction. If the value is a number, it shall be one of: 0 = Left to right, 90 = Bottom to top (Wipe only), 180 = Right to left (Wipe only), 270 = Top to bottom, 315 = Top-left to bottom-right (Glitter only). If the value is a name, it shall be None, which is relevant only for the Fly transition when the value of SS is not 1.0. Default value: 0.</li><li>$this->pagedim[$this->page]['trans']['SS'] = (Fly transition style only) The starting or ending scale at which the changes shall be drawn. If M specifies an inward transition, the scale of the changes drawn shall progress from SS to 1.0 over the course of the transition. If M specifies an outward transition, the scale of the changes drawn shall progress from 1.0 to SS over the course of the transition. Default: 1.0. </li><li>$this->pagedim[$this->page]['trans']['B'] = (Fly transition style only) If true, the area that shall be flown in is rectangular and opaque. Default: false.</li></ul></li><li>$this->pagedim[$this->page]['MediaBox'] : the boundaries of the physical medium on which the page shall be displayed or printed<ul><li>$this->pagedim[$this->page]['MediaBox']['llx'] = lower-left x coordinate in points</li><li>$this->pagedim[$this->page]['MediaBox']['lly'] = lower-left y coordinate in points</li><li>$this->pagedim[$this->page]['MediaBox']['urx'] = upper-right x coordinate in points</li><li>$this->pagedim[$this->page]['MediaBox']['ury'] = upper-right y coordinate in points</li></ul></li><li>$this->pagedim[$this->page]['CropBox'] : the visible region of default user space<ul><li>$this->pagedim[$this->page]['CropBox']['llx'] = lower-left x coordinate in points</li><li>$this->pagedim[$this->page]['CropBox']['lly'] = lower-left y coordinate in points</li><li>$this->pagedim[$this->page]['CropBox']['urx'] = upper-right x coordinate in points</li><li>$this->pagedim[$this->page]['CropBox']['ury'] = upper-right y coordinate in points</li></ul></li><li>$this->pagedim[$this->page]['BleedBox'] : the region to which the contents of the page shall be clipped when output in a production environment<ul><li>$this->pagedim[$this->page]['BleedBox']['llx'] = lower-left x coordinate in points</li><li>$this->pagedim[$this->page]['BleedBox']['lly'] = lower-left y coordinate in points</li><li>$this->pagedim[$this->page]['BleedBox']['urx'] = upper-right x coordinate in points</li><li>$this->pagedim[$this->page]['BleedBox']['ury'] = upper-right y coordinate in points</li></ul></li><li>$this->pagedim[$this->page]['TrimBox'] : the intended dimensions of the finished page after trimming<ul><li>$this->pagedim[$this->page]['TrimBox']['llx'] = lower-left x coordinate in points</li><li>$this->pagedim[$this->page]['TrimBox']['lly'] = lower-left y coordinate in points</li><li>$this->pagedim[$this->page]['TrimBox']['urx'] = upper-right x coordinate in points</li><li>$this->pagedim[$this->page]['TrimBox']['ury'] = upper-right y coordinate in points</li></ul></li><li>$this->pagedim[$this->page]['ArtBox'] : the extent of the page's meaningful content<ul><li>$this->pagedim[$this->page]['ArtBox']['llx'] = lower-left x coordinate in points</li><li>$this->pagedim[$this->page]['ArtBox']['lly'] = lower-left y coordinate in points</li><li>$this->pagedim[$this->page]['ArtBox']['urx'] = upper-right x coordinate in points</li><li>$this->pagedim[$this->page]['ArtBox']['ury'] = upper-right y coordinate in points</li></ul></li></ul>
  2229. * @param $pagenum (int) page number (empty = current page)
  2230. * @return array of page dimensions.
  2231. * @author Nicola Asuni
  2232. * @public
  2233. * @since 4.5.027 (2009-03-16)
  2234. */
  2235. public function getPageDimensions($pagenum='') {
  2236. if (empty($pagenum)) {
  2237. $pagenum = $this->page;
  2238. }
  2239. return $this->pagedim[$pagenum];
  2240. }
  2241. /**
  2242. * Returns the page width in units.
  2243. * @param $pagenum (int) page number (empty = current page)
  2244. * @return int page width.
  2245. * @author Nicola Asuni
  2246. * @public
  2247. * @since 1.5.2
  2248. * @see getPageDimensions()
  2249. */
  2250. public function getPageWidth($pagenum='') {
  2251. if (empty($pagenum)) {
  2252. return $this->w;
  2253. }
  2254. return $this->pagedim[$pagenum]['w'];
  2255. }
  2256. /**
  2257. * Returns the page height in units.
  2258. * @param $pagenum (int) page number (empty = current page)
  2259. * @return int page height.
  2260. * @author Nicola Asuni
  2261. * @public
  2262. * @since 1.5.2
  2263. * @see getPageDimensions()
  2264. */
  2265. public function getPageHeight($pagenum='') {
  2266. if (empty($pagenum)) {
  2267. return $this->h;
  2268. }
  2269. return $this->pagedim[$pagenum]['h'];
  2270. }
  2271. /**
  2272. * Returns the page break margin.
  2273. * @param $pagenum (int) page number (empty = current page)
  2274. * @return int page break margin.
  2275. * @author Nicola Asuni
  2276. * @public
  2277. * @since 1.5.2
  2278. * @see getPageDimensions()
  2279. */
  2280. public function getBreakMargin($pagenum='') {
  2281. if (empty($pagenum)) {
  2282. return $this->bMargin;
  2283. }
  2284. return $this->pagedim[$pagenum]['bm'];
  2285. }
  2286. /**
  2287. * Returns the scale factor (number of points in user unit).
  2288. * @return int scale factor.
  2289. * @author Nicola Asuni
  2290. * @public
  2291. * @since 1.5.2
  2292. */
  2293. public function getScaleFactor() {
  2294. return $this->k;
  2295. }
  2296. /**
  2297. * Defines the left, top and right margins.
  2298. * @param $left (float) Left margin.
  2299. * @param $top (float) Top margin.
  2300. * @param $right (float) Right margin. Default value is the left one.
  2301. * @param $keepmargins (boolean) if true overwrites the default page margins
  2302. * @public
  2303. * @since 1.0
  2304. * @see SetLeftMargin(), SetTopMargin(), SetRightMargin(), SetAutoPageBreak()
  2305. */
  2306. public function SetMargins($left, $top, $right=-1, $keepmargins=false) {
  2307. //Set left, top and right margins
  2308. $this->lMargin = $left;
  2309. $this->tMargin = $top;
  2310. if ($right == -1) {
  2311. $right = $left;
  2312. }
  2313. $this->rMargin = $right;
  2314. if ($keepmargins) {
  2315. // overwrite original values
  2316. $this->original_lMargin = $this->lMargin;
  2317. $this->original_rMargin = $this->rMargin;
  2318. }
  2319. }
  2320. /**
  2321. * 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.
  2322. * @param $margin (float) The margin.
  2323. * @public
  2324. * @since 1.4
  2325. * @see SetTopMargin(), SetRightMargin(), SetAutoPageBreak(), SetMargins()
  2326. */
  2327. public function SetLeftMargin($margin) {
  2328. //Set left margin
  2329. $this->lMargin = $margin;
  2330. if (($this->page > 0) AND ($this->x < $margin)) {
  2331. $this->x = $margin;
  2332. }
  2333. }
  2334. /**
  2335. * Defines the top margin. The method can be called before creating the first page.
  2336. * @param $margin (float) The margin.
  2337. * @public
  2338. * @since 1.5
  2339. * @see SetLeftMargin(), SetRightMargin(), SetAutoPageBreak(), SetMargins()
  2340. */
  2341. public function SetTopMargin($margin) {
  2342. //Set top margin
  2343. $this->tMargin = $margin;
  2344. if (($this->page > 0) AND ($this->y < $margin)) {
  2345. $this->y = $margin;
  2346. }
  2347. }
  2348. /**
  2349. * Defines the right margin. The method can be called before creating the first page.
  2350. * @param $margin (float) The margin.
  2351. * @public
  2352. * @since 1.5
  2353. * @see SetLeftMargin(), SetTopMargin(), SetAutoPageBreak(), SetMargins()
  2354. */
  2355. public function SetRightMargin($margin) {
  2356. $this->rMargin = $margin;
  2357. if (($this->page > 0) AND ($this->x > ($this->w - $margin))) {
  2358. $this->x = $this->w - $margin;
  2359. }
  2360. }
  2361. /**
  2362. * Set the same internal Cell padding for top, right, bottom, left-
  2363. * @param $pad (float) internal padding.
  2364. * @public
  2365. * @since 2.1.000 (2008-01-09)
  2366. * @see getCellPaddings(), setCellPaddings()
  2367. */
  2368. public function SetCellPadding($pad) {
  2369. if ($pad >= 0) {
  2370. $this->cell_padding['L'] = $pad;
  2371. $this->cell_padding['T'] = $pad;
  2372. $this->cell_padding['R'] = $pad;
  2373. $this->cell_padding['B'] = $pad;
  2374. }
  2375. }
  2376. /**
  2377. * Set the internal Cell paddings.
  2378. * @param $left (float) left padding
  2379. * @param $top (float) top padding
  2380. * @param $right (float) right padding
  2381. * @param $bottom (float) bottom padding
  2382. * @public
  2383. * @since 5.9.000 (2010-10-03)
  2384. * @see getCellPaddings(), SetCellPadding()
  2385. */
  2386. public function setCellPaddings($left='', $top='', $right='', $bottom='') {
  2387. if (($left !== '') AND ($left >= 0)) {
  2388. $this->cell_padding['L'] = $left;
  2389. }
  2390. if (($top !== '') AND ($top >= 0)) {
  2391. $this->cell_padding['T'] = $top;
  2392. }
  2393. if (($right !== '') AND ($right >= 0)) {
  2394. $this->cell_padding['R'] = $right;
  2395. }
  2396. if (($bottom !== '') AND ($bottom >= 0)) {
  2397. $this->cell_padding['B'] = $bottom;
  2398. }
  2399. }
  2400. /**
  2401. * Get the internal Cell padding array.
  2402. * @return array of padding values
  2403. * @public
  2404. * @since 5.9.000 (2010-10-03)
  2405. * @see setCellPaddings(), SetCellPadding()
  2406. */
  2407. public function getCellPaddings() {
  2408. return $this->cell_padding;
  2409. }
  2410. /**
  2411. * Set the internal Cell margins.
  2412. * @param $left (float) left margin
  2413. * @param $top (float) top margin
  2414. * @param $right (float) right margin
  2415. * @param $bottom (float) bottom margin
  2416. * @public
  2417. * @since 5.9.000 (2010-10-03)
  2418. * @see getCellMargins()
  2419. */
  2420. public function setCellMargins($left='', $top='', $right='', $bottom='') {
  2421. if (($left !== '') AND ($left >= 0)) {
  2422. $this->cell_margin['L'] = $left;
  2423. }
  2424. if (($top !== '') AND ($top >= 0)) {
  2425. $this->cell_margin['T'] = $top;
  2426. }
  2427. if (($right !== '') AND ($right >= 0)) {
  2428. $this->cell_margin['R'] = $right;
  2429. }
  2430. if (($bottom !== '') AND ($bottom >= 0)) {
  2431. $this->cell_margin['B'] = $bottom;
  2432. }
  2433. }
  2434. /**
  2435. * Get the internal Cell margin array.
  2436. * @return array of margin values
  2437. * @public
  2438. * @since 5.9.000 (2010-10-03)
  2439. * @see setCellMargins()
  2440. */
  2441. public function getCellMargins() {
  2442. return $this->cell_margin;
  2443. }
  2444. /**
  2445. * Adjust the internal Cell padding array to take account of the line width.
  2446. * @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)))
  2447. * @return void|array of adjustments
  2448. * @public
  2449. * @since 5.9.000 (2010-10-03)
  2450. */
  2451. protected function adjustCellPadding($brd=0) {
  2452. if (empty($brd)) {
  2453. return;
  2454. }
  2455. if (is_string($brd)) {
  2456. // convert string to array
  2457. $slen = strlen($brd);
  2458. $newbrd = array();
  2459. for ($i = 0; $i < $slen; ++$i) {
  2460. $newbrd[$brd[$i]] = true;
  2461. }
  2462. $brd = $newbrd;
  2463. } elseif (
  2464. ($brd === 1)
  2465. || ($brd === true)
  2466. || (is_numeric($brd) && ((int)$brd > 0))
  2467. ) {
  2468. $brd = array('LRTB' => true);
  2469. }
  2470. if (!is_array($brd)) {
  2471. return;
  2472. }
  2473. // store current cell padding
  2474. $cp = $this->cell_padding;
  2475. // select border mode
  2476. if (isset($brd['mode'])) {
  2477. $mode = $brd['mode'];
  2478. unset($brd['mode']);
  2479. } else {
  2480. $mode = 'normal';
  2481. }
  2482. // process borders
  2483. foreach ($brd as $border => $style) {
  2484. $line_width = $this->LineWidth;
  2485. if (is_array($style) && isset($style['width'])) {
  2486. // get border width
  2487. $line_width = $style['width'];
  2488. }
  2489. $adj = 0; // line width inside the cell
  2490. switch ($mode) {
  2491. case 'ext': {
  2492. $adj = 0;
  2493. break;
  2494. }
  2495. case 'int': {
  2496. $adj = $line_width;
  2497. break;
  2498. }
  2499. case 'normal':
  2500. default: {
  2501. $adj = ($line_width / 2);
  2502. break;
  2503. }
  2504. }
  2505. // correct internal cell padding if required to avoid overlap between text and lines
  2506. if (
  2507. is_numeric($this->cell_padding['T'])
  2508. && ($this->cell_padding['T'] < $adj)
  2509. && (strpos($border, 'T') !== false)
  2510. ) {
  2511. $this->cell_padding['T'] = $adj;
  2512. }
  2513. if (
  2514. is_numeric($this->cell_padding['R'])
  2515. && ($this->cell_padding['R'] < $adj)
  2516. && (strpos($border, 'R') !== false)
  2517. ) {
  2518. $this->cell_padding['R'] = $adj;
  2519. }
  2520. if (
  2521. is_numeric($this->cell_padding['B'])
  2522. && ($this->cell_padding['B'] < $adj)
  2523. && (strpos($border, 'B') !== false)
  2524. ) {
  2525. $this->cell_padding['B'] = $adj;
  2526. }
  2527. if (
  2528. is_numeric($this->cell_padding['L'])
  2529. && ($this->cell_padding['L'] < $adj)
  2530. && (strpos($border, 'L') !== false)
  2531. ) {
  2532. $this->cell_padding['L'] = $adj;
  2533. }
  2534. }
  2535. return array(
  2536. 'T' => ($this->cell_padding['T'] - $cp['T']),
  2537. 'R' => ($this->cell_padding['R'] - $cp['R']),
  2538. 'B' => ($this->cell_padding['B'] - $cp['B']),
  2539. 'L' => ($this->cell_padding['L'] - $cp['L']),
  2540. );
  2541. }
  2542. /**
  2543. * 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.
  2544. * @param $auto (boolean) Boolean indicating if mode should be on or off.
  2545. * @param $margin (float) Distance from the bottom of the page.
  2546. * @public
  2547. * @since 1.0
  2548. * @see Cell(), MultiCell(), AcceptPageBreak()
  2549. */
  2550. public function SetAutoPageBreak($auto, $margin=0) {
  2551. $this->AutoPageBreak = $auto ? true : false;
  2552. $this->bMargin = $margin;
  2553. $this->PageBreakTrigger = $this->h - $margin;
  2554. }
  2555. /**
  2556. * Return the auto-page-break mode (true or false).
  2557. * @return boolean auto-page-break mode
  2558. * @public
  2559. * @since 5.9.088
  2560. */
  2561. public function getAutoPageBreak() {
  2562. return $this->AutoPageBreak;
  2563. }
  2564. /**
  2565. * Defines the way the document is to be displayed by the viewer.
  2566. * @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>
  2567. * @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>
  2568. * @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>
  2569. * @public
  2570. * @since 1.2
  2571. */
  2572. public function SetDisplayMode($zoom, $layout='SinglePage', $mode='UseNone') {
  2573. if (($zoom == 'fullpage') OR ($zoom == 'fullwidth') OR ($zoom == 'real') OR ($zoom == 'default') OR (!is_string($zoom))) {
  2574. $this->ZoomMode = $zoom;
  2575. } else {
  2576. $this->Error('Incorrect zoom display mode: '.$zoom);
  2577. }
  2578. $this->LayoutMode = TCPDF_STATIC::getPageLayoutMode($layout);
  2579. $this->PageMode = TCPDF_STATIC::getPageMode($mode);
  2580. }
  2581. /**
  2582. * 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.
  2583. * Note: the Zlib extension is required for this feature. If not present, compression will be turned off.
  2584. * @param $compress (boolean) Boolean indicating if compression must be enabled.
  2585. * @public
  2586. * @since 1.4
  2587. */
  2588. public function SetCompression($compress=true) {
  2589. $this->compress = false;
  2590. if (function_exists('gzcompress')) {
  2591. if ($compress) {
  2592. if ( !$this->pdfa_mode) {
  2593. $this->compress = true;
  2594. }
  2595. }
  2596. }
  2597. }
  2598. /**
  2599. * Set flag to force sRGB_IEC61966-2.1 black scaled ICC color profile for the whole document.
  2600. * @param $mode (boolean) If true force sRGB output intent.
  2601. * @public
  2602. * @since 5.9.121 (2011-09-28)
  2603. */
  2604. public function setSRGBmode($mode=false) {
  2605. $this->force_srgb = $mode ? true : false;
  2606. }
  2607. /**
  2608. * Turn on/off Unicode mode for document information dictionary (meta tags).
  2609. * This has effect only when unicode mode is set to false.
  2610. * @param $unicode (boolean) if true set the meta information in Unicode
  2611. * @since 5.9.027 (2010-12-01)
  2612. * @public
  2613. */
  2614. public function SetDocInfoUnicode($unicode=true) {
  2615. $this->docinfounicode = $unicode ? true : false;
  2616. }
  2617. /**
  2618. * Defines the title of the document.
  2619. * @param $title (string) The title.
  2620. * @public
  2621. * @since 1.2
  2622. * @see SetAuthor(), SetCreator(), SetKeywords(), SetSubject()
  2623. */
  2624. public function SetTitle($title) {
  2625. $this->title = $title;
  2626. }
  2627. /**
  2628. * Defines the subject of the document.
  2629. * @param $subject (string) The subject.
  2630. * @public
  2631. * @since 1.2
  2632. * @see SetAuthor(), SetCreator(), SetKeywords(), SetTitle()
  2633. */
  2634. public function SetSubject($subject) {
  2635. $this->subject = $subject;
  2636. }
  2637. /**
  2638. * Defines the author of the document.
  2639. * @param $author (string) The name of the author.
  2640. * @public
  2641. * @since 1.2
  2642. * @see SetCreator(), SetKeywords(), SetSubject(), SetTitle()
  2643. */
  2644. public function SetAuthor($author) {
  2645. $this->author = $author;
  2646. }
  2647. /**
  2648. * Associates keywords with the document, generally in the form 'keyword1 keyword2 ...'.
  2649. * @param $keywords (string) The list of keywords.
  2650. * @public
  2651. * @since 1.2
  2652. * @see SetAuthor(), SetCreator(), SetSubject(), SetTitle()
  2653. */
  2654. public function SetKeywords($keywords) {
  2655. $this->keywords = $keywords;
  2656. }
  2657. /**
  2658. * Defines the creator of the document. This is typically the name of the application that generates the PDF.
  2659. * @param $creator (string) The name of the creator.
  2660. * @public
  2661. * @since 1.2
  2662. * @see SetAuthor(), SetKeywords(), SetSubject(), SetTitle()
  2663. */
  2664. public function SetCreator($creator) {
  2665. $this->creator = $creator;
  2666. }
  2667. /**
  2668. * Whether to allow local file path in image html tags, when prefixed with file://
  2669. *
  2670. * @param $allowLocalFiles bool true, when local files should be allowed. Otherwise false.
  2671. * @public
  2672. * @since 6.4
  2673. */
  2674. public function SetAllowLocalFiles($allowLocalFiles) {
  2675. $this->allowLocalFiles = (bool) $allowLocalFiles;
  2676. }
  2677. /**
  2678. * Throw an exception or print an error message and die if the K_TCPDF_PARSER_THROW_EXCEPTION_ERROR constant is set to true.
  2679. * @param $msg (string) The error message
  2680. * @public
  2681. * @since 1.0
  2682. */
  2683. public function Error($msg) {
  2684. // unset all class variables
  2685. $this->_destroy(true);
  2686. if (defined('K_TCPDF_THROW_EXCEPTION_ERROR') AND !K_TCPDF_THROW_EXCEPTION_ERROR) {
  2687. die('<strong>TCPDF ERROR: </strong>'.$msg);
  2688. } else {
  2689. throw new Exception('TCPDF ERROR: '.$msg);
  2690. }
  2691. }
  2692. /**
  2693. * This method begins the generation of the PDF document.
  2694. * It is not necessary to call it explicitly because AddPage() does it automatically.
  2695. * Note: no page is created by this method
  2696. * @public
  2697. * @since 1.0
  2698. * @see AddPage(), Close()
  2699. */
  2700. public function Open() {
  2701. $this->state = 1;
  2702. }
  2703. /**
  2704. * Terminates the PDF document.
  2705. * It is not necessary to call this method explicitly because Output() does it automatically.
  2706. * If the document contains no page, AddPage() is called to prevent from getting an invalid document.
  2707. * @public
  2708. * @since 1.0
  2709. * @see Open(), Output()
  2710. */
  2711. public function Close() {
  2712. if ($this->state == 3) {
  2713. return;
  2714. }
  2715. if ($this->page == 0) {
  2716. $this->AddPage();
  2717. }
  2718. $this->endLayer();
  2719. if ($this->tcpdflink) {
  2720. // save current graphic settings
  2721. $gvars = $this->getGraphicVars();
  2722. $this->setEqualColumns();
  2723. $this->lastpage(true);
  2724. $this->SetAutoPageBreak(false);
  2725. $this->x = 0;
  2726. $this->y = $this->h - (1 / $this->k);
  2727. $this->lMargin = 0;
  2728. $this->_outSaveGraphicsState();
  2729. $font = defined('PDF_FONT_NAME_MAIN')?PDF_FONT_NAME_MAIN:'helvetica';
  2730. $this->SetFont($font, '', 1);
  2731. $this->setTextRenderingMode(0, false, false);
  2732. $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";
  2733. $lnk = "\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x74\x63\x70\x64\x66\x2e\x6f\x72\x67";
  2734. $this->Cell(0, 0, $msg, 0, 0, 'L', 0, $lnk, 0, false, 'D', 'B');
  2735. $this->_outRestoreGraphicsState();
  2736. // restore graphic settings
  2737. $this->setGraphicVars($gvars);
  2738. }
  2739. // close page
  2740. $this->endPage();
  2741. // close document
  2742. $this->_enddoc();
  2743. // unset all class variables (except critical ones)
  2744. $this->_destroy(false);
  2745. }
  2746. /**
  2747. * Move pointer at the specified document page and update page dimensions.
  2748. * @param $pnum (int) page number (1 ... numpages)
  2749. * @param $resetmargins (boolean) if true reset left, right, top margins and Y position.
  2750. * @public
  2751. * @since 2.1.000 (2008-01-07)
  2752. * @see getPage(), lastpage(), getNumPages()
  2753. */
  2754. public function setPage($pnum, $resetmargins=false) {
  2755. if (($pnum == $this->page) AND ($this->state == 2)) {
  2756. return;
  2757. }
  2758. if (($pnum > 0) AND ($pnum <= $this->numpages)) {
  2759. $this->state = 2;
  2760. // save current graphic settings
  2761. //$gvars = $this->getGraphicVars();
  2762. $oldpage = $this->page;
  2763. $this->page = $pnum;
  2764. $this->wPt = $this->pagedim[$this->page]['w'];
  2765. $this->hPt = $this->pagedim[$this->page]['h'];
  2766. $this->w = $this->pagedim[$this->page]['wk'];
  2767. $this->h = $this->pagedim[$this->page]['hk'];
  2768. $this->tMargin = $this->pagedim[$this->page]['tm'];
  2769. $this->bMargin = $this->pagedim[$this->page]['bm'];
  2770. $this->original_lMargin = $this->pagedim[$this->page]['olm'];
  2771. $this->original_rMargin = $this->pagedim[$this->page]['orm'];
  2772. $this->AutoPageBreak = $this->pagedim[$this->page]['pb'];
  2773. $this->CurOrientation = $this->pagedim[$this->page]['or'];
  2774. $this->SetAutoPageBreak($this->AutoPageBreak, $this->bMargin);
  2775. // restore graphic settings
  2776. //$this->setGraphicVars($gvars);
  2777. if ($resetmargins) {
  2778. $this->lMargin = $this->pagedim[$this->page]['olm'];
  2779. $this->rMargin = $this->pagedim[$this->page]['orm'];
  2780. $this->SetY($this->tMargin);
  2781. } else {
  2782. // account for booklet mode
  2783. if ($this->pagedim[$this->page]['olm'] != $this->pagedim[$oldpage]['olm']) {
  2784. $deltam = $this->pagedim[$this->page]['olm'] - $this->pagedim[$this->page]['orm'];
  2785. $this->lMargin += $deltam;
  2786. $this->rMargin -= $deltam;
  2787. }
  2788. }
  2789. } else {
  2790. $this->Error('Wrong page number on setPage() function: '.$pnum);
  2791. }
  2792. }
  2793. /**
  2794. * Reset pointer to the last document page.
  2795. * @param $resetmargins (boolean) if true reset left, right, top margins and Y position.
  2796. * @public
  2797. * @since 2.0.000 (2008-01-04)
  2798. * @see setPage(), getPage(), getNumPages()
  2799. */
  2800. public function lastPage($resetmargins=false) {
  2801. $this->setPage($this->getNumPages(), $resetmargins);
  2802. }
  2803. /**
  2804. * Get current document page number.
  2805. * @return int page number
  2806. * @public
  2807. * @since 2.1.000 (2008-01-07)
  2808. * @see setPage(), lastpage(), getNumPages()
  2809. */
  2810. public function getPage() {
  2811. return $this->page;
  2812. }
  2813. /**
  2814. * Get the total number of insered pages.
  2815. * @return int number of pages
  2816. * @public
  2817. * @since 2.1.000 (2008-01-07)
  2818. * @see setPage(), getPage(), lastpage()
  2819. */
  2820. public function getNumPages() {
  2821. return $this->numpages;
  2822. }
  2823. /**
  2824. * Adds a new TOC (Table Of Content) page to the document.
  2825. * @param $orientation (string) page orientation.
  2826. * @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().
  2827. * @param $keepmargins (boolean) if true overwrites the default page margins with the current margins
  2828. * @public
  2829. * @since 5.0.001 (2010-05-06)
  2830. * @see AddPage(), startPage(), endPage(), endTOCPage()
  2831. */
  2832. public function addTOCPage($orientation='', $format='', $keepmargins=false) {
  2833. $this->AddPage($orientation, $format, $keepmargins, true);
  2834. }
  2835. /**
  2836. * Terminate the current TOC (Table Of Content) page
  2837. * @public
  2838. * @since 5.0.001 (2010-05-06)
  2839. * @see AddPage(), startPage(), endPage(), addTOCPage()
  2840. */
  2841. public function endTOCPage() {
  2842. $this->endPage(true);
  2843. }
  2844. /**
  2845. * 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).
  2846. * The origin of the coordinate system is at the top-left corner (or top-right for RTL) and increasing ordinates go downwards.
  2847. * @param $orientation (string) page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
  2848. * @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().
  2849. * @param $keepmargins (boolean) if true overwrites the default page margins with the current margins
  2850. * @param $tocpage (boolean) if true set the tocpage state to true (the added page will be used to display Table Of Content).
  2851. * @public
  2852. * @since 1.0
  2853. * @see startPage(), endPage(), addTOCPage(), endTOCPage(), getPageSizeFromFormat(), setPageFormat()
  2854. */
  2855. public function AddPage($orientation='', $format='', $keepmargins=false, $tocpage=false) {
  2856. if ($this->inxobj) {
  2857. // we are inside an XObject template
  2858. return;
  2859. }
  2860. if (!isset($this->original_lMargin) OR $keepmargins) {
  2861. $this->original_lMargin = $this->lMargin;
  2862. }
  2863. if (!isset($this->original_rMargin) OR $keepmargins) {
  2864. $this->original_rMargin = $this->rMargin;
  2865. }
  2866. // terminate previous page
  2867. $this->endPage();
  2868. // start new page
  2869. $this->startPage($orientation, $format, $tocpage);
  2870. }
  2871. /**
  2872. * Terminate the current page
  2873. * @param $tocpage (boolean) if true set the tocpage state to false (end the page used to display Table Of Content).
  2874. * @public
  2875. * @since 4.2.010 (2008-11-14)
  2876. * @see AddPage(), startPage(), addTOCPage(), endTOCPage()
  2877. */
  2878. public function endPage($tocpage=false) {
  2879. // check if page is already closed
  2880. if (($this->page == 0) OR ($this->numpages > $this->page) OR (!$this->pageopen[$this->page])) {
  2881. return;
  2882. }
  2883. // print page footer
  2884. $this->setFooter();
  2885. // close page
  2886. $this->_endpage();
  2887. // mark page as closed
  2888. $this->pageopen[$this->page] = false;
  2889. if ($tocpage) {
  2890. $this->tocpage = false;
  2891. }
  2892. }
  2893. /**
  2894. * Starts a new page to the document. The page must be closed using the endPage() function.
  2895. * The origin of the coordinate system is at the top-left corner and increasing ordinates go downwards.
  2896. * @param $orientation (string) page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
  2897. * @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().
  2898. * @param $tocpage (boolean) if true the page is designated to contain the Table-Of-Content.
  2899. * @since 4.2.010 (2008-11-14)
  2900. * @see AddPage(), endPage(), addTOCPage(), endTOCPage(), getPageSizeFromFormat(), setPageFormat()
  2901. * @public
  2902. */
  2903. public function startPage($orientation='', $format='', $tocpage=false) {
  2904. if ($tocpage) {
  2905. $this->tocpage = true;
  2906. }
  2907. // move page numbers of documents to be attached
  2908. if ($this->tocpage) {
  2909. // move reference to unexistent pages (used for page attachments)
  2910. // adjust outlines
  2911. $tmpoutlines = $this->outlines;
  2912. foreach ($tmpoutlines as $key => $outline) {
  2913. if (!$outline['f'] AND ($outline['p'] > $this->numpages)) {
  2914. $this->outlines[$key]['p'] = ($outline['p'] + 1);
  2915. }
  2916. }
  2917. // adjust dests
  2918. $tmpdests = $this->dests;
  2919. foreach ($tmpdests as $key => $dest) {
  2920. if (!$dest['f'] AND ($dest['p'] > $this->numpages)) {
  2921. $this->dests[$key]['p'] = ($dest['p'] + 1);
  2922. }
  2923. }
  2924. // adjust links
  2925. $tmplinks = $this->links;
  2926. foreach ($tmplinks as $key => $link) {
  2927. if (!$link['f'] AND ($link['p'] > $this->numpages)) {
  2928. $this->links[$key]['p'] = ($link['p'] + 1);
  2929. }
  2930. }
  2931. }
  2932. if ($this->numpages > $this->page) {
  2933. // this page has been already added
  2934. $this->setPage($this->page + 1);
  2935. $this->SetY($this->tMargin);
  2936. return;
  2937. }
  2938. // start a new page
  2939. if ($this->state == 0) {
  2940. $this->Open();
  2941. }
  2942. ++$this->numpages;
  2943. $this->swapMargins($this->booklet);
  2944. // save current graphic settings
  2945. $gvars = $this->getGraphicVars();
  2946. // start new page
  2947. $this->_beginpage($orientation, $format);
  2948. // mark page as open
  2949. $this->pageopen[$this->page] = true;
  2950. // restore graphic settings
  2951. $this->setGraphicVars($gvars);
  2952. // mark this point
  2953. $this->setPageMark();
  2954. // print page header
  2955. $this->setHeader();
  2956. // restore graphic settings
  2957. $this->setGraphicVars($gvars);
  2958. // mark this point
  2959. $this->setPageMark();
  2960. // print table header (if any)
  2961. $this->setTableHeader();
  2962. // set mark for empty page check
  2963. $this->emptypagemrk[$this->page]= $this->pagelen[$this->page];
  2964. }
  2965. /**
  2966. * Set start-writing mark on current page stream used to put borders and fills.
  2967. * Borders and fills are always created after content and inserted on the position marked by this method.
  2968. * This function must be called after calling Image() function for a background image.
  2969. * Background images must be always inserted before calling Multicell() or WriteHTMLCell() or WriteHTML() functions.
  2970. * @public
  2971. * @since 4.0.016 (2008-07-30)
  2972. */
  2973. public function setPageMark() {
  2974. $this->intmrk[$this->page] = $this->pagelen[$this->page];
  2975. $this->bordermrk[$this->page] = $this->intmrk[$this->page];
  2976. $this->setContentMark();
  2977. }
  2978. /**
  2979. * Set start-writing mark on selected page.
  2980. * Borders and fills are always created after content and inserted on the position marked by this method.
  2981. * @param $page (int) page number (default is the current page)
  2982. * @protected
  2983. * @since 4.6.021 (2009-07-20)
  2984. */
  2985. protected function setContentMark($page=0) {
  2986. if ($page <= 0) {
  2987. $page = $this->page;
  2988. }
  2989. if (isset($this->footerlen[$page])) {
  2990. $this->cntmrk[$page] = $this->pagelen[$page] - $this->footerlen[$page];
  2991. } else {
  2992. $this->cntmrk[$page] = $this->pagelen[$page];
  2993. }
  2994. }
  2995. /**
  2996. * Set header data.
  2997. * @param $ln (string) header image logo
  2998. * @param $lw (string) header image logo width in mm
  2999. * @param $ht (string) string to print as title on document header
  3000. * @param $hs (string) string to print on document header
  3001. * @param $tc (array) RGB array color for text.
  3002. * @param $lc (array) RGB array color for line.
  3003. * @public
  3004. */
  3005. public function setHeaderData($ln='', $lw=0, $ht='', $hs='', $tc=array(0,0,0), $lc=array(0,0,0)) {
  3006. $this->header_logo = $ln;
  3007. $this->header_logo_width = $lw;
  3008. $this->header_title = $ht;
  3009. $this->header_string = $hs;
  3010. $this->header_text_color = $tc;
  3011. $this->header_line_color = $lc;
  3012. }
  3013. /**
  3014. * Set footer data.
  3015. * @param $tc (array) RGB array color for text.
  3016. * @param $lc (array) RGB array color for line.
  3017. * @public
  3018. */
  3019. public function setFooterData($tc=array(0,0,0), $lc=array(0,0,0)) {
  3020. $this->footer_text_color = $tc;
  3021. $this->footer_line_color = $lc;
  3022. }
  3023. /**
  3024. * Returns header data:
  3025. * <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>
  3026. * @return array()
  3027. * @public
  3028. * @since 4.0.012 (2008-07-24)
  3029. */
  3030. public function getHeaderData() {
  3031. $ret = array();
  3032. $ret['logo'] = $this->header_logo;
  3033. $ret['logo_width'] = $this->header_logo_width;
  3034. $ret['title'] = $this->header_title;
  3035. $ret['string'] = $this->header_string;
  3036. $ret['text_color'] = $this->header_text_color;
  3037. $ret['line_color'] = $this->header_line_color;
  3038. return $ret;
  3039. }
  3040. /**
  3041. * Set header margin.
  3042. * (minimum distance between header and top page margin)
  3043. * @param $hm (int) distance in user units
  3044. * @public
  3045. */
  3046. public function setHeaderMargin($hm=10) {
  3047. $this->header_margin = $hm;
  3048. }
  3049. /**
  3050. * Returns header margin in user units.
  3051. * @return float
  3052. * @since 4.0.012 (2008-07-24)
  3053. * @public
  3054. */
  3055. public function getHeaderMargin() {
  3056. return $this->header_margin;
  3057. }
  3058. /**
  3059. * Set footer margin.
  3060. * (minimum distance between footer and bottom page margin)
  3061. * @param $fm (int) distance in user units
  3062. * @public
  3063. */
  3064. public function setFooterMargin($fm=10) {
  3065. $this->footer_margin = $fm;
  3066. }
  3067. /**
  3068. * Returns footer margin in user units.
  3069. * @return float
  3070. * @since 4.0.012 (2008-07-24)
  3071. * @public
  3072. */
  3073. public function getFooterMargin() {
  3074. return $this->footer_margin;
  3075. }
  3076. /**
  3077. * Set a flag to print page header.
  3078. * @param $val (boolean) set to true to print the page header (default), false otherwise.
  3079. * @public
  3080. */
  3081. public function setPrintHeader($val=true) {
  3082. $this->print_header = $val ? true : false;
  3083. }
  3084. /**
  3085. * Set a flag to print page footer.
  3086. * @param $val (boolean) set to true to print the page footer (default), false otherwise.
  3087. * @public
  3088. */
  3089. public function setPrintFooter($val=true) {
  3090. $this->print_footer = $val ? true : false;
  3091. }
  3092. /**
  3093. * Return the right-bottom (or left-bottom for RTL) corner X coordinate of last inserted image
  3094. * @return float
  3095. * @public
  3096. */
  3097. public function getImageRBX() {
  3098. return $this->img_rb_x;
  3099. }
  3100. /**
  3101. * Return the right-bottom (or left-bottom for RTL) corner Y coordinate of last inserted image
  3102. * @return float
  3103. * @public
  3104. */
  3105. public function getImageRBY() {
  3106. return $this->img_rb_y;
  3107. }
  3108. /**
  3109. * Reset the xobject template used by Header() method.
  3110. * @public
  3111. */
  3112. public function resetHeaderTemplate() {
  3113. $this->header_xobjid = false;
  3114. }
  3115. /**
  3116. * Set a flag to automatically reset the xobject template used by Header() method at each page.
  3117. * @param $val (boolean) set to true to reset Header xobject template at each page, false otherwise.
  3118. * @public
  3119. */
  3120. public function setHeaderTemplateAutoreset($val=true) {
  3121. $this->header_xobj_autoreset = $val ? true : false;
  3122. }
  3123. /**
  3124. * This method is used to render the page header.
  3125. * It is automatically called by AddPage() and could be overwritten in your own inherited class.
  3126. * @public
  3127. */
  3128. public function Header() {
  3129. if ($this->header_xobjid === false) {
  3130. // start a new XObject Template
  3131. $this->header_xobjid = $this->startTemplate($this->w, $this->tMargin);
  3132. $headerfont = $this->getHeaderFont();
  3133. $headerdata = $this->getHeaderData();
  3134. $this->y = $this->header_margin;
  3135. if ($this->rtl) {
  3136. $this->x = $this->w - $this->original_rMargin;
  3137. } else {
  3138. $this->x = $this->original_lMargin;
  3139. }
  3140. if (($headerdata['logo']) AND ($headerdata['logo'] != K_BLANK_IMAGE)) {
  3141. $imgtype = TCPDF_IMAGES::getImageFileType(K_PATH_IMAGES.$headerdata['logo']);
  3142. if (($imgtype == 'eps') OR ($imgtype == 'ai')) {
  3143. $this->ImageEps(K_PATH_IMAGES.$headerdata['logo'], '', '', $headerdata['logo_width']);
  3144. } elseif ($imgtype == 'svg') {
  3145. $this->ImageSVG(K_PATH_IMAGES.$headerdata['logo'], '', '', $headerdata['logo_width']);
  3146. } else {
  3147. $this->Image(K_PATH_IMAGES.$headerdata['logo'], '', '', $headerdata['logo_width']);
  3148. }
  3149. $imgy = $this->getImageRBY();
  3150. } else {
  3151. $imgy = $this->y;
  3152. }
  3153. $cell_height = $this->getCellHeight($headerfont[2] / $this->k);
  3154. // set starting margin for text data cell
  3155. if ($this->getRTL()) {
  3156. $header_x = $this->original_rMargin + ($headerdata['logo_width'] * 1.1);
  3157. } else {
  3158. $header_x = $this->original_lMargin + ($headerdata['logo_width'] * 1.1);
  3159. }
  3160. $cw = $this->w - $this->original_lMargin - $this->original_rMargin - ($headerdata['logo_width'] * 1.1);
  3161. $this->SetTextColorArray($this->header_text_color);
  3162. // header title
  3163. $this->SetFont($headerfont[0], 'B', $headerfont[2] + 1);
  3164. $this->SetX($header_x);
  3165. $this->Cell($cw, $cell_height, $headerdata['title'], 0, 1, '', 0, '', 0);
  3166. // header string
  3167. $this->SetFont($headerfont[0], $headerfont[1], $headerfont[2]);
  3168. $this->SetX($header_x);
  3169. $this->MultiCell($cw, $cell_height, $headerdata['string'], 0, '', 0, 1, '', '', true, 0, false, true, 0, 'T', false);
  3170. // print an ending header line
  3171. $this->SetLineStyle(array('width' => 0.85 / $this->k, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => $headerdata['line_color']));
  3172. $this->SetY((2.835 / $this->k) + max($imgy, $this->y));
  3173. if ($this->rtl) {
  3174. $this->SetX($this->original_rMargin);
  3175. } else {
  3176. $this->SetX($this->original_lMargin);
  3177. }
  3178. $this->Cell(($this->w - $this->original_lMargin - $this->original_rMargin), 0, '', 'T', 0, 'C');
  3179. $this->endTemplate();
  3180. }
  3181. // print header template
  3182. $x = 0;
  3183. $dx = 0;
  3184. if (!$this->header_xobj_autoreset AND $this->booklet AND (($this->page % 2) == 0)) {
  3185. // adjust margins for booklet mode
  3186. $dx = ($this->original_lMargin - $this->original_rMargin);
  3187. }
  3188. if ($this->rtl) {
  3189. $x = $this->w + $dx;
  3190. } else {
  3191. $x = 0 + $dx;
  3192. }
  3193. $this->printTemplate($this->header_xobjid, $x, 0, 0, 0, '', '', false);
  3194. if ($this->header_xobj_autoreset) {
  3195. // reset header xobject template at each page
  3196. $this->header_xobjid = false;
  3197. }
  3198. }
  3199. /**
  3200. * This method is used to render the page footer.
  3201. * It is automatically called by AddPage() and could be overwritten in your own inherited class.
  3202. * @public
  3203. */
  3204. public function Footer() {
  3205. $cur_y = $this->y;
  3206. $this->SetTextColorArray($this->footer_text_color);
  3207. //set style for cell border
  3208. $line_width = (0.85 / $this->k);
  3209. $this->SetLineStyle(array('width' => $line_width, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => $this->footer_line_color));
  3210. //print document barcode
  3211. $barcode = $this->getBarcode();
  3212. if (!empty($barcode)) {
  3213. $this->Ln($line_width);
  3214. $barcode_width = round(($this->w - $this->original_lMargin - $this->original_rMargin) / 3);
  3215. $style = array(
  3216. 'position' => $this->rtl?'R':'L',
  3217. 'align' => $this->rtl?'R':'L',
  3218. 'stretch' => false,
  3219. 'fitwidth' => true,
  3220. 'cellfitalign' => '',
  3221. 'border' => false,
  3222. 'padding' => 0,
  3223. 'fgcolor' => array(0,0,0),
  3224. 'bgcolor' => false,
  3225. 'text' => false
  3226. );
  3227. $this->write1DBarcode($barcode, 'C128', '', $cur_y + $line_width, '', (($this->footer_margin / 3) - $line_width), 0.3, $style, '');
  3228. }
  3229. $w_page = isset($this->l['w_page']) ? $this->l['w_page'].' ' : '';
  3230. if (empty($this->pagegroups)) {
  3231. $pagenumtxt = $w_page.$this->getAliasNumPage().' / '.$this->getAliasNbPages();
  3232. } else {
  3233. $pagenumtxt = $w_page.$this->getPageNumGroupAlias().' / '.$this->getPageGroupAlias();
  3234. }
  3235. $this->SetY($cur_y);
  3236. //Print page number
  3237. if ($this->getRTL()) {
  3238. $this->SetX($this->original_rMargin);
  3239. $this->Cell(0, 0, $pagenumtxt, 'T', 0, 'L');
  3240. } else {
  3241. $this->SetX($this->original_lMargin);
  3242. $this->Cell(0, 0, $this->getAliasRightShift().$pagenumtxt, 'T', 0, 'R');
  3243. }
  3244. }
  3245. /**
  3246. * This method is used to render the page header.
  3247. * @protected
  3248. * @since 4.0.012 (2008-07-24)
  3249. */
  3250. protected function setHeader() {
  3251. if (!$this->print_header OR ($this->state != 2)) {
  3252. return;
  3253. }
  3254. $this->InHeader = true;
  3255. $this->setGraphicVars($this->default_graphic_vars);
  3256. $temp_thead = $this->thead;
  3257. $temp_theadMargins = $this->theadMargins;
  3258. $lasth = $this->lasth;
  3259. $newline = $this->newline;
  3260. $this->_outSaveGraphicsState();
  3261. $this->rMargin = $this->original_rMargin;
  3262. $this->lMargin = $this->original_lMargin;
  3263. $this->SetCellPadding(0);
  3264. //set current position
  3265. if ($this->rtl) {
  3266. $this->SetXY($this->original_rMargin, $this->header_margin);
  3267. } else {
  3268. $this->SetXY($this->original_lMargin, $this->header_margin);
  3269. }
  3270. $this->SetFont($this->header_font[0], $this->header_font[1], $this->header_font[2]);
  3271. $this->Header();
  3272. //restore position
  3273. if ($this->rtl) {
  3274. $this->SetXY($this->original_rMargin, $this->tMargin);
  3275. } else {
  3276. $this->SetXY($this->original_lMargin, $this->tMargin);
  3277. }
  3278. $this->_outRestoreGraphicsState();
  3279. $this->lasth = $lasth;
  3280. $this->thead = $temp_thead;
  3281. $this->theadMargins = $temp_theadMargins;
  3282. $this->newline = $newline;
  3283. $this->InHeader = false;
  3284. }
  3285. /**
  3286. * This method is used to render the page footer.
  3287. * @protected
  3288. * @since 4.0.012 (2008-07-24)
  3289. */
  3290. protected function setFooter() {
  3291. if ($this->state != 2) {
  3292. return;
  3293. }
  3294. $this->InFooter = true;
  3295. // save current graphic settings
  3296. $gvars = $this->getGraphicVars();
  3297. // mark this point
  3298. $this->footerpos[$this->page] = $this->pagelen[$this->page];
  3299. $this->_out("\n");
  3300. if ($this->print_footer) {
  3301. $this->setGraphicVars($this->default_graphic_vars);
  3302. $this->current_column = 0;
  3303. $this->num_columns = 1;
  3304. $temp_thead = $this->thead;
  3305. $temp_theadMargins = $this->theadMargins;
  3306. $lasth = $this->lasth;
  3307. $this->_outSaveGraphicsState();
  3308. $this->rMargin = $this->original_rMargin;
  3309. $this->lMargin = $this->original_lMargin;
  3310. $this->SetCellPadding(0);
  3311. //set current position
  3312. $footer_y = $this->h - $this->footer_margin;
  3313. if ($this->rtl) {
  3314. $this->SetXY($this->original_rMargin, $footer_y);
  3315. } else {
  3316. $this->SetXY($this->original_lMargin, $footer_y);
  3317. }
  3318. $this->SetFont($this->footer_font[0], $this->footer_font[1], $this->footer_font[2]);
  3319. $this->Footer();
  3320. //restore position
  3321. if ($this->rtl) {
  3322. $this->SetXY($this->original_rMargin, $this->tMargin);
  3323. } else {
  3324. $this->SetXY($this->original_lMargin, $this->tMargin);
  3325. }
  3326. $this->_outRestoreGraphicsState();
  3327. $this->lasth = $lasth;
  3328. $this->thead = $temp_thead;
  3329. $this->theadMargins = $temp_theadMargins;
  3330. }
  3331. // restore graphic settings
  3332. $this->setGraphicVars($gvars);
  3333. $this->current_column = $gvars['current_column'];
  3334. $this->num_columns = $gvars['num_columns'];
  3335. // calculate footer length
  3336. $this->footerlen[$this->page] = $this->pagelen[$this->page] - $this->footerpos[$this->page] + 1;
  3337. $this->InFooter = false;
  3338. }
  3339. /**
  3340. * Check if we are on the page body (excluding page header and footer).
  3341. * @return true if we are not in page header nor in page footer, false otherwise.
  3342. * @protected
  3343. * @since 5.9.091 (2011-06-15)
  3344. */
  3345. protected function inPageBody() {
  3346. return (($this->InHeader === false) AND ($this->InFooter === false));
  3347. }
  3348. /**
  3349. * This method is used to render the table header on new page (if any).
  3350. * @protected
  3351. * @since 4.5.030 (2009-03-25)
  3352. */
  3353. protected function setTableHeader() {
  3354. if ($this->num_columns > 1) {
  3355. // multi column mode
  3356. return;
  3357. }
  3358. if (isset($this->theadMargins['top'])) {
  3359. // restore the original top-margin
  3360. $this->tMargin = $this->theadMargins['top'];
  3361. $this->pagedim[$this->page]['tm'] = $this->tMargin;
  3362. $this->y = $this->tMargin;
  3363. }
  3364. if (!TCPDF_STATIC::empty_string($this->thead) AND (!$this->inthead)) {
  3365. // set margins
  3366. $prev_lMargin = $this->lMargin;
  3367. $prev_rMargin = $this->rMargin;
  3368. $prev_cell_padding = $this->cell_padding;
  3369. $this->lMargin = $this->theadMargins['lmargin'] + ($this->pagedim[$this->page]['olm'] - $this->pagedim[$this->theadMargins['page']]['olm']);
  3370. $this->rMargin = $this->theadMargins['rmargin'] + ($this->pagedim[$this->page]['orm'] - $this->pagedim[$this->theadMargins['page']]['orm']);
  3371. $this->cell_padding = $this->theadMargins['cell_padding'];
  3372. if ($this->rtl) {
  3373. $this->x = $this->w - $this->rMargin;
  3374. } else {
  3375. $this->x = $this->lMargin;
  3376. }
  3377. // account for special "cell" mode
  3378. if ($this->theadMargins['cell']) {
  3379. if ($this->rtl) {
  3380. $this->x -= $this->cell_padding['R'];
  3381. } else {
  3382. $this->x += $this->cell_padding['L'];
  3383. }
  3384. }
  3385. $gvars = $this->getGraphicVars();
  3386. if (!empty($this->theadMargins['gvars'])) {
  3387. // set the correct graphic style
  3388. $this->setGraphicVars($this->theadMargins['gvars']);
  3389. $this->rMargin = $gvars['rMargin'];
  3390. $this->lMargin = $gvars['lMargin'];
  3391. }
  3392. // print table header
  3393. $this->writeHTML($this->thead, false, false, false, false, '');
  3394. $this->setGraphicVars($gvars);
  3395. // set new top margin to skip the table headers
  3396. if (!isset($this->theadMargins['top'])) {
  3397. $this->theadMargins['top'] = $this->tMargin;
  3398. }
  3399. // store end of header position
  3400. if (!isset($this->columns[0]['th'])) {
  3401. $this->columns[0]['th'] = array();
  3402. }
  3403. $this->columns[0]['th']['\''.$this->page.'\''] = $this->y;
  3404. $this->tMargin = $this->y;
  3405. $this->pagedim[$this->page]['tm'] = $this->tMargin;
  3406. $this->lasth = 0;
  3407. $this->lMargin = $prev_lMargin;
  3408. $this->rMargin = $prev_rMargin;
  3409. $this->cell_padding = $prev_cell_padding;
  3410. }
  3411. }
  3412. /**
  3413. * Returns the current page number.
  3414. * @return int page number
  3415. * @public
  3416. * @since 1.0
  3417. * @see getAliasNbPages()
  3418. */
  3419. public function PageNo() {
  3420. return $this->page;
  3421. }
  3422. /**
  3423. * Returns the array of spot colors.
  3424. * @return (array) Spot colors array.
  3425. * @public
  3426. * @since 6.0.038 (2013-09-30)
  3427. */
  3428. public function getAllSpotColors() {
  3429. return $this->spot_colors;
  3430. }
  3431. /**
  3432. * Defines a new spot color.
  3433. * It can be expressed in RGB components or gray scale.
  3434. * The method can be called before the first page is created and the value is retained from page to page.
  3435. * @param $name (string) Full name of the spot color.
  3436. * @param $c (float) Cyan color for CMYK. Value between 0 and 100.
  3437. * @param $m (float) Magenta color for CMYK. Value between 0 and 100.
  3438. * @param $y (float) Yellow color for CMYK. Value between 0 and 100.
  3439. * @param $k (float) Key (Black) color for CMYK. Value between 0 and 100.
  3440. * @public
  3441. * @since 4.0.024 (2008-09-12)
  3442. * @see SetDrawSpotColor(), SetFillSpotColor(), SetTextSpotColor()
  3443. */
  3444. public function AddSpotColor($name, $c, $m, $y, $k) {
  3445. if (!isset($this->spot_colors[$name])) {
  3446. $i = (1 + count($this->spot_colors));
  3447. $this->spot_colors[$name] = array('C' => $c, 'M' => $m, 'Y' => $y, 'K' => $k, 'name' => $name, 'i' => $i);
  3448. }
  3449. }
  3450. /**
  3451. * Set the spot color for the specified type ('draw', 'fill', 'text').
  3452. * @param $type (string) Type of object affected by this color: ('draw', 'fill', 'text').
  3453. * @param $name (string) Name of the spot color.
  3454. * @param $tint (float) Intensity of the color (from 0 to 100 ; 100 = full intensity by default).
  3455. * @return (string) PDF color command.
  3456. * @public
  3457. * @since 5.9.125 (2011-10-03)
  3458. */
  3459. public function setSpotColor($type, $name, $tint=100) {
  3460. $spotcolor = TCPDF_COLORS::getSpotColor($name, $this->spot_colors);
  3461. if ($spotcolor === false) {
  3462. $this->Error('Undefined spot color: '.$name.', you must add it using the AddSpotColor() method.');
  3463. }
  3464. $tint = (max(0, min(100, $tint)) / 100);
  3465. $pdfcolor = sprintf('/CS%d ', $this->spot_colors[$name]['i']);
  3466. switch ($type) {
  3467. case 'draw': {
  3468. $pdfcolor .= sprintf('CS %F SCN', $tint);
  3469. $this->DrawColor = $pdfcolor;
  3470. $this->strokecolor = $spotcolor;
  3471. break;
  3472. }
  3473. case 'fill': {
  3474. $pdfcolor .= sprintf('cs %F scn', $tint);
  3475. $this->FillColor = $pdfcolor;
  3476. $this->bgcolor = $spotcolor;
  3477. break;
  3478. }
  3479. case 'text': {
  3480. $pdfcolor .= sprintf('cs %F scn', $tint);
  3481. $this->TextColor = $pdfcolor;
  3482. $this->fgcolor = $spotcolor;
  3483. break;
  3484. }
  3485. }
  3486. $this->ColorFlag = ($this->FillColor != $this->TextColor);
  3487. if ($this->state == 2) {
  3488. $this->_out($pdfcolor);
  3489. }
  3490. if ($this->inxobj) {
  3491. // we are inside an XObject template
  3492. $this->xobjects[$this->xobjid]['spot_colors'][$name] = $this->spot_colors[$name];
  3493. }
  3494. return $pdfcolor;
  3495. }
  3496. /**
  3497. * Defines the spot color used for all drawing operations (lines, rectangles and cell borders).
  3498. * @param $name (string) Name of the spot color.
  3499. * @param $tint (float) Intensity of the color (from 0 to 100 ; 100 = full intensity by default).
  3500. * @public
  3501. * @since 4.0.024 (2008-09-12)
  3502. * @see AddSpotColor(), SetFillSpotColor(), SetTextSpotColor()
  3503. */
  3504. public function SetDrawSpotColor($name, $tint=100) {
  3505. $this->setSpotColor('draw', $name, $tint);
  3506. }
  3507. /**
  3508. * Defines the spot color used for all filling operations (filled rectangles and cell backgrounds).
  3509. * @param $name (string) Name of the spot color.
  3510. * @param $tint (float) Intensity of the color (from 0 to 100 ; 100 = full intensity by default).
  3511. * @public
  3512. * @since 4.0.024 (2008-09-12)
  3513. * @see AddSpotColor(), SetDrawSpotColor(), SetTextSpotColor()
  3514. */
  3515. public function SetFillSpotColor($name, $tint=100) {
  3516. $this->setSpotColor('fill', $name, $tint);
  3517. }
  3518. /**
  3519. * Defines the spot color used for text.
  3520. * @param $name (string) Name of the spot color.
  3521. * @param $tint (int) Intensity of the color (from 0 to 100 ; 100 = full intensity by default).
  3522. * @public
  3523. * @since 4.0.024 (2008-09-12)
  3524. * @see AddSpotColor(), SetDrawSpotColor(), SetFillSpotColor()
  3525. */
  3526. public function SetTextSpotColor($name, $tint=100) {
  3527. $this->setSpotColor('text', $name, $tint);
  3528. }
  3529. /**
  3530. * Set the color array for the specified type ('draw', 'fill', 'text').
  3531. * It can be expressed in RGB, CMYK or GRAY SCALE components.
  3532. * The method can be called before the first page is created and the value is retained from page to page.
  3533. * @param $type (string) Type of object affected by this color: ('draw', 'fill', 'text').
  3534. * @param $color (array) Array of colors (1=gray, 3=RGB, 4=CMYK or 5=spotcolor=CMYK+name values).
  3535. * @param $ret (boolean) If true do not send the PDF command.
  3536. * @return (string) The PDF command or empty string.
  3537. * @public
  3538. * @since 3.1.000 (2008-06-11)
  3539. */
  3540. public function setColorArray($type, $color, $ret=false) {
  3541. if (is_array($color)) {
  3542. $color = array_values($color);
  3543. // component: grey, RGB red or CMYK cyan
  3544. $c = isset($color[0]) ? $color[0] : -1;
  3545. // component: RGB green or CMYK magenta
  3546. $m = isset($color[1]) ? $color[1] : -1;
  3547. // component: RGB blue or CMYK yellow
  3548. $y = isset($color[2]) ? $color[2] : -1;
  3549. // component: CMYK black
  3550. $k = isset($color[3]) ? $color[3] : -1;
  3551. // color name
  3552. $name = isset($color[4]) ? $color[4] : '';
  3553. if ($c >= 0) {
  3554. return $this->setColor($type, $c, $m, $y, $k, $ret, $name);
  3555. }
  3556. }
  3557. return '';
  3558. }
  3559. /**
  3560. * Defines the color used for all drawing operations (lines, rectangles and cell borders).
  3561. * It can be expressed in RGB, CMYK or GRAY SCALE components.
  3562. * The method can be called before the first page is created and the value is retained from page to page.
  3563. * @param $color (array) Array of colors (1, 3 or 4 values).
  3564. * @param $ret (boolean) If true do not send the PDF command.
  3565. * @return string the PDF command
  3566. * @public
  3567. * @since 3.1.000 (2008-06-11)
  3568. * @see SetDrawColor()
  3569. */
  3570. public function SetDrawColorArray($color, $ret=false) {
  3571. return $this->setColorArray('draw', $color, $ret);
  3572. }
  3573. /**
  3574. * Defines the color used for all filling operations (filled rectangles and cell backgrounds).
  3575. * It can be expressed in RGB, CMYK or GRAY SCALE components.
  3576. * The method can be called before the first page is created and the value is retained from page to page.
  3577. * @param $color (array) Array of colors (1, 3 or 4 values).
  3578. * @param $ret (boolean) If true do not send the PDF command.
  3579. * @public
  3580. * @since 3.1.000 (2008-6-11)
  3581. * @see SetFillColor()
  3582. */
  3583. public function SetFillColorArray($color, $ret=false) {
  3584. return $this->setColorArray('fill', $color, $ret);
  3585. }
  3586. /**
  3587. * Defines the color used for text. It can be expressed in RGB components or gray scale.
  3588. * The method can be called before the first page is created and the value is retained from page to page.
  3589. * @param $color (array) Array of colors (1, 3 or 4 values).
  3590. * @param $ret (boolean) If true do not send the PDF command.
  3591. * @public
  3592. * @since 3.1.000 (2008-6-11)
  3593. * @see SetFillColor()
  3594. */
  3595. public function SetTextColorArray($color, $ret=false) {
  3596. return $this->setColorArray('text', $color, $ret);
  3597. }
  3598. /**
  3599. * Defines the color used by the specified type ('draw', 'fill', 'text').
  3600. * @param $type (string) Type of object affected by this color: ('draw', 'fill', 'text').
  3601. * @param $col1 (float) GRAY level for single color, or Red color for RGB (0-255), or CYAN color for CMYK (0-100).
  3602. * @param $col2 (float) GREEN color for RGB (0-255), or MAGENTA color for CMYK (0-100).
  3603. * @param $col3 (float) BLUE color for RGB (0-255), or YELLOW color for CMYK (0-100).
  3604. * @param $col4 (float) KEY (BLACK) color for CMYK (0-100).
  3605. * @param $ret (boolean) If true do not send the command.
  3606. * @param $name (string) spot color name (if any)
  3607. * @return (string) The PDF command or empty string.
  3608. * @public
  3609. * @since 5.9.125 (2011-10-03)
  3610. */
  3611. public function setColor($type, $col1=0, $col2=-1, $col3=-1, $col4=-1, $ret=false, $name='') {
  3612. // set default values
  3613. if (!is_numeric($col1)) {
  3614. $col1 = 0;
  3615. }
  3616. if (!is_numeric($col2)) {
  3617. $col2 = -1;
  3618. }
  3619. if (!is_numeric($col3)) {
  3620. $col3 = -1;
  3621. }
  3622. if (!is_numeric($col4)) {
  3623. $col4 = -1;
  3624. }
  3625. // set color by case
  3626. $suffix = '';
  3627. if (($col2 == -1) AND ($col3 == -1) AND ($col4 == -1)) {
  3628. // Grey scale
  3629. $col1 = max(0, min(255, $col1));
  3630. $intcolor = array('G' => $col1);
  3631. $pdfcolor = sprintf('%F ', ($col1 / 255));
  3632. $suffix = 'g';
  3633. } elseif ($col4 == -1) {
  3634. // RGB
  3635. $col1 = max(0, min(255, $col1));
  3636. $col2 = max(0, min(255, $col2));
  3637. $col3 = max(0, min(255, $col3));
  3638. $intcolor = array('R' => $col1, 'G' => $col2, 'B' => $col3);
  3639. $pdfcolor = sprintf('%F %F %F ', ($col1 / 255), ($col2 / 255), ($col3 / 255));
  3640. $suffix = 'rg';
  3641. } else {
  3642. $col1 = max(0, min(100, $col1));
  3643. $col2 = max(0, min(100, $col2));
  3644. $col3 = max(0, min(100, $col3));
  3645. $col4 = max(0, min(100, $col4));
  3646. if (empty($name)) {
  3647. // CMYK
  3648. $intcolor = array('C' => $col1, 'M' => $col2, 'Y' => $col3, 'K' => $col4);
  3649. $pdfcolor = sprintf('%F %F %F %F ', ($col1 / 100), ($col2 / 100), ($col3 / 100), ($col4 / 100));
  3650. $suffix = 'k';
  3651. } else {
  3652. // SPOT COLOR
  3653. $intcolor = array('C' => $col1, 'M' => $col2, 'Y' => $col3, 'K' => $col4, 'name' => $name);
  3654. $this->AddSpotColor($name, $col1, $col2, $col3, $col4);
  3655. $pdfcolor = $this->setSpotColor($type, $name, 100);
  3656. }
  3657. }
  3658. switch ($type) {
  3659. case 'draw': {
  3660. $pdfcolor .= strtoupper($suffix);
  3661. $this->DrawColor = $pdfcolor;
  3662. $this->strokecolor = $intcolor;
  3663. break;
  3664. }
  3665. case 'fill': {
  3666. $pdfcolor .= $suffix;
  3667. $this->FillColor = $pdfcolor;
  3668. $this->bgcolor = $intcolor;
  3669. break;
  3670. }
  3671. case 'text': {
  3672. $pdfcolor .= $suffix;
  3673. $this->TextColor = $pdfcolor;
  3674. $this->fgcolor = $intcolor;
  3675. break;
  3676. }
  3677. }
  3678. $this->ColorFlag = ($this->FillColor != $this->TextColor);
  3679. if (($type != 'text') AND ($this->state == 2)) {
  3680. if (!$ret) {
  3681. $this->_out($pdfcolor);
  3682. }
  3683. return $pdfcolor;
  3684. }
  3685. return '';
  3686. }
  3687. /**
  3688. * 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.
  3689. * @param $col1 (float) GRAY level for single color, or Red color for RGB (0-255), or CYAN color for CMYK (0-100).
  3690. * @param $col2 (float) GREEN color for RGB (0-255), or MAGENTA color for CMYK (0-100).
  3691. * @param $col3 (float) BLUE color for RGB (0-255), or YELLOW color for CMYK (0-100).
  3692. * @param $col4 (float) KEY (BLACK) color for CMYK (0-100).
  3693. * @param $ret (boolean) If true do not send the command.
  3694. * @param $name (string) spot color name (if any)
  3695. * @return string the PDF command
  3696. * @public
  3697. * @since 1.3
  3698. * @see SetDrawColorArray(), SetFillColor(), SetTextColor(), Line(), Rect(), Cell(), MultiCell()
  3699. */
  3700. public function SetDrawColor($col1=0, $col2=-1, $col3=-1, $col4=-1, $ret=false, $name='') {
  3701. return $this->setColor('draw', $col1, $col2, $col3, $col4, $ret, $name);
  3702. }
  3703. /**
  3704. * 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.
  3705. * @param $col1 (float) GRAY level for single color, or Red color for RGB (0-255), or CYAN color for CMYK (0-100).
  3706. * @param $col2 (float) GREEN color for RGB (0-255), or MAGENTA color for CMYK (0-100).
  3707. * @param $col3 (float) BLUE color for RGB (0-255), or YELLOW color for CMYK (0-100).
  3708. * @param $col4 (float) KEY (BLACK) color for CMYK (0-100).
  3709. * @param $ret (boolean) If true do not send the command.
  3710. * @param $name (string) Spot color name (if any).
  3711. * @return (string) The PDF command.
  3712. * @public
  3713. * @since 1.3
  3714. * @see SetFillColorArray(), SetDrawColor(), SetTextColor(), Rect(), Cell(), MultiCell()
  3715. */
  3716. public function SetFillColor($col1=0, $col2=-1, $col3=-1, $col4=-1, $ret=false, $name='') {
  3717. return $this->setColor('fill', $col1, $col2, $col3, $col4, $ret, $name);
  3718. }
  3719. /**
  3720. * 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.
  3721. * @param $col1 (float) GRAY level for single color, or Red color for RGB (0-255), or CYAN color for CMYK (0-100).
  3722. * @param $col2 (float) GREEN color for RGB (0-255), or MAGENTA color for CMYK (0-100).
  3723. * @param $col3 (float) BLUE color for RGB (0-255), or YELLOW color for CMYK (0-100).
  3724. * @param $col4 (float) KEY (BLACK) color for CMYK (0-100).
  3725. * @param $ret (boolean) If true do not send the command.
  3726. * @param $name (string) Spot color name (if any).
  3727. * @return (string) Empty string.
  3728. * @public
  3729. * @since 1.3
  3730. * @see SetTextColorArray(), SetDrawColor(), SetFillColor(), Text(), Cell(), MultiCell()
  3731. */
  3732. public function SetTextColor($col1=0, $col2=-1, $col3=-1, $col4=-1, $ret=false, $name='') {
  3733. return $this->setColor('text', $col1, $col2, $col3, $col4, $ret, $name);
  3734. }
  3735. /**
  3736. * Returns the length of a string in user unit. A font must be selected.<br>
  3737. * @param $s (string) The string whose length is to be computed
  3738. * @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.
  3739. * @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.
  3740. * @param $fontsize (float) Font size in points. The default value is the current size.
  3741. * @param $getarray (boolean) if true returns an array of characters widths, if false returns the total length.
  3742. * @return mixed int total string length or array of characted widths
  3743. * @author Nicola Asuni
  3744. * @public
  3745. * @since 1.2
  3746. */
  3747. public function GetStringWidth($s, $fontname='', $fontstyle='', $fontsize=0, $getarray=false) {
  3748. 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);
  3749. }
  3750. /**
  3751. * Returns the string length of an array of chars in user unit or an array of characters widths. A font must be selected.<br>
  3752. * @param $sa (string) The array of chars whose total length is to be computed
  3753. * @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.
  3754. * @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.
  3755. * @param $fontsize (float) Font size in points. The default value is the current size.
  3756. * @param $getarray (boolean) if true returns an array of characters widths, if false returns the total length.
  3757. * @return mixed int total string length or array of characted widths
  3758. * @author Nicola Asuni
  3759. * @public
  3760. * @since 2.4.000 (2008-03-06)
  3761. */
  3762. public function GetArrStringWidth($sa, $fontname='', $fontstyle='', $fontsize=0, $getarray=false) {
  3763. // store current values
  3764. if (!TCPDF_STATIC::empty_string($fontname)) {
  3765. $prev_FontFamily = $this->FontFamily;
  3766. $prev_FontStyle = $this->FontStyle;
  3767. $prev_FontSizePt = $this->FontSizePt;
  3768. $this->SetFont($fontname, $fontstyle, $fontsize, '', 'default', false);
  3769. }
  3770. // convert UTF-8 array to Latin1 if required
  3771. if ($this->isunicode AND (!$this->isUnicodeFont())) {
  3772. $sa = TCPDF_FONTS::UTF8ArrToLatin1Arr($sa);
  3773. }
  3774. $w = 0; // total width
  3775. $wa = array(); // array of characters widths
  3776. foreach ($sa as $ck => $char) {
  3777. // character width
  3778. $cw = $this->GetCharWidth($char, isset($sa[($ck + 1)]));
  3779. $wa[] = $cw;
  3780. $w += $cw;
  3781. }
  3782. // restore previous values
  3783. if (!TCPDF_STATIC::empty_string($fontname)) {
  3784. $this->SetFont($prev_FontFamily, $prev_FontStyle, $prev_FontSizePt, '', 'default', false);
  3785. }
  3786. if ($getarray) {
  3787. return $wa;
  3788. }
  3789. return $w;
  3790. }
  3791. /**
  3792. * Returns the length of the char in user unit for the current font considering current stretching and spacing (tracking).
  3793. * @param $char (int) The char code whose length is to be returned
  3794. * @param $notlast (boolean) If false ignore the font-spacing.
  3795. * @return float char width
  3796. * @author Nicola Asuni
  3797. * @public
  3798. * @since 2.4.000 (2008-03-06)
  3799. */
  3800. public function GetCharWidth($char, $notlast=true) {
  3801. // get raw width
  3802. $chw = $this->getRawCharWidth($char);
  3803. if (($this->font_spacing < 0) OR (($this->font_spacing > 0) AND $notlast)) {
  3804. // increase/decrease font spacing
  3805. $chw += $this->font_spacing;
  3806. }
  3807. if ($this->font_stretching != 100) {
  3808. // fixed stretching mode
  3809. $chw *= ($this->font_stretching / 100);
  3810. }
  3811. return $chw;
  3812. }
  3813. /**
  3814. * Returns the length of the char in user unit for the current font.
  3815. * @param $char (int) The char code whose length is to be returned
  3816. * @return float char width
  3817. * @author Nicola Asuni
  3818. * @public
  3819. * @since 5.9.000 (2010-09-28)
  3820. */
  3821. public function getRawCharWidth($char) {
  3822. if ($char == 173) {
  3823. // SHY character will not be printed
  3824. return (0);
  3825. }
  3826. if (isset($this->CurrentFont['cw'][$char])) {
  3827. $w = $this->CurrentFont['cw'][$char];
  3828. } elseif (isset($this->CurrentFont['dw'])) {
  3829. // default width
  3830. $w = $this->CurrentFont['dw'];
  3831. } elseif (isset($this->CurrentFont['cw'][32])) {
  3832. // default width
  3833. $w = $this->CurrentFont['cw'][32];
  3834. } else {
  3835. $w = 600;
  3836. }
  3837. return $this->getAbsFontMeasure($w);
  3838. }
  3839. /**
  3840. * Returns the numbero of characters in a string.
  3841. * @param $s (string) The input string.
  3842. * @return int number of characters
  3843. * @public
  3844. * @since 2.0.0001 (2008-01-07)
  3845. */
  3846. public function GetNumChars($s) {
  3847. if ($this->isUnicodeFont()) {
  3848. return count(TCPDF_FONTS::UTF8StringToArray($s, $this->isunicode, $this->CurrentFont));
  3849. }
  3850. return strlen($s);
  3851. }
  3852. /**
  3853. * Fill the list of available fonts ($this->fontlist).
  3854. * @protected
  3855. * @since 4.0.013 (2008-07-28)
  3856. */
  3857. protected function getFontsList() {
  3858. if (($fontsdir = opendir(TCPDF_FONTS::_getfontpath())) !== false) {
  3859. while (($file = readdir($fontsdir)) !== false) {
  3860. if (substr($file, -4) == '.php') {
  3861. array_push($this->fontlist, strtolower(basename($file, '.php')));
  3862. }
  3863. }
  3864. closedir($fontsdir);
  3865. }
  3866. }
  3867. /**
  3868. * Imports a TrueType, Type1, core, or CID0 font and makes it available.
  3869. * It is necessary to generate a font definition file first (read /fonts/utils/README.TXT).
  3870. * 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.
  3871. * @param $family (string) Font family. The name can be chosen arbitrarily. If it is a standard family name, it will override the corresponding font.
  3872. * @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>
  3873. * @param $fontfile (string) The font definition file. By default, the name is built from the family and style, in lower case with no spaces.
  3874. * @return array containing the font data, or false in case of error.
  3875. * @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.
  3876. * @public
  3877. * @since 1.5
  3878. * @see SetFont(), setFontSubsetting()
  3879. */
  3880. public function AddFont($family, $style='', $fontfile='', $subset='default') {
  3881. if ($subset === 'default') {
  3882. $subset = $this->font_subsetting;
  3883. }
  3884. if ($this->pdfa_mode) {
  3885. $subset = false;
  3886. }
  3887. if (TCPDF_STATIC::empty_string($family)) {
  3888. if (!TCPDF_STATIC::empty_string($this->FontFamily)) {
  3889. $family = $this->FontFamily;
  3890. } else {
  3891. $this->Error('Empty font family');
  3892. }
  3893. }
  3894. // move embedded styles on $style
  3895. if (substr($family, -1) == 'I') {
  3896. $style .= 'I';
  3897. $family = substr($family, 0, -1);
  3898. }
  3899. if (substr($family, -1) == 'B') {
  3900. $style .= 'B';
  3901. $family = substr($family, 0, -1);
  3902. }
  3903. // normalize family name
  3904. $family = strtolower($family);
  3905. if ((!$this->isunicode) AND ($family == 'arial')) {
  3906. $family = 'helvetica';
  3907. }
  3908. if (($family == 'symbol') OR ($family == 'zapfdingbats')) {
  3909. $style = '';
  3910. }
  3911. if ($this->pdfa_mode AND (isset($this->CoreFonts[$family]))) {
  3912. // all fonts must be embedded
  3913. $family = 'pdfa'.$family;
  3914. }
  3915. $tempstyle = strtoupper($style);
  3916. $style = '';
  3917. // underline
  3918. if (strpos($tempstyle, 'U') !== false) {
  3919. $this->underline = true;
  3920. } else {
  3921. $this->underline = false;
  3922. }
  3923. // line-through (deleted)
  3924. if (strpos($tempstyle, 'D') !== false) {
  3925. $this->linethrough = true;
  3926. } else {
  3927. $this->linethrough = false;
  3928. }
  3929. // overline
  3930. if (strpos($tempstyle, 'O') !== false) {
  3931. $this->overline = true;
  3932. } else {
  3933. $this->overline = false;
  3934. }
  3935. // bold
  3936. if (strpos($tempstyle, 'B') !== false) {
  3937. $style .= 'B';
  3938. }
  3939. // oblique
  3940. if (strpos($tempstyle, 'I') !== false) {
  3941. $style .= 'I';
  3942. }
  3943. $bistyle = $style;
  3944. $fontkey = $family.$style;
  3945. $font_style = $style.($this->underline ? 'U' : '').($this->linethrough ? 'D' : '').($this->overline ? 'O' : '');
  3946. $fontdata = array('fontkey' => $fontkey, 'family' => $family, 'style' => $font_style);
  3947. // check if the font has been already added
  3948. $fb = $this->getFontBuffer($fontkey);
  3949. if ($fb !== false) {
  3950. if ($this->inxobj) {
  3951. // we are inside an XObject template
  3952. $this->xobjects[$this->xobjid]['fonts'][$fontkey] = $fb['i'];
  3953. }
  3954. return $fontdata;
  3955. }
  3956. // get specified font directory (if any)
  3957. $fontdir = false;
  3958. if (!TCPDF_STATIC::empty_string($fontfile)) {
  3959. $fontdir = dirname($fontfile);
  3960. if (TCPDF_STATIC::empty_string($fontdir) OR ($fontdir == '.')) {
  3961. $fontdir = '';
  3962. } else {
  3963. $fontdir .= '/';
  3964. }
  3965. }
  3966. // true when the font style variation is missing
  3967. $missing_style = false;
  3968. // search and include font file
  3969. if (TCPDF_STATIC::empty_string($fontfile) OR (!@TCPDF_STATIC::file_exists($fontfile))) {
  3970. // build a standard filenames for specified font
  3971. $tmp_fontfile = str_replace(' ', '', $family).strtolower($style).'.php';
  3972. $fontfile = TCPDF_FONTS::getFontFullPath($tmp_fontfile, $fontdir);
  3973. if (TCPDF_STATIC::empty_string($fontfile)) {
  3974. $missing_style = true;
  3975. // try to remove the style part
  3976. $tmp_fontfile = str_replace(' ', '', $family).'.php';
  3977. $fontfile = TCPDF_FONTS::getFontFullPath($tmp_fontfile, $fontdir);
  3978. }
  3979. }
  3980. // include font file
  3981. if (!TCPDF_STATIC::empty_string($fontfile) AND (@TCPDF_STATIC::file_exists($fontfile))) {
  3982. include($fontfile);
  3983. } else {
  3984. $this->Error('Could not include font definition file: '.$family.'');
  3985. }
  3986. // check font parameters
  3987. if ((!isset($type)) OR (!isset($cw))) {
  3988. $this->Error('The font definition file has a bad format: '.$fontfile.'');
  3989. }
  3990. // SET default parameters
  3991. if (!isset($file) OR TCPDF_STATIC::empty_string($file)) {
  3992. $file = '';
  3993. }
  3994. if (!isset($enc) OR TCPDF_STATIC::empty_string($enc)) {
  3995. $enc = '';
  3996. }
  3997. if (!isset($cidinfo) OR TCPDF_STATIC::empty_string($cidinfo)) {
  3998. $cidinfo = array('Registry'=>'Adobe', 'Ordering'=>'Identity', 'Supplement'=>0);
  3999. $cidinfo['uni2cid'] = array();
  4000. }
  4001. if (!isset($ctg) OR TCPDF_STATIC::empty_string($ctg)) {
  4002. $ctg = '';
  4003. }
  4004. if (!isset($desc) OR TCPDF_STATIC::empty_string($desc)) {
  4005. $desc = array();
  4006. }
  4007. if (!isset($up) OR TCPDF_STATIC::empty_string($up)) {
  4008. $up = -100;
  4009. }
  4010. if (!isset($ut) OR TCPDF_STATIC::empty_string($ut)) {
  4011. $ut = 50;
  4012. }
  4013. if (!isset($cw) OR TCPDF_STATIC::empty_string($cw)) {
  4014. $cw = array();
  4015. }
  4016. if (!isset($dw) OR TCPDF_STATIC::empty_string($dw)) {
  4017. // set default width
  4018. if (isset($desc['MissingWidth']) AND ($desc['MissingWidth'] > 0)) {
  4019. $dw = $desc['MissingWidth'];
  4020. } elseif (isset($cw[32])) {
  4021. $dw = $cw[32];
  4022. } else {
  4023. $dw = 600;
  4024. }
  4025. }
  4026. ++$this->numfonts;
  4027. if ($type == 'core') {
  4028. $name = $this->CoreFonts[$fontkey];
  4029. $subset = false;
  4030. } elseif (($type == 'TrueType') OR ($type == 'Type1')) {
  4031. $subset = false;
  4032. } elseif ($type == 'TrueTypeUnicode') {
  4033. $enc = 'Identity-H';
  4034. } elseif ($type == 'cidfont0') {
  4035. if ($this->pdfa_mode) {
  4036. $this->Error('All fonts must be embedded in PDF/A mode!');
  4037. }
  4038. } else {
  4039. $this->Error('Unknow font type: '.$type.'');
  4040. }
  4041. // set name if unset
  4042. if (!isset($name) OR empty($name)) {
  4043. $name = $fontkey;
  4044. }
  4045. // create artificial font style variations if missing (only works with non-embedded fonts)
  4046. if (($type != 'core') AND $missing_style) {
  4047. // style variations
  4048. $styles = array('' => '', 'B' => ',Bold', 'I' => ',Italic', 'BI' => ',BoldItalic');
  4049. $name .= $styles[$bistyle];
  4050. // artificial bold
  4051. if (strpos($bistyle, 'B') !== false) {
  4052. if (isset($desc['StemV'])) {
  4053. // from normal to bold
  4054. $desc['StemV'] = round($desc['StemV'] * 1.75);
  4055. } else {
  4056. // bold
  4057. $desc['StemV'] = 123;
  4058. }
  4059. }
  4060. // artificial italic
  4061. if (strpos($bistyle, 'I') !== false) {
  4062. if (isset($desc['ItalicAngle'])) {
  4063. $desc['ItalicAngle'] -= 11;
  4064. } else {
  4065. $desc['ItalicAngle'] = -11;
  4066. }
  4067. if (isset($desc['Flags'])) {
  4068. $desc['Flags'] |= 64; //bit 7
  4069. } else {
  4070. $desc['Flags'] = 64;
  4071. }
  4072. }
  4073. }
  4074. // check if the array of characters bounding boxes is defined
  4075. if (!isset($cbbox)) {
  4076. $cbbox = array();
  4077. }
  4078. // initialize subsetchars
  4079. $subsetchars = array_fill(0, 255, true);
  4080. $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));
  4081. if ($this->inxobj) {
  4082. // we are inside an XObject template
  4083. $this->xobjects[$this->xobjid]['fonts'][$fontkey] = $this->numfonts;
  4084. }
  4085. if (isset($diff) AND (!empty($diff))) {
  4086. //Search existing encodings
  4087. $d = 0;
  4088. $nb = count($this->diffs);
  4089. for ($i=1; $i <= $nb; ++$i) {
  4090. if ($this->diffs[$i] == $diff) {
  4091. $d = $i;
  4092. break;
  4093. }
  4094. }
  4095. if ($d == 0) {
  4096. $d = $nb + 1;
  4097. $this->diffs[$d] = $diff;
  4098. }
  4099. $this->setFontSubBuffer($fontkey, 'diff', $d);
  4100. }
  4101. if (!TCPDF_STATIC::empty_string($file)) {
  4102. if (!isset($this->FontFiles[$file])) {
  4103. if ((strcasecmp($type,'TrueType') == 0) OR (strcasecmp($type, 'TrueTypeUnicode') == 0)) {
  4104. $this->FontFiles[$file] = array('length1' => $originalsize, 'fontdir' => $fontdir, 'subset' => $subset, 'fontkeys' => array($fontkey));
  4105. } elseif ($type != 'core') {
  4106. $this->FontFiles[$file] = array('length1' => $size1, 'length2' => $size2, 'fontdir' => $fontdir, 'subset' => $subset, 'fontkeys' => array($fontkey));
  4107. }
  4108. } else {
  4109. // update fontkeys that are sharing this font file
  4110. $this->FontFiles[$file]['subset'] = ($this->FontFiles[$file]['subset'] AND $subset);
  4111. if (!in_array($fontkey, $this->FontFiles[$file]['fontkeys'])) {
  4112. $this->FontFiles[$file]['fontkeys'][] = $fontkey;
  4113. }
  4114. }
  4115. }
  4116. return $fontdata;
  4117. }
  4118. /**
  4119. * Sets the font used to print character strings.
  4120. * The font can be either a standard one or a font added via the AddFont() method. Standard fonts use Windows encoding cp1252 (Western Europe).
  4121. * The method can be called before the first page is created and the font is retained from page to page.
  4122. * If you just wish to change the current font size, it is simpler to call SetFontSize().
  4123. * 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 />
  4124. * @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.
  4125. * @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.
  4126. * @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
  4127. * @param $fontfile (string) The font definition file. By default, the name is built from the family and style, in lower case with no spaces.
  4128. * @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.
  4129. * @param $out (boolean) if true output the font size command, otherwise only set the font properties.
  4130. * @author Nicola Asuni
  4131. * @public
  4132. * @since 1.0
  4133. * @see AddFont(), SetFontSize()
  4134. */
  4135. public function SetFont($family, $style='', $size=null, $fontfile='', $subset='default', $out=true) {
  4136. //Select a font; size given in points
  4137. if ($size === null) {
  4138. $size = $this->FontSizePt;
  4139. }
  4140. if ($size < 0) {
  4141. $size = 0;
  4142. }
  4143. // try to add font (if not already added)
  4144. $fontdata = $this->AddFont($family, $style, $fontfile, $subset);
  4145. $this->FontFamily = $fontdata['family'];
  4146. $this->FontStyle = $fontdata['style'];
  4147. if (isset($this->CurrentFont['fontkey']) AND isset($this->CurrentFont['subsetchars'])) {
  4148. // save subset chars of the previous font
  4149. $this->setFontSubBuffer($this->CurrentFont['fontkey'], 'subsetchars', $this->CurrentFont['subsetchars']);
  4150. }
  4151. $this->CurrentFont = $this->getFontBuffer($fontdata['fontkey']);
  4152. $this->SetFontSize($size, $out);
  4153. }
  4154. /**
  4155. * Defines the size of the current font.
  4156. * @param $size (float) The font size in points.
  4157. * @param $out (boolean) if true output the font size command, otherwise only set the font properties.
  4158. * @public
  4159. * @since 1.0
  4160. * @see SetFont()
  4161. */
  4162. public function SetFontSize($size, $out=true) {
  4163. $size = (float)$size;
  4164. // font size in points
  4165. $this->FontSizePt = $size;
  4166. // font size in user units
  4167. $this->FontSize = $size / $this->k;
  4168. // calculate some font metrics
  4169. if (isset($this->CurrentFont['desc']['FontBBox'])) {
  4170. $bbox = explode(' ', substr($this->CurrentFont['desc']['FontBBox'], 1, -1));
  4171. $font_height = ((intval($bbox[3]) - intval($bbox[1])) * $size / 1000);
  4172. } else {
  4173. $font_height = $size * 1.219;
  4174. }
  4175. if (isset($this->CurrentFont['desc']['Ascent']) AND ($this->CurrentFont['desc']['Ascent'] > 0)) {
  4176. $font_ascent = ($this->CurrentFont['desc']['Ascent'] * $size / 1000);
  4177. }
  4178. if (isset($this->CurrentFont['desc']['Descent']) AND ($this->CurrentFont['desc']['Descent'] <= 0)) {
  4179. $font_descent = (- $this->CurrentFont['desc']['Descent'] * $size / 1000);
  4180. }
  4181. if (!isset($font_ascent) AND !isset($font_descent)) {
  4182. // core font
  4183. $font_ascent = 0.76 * $font_height;
  4184. $font_descent = $font_height - $font_ascent;
  4185. } elseif (!isset($font_descent)) {
  4186. $font_descent = $font_height - $font_ascent;
  4187. } elseif (!isset($font_ascent)) {
  4188. $font_ascent = $font_height - $font_descent;
  4189. }
  4190. $this->FontAscent = ($font_ascent / $this->k);
  4191. $this->FontDescent = ($font_descent / $this->k);
  4192. if ($out AND ($this->page > 0) AND (isset($this->CurrentFont['i'])) AND ($this->state == 2)) {
  4193. $this->_out(sprintf('BT /F%d %F Tf ET', $this->CurrentFont['i'], $this->FontSizePt));
  4194. }
  4195. }
  4196. /**
  4197. * Returns the bounding box of the current font in user units.
  4198. * @return array
  4199. * @public
  4200. * @since 5.9.152 (2012-03-23)
  4201. */
  4202. public function getFontBBox() {
  4203. $fbbox = array();
  4204. if (isset($this->CurrentFont['desc']['FontBBox'])) {
  4205. $tmpbbox = explode(' ', substr($this->CurrentFont['desc']['FontBBox'], 1, -1));
  4206. $fbbox = array_map(array($this,'getAbsFontMeasure'), $tmpbbox);
  4207. } else {
  4208. // Find max width
  4209. if (isset($this->CurrentFont['desc']['MaxWidth'])) {
  4210. $maxw = $this->getAbsFontMeasure(intval($this->CurrentFont['desc']['MaxWidth']));
  4211. } else {
  4212. $maxw = 0;
  4213. if (isset($this->CurrentFont['desc']['MissingWidth'])) {
  4214. $maxw = max($maxw, $this->CurrentFont['desc']['MissingWidth']);
  4215. }
  4216. if (isset($this->CurrentFont['desc']['AvgWidth'])) {
  4217. $maxw = max($maxw, $this->CurrentFont['desc']['AvgWidth']);
  4218. }
  4219. if (isset($this->CurrentFont['dw'])) {
  4220. $maxw = max($maxw, $this->CurrentFont['dw']);
  4221. }
  4222. foreach ($this->CurrentFont['cw'] as $char => $w) {
  4223. $maxw = max($maxw, $w);
  4224. }
  4225. if ($maxw == 0) {
  4226. $maxw = 600;
  4227. }
  4228. $maxw = $this->getAbsFontMeasure($maxw);
  4229. }
  4230. $fbbox = array(0, (0 - $this->FontDescent), $maxw, $this->FontAscent);
  4231. }
  4232. return $fbbox;
  4233. }
  4234. /**
  4235. * Convert a relative font measure into absolute value.
  4236. * @param $s (int) Font measure.
  4237. * @return float Absolute measure.
  4238. * @since 5.9.186 (2012-09-13)
  4239. */
  4240. public function getAbsFontMeasure($s) {
  4241. return ($s * $this->FontSize / 1000);
  4242. }
  4243. /**
  4244. * Returns the glyph bounding box of the specified character in the current font in user units.
  4245. * @param $char (int) Input character code.
  4246. * @return mixed array(xMin, yMin, xMax, yMax) or FALSE if not defined.
  4247. * @since 5.9.186 (2012-09-13)
  4248. */
  4249. public function getCharBBox($char) {
  4250. $c = intval($char);
  4251. if (isset($this->CurrentFont['cw'][$c])) {
  4252. // glyph is defined ... use zero width & height for glyphs without outlines
  4253. $result = array(0,0,0,0);
  4254. if (isset($this->CurrentFont['cbbox'][$c])) {
  4255. $result = $this->CurrentFont['cbbox'][$c];
  4256. }
  4257. return array_map(array($this,'getAbsFontMeasure'), $result);
  4258. }
  4259. return false;
  4260. }
  4261. /**
  4262. * Return the font descent value
  4263. * @param $font (string) font name
  4264. * @param $style (string) font style
  4265. * @param $size (float) The size (in points)
  4266. * @return int font descent
  4267. * @public
  4268. * @author Nicola Asuni
  4269. * @since 4.9.003 (2010-03-30)
  4270. */
  4271. public function getFontDescent($font, $style='', $size=0) {
  4272. $fontdata = $this->AddFont($font, $style);
  4273. $fontinfo = $this->getFontBuffer($fontdata['fontkey']);
  4274. if (isset($fontinfo['desc']['Descent']) AND ($fontinfo['desc']['Descent'] <= 0)) {
  4275. $descent = (- $fontinfo['desc']['Descent'] * $size / 1000);
  4276. } else {
  4277. $descent = (1.219 * 0.24 * $size);
  4278. }
  4279. return ($descent / $this->k);
  4280. }
  4281. /**
  4282. * Return the font ascent value.
  4283. * @param $font (string) font name
  4284. * @param $style (string) font style
  4285. * @param $size (float) The size (in points)
  4286. * @return int font ascent
  4287. * @public
  4288. * @author Nicola Asuni
  4289. * @since 4.9.003 (2010-03-30)
  4290. */
  4291. public function getFontAscent($font, $style='', $size=0) {
  4292. $fontdata = $this->AddFont($font, $style);
  4293. $fontinfo = $this->getFontBuffer($fontdata['fontkey']);
  4294. if (isset($fontinfo['desc']['Ascent']) AND ($fontinfo['desc']['Ascent'] > 0)) {
  4295. $ascent = ($fontinfo['desc']['Ascent'] * $size / 1000);
  4296. } else {
  4297. $ascent = 1.219 * 0.76 * $size;
  4298. }
  4299. return ($ascent / $this->k);
  4300. }
  4301. /**
  4302. * Return true in the character is present in the specified font.
  4303. * @param $char (mixed) Character to check (integer value or string)
  4304. * @param $font (string) Font name (family name).
  4305. * @param $style (string) Font style.
  4306. * @return (boolean) true if the char is defined, false otherwise.
  4307. * @public
  4308. * @since 5.9.153 (2012-03-28)
  4309. */
  4310. public function isCharDefined($char, $font='', $style='') {
  4311. if (is_string($char)) {
  4312. // get character code
  4313. $char = TCPDF_FONTS::UTF8StringToArray($char, $this->isunicode, $this->CurrentFont);
  4314. $char = $char[0];
  4315. }
  4316. if (TCPDF_STATIC::empty_string($font)) {
  4317. if (TCPDF_STATIC::empty_string($style)) {
  4318. return (isset($this->CurrentFont['cw'][intval($char)]));
  4319. }
  4320. $font = $this->FontFamily;
  4321. }
  4322. $fontdata = $this->AddFont($font, $style);
  4323. $fontinfo = $this->getFontBuffer($fontdata['fontkey']);
  4324. return (isset($fontinfo['cw'][intval($char)]));
  4325. }
  4326. /**
  4327. * Replace missing font characters on selected font with specified substitutions.
  4328. * @param $text (string) Text to process.
  4329. * @param $font (string) Font name (family name).
  4330. * @param $style (string) Font style.
  4331. * @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.
  4332. * @return (string) Processed text.
  4333. * @public
  4334. * @since 5.9.153 (2012-03-28)
  4335. */
  4336. public function replaceMissingChars($text, $font='', $style='', $subs=array()) {
  4337. if (empty($subs)) {
  4338. return $text;
  4339. }
  4340. if (TCPDF_STATIC::empty_string($font)) {
  4341. $font = $this->FontFamily;
  4342. }
  4343. $fontdata = $this->AddFont($font, $style);
  4344. $fontinfo = $this->getFontBuffer($fontdata['fontkey']);
  4345. $uniarr = TCPDF_FONTS::UTF8StringToArray($text, $this->isunicode, $this->CurrentFont);
  4346. foreach ($uniarr as $k => $chr) {
  4347. if (!isset($fontinfo['cw'][$chr])) {
  4348. // this character is missing on the selected font
  4349. if (isset($subs[$chr])) {
  4350. // we have available substitutions
  4351. if (is_array($subs[$chr])) {
  4352. foreach($subs[$chr] as $s) {
  4353. if (isset($fontinfo['cw'][$s])) {
  4354. $uniarr[$k] = $s;
  4355. break;
  4356. }
  4357. }
  4358. } elseif (isset($fontinfo['cw'][$subs[$chr]])) {
  4359. $uniarr[$k] = $subs[$chr];
  4360. }
  4361. }
  4362. }
  4363. }
  4364. return TCPDF_FONTS::UniArrSubString(TCPDF_FONTS::UTF8ArrayToUniArray($uniarr, $this->isunicode));
  4365. }
  4366. /**
  4367. * Defines the default monospaced font.
  4368. * @param $font (string) Font name.
  4369. * @public
  4370. * @since 4.5.025
  4371. */
  4372. public function SetDefaultMonospacedFont($font) {
  4373. $this->default_monospaced_font = $font;
  4374. }
  4375. /**
  4376. * 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 />
  4377. * The identifier can then be passed to Cell(), Write(), Image() or Link(). The destination is defined with SetLink().
  4378. * @public
  4379. * @since 1.5
  4380. * @see Cell(), Write(), Image(), Link(), SetLink()
  4381. */
  4382. public function AddLink() {
  4383. // create a new internal link
  4384. $n = count($this->links) + 1;
  4385. $this->links[$n] = array('p' => 0, 'y' => 0, 'f' => false);
  4386. return $n;
  4387. }
  4388. /**
  4389. * Defines the page and position a link points to.
  4390. * @param $link (int) The link identifier returned by AddLink()
  4391. * @param $y (float) Ordinate of target position; -1 indicates the current position. The default value is 0 (top of page)
  4392. * @param $page (int|string) Number of target page; -1 indicates the current page (default value). If you prefix a page number with the * character, then this page will not be changed when adding/deleting/moving pages.
  4393. * @public
  4394. * @since 1.5
  4395. * @see AddLink()
  4396. */
  4397. public function SetLink($link, $y=0, $page=-1) {
  4398. $fixed = false;
  4399. if (!empty($page) AND (substr($page, 0, 1) == '*')) {
  4400. $page = intval(substr($page, 1));
  4401. // this page number will not be changed when moving/add/deleting pages
  4402. $fixed = true;
  4403. }
  4404. if ($page < 0) {
  4405. $page = $this->page;
  4406. }
  4407. if ($y == -1) {
  4408. $y = $this->y;
  4409. }
  4410. $this->links[$link] = array('p' => $page, 'y' => $y, 'f' => $fixed);
  4411. }
  4412. /**
  4413. * Puts a link on a rectangular area of the page.
  4414. * 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.
  4415. * @param $x (float) Abscissa of the upper-left corner of the rectangle
  4416. * @param $y (float) Ordinate of the upper-left corner of the rectangle
  4417. * @param $w (float) Width of the rectangle
  4418. * @param $h (float) Height of the rectangle
  4419. * @param $link (mixed) URL or identifier returned by AddLink()
  4420. * @param $spaces (int) number of spaces on the text to link
  4421. * @public
  4422. * @since 1.5
  4423. * @see AddLink(), Annotation(), Cell(), Write(), Image()
  4424. */
  4425. public function Link($x, $y, $w, $h, $link, $spaces=0) {
  4426. $this->Annotation($x, $y, $w, $h, $link, array('Subtype'=>'Link'), $spaces);
  4427. }
  4428. /**
  4429. * Puts a markup annotation on a rectangular area of the page.
  4430. * !!!!THE ANNOTATION SUPPORT IS NOT YET FULLY IMPLEMENTED !!!!
  4431. * @param $x (float) Abscissa of the upper-left corner of the rectangle
  4432. * @param $y (float) Ordinate of the upper-left corner of the rectangle
  4433. * @param $w (float) Width of the rectangle
  4434. * @param $h (float) Height of the rectangle
  4435. * @param $text (string) annotation text or alternate content
  4436. * @param $opt (array) array of options (see section 8.4 of PDF reference 1.7).
  4437. * @param $spaces (int) number of spaces on the text to link
  4438. * @public
  4439. * @since 4.0.018 (2008-08-06)
  4440. */
  4441. public function Annotation($x, $y, $w, $h, $text, $opt=array('Subtype'=>'Text'), $spaces=0) {
  4442. if ($this->inxobj) {
  4443. // store parameters for later use on template
  4444. $this->xobjects[$this->xobjid]['annotations'][] = array('x' => $x, 'y' => $y, 'w' => $w, 'h' => $h, 'text' => $text, 'opt' => $opt, 'spaces' => $spaces);
  4445. return;
  4446. }
  4447. if ($x === '') {
  4448. $x = $this->x;
  4449. }
  4450. if ($y === '') {
  4451. $y = $this->y;
  4452. }
  4453. // check page for no-write regions and adapt page margins if necessary
  4454. list($x, $y) = $this->checkPageRegions($h, $x, $y);
  4455. // recalculate coordinates to account for graphic transformations
  4456. if (isset($this->transfmatrix) AND !empty($this->transfmatrix)) {
  4457. for ($i=$this->transfmatrix_key; $i > 0; --$i) {
  4458. $maxid = count($this->transfmatrix[$i]) - 1;
  4459. for ($j=$maxid; $j >= 0; --$j) {
  4460. $ctm = $this->transfmatrix[$i][$j];
  4461. if (isset($ctm['a'])) {
  4462. $x = $x * $this->k;
  4463. $y = ($this->h - $y) * $this->k;
  4464. $w = $w * $this->k;
  4465. $h = $h * $this->k;
  4466. // top left
  4467. $xt = $x;
  4468. $yt = $y;
  4469. $x1 = ($ctm['a'] * $xt) + ($ctm['c'] * $yt) + $ctm['e'];
  4470. $y1 = ($ctm['b'] * $xt) + ($ctm['d'] * $yt) + $ctm['f'];
  4471. // top right
  4472. $xt = $x + $w;
  4473. $yt = $y;
  4474. $x2 = ($ctm['a'] * $xt) + ($ctm['c'] * $yt) + $ctm['e'];
  4475. $y2 = ($ctm['b'] * $xt) + ($ctm['d'] * $yt) + $ctm['f'];
  4476. // bottom left
  4477. $xt = $x;
  4478. $yt = $y - $h;
  4479. $x3 = ($ctm['a'] * $xt) + ($ctm['c'] * $yt) + $ctm['e'];
  4480. $y3 = ($ctm['b'] * $xt) + ($ctm['d'] * $yt) + $ctm['f'];
  4481. // bottom right
  4482. $xt = $x + $w;
  4483. $yt = $y - $h;
  4484. $x4 = ($ctm['a'] * $xt) + ($ctm['c'] * $yt) + $ctm['e'];
  4485. $y4 = ($ctm['b'] * $xt) + ($ctm['d'] * $yt) + $ctm['f'];
  4486. // new coordinates (rectangle area)
  4487. $x = min($x1, $x2, $x3, $x4);
  4488. $y = max($y1, $y2, $y3, $y4);
  4489. $w = (max($x1, $x2, $x3, $x4) - $x) / $this->k;
  4490. $h = ($y - min($y1, $y2, $y3, $y4)) / $this->k;
  4491. $x = $x / $this->k;
  4492. $y = $this->h - ($y / $this->k);
  4493. }
  4494. }
  4495. }
  4496. }
  4497. if ($this->page <= 0) {
  4498. $page = 1;
  4499. } else {
  4500. $page = $this->page;
  4501. }
  4502. if (!isset($this->PageAnnots[$page])) {
  4503. $this->PageAnnots[$page] = array();
  4504. }
  4505. $this->PageAnnots[$page][] = array('n' => ++$this->n, 'x' => $x, 'y' => $y, 'w' => $w, 'h' => $h, 'txt' => $text, 'opt' => $opt, 'numspaces' => $spaces);
  4506. if (!$this->pdfa_mode || ($this->pdfa_mode && $this->pdfa_version == 3)) {
  4507. if ((($opt['Subtype'] == 'FileAttachment') OR ($opt['Subtype'] == 'Sound')) AND (!TCPDF_STATIC::empty_string($opt['FS']))
  4508. AND (@TCPDF_STATIC::file_exists($opt['FS']) OR TCPDF_STATIC::isValidURL($opt['FS']))
  4509. AND (!isset($this->embeddedfiles[basename($opt['FS'])]))) {
  4510. $this->embeddedfiles[basename($opt['FS'])] = array('f' => ++$this->n, 'n' => ++$this->n, 'file' => $opt['FS']);
  4511. }
  4512. }
  4513. // Add widgets annotation's icons
  4514. if (isset($opt['mk']['i']) AND @TCPDF_STATIC::file_exists($opt['mk']['i'])) {
  4515. $this->Image($opt['mk']['i'], '', '', 10, 10, '', '', '', false, 300, '', false, false, 0, false, true);
  4516. }
  4517. if (isset($opt['mk']['ri']) AND @TCPDF_STATIC::file_exists($opt['mk']['ri'])) {
  4518. $this->Image($opt['mk']['ri'], '', '', 0, 0, '', '', '', false, 300, '', false, false, 0, false, true);
  4519. }
  4520. if (isset($opt['mk']['ix']) AND @TCPDF_STATIC::file_exists($opt['mk']['ix'])) {
  4521. $this->Image($opt['mk']['ix'], '', '', 0, 0, '', '', '', false, 300, '', false, false, 0, false, true);
  4522. }
  4523. }
  4524. /**
  4525. * Embedd the attached files.
  4526. * @since 4.4.000 (2008-12-07)
  4527. * @protected
  4528. * @see Annotation()
  4529. */
  4530. protected function _putEmbeddedFiles() {
  4531. if ($this->pdfa_mode && $this->pdfa_version != 3) {
  4532. // embedded files are not allowed in PDF/A mode version 1 and 2
  4533. return;
  4534. }
  4535. reset($this->embeddedfiles);
  4536. foreach ($this->embeddedfiles as $filename => $filedata) {
  4537. $data = $this->getCachedFileContents($filedata['file']);
  4538. if ($data !== FALSE) {
  4539. $rawsize = strlen($data);
  4540. if ($rawsize > 0) {
  4541. // update name tree
  4542. $this->efnames[$filename] = $filedata['f'].' 0 R';
  4543. // embedded file specification object
  4544. $out = $this->_getobj($filedata['f'])."\n";
  4545. $out .= '<</Type /Filespec /F '.$this->_datastring($filename, $filedata['f']);
  4546. $out .= ' /UF '.$this->_datastring($filename, $filedata['f']);
  4547. $out .= ' /AFRelationship /Source';
  4548. $out .= ' /EF <</F '.$filedata['n'].' 0 R>> >>';
  4549. $out .= "\n".'endobj';
  4550. $this->_out($out);
  4551. // embedded file object
  4552. $filter = '';
  4553. if ($this->compress) {
  4554. $data = gzcompress($data);
  4555. $filter = ' /Filter /FlateDecode';
  4556. }
  4557. if ($this->pdfa_version == 3) {
  4558. $filter = ' /Subtype /text#2Fxml';
  4559. }
  4560. $stream = $this->_getrawstream($data, $filedata['n']);
  4561. $out = $this->_getobj($filedata['n'])."\n";
  4562. $out .= '<< /Type /EmbeddedFile'.$filter.' /Length '.strlen($stream).' /Params <</Size '.$rawsize.'>> >>';
  4563. $out .= ' stream'."\n".$stream."\n".'endstream';
  4564. $out .= "\n".'endobj';
  4565. $this->_out($out);
  4566. }
  4567. }
  4568. }
  4569. }
  4570. /**
  4571. * Prints a text cell at the specified position.
  4572. * This method allows to place a string precisely on the page.
  4573. * @param $x (float) Abscissa of the cell origin
  4574. * @param $y (float) Ordinate of the cell origin
  4575. * @param $txt (string) String to print
  4576. * @param $fstroke (int) outline size in user units (false = disable)
  4577. * @param $fclip (boolean) if true activate clipping mode (you must call StartTransform() before this function and StopTransform() to stop the clipping tranformation).
  4578. * @param $ffill (boolean) if true fills the text
  4579. * @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)))
  4580. * @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.
  4581. * @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>
  4582. * @param $fill (boolean) Indicates if the cell background must be painted (true) or transparent (false).
  4583. * @param $link (mixed) URL or identifier returned by AddLink().
  4584. * @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.
  4585. * @param $ignore_min_height (boolean) if true ignore automatic minimum height value.
  4586. * @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>
  4587. * @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>
  4588. * @param $rtloff (boolean) if true uses the page top-left corner as origin of axis for $x and $y initial position.
  4589. * @public
  4590. * @since 1.0
  4591. * @see Cell(), Write(), MultiCell(), WriteHTML(), WriteHTMLCell()
  4592. */
  4593. 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) {
  4594. $textrendermode = $this->textrendermode;
  4595. $textstrokewidth = $this->textstrokewidth;
  4596. $this->setTextRenderingMode($fstroke, $ffill, $fclip);
  4597. $this->SetXY($x, $y, $rtloff);
  4598. $this->Cell(0, 0, $txt, $border, $ln, $align, $fill, $link, $stretch, $ignore_min_height, $calign, $valign);
  4599. // restore previous rendering mode
  4600. $this->textrendermode = $textrendermode;
  4601. $this->textstrokewidth = $textstrokewidth;
  4602. }
  4603. /**
  4604. * Whenever a page break condition is met, the method is called, and the break is issued or not depending on the returned value.
  4605. * The default implementation returns a value according to the mode selected by SetAutoPageBreak().<br />
  4606. * This method is called automatically and should not be called directly by the application.
  4607. * @return boolean
  4608. * @public
  4609. * @since 1.4
  4610. * @see SetAutoPageBreak()
  4611. */
  4612. public function AcceptPageBreak() {
  4613. if ($this->num_columns > 1) {
  4614. // multi column mode
  4615. if ($this->current_column < ($this->num_columns - 1)) {
  4616. // go to next column
  4617. $this->selectColumn($this->current_column + 1);
  4618. } elseif ($this->AutoPageBreak) {
  4619. // add a new page
  4620. $this->AddPage();
  4621. // set first column
  4622. $this->selectColumn(0);
  4623. }
  4624. // avoid page breaking from checkPageBreak()
  4625. return false;
  4626. }
  4627. return $this->AutoPageBreak;
  4628. }
  4629. /**
  4630. * Add page if needed.
  4631. * @param $h (float) Cell height. Default value: 0.
  4632. * @param $y (mixed) starting y position, leave empty for current position.
  4633. * @param $addpage (boolean) if true add a page, otherwise only return the true/false state
  4634. * @return boolean true in case of page break, false otherwise.
  4635. * @since 3.2.000 (2008-07-01)
  4636. * @protected
  4637. */
  4638. protected function checkPageBreak($h=0, $y='', $addpage=true) {
  4639. if (TCPDF_STATIC::empty_string($y)) {
  4640. $y = $this->y;
  4641. }
  4642. $current_page = $this->page;
  4643. if ((($y + $h) > $this->PageBreakTrigger) AND ($this->inPageBody()) AND ($this->AcceptPageBreak())) {
  4644. if ($addpage) {
  4645. //Automatic page break
  4646. $x = $this->x;
  4647. $this->AddPage($this->CurOrientation);
  4648. $this->y = $this->tMargin;
  4649. $oldpage = $this->page - 1;
  4650. if ($this->rtl) {
  4651. if ($this->pagedim[$this->page]['orm'] != $this->pagedim[$oldpage]['orm']) {
  4652. $this->x = $x - ($this->pagedim[$this->page]['orm'] - $this->pagedim[$oldpage]['orm']);
  4653. } else {
  4654. $this->x = $x;
  4655. }
  4656. } else {
  4657. if ($this->pagedim[$this->page]['olm'] != $this->pagedim[$oldpage]['olm']) {
  4658. $this->x = $x + ($this->pagedim[$this->page]['olm'] - $this->pagedim[$oldpage]['olm']);
  4659. } else {
  4660. $this->x = $x;
  4661. }
  4662. }
  4663. }
  4664. return true;
  4665. }
  4666. if ($current_page != $this->page) {
  4667. // account for columns mode
  4668. return true;
  4669. }
  4670. return false;
  4671. }
  4672. /**
  4673. * 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 />
  4674. * If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting.
  4675. * @param $w (float) Cell width. If 0, the cell extends up to the right margin.
  4676. * @param $h (float) Cell height. Default value: 0.
  4677. * @param $txt (string) String to print. Default value: empty string.
  4678. * @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)))
  4679. * @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.
  4680. * @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>
  4681. * @param $fill (boolean) Indicates if the cell background must be painted (true) or transparent (false).
  4682. * @param $link (mixed) URL or identifier returned by AddLink().
  4683. * @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.
  4684. * @param $ignore_min_height (boolean) if true ignore automatic minimum height value.
  4685. * @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>
  4686. * @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>
  4687. * @public
  4688. * @since 1.0
  4689. * @see SetFont(), SetDrawColor(), SetFillColor(), SetTextColor(), SetLineWidth(), AddLink(), Ln(), MultiCell(), Write(), SetAutoPageBreak()
  4690. */
  4691. 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') {
  4692. $prev_cell_margin = $this->cell_margin;
  4693. $prev_cell_padding = $this->cell_padding;
  4694. $this->adjustCellPadding($border);
  4695. if (!$ignore_min_height) {
  4696. $min_cell_height = $this->getCellHeight($this->FontSize);
  4697. if ($h < $min_cell_height) {
  4698. $h = $min_cell_height;
  4699. }
  4700. }
  4701. $this->checkPageBreak($h + $this->cell_margin['T'] + $this->cell_margin['B']);
  4702. // apply text shadow if enabled
  4703. if ($this->txtshadow['enabled']) {
  4704. // save data
  4705. $x = $this->x;
  4706. $y = $this->y;
  4707. $bc = $this->bgcolor;
  4708. $fc = $this->fgcolor;
  4709. $sc = $this->strokecolor;
  4710. $alpha = $this->alpha;
  4711. // print shadow
  4712. $this->x += $this->txtshadow['depth_w'];
  4713. $this->y += $this->txtshadow['depth_h'];
  4714. $this->SetFillColorArray($this->txtshadow['color']);
  4715. $this->SetTextColorArray($this->txtshadow['color']);
  4716. $this->SetDrawColorArray($this->txtshadow['color']);
  4717. if ($this->txtshadow['opacity'] != $alpha['CA']) {
  4718. $this->setAlpha($this->txtshadow['opacity'], $this->txtshadow['blend_mode']);
  4719. }
  4720. if ($this->state == 2) {
  4721. $this->_out($this->getCellCode($w, $h, $txt, $border, $ln, $align, $fill, $link, $stretch, true, $calign, $valign));
  4722. }
  4723. //restore data
  4724. $this->x = $x;
  4725. $this->y = $y;
  4726. $this->SetFillColorArray($bc);
  4727. $this->SetTextColorArray($fc);
  4728. $this->SetDrawColorArray($sc);
  4729. if ($this->txtshadow['opacity'] != $alpha['CA']) {
  4730. $this->setAlpha($alpha['CA'], $alpha['BM'], $alpha['ca'], $alpha['AIS']);
  4731. }
  4732. }
  4733. if ($this->state == 2) {
  4734. $this->_out($this->getCellCode($w, $h, $txt, $border, $ln, $align, $fill, $link, $stretch, true, $calign, $valign));
  4735. }
  4736. $this->cell_padding = $prev_cell_padding;
  4737. $this->cell_margin = $prev_cell_margin;
  4738. }
  4739. /**
  4740. * 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 />
  4741. * If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting.
  4742. * @param $w (float) Cell width. If 0, the cell extends up to the right margin.
  4743. * @param $h (float) Cell height. Default value: 0.
  4744. * @param $txt (string) String to print. Default value: empty string.
  4745. * @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)))
  4746. * @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.
  4747. * @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>
  4748. * @param $fill (boolean) Indicates if the cell background must be painted (true) or transparent (false).
  4749. * @param $link (mixed) URL or identifier returned by AddLink().
  4750. * @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.
  4751. * @param $ignore_min_height (boolean) if true ignore automatic minimum height value.
  4752. * @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>
  4753. * @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>
  4754. * @return string containing cell code
  4755. * @protected
  4756. * @since 1.0
  4757. * @see Cell()
  4758. */
  4759. 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') {
  4760. // replace 'NO-BREAK SPACE' (U+00A0) character with a simple space
  4761. $txt = str_replace(TCPDF_FONTS::unichr(160, $this->isunicode), ' ', $txt);
  4762. $prev_cell_margin = $this->cell_margin;
  4763. $prev_cell_padding = $this->cell_padding;
  4764. $txt = TCPDF_STATIC::removeSHY($txt, $this->isunicode);
  4765. $rs = ''; //string to be returned
  4766. $this->adjustCellPadding($border);
  4767. if (!$ignore_min_height) {
  4768. $min_cell_height = $this->getCellHeight($this->FontSize);
  4769. if ($h < $min_cell_height) {
  4770. $h = $min_cell_height;
  4771. }
  4772. }
  4773. $k = $this->k;
  4774. // check page for no-write regions and adapt page margins if necessary
  4775. list($this->x, $this->y) = $this->checkPageRegions($h, $this->x, $this->y);
  4776. if ($this->rtl) {
  4777. $x = $this->x - $this->cell_margin['R'];
  4778. } else {
  4779. $x = $this->x + $this->cell_margin['L'];
  4780. }
  4781. $y = $this->y + $this->cell_margin['T'];
  4782. $prev_font_stretching = $this->font_stretching;
  4783. $prev_font_spacing = $this->font_spacing;
  4784. // cell vertical alignment
  4785. switch ($calign) {
  4786. case 'A': {
  4787. // font top
  4788. switch ($valign) {
  4789. case 'T': {
  4790. // top
  4791. $y -= $this->cell_padding['T'];
  4792. break;
  4793. }
  4794. case 'B': {
  4795. // bottom
  4796. $y -= ($h - $this->cell_padding['B'] - $this->FontAscent - $this->FontDescent);
  4797. break;
  4798. }
  4799. default:
  4800. case 'C':
  4801. case 'M': {
  4802. // center
  4803. $y -= (($h - $this->FontAscent - $this->FontDescent) / 2);
  4804. break;
  4805. }
  4806. }
  4807. break;
  4808. }
  4809. case 'L': {
  4810. // font baseline
  4811. switch ($valign) {
  4812. case 'T': {
  4813. // top
  4814. $y -= ($this->cell_padding['T'] + $this->FontAscent);
  4815. break;
  4816. }
  4817. case 'B': {
  4818. // bottom
  4819. $y -= ($h - $this->cell_padding['B'] - $this->FontDescent);
  4820. break;
  4821. }
  4822. default:
  4823. case 'C':
  4824. case 'M': {
  4825. // center
  4826. $y -= (($h + $this->FontAscent - $this->FontDescent) / 2);
  4827. break;
  4828. }
  4829. }
  4830. break;
  4831. }
  4832. case 'D': {
  4833. // font bottom
  4834. switch ($valign) {
  4835. case 'T': {
  4836. // top
  4837. $y -= ($this->cell_padding['T'] + $this->FontAscent + $this->FontDescent);
  4838. break;
  4839. }
  4840. case 'B': {
  4841. // bottom
  4842. $y -= ($h - $this->cell_padding['B']);
  4843. break;
  4844. }
  4845. default:
  4846. case 'C':
  4847. case 'M': {
  4848. // center
  4849. $y -= (($h + $this->FontAscent + $this->FontDescent) / 2);
  4850. break;
  4851. }
  4852. }
  4853. break;
  4854. }
  4855. case 'B': {
  4856. // cell bottom
  4857. $y -= $h;
  4858. break;
  4859. }
  4860. case 'C':
  4861. case 'M': {
  4862. // cell center
  4863. $y -= ($h / 2);
  4864. break;
  4865. }
  4866. default:
  4867. case 'T': {
  4868. // cell top
  4869. break;
  4870. }
  4871. }
  4872. // text vertical alignment
  4873. switch ($valign) {
  4874. case 'T': {
  4875. // top
  4876. $yt = $y + $this->cell_padding['T'];
  4877. break;
  4878. }
  4879. case 'B': {
  4880. // bottom
  4881. $yt = $y + $h - $this->cell_padding['B'] - $this->FontAscent - $this->FontDescent;
  4882. break;
  4883. }
  4884. default:
  4885. case 'C':
  4886. case 'M': {
  4887. // center
  4888. $yt = $y + (($h - $this->FontAscent - $this->FontDescent) / 2);
  4889. break;
  4890. }
  4891. }
  4892. $basefonty = $yt + $this->FontAscent;
  4893. if (TCPDF_STATIC::empty_string($w) OR ($w <= 0)) {
  4894. if ($this->rtl) {
  4895. $w = $x - $this->lMargin;
  4896. } else {
  4897. $w = $this->w - $this->rMargin - $x;
  4898. }
  4899. }
  4900. $s = '';
  4901. // fill and borders
  4902. if (is_string($border) AND (strlen($border) == 4)) {
  4903. // full border
  4904. $border = 1;
  4905. }
  4906. if ($fill OR ($border == 1)) {
  4907. if ($fill) {
  4908. $op = ($border == 1) ? 'B' : 'f';
  4909. } else {
  4910. $op = 'S';
  4911. }
  4912. if ($this->rtl) {
  4913. $xk = (($x - $w) * $k);
  4914. } else {
  4915. $xk = ($x * $k);
  4916. }
  4917. $s .= sprintf('%F %F %F %F re %s ', $xk, (($this->h - $y) * $k), ($w * $k), (-$h * $k), $op);
  4918. }
  4919. // draw borders
  4920. $s .= $this->getCellBorder($x, $y, $w, $h, $border);
  4921. if ($txt != '') {
  4922. $txt2 = $txt;
  4923. if ($this->isunicode) {
  4924. if (($this->CurrentFont['type'] == 'core') OR ($this->CurrentFont['type'] == 'TrueType') OR ($this->CurrentFont['type'] == 'Type1')) {
  4925. $txt2 = TCPDF_FONTS::UTF8ToLatin1($txt2, $this->isunicode, $this->CurrentFont);
  4926. } else {
  4927. $unicode = TCPDF_FONTS::UTF8StringToArray($txt, $this->isunicode, $this->CurrentFont); // array of UTF-8 unicode values
  4928. $unicode = TCPDF_FONTS::utf8Bidi($unicode, '', $this->tmprtl, $this->isunicode, $this->CurrentFont);
  4929. // replace thai chars (if any)
  4930. if (defined('K_THAI_TOPCHARS') AND (K_THAI_TOPCHARS == true)) {
  4931. // number of chars
  4932. $numchars = count($unicode);
  4933. // po pla, for far, for fan
  4934. $longtail = array(0x0e1b, 0x0e1d, 0x0e1f);
  4935. // do chada, to patak
  4936. $lowtail = array(0x0e0e, 0x0e0f);
  4937. // mai hun arkad, sara i, sara ii, sara ue, sara uee
  4938. $upvowel = array(0x0e31, 0x0e34, 0x0e35, 0x0e36, 0x0e37);
  4939. // mai ek, mai tho, mai tri, mai chattawa, karan
  4940. $tonemark = array(0x0e48, 0x0e49, 0x0e4a, 0x0e4b, 0x0e4c);
  4941. // sara u, sara uu, pinthu
  4942. $lowvowel = array(0x0e38, 0x0e39, 0x0e3a);
  4943. $output = array();
  4944. for ($i = 0; $i < $numchars; $i++) {
  4945. if (($unicode[$i] >= 0x0e00) && ($unicode[$i] <= 0x0e5b)) {
  4946. $ch0 = $unicode[$i];
  4947. $ch1 = ($i > 0) ? $unicode[($i - 1)] : 0;
  4948. $ch2 = ($i > 1) ? $unicode[($i - 2)] : 0;
  4949. $chn = ($i < ($numchars - 1)) ? $unicode[($i + 1)] : 0;
  4950. if (in_array($ch0, $tonemark)) {
  4951. if ($chn == 0x0e33) {
  4952. // sara um
  4953. if (in_array($ch1, $longtail)) {
  4954. // tonemark at upper left
  4955. $output[] = $this->replaceChar($ch0, (0xf713 + $ch0 - 0x0e48));
  4956. } else {
  4957. // tonemark at upper right (normal position)
  4958. $output[] = $ch0;
  4959. }
  4960. } elseif (in_array($ch1, $longtail) OR (in_array($ch2, $longtail) AND in_array($ch1, $lowvowel))) {
  4961. // tonemark at lower left
  4962. $output[] = $this->replaceChar($ch0, (0xf705 + $ch0 - 0x0e48));
  4963. } elseif (in_array($ch1, $upvowel)) {
  4964. if (in_array($ch2, $longtail)) {
  4965. // tonemark at upper left
  4966. $output[] = $this->replaceChar($ch0, (0xf713 + $ch0 - 0x0e48));
  4967. } else {
  4968. // tonemark at upper right (normal position)
  4969. $output[] = $ch0;
  4970. }
  4971. } else {
  4972. // tonemark at lower right
  4973. $output[] = $this->replaceChar($ch0, (0xf70a + $ch0 - 0x0e48));
  4974. }
  4975. } elseif (($ch0 == 0x0e33) AND (in_array($ch1, $longtail) OR (in_array($ch2, $longtail) AND in_array($ch1, $tonemark)))) {
  4976. // add lower left nikhahit and sara aa
  4977. if ($this->isCharDefined(0xf711) AND $this->isCharDefined(0x0e32)) {
  4978. $output[] = 0xf711;
  4979. $this->CurrentFont['subsetchars'][0xf711] = true;
  4980. $output[] = 0x0e32;
  4981. $this->CurrentFont['subsetchars'][0x0e32] = true;
  4982. } else {
  4983. $output[] = $ch0;
  4984. }
  4985. } elseif (in_array($ch1, $longtail)) {
  4986. if ($ch0 == 0x0e31) {
  4987. // lower left mai hun arkad
  4988. $output[] = $this->replaceChar($ch0, 0xf710);
  4989. } elseif (in_array($ch0, $upvowel)) {
  4990. // lower left
  4991. $output[] = $this->replaceChar($ch0, (0xf701 + $ch0 - 0x0e34));
  4992. } elseif ($ch0 == 0x0e47) {
  4993. // lower left mai tai koo
  4994. $output[] = $this->replaceChar($ch0, 0xf712);
  4995. } else {
  4996. // normal character
  4997. $output[] = $ch0;
  4998. }
  4999. } elseif (in_array($ch1, $lowtail) AND in_array($ch0, $lowvowel)) {
  5000. // lower vowel
  5001. $output[] = $this->replaceChar($ch0, (0xf718 + $ch0 - 0x0e38));
  5002. } elseif (($ch0 == 0x0e0d) AND in_array($chn, $lowvowel)) {
  5003. // yo ying without lower part
  5004. $output[] = $this->replaceChar($ch0, 0xf70f);
  5005. } elseif (($ch0 == 0x0e10) AND in_array($chn, $lowvowel)) {
  5006. // tho santan without lower part
  5007. $output[] = $this->replaceChar($ch0, 0xf700);
  5008. } else {
  5009. $output[] = $ch0;
  5010. }
  5011. } else {
  5012. // non-thai character
  5013. $output[] = $unicode[$i];
  5014. }
  5015. }
  5016. $unicode = $output;
  5017. // update font subsetchars
  5018. $this->setFontSubBuffer($this->CurrentFont['fontkey'], 'subsetchars', $this->CurrentFont['subsetchars']);
  5019. } // end of K_THAI_TOPCHARS
  5020. $txt2 = TCPDF_FONTS::arrUTF8ToUTF16BE($unicode, false);
  5021. }
  5022. }
  5023. $txt2 = TCPDF_STATIC::_escape($txt2);
  5024. // get current text width (considering general font stretching and spacing)
  5025. $txwidth = $this->GetStringWidth($txt);
  5026. $width = $txwidth;
  5027. // check for stretch mode
  5028. if ($stretch > 0) {
  5029. // calculate ratio between cell width and text width
  5030. if ($width <= 0) {
  5031. $ratio = 1;
  5032. } else {
  5033. $ratio = (($w - $this->cell_padding['L'] - $this->cell_padding['R']) / $width);
  5034. }
  5035. // check if stretching is required
  5036. if (($ratio < 1) OR (($ratio > 1) AND (($stretch % 2) == 0))) {
  5037. // the text will be stretched to fit cell width
  5038. if ($stretch > 2) {
  5039. // set new character spacing
  5040. $this->font_spacing += ($w - $this->cell_padding['L'] - $this->cell_padding['R'] - $width) / (max(($this->GetNumChars($txt) - 1), 1) * ($this->font_stretching / 100));
  5041. } else {
  5042. // set new horizontal stretching
  5043. $this->font_stretching *= $ratio;
  5044. }
  5045. // recalculate text width (the text fills the entire cell)
  5046. $width = $w - $this->cell_padding['L'] - $this->cell_padding['R'];
  5047. // reset alignment
  5048. $align = '';
  5049. }
  5050. }
  5051. if ($this->font_stretching != 100) {
  5052. // apply font stretching
  5053. $rs .= sprintf('BT %F Tz ET ', $this->font_stretching);
  5054. }
  5055. if ($this->font_spacing != 0) {
  5056. // increase/decrease font spacing
  5057. $rs .= sprintf('BT %F Tc ET ', ($this->font_spacing * $this->k));
  5058. }
  5059. if ($this->ColorFlag AND ($this->textrendermode < 4)) {
  5060. $s .= 'q '.$this->TextColor.' ';
  5061. }
  5062. // rendering mode
  5063. $s .= sprintf('BT %d Tr %F w ET ', $this->textrendermode, ($this->textstrokewidth * $this->k));
  5064. // count number of spaces
  5065. $ns = substr_count($txt, chr(32));
  5066. // Justification
  5067. $spacewidth = 0;
  5068. if (($align == 'J') AND ($ns > 0)) {
  5069. if ($this->isUnicodeFont()) {
  5070. // get string width without spaces
  5071. $width = $this->GetStringWidth(str_replace(' ', '', $txt));
  5072. // calculate average space width
  5073. $spacewidth = -1000 * ($w - $width - $this->cell_padding['L'] - $this->cell_padding['R']) / ($ns?$ns:1) / ($this->FontSize?$this->FontSize:1);
  5074. if ($this->font_stretching != 100) {
  5075. // word spacing is affected by stretching
  5076. $spacewidth /= ($this->font_stretching / 100);
  5077. }
  5078. // set word position to be used with TJ operator
  5079. $txt2 = str_replace(chr(0).chr(32), ') '.sprintf('%F', $spacewidth).' (', $txt2);
  5080. $unicode_justification = true;
  5081. } else {
  5082. // get string width
  5083. $width = $txwidth;
  5084. // new space width
  5085. $spacewidth = (($w - $width - $this->cell_padding['L'] - $this->cell_padding['R']) / ($ns?$ns:1)) * $this->k;
  5086. if ($this->font_stretching != 100) {
  5087. // word spacing (Tw) is affected by stretching
  5088. $spacewidth /= ($this->font_stretching / 100);
  5089. }
  5090. // set word spacing
  5091. $rs .= sprintf('BT %F Tw ET ', $spacewidth);
  5092. }
  5093. $width = $w - $this->cell_padding['L'] - $this->cell_padding['R'];
  5094. }
  5095. // replace carriage return characters
  5096. $txt2 = str_replace("\r", ' ', $txt2);
  5097. switch ($align) {
  5098. case 'C': {
  5099. $dx = ($w - $width) / 2;
  5100. break;
  5101. }
  5102. case 'R': {
  5103. if ($this->rtl) {
  5104. $dx = $this->cell_padding['R'];
  5105. } else {
  5106. $dx = $w - $width - $this->cell_padding['R'];
  5107. }
  5108. break;
  5109. }
  5110. case 'L': {
  5111. if ($this->rtl) {
  5112. $dx = $w - $width - $this->cell_padding['L'];
  5113. } else {
  5114. $dx = $this->cell_padding['L'];
  5115. }
  5116. break;
  5117. }
  5118. case 'J':
  5119. default: {
  5120. if ($this->rtl) {
  5121. $dx = $this->cell_padding['R'];
  5122. } else {
  5123. $dx = $this->cell_padding['L'];
  5124. }
  5125. break;
  5126. }
  5127. }
  5128. if ($this->rtl) {
  5129. $xdx = $x - $dx - $width;
  5130. } else {
  5131. $xdx = $x + $dx;
  5132. }
  5133. $xdk = $xdx * $k;
  5134. // print text
  5135. $s .= sprintf('BT %F %F Td [(%s)] TJ ET', $xdk, (($this->h - $basefonty) * $k), $txt2);
  5136. if (isset($uniblock)) {
  5137. // print overlapping characters as separate string
  5138. $xshift = 0; // horizontal shift
  5139. $ty = (($this->h - $basefonty + (0.2 * $this->FontSize)) * $k);
  5140. $spw = (($w - $txwidth - $this->cell_padding['L'] - $this->cell_padding['R']) / ($ns?$ns:1));
  5141. foreach ($uniblock as $uk => $uniarr) {
  5142. if (($uk % 2) == 0) {
  5143. // x space to skip
  5144. if ($spacewidth != 0) {
  5145. // justification shift
  5146. $xshift += (count(array_keys($uniarr, 32)) * $spw);
  5147. }
  5148. $xshift += $this->GetArrStringWidth($uniarr); // + shift justification
  5149. } else {
  5150. // character to print
  5151. $topchr = TCPDF_FONTS::arrUTF8ToUTF16BE($uniarr, false);
  5152. $topchr = TCPDF_STATIC::_escape($topchr);
  5153. $s .= sprintf(' BT %F %F Td [(%s)] TJ ET', ($xdk + ($xshift * $k)), $ty, $topchr);
  5154. }
  5155. }
  5156. }
  5157. if ($this->underline) {
  5158. $s .= ' '.$this->_dounderlinew($xdx, $basefonty, $width);
  5159. }
  5160. if ($this->linethrough) {
  5161. $s .= ' '.$this->_dolinethroughw($xdx, $basefonty, $width);
  5162. }
  5163. if ($this->overline) {
  5164. $s .= ' '.$this->_dooverlinew($xdx, $basefonty, $width);
  5165. }
  5166. if ($this->ColorFlag AND ($this->textrendermode < 4)) {
  5167. $s .= ' Q';
  5168. }
  5169. if ($link) {
  5170. $this->Link($xdx, $yt, $width, ($this->FontAscent + $this->FontDescent), $link, $ns);
  5171. }
  5172. }
  5173. // output cell
  5174. if ($s) {
  5175. // output cell
  5176. $rs .= $s;
  5177. if ($this->font_spacing != 0) {
  5178. // reset font spacing mode
  5179. $rs .= ' BT 0 Tc ET';
  5180. }
  5181. if ($this->font_stretching != 100) {
  5182. // reset font stretching mode
  5183. $rs .= ' BT 100 Tz ET';
  5184. }
  5185. }
  5186. // reset word spacing
  5187. if (!$this->isUnicodeFont() AND ($align == 'J')) {
  5188. $rs .= ' BT 0 Tw ET';
  5189. }
  5190. // reset stretching and spacing
  5191. $this->font_stretching = $prev_font_stretching;
  5192. $this->font_spacing = $prev_font_spacing;
  5193. $this->lasth = $h;
  5194. if ($ln > 0) {
  5195. //Go to the beginning of the next line
  5196. $this->y = $y + $h + $this->cell_margin['B'];
  5197. if ($ln == 1) {
  5198. if ($this->rtl) {
  5199. $this->x = $this->w - $this->rMargin;
  5200. } else {
  5201. $this->x = $this->lMargin;
  5202. }
  5203. }
  5204. } else {
  5205. // go left or right by case
  5206. if ($this->rtl) {
  5207. $this->x = $x - $w - $this->cell_margin['L'];
  5208. } else {
  5209. $this->x = $x + $w + $this->cell_margin['R'];
  5210. }
  5211. }
  5212. $gstyles = ''.$this->linestyleWidth.' '.$this->linestyleCap.' '.$this->linestyleJoin.' '.$this->linestyleDash.' '.$this->DrawColor.' '.$this->FillColor."\n";
  5213. $rs = $gstyles.$rs;
  5214. $this->cell_padding = $prev_cell_padding;
  5215. $this->cell_margin = $prev_cell_margin;
  5216. return $rs;
  5217. }
  5218. /**
  5219. * Replace a char if is defined on the current font.
  5220. * @param $oldchar (int) Integer code (unicode) of the character to replace.
  5221. * @param $newchar (int) Integer code (unicode) of the new character.
  5222. * @return int the replaced char or the old char in case the new char i not defined
  5223. * @protected
  5224. * @since 5.9.167 (2012-06-22)
  5225. */
  5226. protected function replaceChar($oldchar, $newchar) {
  5227. if ($this->isCharDefined($newchar)) {
  5228. // add the new char on the subset list
  5229. $this->CurrentFont['subsetchars'][$newchar] = true;
  5230. // return the new character
  5231. return $newchar;
  5232. }
  5233. // return the old char
  5234. return $oldchar;
  5235. }
  5236. /**
  5237. * Returns the code to draw the cell border
  5238. * @param $x (float) X coordinate.
  5239. * @param $y (float) Y coordinate.
  5240. * @param $w (float) Cell width.
  5241. * @param $h (float) Cell height.
  5242. * @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)))
  5243. * @return string containing cell border code
  5244. * @protected
  5245. * @see SetLineStyle()
  5246. * @since 5.7.000 (2010-08-02)
  5247. */
  5248. protected function getCellBorder($x, $y, $w, $h, $brd) {
  5249. $s = ''; // string to be returned
  5250. if (empty($brd)) {
  5251. return $s;
  5252. }
  5253. if ($brd == 1) {
  5254. $brd = array('LRTB' => true);
  5255. }
  5256. // calculate coordinates for border
  5257. $k = $this->k;
  5258. if ($this->rtl) {
  5259. $xeL = ($x - $w) * $k;
  5260. $xeR = $x * $k;
  5261. } else {
  5262. $xeL = $x * $k;
  5263. $xeR = ($x + $w) * $k;
  5264. }
  5265. $yeL = (($this->h - ($y + $h)) * $k);
  5266. $yeT = (($this->h - $y) * $k);
  5267. $xeT = $xeL;
  5268. $xeB = $xeR;
  5269. $yeR = $yeT;
  5270. $yeB = $yeL;
  5271. if (is_string($brd)) {
  5272. // convert string to array
  5273. $slen = strlen($brd);
  5274. $newbrd = array();
  5275. for ($i = 0; $i < $slen; ++$i) {
  5276. $newbrd[$brd[$i]] = array('cap' => 'square', 'join' => 'miter');
  5277. }
  5278. $brd = $newbrd;
  5279. }
  5280. if (isset($brd['mode'])) {
  5281. $mode = $brd['mode'];
  5282. unset($brd['mode']);
  5283. } else {
  5284. $mode = 'normal';
  5285. }
  5286. foreach ($brd as $border => $style) {
  5287. if (is_array($style) AND !empty($style)) {
  5288. // apply border style
  5289. $prev_style = $this->linestyleWidth.' '.$this->linestyleCap.' '.$this->linestyleJoin.' '.$this->linestyleDash.' '.$this->DrawColor.' ';
  5290. $s .= $this->SetLineStyle($style, true)."\n";
  5291. }
  5292. switch ($mode) {
  5293. case 'ext': {
  5294. $off = (($this->LineWidth / 2) * $k);
  5295. $xL = $xeL - $off;
  5296. $xR = $xeR + $off;
  5297. $yT = $yeT + $off;
  5298. $yL = $yeL - $off;
  5299. $xT = $xL;
  5300. $xB = $xR;
  5301. $yR = $yT;
  5302. $yB = $yL;
  5303. $w += $this->LineWidth;
  5304. $h += $this->LineWidth;
  5305. break;
  5306. }
  5307. case 'int': {
  5308. $off = ($this->LineWidth / 2) * $k;
  5309. $xL = $xeL + $off;
  5310. $xR = $xeR - $off;
  5311. $yT = $yeT - $off;
  5312. $yL = $yeL + $off;
  5313. $xT = $xL;
  5314. $xB = $xR;
  5315. $yR = $yT;
  5316. $yB = $yL;
  5317. $w -= $this->LineWidth;
  5318. $h -= $this->LineWidth;
  5319. break;
  5320. }
  5321. case 'normal':
  5322. default: {
  5323. $xL = $xeL;
  5324. $xT = $xeT;
  5325. $xB = $xeB;
  5326. $xR = $xeR;
  5327. $yL = $yeL;
  5328. $yT = $yeT;
  5329. $yB = $yeB;
  5330. $yR = $yeR;
  5331. break;
  5332. }
  5333. }
  5334. // draw borders by case
  5335. if (strlen($border) == 4) {
  5336. $s .= sprintf('%F %F %F %F re S ', $xT, $yT, ($w * $k), (-$h * $k));
  5337. } elseif (strlen($border) == 3) {
  5338. if (strpos($border,'B') === false) { // LTR
  5339. $s .= sprintf('%F %F m ', $xL, $yL);
  5340. $s .= sprintf('%F %F l ', $xT, $yT);
  5341. $s .= sprintf('%F %F l ', $xR, $yR);
  5342. $s .= sprintf('%F %F l ', $xB, $yB);
  5343. $s .= 'S ';
  5344. } elseif (strpos($border,'L') === false) { // TRB
  5345. $s .= sprintf('%F %F m ', $xT, $yT);
  5346. $s .= sprintf('%F %F l ', $xR, $yR);
  5347. $s .= sprintf('%F %F l ', $xB, $yB);
  5348. $s .= sprintf('%F %F l ', $xL, $yL);
  5349. $s .= 'S ';
  5350. } elseif (strpos($border,'T') === false) { // RBL
  5351. $s .= sprintf('%F %F m ', $xR, $yR);
  5352. $s .= sprintf('%F %F l ', $xB, $yB);
  5353. $s .= sprintf('%F %F l ', $xL, $yL);
  5354. $s .= sprintf('%F %F l ', $xT, $yT);
  5355. $s .= 'S ';
  5356. } elseif (strpos($border,'R') === false) { // BLT
  5357. $s .= sprintf('%F %F m ', $xB, $yB);
  5358. $s .= sprintf('%F %F l ', $xL, $yL);
  5359. $s .= sprintf('%F %F l ', $xT, $yT);
  5360. $s .= sprintf('%F %F l ', $xR, $yR);
  5361. $s .= 'S ';
  5362. }
  5363. } elseif (strlen($border) == 2) {
  5364. if ((strpos($border,'L') !== false) AND (strpos($border,'T') !== false)) { // LT
  5365. $s .= sprintf('%F %F m ', $xL, $yL);
  5366. $s .= sprintf('%F %F l ', $xT, $yT);
  5367. $s .= sprintf('%F %F l ', $xR, $yR);
  5368. $s .= 'S ';
  5369. } elseif ((strpos($border,'T') !== false) AND (strpos($border,'R') !== false)) { // TR
  5370. $s .= sprintf('%F %F m ', $xT, $yT);
  5371. $s .= sprintf('%F %F l ', $xR, $yR);
  5372. $s .= sprintf('%F %F l ', $xB, $yB);
  5373. $s .= 'S ';
  5374. } elseif ((strpos($border,'R') !== false) AND (strpos($border,'B') !== false)) { // RB
  5375. $s .= sprintf('%F %F m ', $xR, $yR);
  5376. $s .= sprintf('%F %F l ', $xB, $yB);
  5377. $s .= sprintf('%F %F l ', $xL, $yL);
  5378. $s .= 'S ';
  5379. } elseif ((strpos($border,'B') !== false) AND (strpos($border,'L') !== false)) { // BL
  5380. $s .= sprintf('%F %F m ', $xB, $yB);
  5381. $s .= sprintf('%F %F l ', $xL, $yL);
  5382. $s .= sprintf('%F %F l ', $xT, $yT);
  5383. $s .= 'S ';
  5384. } elseif ((strpos($border,'L') !== false) AND (strpos($border,'R') !== false)) { // LR
  5385. $s .= sprintf('%F %F m ', $xL, $yL);
  5386. $s .= sprintf('%F %F l ', $xT, $yT);
  5387. $s .= 'S ';
  5388. $s .= sprintf('%F %F m ', $xR, $yR);
  5389. $s .= sprintf('%F %F l ', $xB, $yB);
  5390. $s .= 'S ';
  5391. } elseif ((strpos($border,'T') !== false) AND (strpos($border,'B') !== false)) { // TB
  5392. $s .= sprintf('%F %F m ', $xT, $yT);
  5393. $s .= sprintf('%F %F l ', $xR, $yR);
  5394. $s .= 'S ';
  5395. $s .= sprintf('%F %F m ', $xB, $yB);
  5396. $s .= sprintf('%F %F l ', $xL, $yL);
  5397. $s .= 'S ';
  5398. }
  5399. } else { // strlen($border) == 1
  5400. if (strpos($border,'L') !== false) { // L
  5401. $s .= sprintf('%F %F m ', $xL, $yL);
  5402. $s .= sprintf('%F %F l ', $xT, $yT);
  5403. $s .= 'S ';
  5404. } elseif (strpos($border,'T') !== false) { // T
  5405. $s .= sprintf('%F %F m ', $xT, $yT);
  5406. $s .= sprintf('%F %F l ', $xR, $yR);
  5407. $s .= 'S ';
  5408. } elseif (strpos($border,'R') !== false) { // R
  5409. $s .= sprintf('%F %F m ', $xR, $yR);
  5410. $s .= sprintf('%F %F l ', $xB, $yB);
  5411. $s .= 'S ';
  5412. } elseif (strpos($border,'B') !== false) { // B
  5413. $s .= sprintf('%F %F m ', $xB, $yB);
  5414. $s .= sprintf('%F %F l ', $xL, $yL);
  5415. $s .= 'S ';
  5416. }
  5417. }
  5418. if (is_array($style) AND !empty($style)) {
  5419. // reset border style to previous value
  5420. $s .= "\n".$this->linestyleWidth.' '.$this->linestyleCap.' '.$this->linestyleJoin.' '.$this->linestyleDash.' '.$this->DrawColor."\n";
  5421. }
  5422. }
  5423. return $s;
  5424. }
  5425. /**
  5426. * This method allows printing text with line breaks.
  5427. * 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 />
  5428. * Text can be aligned, centered or justified. The cell block can be framed and the background painted.
  5429. * @param $w (float) Width of cells. If 0, they extend up to the right margin of the page.
  5430. * @param $h (float) Cell minimum height. The cell extends automatically if needed.
  5431. * @param $txt (string) String to print
  5432. * @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)))
  5433. * @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>
  5434. * @param $fill (boolean) Indicates if the cell background must be painted (true) or transparent (false).
  5435. * @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>
  5436. * @param $x (float) x position in user units
  5437. * @param $y (float) y position in user units
  5438. * @param $reseth (boolean) if true reset the last cell height (default true).
  5439. * @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.
  5440. * @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.
  5441. * @param $autopadding (boolean) if true, uses internal padding and automatically adjust it to account for line width.
  5442. * @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.
  5443. * @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.
  5444. * @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.
  5445. * @return int Return the number of cells or 1 for html mode.
  5446. * @public
  5447. * @since 1.3
  5448. * @see SetFont(), SetDrawColor(), SetFillColor(), SetTextColor(), SetLineWidth(), Cell(), Write(), SetAutoPageBreak()
  5449. */
  5450. 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) {
  5451. $prev_cell_margin = $this->cell_margin;
  5452. $prev_cell_padding = $this->cell_padding;
  5453. // adjust internal padding
  5454. $this->adjustCellPadding($border);
  5455. $mc_padding = $this->cell_padding;
  5456. $mc_margin = $this->cell_margin;
  5457. $this->cell_padding['T'] = 0;
  5458. $this->cell_padding['B'] = 0;
  5459. $this->setCellMargins(0, 0, 0, 0);
  5460. if (TCPDF_STATIC::empty_string($this->lasth) OR $reseth) {
  5461. // reset row height
  5462. $this->resetLastH();
  5463. }
  5464. if (!TCPDF_STATIC::empty_string($y)) {
  5465. $this->SetY($y); // set y in order to convert negative y values to positive ones
  5466. }
  5467. $y = $this->GetY();
  5468. $resth = 0;
  5469. if (($h > 0) AND $this->inPageBody() AND (($y + $h + $mc_margin['T'] + $mc_margin['B']) > $this->PageBreakTrigger)) {
  5470. // spit cell in more pages/columns
  5471. $newh = ($this->PageBreakTrigger - $y);
  5472. $resth = ($h - $newh); // cell to be printed on the next page/column
  5473. $h = $newh;
  5474. }
  5475. // get current page number
  5476. $startpage = $this->page;
  5477. // get current column
  5478. $startcolumn = $this->current_column;
  5479. if (!TCPDF_STATIC::empty_string($x)) {
  5480. $this->SetX($x);
  5481. } else {
  5482. $x = $this->GetX();
  5483. }
  5484. // check page for no-write regions and adapt page margins if necessary
  5485. list($x, $y) = $this->checkPageRegions(0, $x, $y);
  5486. // apply margins
  5487. $oy = $y + $mc_margin['T'];
  5488. if ($this->rtl) {
  5489. $ox = ($this->w - $x - $mc_margin['R']);
  5490. } else {
  5491. $ox = ($x + $mc_margin['L']);
  5492. }
  5493. $this->x = $ox;
  5494. $this->y = $oy;
  5495. // set width
  5496. if (TCPDF_STATIC::empty_string($w) OR ($w <= 0)) {
  5497. if ($this->rtl) {
  5498. $w = ($this->x - $this->lMargin - $mc_margin['L']);
  5499. } else {
  5500. $w = ($this->w - $this->x - $this->rMargin - $mc_margin['R']);
  5501. }
  5502. }
  5503. // store original margin values
  5504. $lMargin = $this->lMargin;
  5505. $rMargin = $this->rMargin;
  5506. if ($this->rtl) {
  5507. $this->rMargin = ($this->w - $this->x);
  5508. $this->lMargin = ($this->x - $w);
  5509. } else {
  5510. $this->lMargin = ($this->x);
  5511. $this->rMargin = ($this->w - $this->x - $w);
  5512. }
  5513. $this->clMargin = $this->lMargin;
  5514. $this->crMargin = $this->rMargin;
  5515. if ($autopadding) {
  5516. // add top padding
  5517. $this->y += $mc_padding['T'];
  5518. }
  5519. if ($ishtml) { // ******* Write HTML text
  5520. $this->writeHTML($txt, true, false, $reseth, true, $align);
  5521. $nl = 1;
  5522. } else { // ******* Write simple text
  5523. $prev_FontSizePt = $this->FontSizePt;
  5524. if ($fitcell) {
  5525. // ajust height values
  5526. $tobottom = ($this->h - $this->y - $this->bMargin - $this->cell_padding['T'] - $this->cell_padding['B']);
  5527. $h = $maxh = max(min($h, $tobottom), min($maxh, $tobottom));
  5528. }
  5529. // vertical alignment
  5530. if ($maxh > 0) {
  5531. // get text height
  5532. $text_height = $this->getStringHeight($w, $txt, $reseth, $autopadding, $mc_padding, $border);
  5533. if ($fitcell AND ($text_height > $maxh) AND ($this->FontSizePt > 1)) {
  5534. // try to reduce font size to fit text on cell (use a quick search algorithm)
  5535. $fmin = 1;
  5536. $fmax = $this->FontSizePt;
  5537. $diff_epsilon = (1 / $this->k); // one point (min resolution)
  5538. $maxit = (2 * min(100, max(10, intval($fmax)))); // max number of iterations
  5539. while ($maxit >= 0) {
  5540. $fmid = (($fmax + $fmin) / 2);
  5541. $this->SetFontSize($fmid, false);
  5542. $this->resetLastH();
  5543. $text_height = $this->getStringHeight($w, $txt, $reseth, $autopadding, $mc_padding, $border);
  5544. $diff = ($maxh - $text_height);
  5545. if ($diff >= 0) {
  5546. if ($diff <= $diff_epsilon) {
  5547. break;
  5548. }
  5549. $fmin = $fmid;
  5550. } else {
  5551. $fmax = $fmid;
  5552. }
  5553. --$maxit;
  5554. }
  5555. if ($maxit < 0) {
  5556. // premature exit, we get the minimum font value to fit the cell
  5557. $this->SetFontSize($fmin);
  5558. $this->resetLastH();
  5559. $text_height = $this->getStringHeight($w, $txt, $reseth, $autopadding, $mc_padding, $border);
  5560. } else {
  5561. $this->SetFontSize($fmid);
  5562. $this->resetLastH();
  5563. }
  5564. }
  5565. if ($text_height < $maxh) {
  5566. if ($valign == 'M') {
  5567. // text vertically centered
  5568. $this->y += (($maxh - $text_height) / 2);
  5569. } elseif ($valign == 'B') {
  5570. // text vertically aligned on bottom
  5571. $this->y += ($maxh - $text_height);
  5572. }
  5573. }
  5574. }
  5575. $nl = $this->Write($this->lasth, $txt, '', 0, $align, true, $stretch, false, true, $maxh, 0, $mc_margin);
  5576. if ($fitcell) {
  5577. // restore font size
  5578. $this->SetFontSize($prev_FontSizePt);
  5579. }
  5580. }
  5581. if ($autopadding) {
  5582. // add bottom padding
  5583. $this->y += $mc_padding['B'];
  5584. }
  5585. // Get end-of-text Y position
  5586. $currentY = $this->y;
  5587. // get latest page number
  5588. $endpage = $this->page;
  5589. if ($resth > 0) {
  5590. $skip = ($endpage - $startpage);
  5591. $tmpresth = $resth;
  5592. while ($tmpresth > 0) {
  5593. if ($skip <= 0) {
  5594. // add a page (or trig AcceptPageBreak() for multicolumn mode)
  5595. $this->checkPageBreak($this->PageBreakTrigger + 1);
  5596. }
  5597. if ($this->num_columns > 1) {
  5598. $tmpresth -= ($this->h - $this->y - $this->bMargin);
  5599. } else {
  5600. $tmpresth -= ($this->h - $this->tMargin - $this->bMargin);
  5601. }
  5602. --$skip;
  5603. }
  5604. $currentY = $this->y;
  5605. $endpage = $this->page;
  5606. }
  5607. // get latest column
  5608. $endcolumn = $this->current_column;
  5609. if ($this->num_columns == 0) {
  5610. $this->num_columns = 1;
  5611. }
  5612. // disable page regions check
  5613. $check_page_regions = $this->check_page_regions;
  5614. $this->check_page_regions = false;
  5615. // get border modes
  5616. $border_start = TCPDF_STATIC::getBorderMode($border, $position='start', $this->opencell);
  5617. $border_end = TCPDF_STATIC::getBorderMode($border, $position='end', $this->opencell);
  5618. $border_middle = TCPDF_STATIC::getBorderMode($border, $position='middle', $this->opencell);
  5619. // design borders around HTML cells.
  5620. for ($page = $startpage; $page <= $endpage; ++$page) { // for each page
  5621. $ccode = '';
  5622. $this->setPage($page);
  5623. if ($this->num_columns < 2) {
  5624. // single-column mode
  5625. $this->SetX($x);
  5626. $this->y = $this->tMargin;
  5627. }
  5628. // account for margin changes
  5629. if ($page > $startpage) {
  5630. if (($this->rtl) AND ($this->pagedim[$page]['orm'] != $this->pagedim[$startpage]['orm'])) {
  5631. $this->x -= ($this->pagedim[$page]['orm'] - $this->pagedim[$startpage]['orm']);
  5632. } elseif ((!$this->rtl) AND ($this->pagedim[$page]['olm'] != $this->pagedim[$startpage]['olm'])) {
  5633. $this->x += ($this->pagedim[$page]['olm'] - $this->pagedim[$startpage]['olm']);
  5634. }
  5635. }
  5636. if ($startpage == $endpage) {
  5637. // single page
  5638. for ($column = $startcolumn; $column <= $endcolumn; ++$column) { // for each column
  5639. if ($column != $this->current_column) {
  5640. $this->selectColumn($column);
  5641. }
  5642. if ($this->rtl) {
  5643. $this->x -= $mc_margin['R'];
  5644. } else {
  5645. $this->x += $mc_margin['L'];
  5646. }
  5647. if ($startcolumn == $endcolumn) { // single column
  5648. $cborder = $border;
  5649. $h = max($h, ($currentY - $oy));
  5650. $this->y = $oy;
  5651. } elseif ($column == $startcolumn) { // first column
  5652. $cborder = $border_start;
  5653. $this->y = $oy;
  5654. $h = $this->h - $this->y - $this->bMargin;
  5655. } elseif ($column == $endcolumn) { // end column
  5656. $cborder = $border_end;
  5657. $h = $currentY - $this->y;
  5658. if ($resth > $h) {
  5659. $h = $resth;
  5660. }
  5661. } else { // middle column
  5662. $cborder = $border_middle;
  5663. $h = $this->h - $this->y - $this->bMargin;
  5664. $resth -= $h;
  5665. }
  5666. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  5667. } // end for each column
  5668. } elseif ($page == $startpage) { // first page
  5669. for ($column = $startcolumn; $column < $this->num_columns; ++$column) { // for each column
  5670. if ($column != $this->current_column) {
  5671. $this->selectColumn($column);
  5672. }
  5673. if ($this->rtl) {
  5674. $this->x -= $mc_margin['R'];
  5675. } else {
  5676. $this->x += $mc_margin['L'];
  5677. }
  5678. if ($column == $startcolumn) { // first column
  5679. $cborder = $border_start;
  5680. $this->y = $oy;
  5681. $h = $this->h - $this->y - $this->bMargin;
  5682. } else { // middle column
  5683. $cborder = $border_middle;
  5684. $h = $this->h - $this->y - $this->bMargin;
  5685. $resth -= $h;
  5686. }
  5687. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  5688. } // end for each column
  5689. } elseif ($page == $endpage) { // last page
  5690. for ($column = 0; $column <= $endcolumn; ++$column) { // for each column
  5691. if ($column != $this->current_column) {
  5692. $this->selectColumn($column);
  5693. }
  5694. if ($this->rtl) {
  5695. $this->x -= $mc_margin['R'];
  5696. } else {
  5697. $this->x += $mc_margin['L'];
  5698. }
  5699. if ($column == $endcolumn) {
  5700. // end column
  5701. $cborder = $border_end;
  5702. $h = $currentY - $this->y;
  5703. if ($resth > $h) {
  5704. $h = $resth;
  5705. }
  5706. } else {
  5707. // middle column
  5708. $cborder = $border_middle;
  5709. $h = $this->h - $this->y - $this->bMargin;
  5710. $resth -= $h;
  5711. }
  5712. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  5713. } // end for each column
  5714. } else { // middle page
  5715. for ($column = 0; $column < $this->num_columns; ++$column) { // for each column
  5716. $this->selectColumn($column);
  5717. if ($this->rtl) {
  5718. $this->x -= $mc_margin['R'];
  5719. } else {
  5720. $this->x += $mc_margin['L'];
  5721. }
  5722. $cborder = $border_middle;
  5723. $h = $this->h - $this->y - $this->bMargin;
  5724. $resth -= $h;
  5725. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  5726. } // end for each column
  5727. }
  5728. if ($cborder OR $fill) {
  5729. $offsetlen = strlen($ccode);
  5730. // draw border and fill
  5731. if ($this->inxobj) {
  5732. // we are inside an XObject template
  5733. if (end($this->xobjects[$this->xobjid]['transfmrk']) !== false) {
  5734. $pagemarkkey = key($this->xobjects[$this->xobjid]['transfmrk']);
  5735. $pagemark = $this->xobjects[$this->xobjid]['transfmrk'][$pagemarkkey];
  5736. $this->xobjects[$this->xobjid]['transfmrk'][$pagemarkkey] += $offsetlen;
  5737. } else {
  5738. $pagemark = $this->xobjects[$this->xobjid]['intmrk'];
  5739. $this->xobjects[$this->xobjid]['intmrk'] += $offsetlen;
  5740. }
  5741. $pagebuff = $this->xobjects[$this->xobjid]['outdata'];
  5742. $pstart = substr($pagebuff, 0, $pagemark);
  5743. $pend = substr($pagebuff, $pagemark);
  5744. $this->xobjects[$this->xobjid]['outdata'] = $pstart.$ccode.$pend;
  5745. } else {
  5746. if (end($this->transfmrk[$this->page]) !== false) {
  5747. $pagemarkkey = key($this->transfmrk[$this->page]);
  5748. $pagemark = $this->transfmrk[$this->page][$pagemarkkey];
  5749. $this->transfmrk[$this->page][$pagemarkkey] += $offsetlen;
  5750. } elseif ($this->InFooter) {
  5751. $pagemark = $this->footerpos[$this->page];
  5752. $this->footerpos[$this->page] += $offsetlen;
  5753. } else {
  5754. $pagemark = $this->intmrk[$this->page];
  5755. $this->intmrk[$this->page] += $offsetlen;
  5756. }
  5757. $pagebuff = $this->getPageBuffer($this->page);
  5758. $pstart = substr($pagebuff, 0, $pagemark);
  5759. $pend = substr($pagebuff, $pagemark);
  5760. $this->setPageBuffer($this->page, $pstart.$ccode.$pend);
  5761. }
  5762. }
  5763. } // end for each page
  5764. // restore page regions check
  5765. $this->check_page_regions = $check_page_regions;
  5766. // Get end-of-cell Y position
  5767. $currentY = $this->GetY();
  5768. // restore previous values
  5769. if ($this->num_columns > 1) {
  5770. $this->selectColumn();
  5771. } else {
  5772. // restore original margins
  5773. $this->lMargin = $lMargin;
  5774. $this->rMargin = $rMargin;
  5775. if ($this->page > $startpage) {
  5776. // check for margin variations between pages (i.e. booklet mode)
  5777. $dl = ($this->pagedim[$this->page]['olm'] - $this->pagedim[$startpage]['olm']);
  5778. $dr = ($this->pagedim[$this->page]['orm'] - $this->pagedim[$startpage]['orm']);
  5779. if (($dl != 0) OR ($dr != 0)) {
  5780. $this->lMargin += $dl;
  5781. $this->rMargin += $dr;
  5782. }
  5783. }
  5784. }
  5785. if ($ln > 0) {
  5786. //Go to the beginning of the next line
  5787. $this->SetY($currentY + $mc_margin['B']);
  5788. if ($ln == 2) {
  5789. $this->SetX($x + $w + $mc_margin['L'] + $mc_margin['R']);
  5790. }
  5791. } else {
  5792. // go left or right by case
  5793. $this->setPage($startpage);
  5794. $this->y = $y;
  5795. $this->SetX($x + $w + $mc_margin['L'] + $mc_margin['R']);
  5796. }
  5797. $this->setContentMark();
  5798. $this->cell_padding = $prev_cell_padding;
  5799. $this->cell_margin = $prev_cell_margin;
  5800. $this->clMargin = $this->lMargin;
  5801. $this->crMargin = $this->rMargin;
  5802. return $nl;
  5803. }
  5804. /**
  5805. * This method return the estimated number of lines for print a simple text string using Multicell() method.
  5806. * @param $txt (string) String for calculating his height
  5807. * @param $w (float) Width of cells. If 0, they extend up to the right margin of the page.
  5808. * @param $reseth (boolean) if true reset the last cell height (default false).
  5809. * @param $autopadding (boolean) if true, uses internal padding and automatically adjust it to account for line width (default true).
  5810. * @param $cellpadding (float) Internal cell padding, if empty uses default cell padding.
  5811. * @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)))
  5812. * @return float Return the minimal height needed for multicell method for printing the $txt param.
  5813. * @author Alexander Escalona Fern\E1ndez, Nicola Asuni
  5814. * @public
  5815. * @since 4.5.011
  5816. */
  5817. public function getNumLines($txt, $w=0, $reseth=false, $autopadding=true, $cellpadding='', $border=0) {
  5818. if ($txt === NULL) {
  5819. return 0;
  5820. }
  5821. if ($txt === '') {
  5822. // empty string
  5823. return 1;
  5824. }
  5825. // adjust internal padding
  5826. $prev_cell_padding = $this->cell_padding;
  5827. $prev_lasth = $this->lasth;
  5828. if (is_array($cellpadding)) {
  5829. $this->cell_padding = $cellpadding;
  5830. }
  5831. $this->adjustCellPadding($border);
  5832. if (TCPDF_STATIC::empty_string($w) OR ($w <= 0)) {
  5833. if ($this->rtl) {
  5834. $w = $this->x - $this->lMargin;
  5835. } else {
  5836. $w = $this->w - $this->rMargin - $this->x;
  5837. }
  5838. }
  5839. $wmax = $w - $this->cell_padding['L'] - $this->cell_padding['R'];
  5840. if ($reseth) {
  5841. // reset row height
  5842. $this->resetLastH();
  5843. }
  5844. $lines = 1;
  5845. $sum = 0;
  5846. $chars = TCPDF_FONTS::utf8Bidi(TCPDF_FONTS::UTF8StringToArray($txt, $this->isunicode, $this->CurrentFont), $txt, $this->tmprtl, $this->isunicode, $this->CurrentFont);
  5847. $charsWidth = $this->GetArrStringWidth($chars, '', '', 0, true);
  5848. $length = count($chars);
  5849. $lastSeparator = -1;
  5850. for ($i = 0; $i < $length; ++$i) {
  5851. $c = $chars[$i];
  5852. $charWidth = $charsWidth[$i];
  5853. if (($c != 160)
  5854. AND (($c == 173)
  5855. OR preg_match($this->re_spaces, TCPDF_FONTS::unichr($c, $this->isunicode))
  5856. OR (($c == 45)
  5857. AND ($i > 0) AND ($i < ($length - 1))
  5858. AND @preg_match('/[\p{L}]/'.$this->re_space['m'], TCPDF_FONTS::unichr($chars[($i - 1)], $this->isunicode))
  5859. AND @preg_match('/[\p{L}]/'.$this->re_space['m'], TCPDF_FONTS::unichr($chars[($i + 1)], $this->isunicode))
  5860. )
  5861. )
  5862. ) {
  5863. $lastSeparator = $i;
  5864. }
  5865. if ((($sum + $charWidth) > $wmax) OR ($c == 10)) {
  5866. ++$lines;
  5867. if ($c == 10) {
  5868. $lastSeparator = -1;
  5869. $sum = 0;
  5870. } elseif ($lastSeparator != -1) {
  5871. $i = $lastSeparator;
  5872. $lastSeparator = -1;
  5873. $sum = 0;
  5874. } else {
  5875. $sum = $charWidth;
  5876. }
  5877. } else {
  5878. $sum += $charWidth;
  5879. }
  5880. }
  5881. if ($chars[($length - 1)] == 10) {
  5882. --$lines;
  5883. }
  5884. $this->cell_padding = $prev_cell_padding;
  5885. $this->lasth = $prev_lasth;
  5886. return $lines;
  5887. }
  5888. /**
  5889. * This method return the estimated height needed for printing a simple text string using the Multicell() method.
  5890. * Generally, if you want to know the exact height for a block of content you can use the following alternative technique:
  5891. * @pre
  5892. * // store current object
  5893. * $pdf->startTransaction();
  5894. * // store starting values
  5895. * $start_y = $pdf->GetY();
  5896. * $start_page = $pdf->getPage();
  5897. * // call your printing functions with your parameters
  5898. * // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  5899. * $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);
  5900. * // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  5901. * // get the new Y
  5902. * $end_y = $pdf->GetY();
  5903. * $end_page = $pdf->getPage();
  5904. * // calculate height
  5905. * $height = 0;
  5906. * if ($end_page == $start_page) {
  5907. * $height = $end_y - $start_y;
  5908. * } else {
  5909. * for ($page=$start_page; $page <= $end_page; ++$page) {
  5910. * $this->setPage($page);
  5911. * if ($page == $start_page) {
  5912. * // first page
  5913. * $height += $this->h - $start_y - $this->bMargin;
  5914. * } elseif ($page == $end_page) {
  5915. * // last page
  5916. * $height += $end_y - $this->tMargin;
  5917. * } else {
  5918. * $height += $this->h - $this->tMargin - $this->bMargin;
  5919. * }
  5920. * }
  5921. * }
  5922. * // restore previous object
  5923. * $pdf = $pdf->rollbackTransaction();
  5924. *
  5925. * @param $w (float) Width of cells. If 0, they extend up to the right margin of the page.
  5926. * @param $txt (string) String for calculating his height
  5927. * @param $reseth (boolean) if true reset the last cell height (default false).
  5928. * @param $autopadding (boolean) if true, uses internal padding and automatically adjust it to account for line width (default true).
  5929. * @param $cellpadding (float) Internal cell padding, if empty uses default cell padding.
  5930. * @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)))
  5931. * @return float Return the minimal height needed for multicell method for printing the $txt param.
  5932. * @author Nicola Asuni, Alexander Escalona Fern\E1ndez
  5933. * @public
  5934. */
  5935. public function getStringHeight($w, $txt, $reseth=false, $autopadding=true, $cellpadding='', $border=0) {
  5936. // adjust internal padding
  5937. $prev_cell_padding = $this->cell_padding;
  5938. $prev_lasth = $this->lasth;
  5939. if (is_array($cellpadding)) {
  5940. $this->cell_padding = $cellpadding;
  5941. }
  5942. $this->adjustCellPadding($border);
  5943. $lines = $this->getNumLines($txt, $w, $reseth, $autopadding, $cellpadding, $border);
  5944. $height = $this->getCellHeight(($lines * $this->FontSize), $autopadding);
  5945. $this->cell_padding = $prev_cell_padding;
  5946. $this->lasth = $prev_lasth;
  5947. return $height;
  5948. }
  5949. /**
  5950. * This method prints text from the current position.<br />
  5951. * @param $h (float) Line height
  5952. * @param $txt (string) String to print
  5953. * @param $link (mixed) URL or identifier returned by AddLink()
  5954. * @param $fill (boolean) Indicates if the cell background must be painted (true) or transparent (false).
  5955. * @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>
  5956. * @param $ln (boolean) if true set cursor at the bottom of the line, otherwise set cursor at the top of the line.
  5957. * @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.
  5958. * @param $firstline (boolean) if true prints only the first line and return the remaining string.
  5959. * @param $firstblock (boolean) if true the string is the starting of a line.
  5960. * @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.
  5961. * @param $wadj (float) first line width will be reduced by this amount (used in HTML mode).
  5962. * @param $margin (array) margin array of the parent container
  5963. * @return mixed Return the number of cells or the remaining string if $firstline = true.
  5964. * @public
  5965. * @since 1.5
  5966. */
  5967. public function Write($h, $txt, $link='', $fill=false, $align='', $ln=false, $stretch=0, $firstline=false, $firstblock=false, $maxh=0, $wadj=0, $margin='') {
  5968. // check page for no-write regions and adapt page margins if necessary
  5969. list($this->x, $this->y) = $this->checkPageRegions($h, $this->x, $this->y);
  5970. if (strlen($txt) == 0) {
  5971. // fix empty text
  5972. $txt = ' ';
  5973. }
  5974. if ($margin === '') {
  5975. // set default margins
  5976. $margin = $this->cell_margin;
  5977. }
  5978. // remove carriage returns
  5979. $s = str_replace("\r", '', $txt);
  5980. // check if string contains arabic text
  5981. if (preg_match(TCPDF_FONT_DATA::$uni_RE_PATTERN_ARABIC, $s)) {
  5982. $arabic = true;
  5983. } else {
  5984. $arabic = false;
  5985. }
  5986. // check if string contains RTL text
  5987. if ($arabic OR ($this->tmprtl == 'R') OR preg_match(TCPDF_FONT_DATA::$uni_RE_PATTERN_RTL, $s)) {
  5988. $rtlmode = true;
  5989. } else {
  5990. $rtlmode = false;
  5991. }
  5992. // get a char width
  5993. $chrwidth = $this->GetCharWidth(46); // dot character
  5994. // get array of unicode values
  5995. $chars = TCPDF_FONTS::UTF8StringToArray($s, $this->isunicode, $this->CurrentFont);
  5996. // calculate maximum width for a single character on string
  5997. $chrw = $this->GetArrStringWidth($chars, '', '', 0, true);
  5998. array_walk($chrw, array($this, 'getRawCharWidth'));
  5999. $maxchwidth = max($chrw);
  6000. // get array of chars
  6001. $uchars = TCPDF_FONTS::UTF8ArrayToUniArray($chars, $this->isunicode);
  6002. // get the number of characters
  6003. $nb = count($chars);
  6004. // replacement for SHY character (minus symbol)
  6005. $shy_replacement = 45;
  6006. $shy_replacement_char = TCPDF_FONTS::unichr($shy_replacement, $this->isunicode);
  6007. // widht for SHY replacement
  6008. $shy_replacement_width = $this->GetCharWidth($shy_replacement);
  6009. // page width
  6010. $pw = $w = $this->w - $this->lMargin - $this->rMargin;
  6011. // calculate remaining line width ($w)
  6012. if ($this->rtl) {
  6013. $w = $this->x - $this->lMargin;
  6014. } else {
  6015. $w = $this->w - $this->rMargin - $this->x;
  6016. }
  6017. // max column width
  6018. $wmax = ($w - $wadj);
  6019. if (!$firstline) {
  6020. $wmax -= ($this->cell_padding['L'] + $this->cell_padding['R']);
  6021. }
  6022. if ((!$firstline) AND (($chrwidth > $wmax) OR ($maxchwidth > $wmax))) {
  6023. // the maximum width character do not fit on column
  6024. return '';
  6025. }
  6026. // minimum row height
  6027. $row_height = max($h, $this->getCellHeight($this->FontSize));
  6028. // max Y
  6029. $maxy = $this->y + $maxh - max($row_height, $h);
  6030. $start_page = $this->page;
  6031. $i = 0; // character position
  6032. $j = 0; // current starting position
  6033. $sep = -1; // position of the last blank space
  6034. $prevsep = $sep; // previous separator
  6035. $shy = false; // true if the last blank is a soft hypen (SHY)
  6036. $prevshy = $shy; // previous shy mode
  6037. $l = 0; // current string length
  6038. $nl = 0; //number of lines
  6039. $linebreak = false;
  6040. $pc = 0; // previous character
  6041. // for each character
  6042. while ($i < $nb) {
  6043. if (($maxh > 0) AND ($this->y > $maxy) ) {
  6044. break;
  6045. }
  6046. //Get the current character
  6047. $c = $chars[$i];
  6048. if ($c == 10) { // 10 = "\n" = new line
  6049. //Explicit line break
  6050. if ($align == 'J') {
  6051. if ($this->rtl) {
  6052. $talign = 'R';
  6053. } else {
  6054. $talign = 'L';
  6055. }
  6056. } else {
  6057. $talign = $align;
  6058. }
  6059. $tmpstr = TCPDF_FONTS::UniArrSubString($uchars, $j, $i);
  6060. if ($firstline) {
  6061. $startx = $this->x;
  6062. $tmparr = array_slice($chars, $j, ($i - $j));
  6063. if ($rtlmode) {
  6064. $tmparr = TCPDF_FONTS::utf8Bidi($tmparr, $tmpstr, $this->tmprtl, $this->isunicode, $this->CurrentFont);
  6065. }
  6066. $linew = $this->GetArrStringWidth($tmparr);
  6067. unset($tmparr);
  6068. if ($this->rtl) {
  6069. $this->endlinex = $startx - $linew;
  6070. } else {
  6071. $this->endlinex = $startx + $linew;
  6072. }
  6073. $w = $linew;
  6074. $tmpcellpadding = $this->cell_padding;
  6075. if ($maxh == 0) {
  6076. $this->SetCellPadding(0);
  6077. }
  6078. }
  6079. if ($firstblock AND $this->isRTLTextDir()) {
  6080. $tmpstr = $this->stringRightTrim($tmpstr);
  6081. }
  6082. // Skip newlines at the beginning of a page or column
  6083. if (!empty($tmpstr) OR ($this->y < ($this->PageBreakTrigger - $row_height))) {
  6084. $this->Cell($w, $h, $tmpstr, 0, 1, $talign, $fill, $link, $stretch);
  6085. }
  6086. unset($tmpstr);
  6087. if ($firstline) {
  6088. $this->cell_padding = $tmpcellpadding;
  6089. return (TCPDF_FONTS::UniArrSubString($uchars, $i));
  6090. }
  6091. ++$nl;
  6092. $j = $i + 1;
  6093. $l = 0;
  6094. $sep = -1;
  6095. $prevsep = $sep;
  6096. $shy = false;
  6097. // account for margin changes
  6098. if ((($this->y + $this->lasth) > $this->PageBreakTrigger) AND ($this->inPageBody())) {
  6099. $this->AcceptPageBreak();
  6100. if ($this->rtl) {
  6101. $this->x -= $margin['R'];
  6102. } else {
  6103. $this->x += $margin['L'];
  6104. }
  6105. $this->lMargin += $margin['L'];
  6106. $this->rMargin += $margin['R'];
  6107. }
  6108. $w = $this->getRemainingWidth();
  6109. $wmax = ($w - $this->cell_padding['L'] - $this->cell_padding['R']);
  6110. } else {
  6111. // 160 is the non-breaking space.
  6112. // 173 is SHY (Soft Hypen).
  6113. // \p{Z} or \p{Separator}: any kind of Unicode whitespace or invisible separator.
  6114. // \p{Lo} or \p{Other_Letter}: a Unicode letter or ideograph that does not have lowercase and uppercase variants.
  6115. // \p{Lo} is needed because Chinese characters are packed next to each other without spaces in between.
  6116. if (($c != 160)
  6117. AND (($c == 173)
  6118. OR preg_match($this->re_spaces, TCPDF_FONTS::unichr($c, $this->isunicode))
  6119. OR (($c == 45)
  6120. AND ($i < ($nb - 1))
  6121. AND @preg_match('/[\p{L}]/'.$this->re_space['m'], TCPDF_FONTS::unichr($pc, $this->isunicode))
  6122. AND @preg_match('/[\p{L}]/'.$this->re_space['m'], TCPDF_FONTS::unichr($chars[($i + 1)], $this->isunicode))
  6123. )
  6124. )
  6125. ) {
  6126. // update last blank space position
  6127. $prevsep = $sep;
  6128. $sep = $i;
  6129. // check if is a SHY
  6130. if (($c == 173) OR ($c == 45)) {
  6131. $prevshy = $shy;
  6132. $shy = true;
  6133. if ($pc == 45) {
  6134. $tmp_shy_replacement_width = 0;
  6135. $tmp_shy_replacement_char = '';
  6136. } else {
  6137. $tmp_shy_replacement_width = $shy_replacement_width;
  6138. $tmp_shy_replacement_char = $shy_replacement_char;
  6139. }
  6140. } else {
  6141. $shy = false;
  6142. }
  6143. }
  6144. // update string length
  6145. if ($this->isUnicodeFont() AND ($arabic)) {
  6146. // with bidirectional algorithm some chars may be changed affecting the line length
  6147. // *** very slow ***
  6148. $l = $this->GetArrStringWidth(TCPDF_FONTS::utf8Bidi(array_slice($chars, $j, ($i - $j)), '', $this->tmprtl, $this->isunicode, $this->CurrentFont));
  6149. } else {
  6150. $l += $this->GetCharWidth($c, ($i+1 < $nb));
  6151. }
  6152. if (($l > $wmax) OR (($c == 173) AND (($l + $tmp_shy_replacement_width) >= $wmax))) {
  6153. if (($c == 173) AND (($l + $tmp_shy_replacement_width) > $wmax)) {
  6154. $sep = $prevsep;
  6155. $shy = $prevshy;
  6156. }
  6157. // we have reached the end of column
  6158. if ($sep == -1) {
  6159. // check if the line was already started
  6160. if (($this->rtl AND ($this->x <= ($this->w - $this->rMargin - $this->cell_padding['R'] - $margin['R'] - $chrwidth)))
  6161. OR ((!$this->rtl) AND ($this->x >= ($this->lMargin + $this->cell_padding['L'] + $margin['L'] + $chrwidth)))) {
  6162. // print a void cell and go to next line
  6163. $this->Cell($w, $h, '', 0, 1);
  6164. $linebreak = true;
  6165. if ($firstline) {
  6166. return (TCPDF_FONTS::UniArrSubString($uchars, $j));
  6167. }
  6168. } else {
  6169. // truncate the word because do not fit on column
  6170. $tmpstr = TCPDF_FONTS::UniArrSubString($uchars, $j, $i);
  6171. if ($firstline) {
  6172. $startx = $this->x;
  6173. $tmparr = array_slice($chars, $j, ($i - $j));
  6174. if ($rtlmode) {
  6175. $tmparr = TCPDF_FONTS::utf8Bidi($tmparr, $tmpstr, $this->tmprtl, $this->isunicode, $this->CurrentFont);
  6176. }
  6177. $linew = $this->GetArrStringWidth($tmparr);
  6178. unset($tmparr);
  6179. if ($this->rtl) {
  6180. $this->endlinex = $startx - $linew;
  6181. } else {
  6182. $this->endlinex = $startx + $linew;
  6183. }
  6184. $w = $linew;
  6185. $tmpcellpadding = $this->cell_padding;
  6186. if ($maxh == 0) {
  6187. $this->SetCellPadding(0);
  6188. }
  6189. }
  6190. if ($firstblock AND $this->isRTLTextDir()) {
  6191. $tmpstr = $this->stringRightTrim($tmpstr);
  6192. }
  6193. $this->Cell($w, $h, $tmpstr, 0, 1, $align, $fill, $link, $stretch);
  6194. unset($tmpstr);
  6195. if ($firstline) {
  6196. $this->cell_padding = $tmpcellpadding;
  6197. return (TCPDF_FONTS::UniArrSubString($uchars, $i));
  6198. }
  6199. $j = $i;
  6200. --$i;
  6201. }
  6202. } else {
  6203. // word wrapping
  6204. if ($this->rtl AND (!$firstblock) AND ($sep < $i)) {
  6205. $endspace = 1;
  6206. } else {
  6207. $endspace = 0;
  6208. }
  6209. // check the length of the next string
  6210. $strrest = TCPDF_FONTS::UniArrSubString($uchars, ($sep + $endspace));
  6211. $nextstr = TCPDF_STATIC::pregSplit('/'.$this->re_space['p'].'/', $this->re_space['m'], $this->stringTrim($strrest));
  6212. if (isset($nextstr[0]) AND ($this->GetStringWidth($nextstr[0]) > $pw)) {
  6213. // truncate the word because do not fit on a full page width
  6214. $tmpstr = TCPDF_FONTS::UniArrSubString($uchars, $j, $i);
  6215. if ($firstline) {
  6216. $startx = $this->x;
  6217. $tmparr = array_slice($chars, $j, ($i - $j));
  6218. if ($rtlmode) {
  6219. $tmparr = TCPDF_FONTS::utf8Bidi($tmparr, $tmpstr, $this->tmprtl, $this->isunicode, $this->CurrentFont);
  6220. }
  6221. $linew = $this->GetArrStringWidth($tmparr);
  6222. unset($tmparr);
  6223. if ($this->rtl) {
  6224. $this->endlinex = ($startx - $linew);
  6225. } else {
  6226. $this->endlinex = ($startx + $linew);
  6227. }
  6228. $w = $linew;
  6229. $tmpcellpadding = $this->cell_padding;
  6230. if ($maxh == 0) {
  6231. $this->SetCellPadding(0);
  6232. }
  6233. }
  6234. if ($firstblock AND $this->isRTLTextDir()) {
  6235. $tmpstr = $this->stringRightTrim($tmpstr);
  6236. }
  6237. $this->Cell($w, $h, $tmpstr, 0, 1, $align, $fill, $link, $stretch);
  6238. unset($tmpstr);
  6239. if ($firstline) {
  6240. $this->cell_padding = $tmpcellpadding;
  6241. return (TCPDF_FONTS::UniArrSubString($uchars, $i));
  6242. }
  6243. $j = $i;
  6244. --$i;
  6245. } else {
  6246. // word wrapping
  6247. if ($shy) {
  6248. // add hypen (minus symbol) at the end of the line
  6249. $shy_width = $tmp_shy_replacement_width;
  6250. if ($this->rtl) {
  6251. $shy_char_left = $tmp_shy_replacement_char;
  6252. $shy_char_right = '';
  6253. } else {
  6254. $shy_char_left = '';
  6255. $shy_char_right = $tmp_shy_replacement_char;
  6256. }
  6257. } else {
  6258. $shy_width = 0;
  6259. $shy_char_left = '';
  6260. $shy_char_right = '';
  6261. }
  6262. $tmpstr = TCPDF_FONTS::UniArrSubString($uchars, $j, ($sep + $endspace));
  6263. if ($firstline) {
  6264. $startx = $this->x;
  6265. $tmparr = array_slice($chars, $j, (($sep + $endspace) - $j));
  6266. if ($rtlmode) {
  6267. $tmparr = TCPDF_FONTS::utf8Bidi($tmparr, $tmpstr, $this->tmprtl, $this->isunicode, $this->CurrentFont);
  6268. }
  6269. $linew = $this->GetArrStringWidth($tmparr);
  6270. unset($tmparr);
  6271. if ($this->rtl) {
  6272. $this->endlinex = $startx - $linew - $shy_width;
  6273. } else {
  6274. $this->endlinex = $startx + $linew + $shy_width;
  6275. }
  6276. $w = $linew;
  6277. $tmpcellpadding = $this->cell_padding;
  6278. if ($maxh == 0) {
  6279. $this->SetCellPadding(0);
  6280. }
  6281. }
  6282. // print the line
  6283. if ($firstblock AND $this->isRTLTextDir()) {
  6284. $tmpstr = $this->stringRightTrim($tmpstr);
  6285. }
  6286. $this->Cell($w, $h, $shy_char_left.$tmpstr.$shy_char_right, 0, 1, $align, $fill, $link, $stretch);
  6287. unset($tmpstr);
  6288. if ($firstline) {
  6289. if ($chars[$sep] == 45) {
  6290. $endspace += 1;
  6291. }
  6292. // return the remaining text
  6293. $this->cell_padding = $tmpcellpadding;
  6294. return (TCPDF_FONTS::UniArrSubString($uchars, ($sep + $endspace)));
  6295. }
  6296. $i = $sep;
  6297. $sep = -1;
  6298. $shy = false;
  6299. $j = ($i + 1);
  6300. }
  6301. }
  6302. // account for margin changes
  6303. if ((($this->y + $this->lasth) > $this->PageBreakTrigger) AND ($this->inPageBody())) {
  6304. $this->AcceptPageBreak();
  6305. if ($this->rtl) {
  6306. $this->x -= $margin['R'];
  6307. } else {
  6308. $this->x += $margin['L'];
  6309. }
  6310. $this->lMargin += $margin['L'];
  6311. $this->rMargin += $margin['R'];
  6312. }
  6313. $w = $this->getRemainingWidth();
  6314. $wmax = $w - $this->cell_padding['L'] - $this->cell_padding['R'];
  6315. if ($linebreak) {
  6316. $linebreak = false;
  6317. } else {
  6318. ++$nl;
  6319. $l = 0;
  6320. }
  6321. }
  6322. }
  6323. // save last character
  6324. $pc = $c;
  6325. ++$i;
  6326. } // end while i < nb
  6327. // print last substring (if any)
  6328. if ($l > 0) {
  6329. switch ($align) {
  6330. case 'J':
  6331. case 'C': {
  6332. $w = $w;
  6333. break;
  6334. }
  6335. case 'L': {
  6336. if ($this->rtl) {
  6337. $w = $w;
  6338. } else {
  6339. $w = $l;
  6340. }
  6341. break;
  6342. }
  6343. case 'R': {
  6344. if ($this->rtl) {
  6345. $w = $l;
  6346. } else {
  6347. $w = $w;
  6348. }
  6349. break;
  6350. }
  6351. default: {
  6352. $w = $l;
  6353. break;
  6354. }
  6355. }
  6356. $tmpstr = TCPDF_FONTS::UniArrSubString($uchars, $j, $nb);
  6357. if ($firstline) {
  6358. $startx = $this->x;
  6359. $tmparr = array_slice($chars, $j, ($nb - $j));
  6360. if ($rtlmode) {
  6361. $tmparr = TCPDF_FONTS::utf8Bidi($tmparr, $tmpstr, $this->tmprtl, $this->isunicode, $this->CurrentFont);
  6362. }
  6363. $linew = $this->GetArrStringWidth($tmparr);
  6364. unset($tmparr);
  6365. if ($this->rtl) {
  6366. $this->endlinex = $startx - $linew;
  6367. } else {
  6368. $this->endlinex = $startx + $linew;
  6369. }
  6370. $w = $linew;
  6371. $tmpcellpadding = $this->cell_padding;
  6372. if ($maxh == 0) {
  6373. $this->SetCellPadding(0);
  6374. }
  6375. }
  6376. if ($firstblock AND $this->isRTLTextDir()) {
  6377. $tmpstr = $this->stringRightTrim($tmpstr);
  6378. }
  6379. $this->Cell($w, $h, $tmpstr, 0, $ln, $align, $fill, $link, $stretch);
  6380. unset($tmpstr);
  6381. if ($firstline) {
  6382. $this->cell_padding = $tmpcellpadding;
  6383. return (TCPDF_FONTS::UniArrSubString($uchars, $nb));
  6384. }
  6385. ++$nl;
  6386. }
  6387. if ($firstline) {
  6388. return '';
  6389. }
  6390. return $nl;
  6391. }
  6392. /**
  6393. * Returns the remaining width between the current position and margins.
  6394. * @return int Return the remaining width
  6395. * @protected
  6396. */
  6397. protected function getRemainingWidth() {
  6398. list($this->x, $this->y) = $this->checkPageRegions(0, $this->x, $this->y);
  6399. if ($this->rtl) {
  6400. return ($this->x - $this->lMargin);
  6401. } else {
  6402. return ($this->w - $this->rMargin - $this->x);
  6403. }
  6404. }
  6405. /**
  6406. * Set the block dimensions accounting for page breaks and page/column fitting
  6407. * @param $w (float) width
  6408. * @param $h (float) height
  6409. * @param $x (float) X coordinate
  6410. * @param $y (float) Y coodiante
  6411. * @param $fitonpage (boolean) if true the block is resized to not exceed page dimensions.
  6412. * @return array($w, $h, $x, $y)
  6413. * @protected
  6414. * @since 5.5.009 (2010-07-05)
  6415. */
  6416. protected function fitBlock($w, $h, $x, $y, $fitonpage=false) {
  6417. if ($w <= 0) {
  6418. // set maximum width
  6419. $w = ($this->w - $this->lMargin - $this->rMargin);
  6420. if ($w <= 0) {
  6421. $w = 1;
  6422. }
  6423. }
  6424. if ($h <= 0) {
  6425. // set maximum height
  6426. $h = ($this->PageBreakTrigger - $this->tMargin);
  6427. if ($h <= 0) {
  6428. $h = 1;
  6429. }
  6430. }
  6431. // resize the block to be vertically contained on a single page or single column
  6432. if ($fitonpage OR $this->AutoPageBreak) {
  6433. $ratio_wh = ($w / $h);
  6434. if ($h > ($this->PageBreakTrigger - $this->tMargin)) {
  6435. $h = $this->PageBreakTrigger - $this->tMargin;
  6436. $w = ($h * $ratio_wh);
  6437. }
  6438. // resize the block to be horizontally contained on a single page or single column
  6439. if ($fitonpage) {
  6440. $maxw = ($this->w - $this->lMargin - $this->rMargin);
  6441. if ($w > $maxw) {
  6442. $w = $maxw;
  6443. $h = ($w / $ratio_wh);
  6444. }
  6445. }
  6446. }
  6447. // Check whether we need a new page or new column first as this does not fit
  6448. $prev_x = $this->x;
  6449. $prev_y = $this->y;
  6450. if ($this->checkPageBreak($h, $y) OR ($this->y < $prev_y)) {
  6451. $y = $this->y;
  6452. if ($this->rtl) {
  6453. $x += ($prev_x - $this->x);
  6454. } else {
  6455. $x += ($this->x - $prev_x);
  6456. }
  6457. $this->newline = true;
  6458. }
  6459. // resize the block to be contained on the remaining available page or column space
  6460. if ($fitonpage) {
  6461. $ratio_wh = ($w / $h);
  6462. if (($y + $h) > $this->PageBreakTrigger) {
  6463. $h = $this->PageBreakTrigger - $y;
  6464. $w = ($h * $ratio_wh);
  6465. }
  6466. if ((!$this->rtl) AND (($x + $w) > ($this->w - $this->rMargin))) {
  6467. $w = $this->w - $this->rMargin - $x;
  6468. $h = ($w / $ratio_wh);
  6469. } elseif (($this->rtl) AND (($x - $w) < ($this->lMargin))) {
  6470. $w = $x - $this->lMargin;
  6471. $h = ($w / $ratio_wh);
  6472. }
  6473. }
  6474. return array($w, $h, $x, $y);
  6475. }
  6476. /**
  6477. * Puts an image in the page.
  6478. * The upper-left corner must be given.
  6479. * The dimensions can be specified in different ways:<ul>
  6480. * <li>explicit width and height (expressed in user unit)</li>
  6481. * <li>one explicit dimension, the other being calculated automatically in order to keep the original proportions</li>
  6482. * <li>no explicit dimension, in which case the image is put at 72 dpi</li></ul>
  6483. * 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;
  6484. * The format can be specified explicitly or inferred from the file extension.<br />
  6485. * It is possible to put a link on the image.<br />
  6486. * Remark: if an image is used several times, only one copy will be embedded in the file.<br />
  6487. * @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').
  6488. * @param $x (float) Abscissa of the upper-left corner (LTR) or upper-right corner (RTL).
  6489. * @param $y (float) Ordinate of the upper-left corner (LTR) or upper-right corner (RTL).
  6490. * @param $w (float) Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
  6491. * @param $h (float) Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
  6492. * @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.
  6493. * @param $link (mixed) URL or identifier returned by AddLink().
  6494. * @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>
  6495. * @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).
  6496. * @param $dpi (int) dot-per-inch resolution used on resize
  6497. * @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>
  6498. * @param $ismask (boolean) true if this image is a mask, false otherwise
  6499. * @param $imgmask (mixed) image object returned by this function or false
  6500. * @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)))
  6501. * @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).
  6502. * @param $hidden (boolean) If true do not display the image.
  6503. * @param $fitonpage (boolean) If true the image is resized to not exceed page dimensions.
  6504. * @param $alt (boolean) If true the image will be added as alternative and not directly printed (the ID of the image will be returned).
  6505. * @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.
  6506. * @return image information
  6507. * @public
  6508. * @since 1.1
  6509. */
  6510. 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()) {
  6511. if ($this->state != 2) {
  6512. return;
  6513. }
  6514. if (strcmp($x, '') === 0) {
  6515. $x = $this->x;
  6516. }
  6517. if (strcmp($y, '') === 0) {
  6518. $y = $this->y;
  6519. }
  6520. // check page for no-write regions and adapt page margins if necessary
  6521. list($x, $y) = $this->checkPageRegions($h, $x, $y);
  6522. $exurl = ''; // external streams
  6523. $imsize = FALSE;
  6524. // Make sure the file variable is not empty or null because accessing $file[0] later
  6525. // results in error when running PHP 7.4
  6526. if (empty($file)) {
  6527. return false;
  6528. }
  6529. // check if we are passing an image as file or string
  6530. if ($file[0] === '@') {
  6531. // image from string
  6532. $imgdata = substr($file, 1);
  6533. } else { // image file
  6534. if ($file[0] === '*') {
  6535. // image as external stream
  6536. $file = substr($file, 1);
  6537. $exurl = $file;
  6538. }
  6539. // check if file exist and it is valid
  6540. if (!@$this->fileExists($file)) {
  6541. return false;
  6542. }
  6543. if (false !== $info = $this->getImageBuffer($file)) {
  6544. $imsize = array($info['w'], $info['h']);
  6545. } elseif (($imsize = @getimagesize($file)) === FALSE && strpos($file, '__tcpdf_'.$this->file_id.'_img') === FALSE){
  6546. $imgdata = $this->getCachedFileContents($file);
  6547. }
  6548. }
  6549. if (!empty($imgdata)) {
  6550. // copy image to cache
  6551. $original_file = $file;
  6552. $file = TCPDF_STATIC::getObjFilename('img', $this->file_id);
  6553. $fp = TCPDF_STATIC::fopenLocal($file, 'w');
  6554. if (!$fp) {
  6555. $this->Error('Unable to write file: '.$file);
  6556. }
  6557. fwrite($fp, $imgdata);
  6558. fclose($fp);
  6559. unset($imgdata);
  6560. $imsize = @getimagesize($file);
  6561. if ($imsize === FALSE) {
  6562. unlink($file);
  6563. $file = $original_file;
  6564. }
  6565. }
  6566. if ($imsize === FALSE) {
  6567. if (($w > 0) AND ($h > 0)) {
  6568. // get measures from specified data
  6569. $pw = $this->getHTMLUnitToUnits($w, 0, $this->pdfunit, true) * $this->imgscale * $this->k;
  6570. $ph = $this->getHTMLUnitToUnits($h, 0, $this->pdfunit, true) * $this->imgscale * $this->k;
  6571. $imsize = array($pw, $ph);
  6572. } else {
  6573. $this->Error('[Image] Unable to get the size of the image: '.$file);
  6574. }
  6575. }
  6576. // file hash
  6577. $filehash = md5($file);
  6578. // get original image width and height in pixels
  6579. list($pixw, $pixh) = $imsize;
  6580. // calculate image width and height on document
  6581. if (($w <= 0) AND ($h <= 0)) {
  6582. // convert image size to document unit
  6583. $w = $this->pixelsToUnits($pixw);
  6584. $h = $this->pixelsToUnits($pixh);
  6585. } elseif ($w <= 0) {
  6586. $w = $h * $pixw / $pixh;
  6587. } elseif ($h <= 0) {
  6588. $h = $w * $pixh / $pixw;
  6589. } elseif (($fitbox !== false) AND ($w > 0) AND ($h > 0)) {
  6590. if (strlen($fitbox) !== 2) {
  6591. // set default alignment
  6592. $fitbox = '--';
  6593. }
  6594. // scale image dimensions proportionally to fit within the ($w, $h) box
  6595. if ((($w * $pixh) / ($h * $pixw)) < 1) {
  6596. // store current height
  6597. $oldh = $h;
  6598. // calculate new height
  6599. $h = $w * $pixh / $pixw;
  6600. // height difference
  6601. $hdiff = ($oldh - $h);
  6602. // vertical alignment
  6603. switch (strtoupper($fitbox[1])) {
  6604. case 'T': {
  6605. break;
  6606. }
  6607. case 'M': {
  6608. $y += ($hdiff / 2);
  6609. break;
  6610. }
  6611. case 'B': {
  6612. $y += $hdiff;
  6613. break;
  6614. }
  6615. }
  6616. } else {
  6617. // store current width
  6618. $oldw = $w;
  6619. // calculate new width
  6620. $w = $h * $pixw / $pixh;
  6621. // width difference
  6622. $wdiff = ($oldw - $w);
  6623. // horizontal alignment
  6624. switch (strtoupper($fitbox[0])) {
  6625. case 'L': {
  6626. if ($this->rtl) {
  6627. $x -= $wdiff;
  6628. }
  6629. break;
  6630. }
  6631. case 'C': {
  6632. if ($this->rtl) {
  6633. $x -= ($wdiff / 2);
  6634. } else {
  6635. $x += ($wdiff / 2);
  6636. }
  6637. break;
  6638. }
  6639. case 'R': {
  6640. if (!$this->rtl) {
  6641. $x += $wdiff;
  6642. }
  6643. break;
  6644. }
  6645. }
  6646. }
  6647. }
  6648. // fit the image on available space
  6649. list($w, $h, $x, $y) = $this->fitBlock($w, $h, $x, $y, $fitonpage);
  6650. // calculate new minimum dimensions in pixels
  6651. $neww = round($w * $this->k * $dpi / $this->dpi);
  6652. $newh = round($h * $this->k * $dpi / $this->dpi);
  6653. // check if resize is necessary (resize is used only to reduce the image)
  6654. $newsize = ($neww * $newh);
  6655. $pixsize = ($pixw * $pixh);
  6656. if (intval($resize) == 2) {
  6657. $resize = true;
  6658. } elseif ($newsize >= $pixsize) {
  6659. $resize = false;
  6660. }
  6661. // check if image has been already added on document
  6662. $newimage = true;
  6663. if (in_array($file, $this->imagekeys)) {
  6664. $newimage = false;
  6665. // get existing image data
  6666. $info = $this->getImageBuffer($file);
  6667. if (strpos($file, '__tcpdf_'.$this->file_id.'_imgmask_') === FALSE) {
  6668. // check if the newer image is larger
  6669. $oldsize = ($info['w'] * $info['h']);
  6670. if ((($oldsize < $newsize) AND ($resize)) OR (($oldsize < $pixsize) AND (!$resize))) {
  6671. $newimage = true;
  6672. }
  6673. }
  6674. } elseif (($ismask === false) AND ($imgmask === false) AND (strpos($file, '__tcpdf_'.$this->file_id.'_imgmask_') === FALSE)) {
  6675. // create temp image file (without alpha channel)
  6676. $tempfile_plain = K_PATH_CACHE.'__tcpdf_'.$this->file_id.'_imgmask_plain_'.$filehash;
  6677. // create temp alpha file
  6678. $tempfile_alpha = K_PATH_CACHE.'__tcpdf_'.$this->file_id.'_imgmask_alpha_'.$filehash;
  6679. // check for cached images
  6680. if (in_array($tempfile_plain, $this->imagekeys)) {
  6681. // get existing image data
  6682. $info = $this->getImageBuffer($tempfile_plain);
  6683. // check if the newer image is larger
  6684. $oldsize = ($info['w'] * $info['h']);
  6685. if ((($oldsize < $newsize) AND ($resize)) OR (($oldsize < $pixsize) AND (!$resize))) {
  6686. $newimage = true;
  6687. } else {
  6688. $newimage = false;
  6689. // embed mask image
  6690. $imgmask = $this->Image($tempfile_alpha, $x, $y, $w, $h, 'PNG', '', '', $resize, $dpi, '', true, false);
  6691. // embed image, masked with previously embedded mask
  6692. return $this->Image($tempfile_plain, $x, $y, $w, $h, $type, $link, $align, $resize, $dpi, $palign, false, $imgmask);
  6693. }
  6694. }
  6695. }
  6696. if ($newimage) {
  6697. //First use of image, get info
  6698. $type = strtolower($type);
  6699. if ($type == '') {
  6700. $type = TCPDF_IMAGES::getImageFileType($file, $imsize);
  6701. } elseif ($type == 'jpg') {
  6702. $type = 'jpeg';
  6703. }
  6704. $mqr = TCPDF_STATIC::get_mqr();
  6705. TCPDF_STATIC::set_mqr(false);
  6706. // Specific image handlers (defined on TCPDF_IMAGES CLASS)
  6707. $mtd = '_parse'.$type;
  6708. // GD image handler function
  6709. $gdfunction = 'imagecreatefrom'.$type;
  6710. $info = false;
  6711. if ((method_exists('TCPDF_IMAGES', $mtd)) AND (!($resize AND (function_exists($gdfunction) OR extension_loaded('imagick'))))) {
  6712. // TCPDF image functions
  6713. $info = TCPDF_IMAGES::$mtd($file);
  6714. if (($ismask === false) AND ($imgmask === false) AND (strpos($file, '__tcpdf_'.$this->file_id.'_imgmask_') === FALSE)
  6715. AND (($info === 'pngalpha') OR (isset($info['trns']) AND !empty($info['trns'])))) {
  6716. return $this->ImagePngAlpha($file, $x, $y, $pixw, $pixh, $w, $h, 'PNG', $link, $align, $resize, $dpi, $palign, $filehash);
  6717. }
  6718. }
  6719. if (($info === false) AND function_exists($gdfunction)) {
  6720. try {
  6721. // GD library
  6722. $img = $gdfunction($file);
  6723. if ($img !== false) {
  6724. if ($resize) {
  6725. $imgr = imagecreatetruecolor($neww, $newh);
  6726. if (($type == 'gif') OR ($type == 'png')) {
  6727. $imgr = TCPDF_IMAGES::setGDImageTransparency($imgr, $img);
  6728. }
  6729. imagecopyresampled($imgr, $img, 0, 0, 0, 0, $neww, $newh, $pixw, $pixh);
  6730. $img = $imgr;
  6731. }
  6732. if (($type == 'gif') OR ($type == 'png')) {
  6733. $info = TCPDF_IMAGES::_toPNG($img, TCPDF_STATIC::getObjFilename('img', $this->file_id));
  6734. } else {
  6735. $info = TCPDF_IMAGES::_toJPEG($img, $this->jpeg_quality, TCPDF_STATIC::getObjFilename('img', $this->file_id));
  6736. }
  6737. }
  6738. } catch(Exception $e) {
  6739. $info = false;
  6740. }
  6741. }
  6742. if (($info === false) AND extension_loaded('imagick')) {
  6743. try {
  6744. // ImageMagick library
  6745. $img = new Imagick();
  6746. if ($type == 'svg') {
  6747. if ($file[0] === '@') {
  6748. // image from string
  6749. $svgimg = substr($file, 1);
  6750. } else {
  6751. // get SVG file content
  6752. $svgimg = $this->getCachedFileContents($file);
  6753. }
  6754. if ($svgimg !== FALSE) {
  6755. // get width and height
  6756. $regs = array();
  6757. if (preg_match('/<svg([^\>]*)>/si', $svgimg, $regs)) {
  6758. $svgtag = $regs[1];
  6759. $tmp = array();
  6760. if (preg_match('/[\s]+width[\s]*=[\s]*"([^"]*)"/si', $svgtag, $tmp)) {
  6761. $ow = $this->getHTMLUnitToUnits($tmp[1], 1, $this->svgunit, false);
  6762. $owu = sprintf('%F', ($ow * $dpi / 72)).$this->pdfunit;
  6763. $svgtag = preg_replace('/[\s]+width[\s]*=[\s]*"[^"]*"/si', ' width="'.$owu.'"', $svgtag, 1);
  6764. } else {
  6765. $ow = $w;
  6766. }
  6767. $tmp = array();
  6768. if (preg_match('/[\s]+height[\s]*=[\s]*"([^"]*)"/si', $svgtag, $tmp)) {
  6769. $oh = $this->getHTMLUnitToUnits($tmp[1], 1, $this->svgunit, false);
  6770. $ohu = sprintf('%F', ($oh * $dpi / 72)).$this->pdfunit;
  6771. $svgtag = preg_replace('/[\s]+height[\s]*=[\s]*"[^"]*"/si', ' height="'.$ohu.'"', $svgtag, 1);
  6772. } else {
  6773. $oh = $h;
  6774. }
  6775. $tmp = array();
  6776. if (!preg_match('/[\s]+viewBox[\s]*=[\s]*"[\s]*([0-9\.]+)[\s]+([0-9\.]+)[\s]+([0-9\.]+)[\s]+([0-9\.]+)[\s]*"/si', $svgtag, $tmp)) {
  6777. $vbw = ($ow * $this->imgscale * $this->k);
  6778. $vbh = ($oh * $this->imgscale * $this->k);
  6779. $vbox = sprintf(' viewBox="0 0 %F %F" ', $vbw, $vbh);
  6780. $svgtag = $vbox.$svgtag;
  6781. }
  6782. $svgimg = preg_replace('/<svg([^\>]*)>/si', '<svg'.$svgtag.'>', $svgimg, 1);
  6783. }
  6784. $img->readImageBlob($svgimg);
  6785. }
  6786. } else {
  6787. $img->readImage($file);
  6788. }
  6789. if ($resize) {
  6790. $img->resizeImage($neww, $newh, 10, 1, false);
  6791. }
  6792. $img->setCompressionQuality($this->jpeg_quality);
  6793. $img->setImageFormat('jpeg');
  6794. $tempname = TCPDF_STATIC::getObjFilename('img', $this->file_id);
  6795. $img->writeImage($tempname);
  6796. $info = TCPDF_IMAGES::_parsejpeg($tempname);
  6797. unlink($tempname);
  6798. $img->destroy();
  6799. } catch(Exception $e) {
  6800. $info = false;
  6801. }
  6802. }
  6803. if ($info === false) {
  6804. // unable to process image
  6805. return;
  6806. }
  6807. TCPDF_STATIC::set_mqr($mqr);
  6808. if ($ismask) {
  6809. // force grayscale
  6810. $info['cs'] = 'DeviceGray';
  6811. }
  6812. if ($imgmask !== false) {
  6813. $info['masked'] = $imgmask;
  6814. }
  6815. if (!empty($exurl)) {
  6816. $info['exurl'] = $exurl;
  6817. }
  6818. // array of alternative images
  6819. $info['altimgs'] = $altimgs;
  6820. // add image to document
  6821. $info['i'] = $this->setImageBuffer($file, $info);
  6822. }
  6823. // set alignment
  6824. $this->img_rb_x = $x + $w;
  6825. $this->img_rb_y = $y + $h;
  6826. // set alignment
  6827. if ($palign == 'L') {
  6828. $ximg = $this->lMargin;
  6829. } elseif ($palign == 'C') {
  6830. $ximg = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
  6831. } elseif ($palign == 'R') {
  6832. $ximg = $this->w - $this->rMargin - $w;
  6833. } else {
  6834. $ximg = $x;
  6835. }
  6836. if ($ismask OR $hidden) {
  6837. // image is not displayed
  6838. return $info['i'];
  6839. }
  6840. $xkimg = $ximg * $this->k;
  6841. if (!$alt) {
  6842. // only non-alternative immages will be set
  6843. $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']));
  6844. }
  6845. if (!empty($border)) {
  6846. $bx = $this->x;
  6847. $by = $this->y;
  6848. $this->x = $ximg;
  6849. if ($this->rtl) {
  6850. $this->x += $w;
  6851. }
  6852. $this->y = $y;
  6853. $this->Cell($w, $h, '', $border, 0, '', 0, '', 0, true);
  6854. $this->x = $bx;
  6855. $this->y = $by;
  6856. }
  6857. if ($link) {
  6858. $this->Link($ximg, $y, $w, $h, $link, 0);
  6859. }
  6860. // set pointer to align the next text/objects
  6861. switch($align) {
  6862. case 'T': {
  6863. $this->y = $y;
  6864. $this->x = $this->img_rb_x;
  6865. break;
  6866. }
  6867. case 'M': {
  6868. $this->y = $y + round($h/2);
  6869. $this->x = $this->img_rb_x;
  6870. break;
  6871. }
  6872. case 'B': {
  6873. $this->y = $this->img_rb_y;
  6874. $this->x = $this->img_rb_x;
  6875. break;
  6876. }
  6877. case 'N': {
  6878. $this->SetY($this->img_rb_y);
  6879. break;
  6880. }
  6881. default:{
  6882. break;
  6883. }
  6884. }
  6885. $this->endlinex = $this->img_rb_x;
  6886. if ($this->inxobj) {
  6887. // we are inside an XObject template
  6888. $this->xobjects[$this->xobjid]['images'][] = $info['i'];
  6889. }
  6890. return $info['i'];
  6891. }
  6892. /**
  6893. * Extract info from a PNG image with alpha channel using the Imagick or GD library.
  6894. * @param $file (string) Name of the file containing the image.
  6895. * @param $x (float) Abscissa of the upper-left corner.
  6896. * @param $y (float) Ordinate of the upper-left corner.
  6897. * @param $wpx (float) Original width of the image in pixels.
  6898. * @param $hpx (float) original height of the image in pixels.
  6899. * @param $w (float) Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
  6900. * @param $h (float) Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
  6901. * @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.
  6902. * @param $link (mixed) URL or identifier returned by AddLink().
  6903. * @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>
  6904. * @param $resize (boolean) If true resize (reduce) the image to fit $w and $h (requires GD library).
  6905. * @param $dpi (int) dot-per-inch resolution used on resize
  6906. * @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>
  6907. * @param $filehash (string) File hash used to build unique file names.
  6908. * @author Nicola Asuni
  6909. * @protected
  6910. * @since 4.3.007 (2008-12-04)
  6911. * @see Image()
  6912. */
  6913. protected function ImagePngAlpha($file, $x, $y, $wpx, $hpx, $w, $h, $type, $link, $align, $resize, $dpi, $palign, $filehash='') {
  6914. // create temp images
  6915. if (empty($filehash)) {
  6916. $filehash = md5($file);
  6917. }
  6918. // create temp image file (without alpha channel)
  6919. $tempfile_plain = K_PATH_CACHE.'__tcpdf_'.$this->file_id.'_imgmask_plain_'.$filehash;
  6920. // create temp alpha file
  6921. $tempfile_alpha = K_PATH_CACHE.'__tcpdf_'.$this->file_id.'_imgmask_alpha_'.$filehash;
  6922. $parsed = false;
  6923. $parse_error = '';
  6924. // ImageMagick extension
  6925. if (($parsed === false) AND extension_loaded('imagick')) {
  6926. try {
  6927. // ImageMagick library
  6928. $img = new Imagick();
  6929. $img->readImage($file);
  6930. // clone image object
  6931. $imga = TCPDF_STATIC::objclone($img);
  6932. // extract alpha channel
  6933. if (method_exists($img, 'setImageAlphaChannel') AND defined('Imagick::ALPHACHANNEL_EXTRACT')) {
  6934. $img->setImageAlphaChannel(Imagick::ALPHACHANNEL_EXTRACT);
  6935. } else {
  6936. $img->separateImageChannel(8); // 8 = (imagick::CHANNEL_ALPHA | imagick::CHANNEL_OPACITY | imagick::CHANNEL_MATTE);
  6937. $img->negateImage(true);
  6938. }
  6939. $img->setImageFormat('png');
  6940. $img->writeImage($tempfile_alpha);
  6941. // remove alpha channel
  6942. if (method_exists($imga, 'setImageMatte')) {
  6943. $imga->setImageMatte(false);
  6944. } else {
  6945. $imga->separateImageChannel(39); // 39 = (imagick::CHANNEL_ALL & ~(imagick::CHANNEL_ALPHA | imagick::CHANNEL_OPACITY | imagick::CHANNEL_MATTE));
  6946. }
  6947. $imga->setImageFormat('png');
  6948. $imga->writeImage($tempfile_plain);
  6949. $parsed = true;
  6950. } catch (Exception $e) {
  6951. // Imagemagick fails, try with GD
  6952. $parse_error = 'Imagick library error: '.$e->getMessage();
  6953. }
  6954. }
  6955. // GD extension
  6956. if (($parsed === false) AND function_exists('imagecreatefrompng')) {
  6957. try {
  6958. // generate images
  6959. $img = imagecreatefrompng($file);
  6960. $imgalpha = imagecreate($wpx, $hpx);
  6961. // generate gray scale palette (0 -> 255)
  6962. for ($c = 0; $c < 256; ++$c) {
  6963. ImageColorAllocate($imgalpha, $c, $c, $c);
  6964. }
  6965. // extract alpha channel
  6966. for ($xpx = 0; $xpx < $wpx; ++$xpx) {
  6967. for ($ypx = 0; $ypx < $hpx; ++$ypx) {
  6968. $color = imagecolorat($img, $xpx, $ypx);
  6969. // get and correct gamma color
  6970. $alpha = $this->getGDgamma($img, $color);
  6971. imagesetpixel($imgalpha, $xpx, $ypx, $alpha);
  6972. }
  6973. }
  6974. imagepng($imgalpha, $tempfile_alpha);
  6975. imagedestroy($imgalpha);
  6976. // extract image without alpha channel
  6977. $imgplain = imagecreatetruecolor($wpx, $hpx);
  6978. imagecopy($imgplain, $img, 0, 0, 0, 0, $wpx, $hpx);
  6979. imagepng($imgplain, $tempfile_plain);
  6980. imagedestroy($imgplain);
  6981. $parsed = true;
  6982. } catch (Exception $e) {
  6983. // GD fails
  6984. $parse_error = 'GD library error: '.$e->getMessage();
  6985. }
  6986. }
  6987. if ($parsed === false) {
  6988. if (empty($parse_error)) {
  6989. $this->Error('TCPDF requires the Imagick or GD extension to handle PNG images with alpha channel.');
  6990. } else {
  6991. $this->Error($parse_error);
  6992. }
  6993. }
  6994. // embed mask image
  6995. $imgmask = $this->Image($tempfile_alpha, $x, $y, $w, $h, 'PNG', '', '', $resize, $dpi, '', true, false);
  6996. // embed image, masked with previously embedded mask
  6997. $this->Image($tempfile_plain, $x, $y, $w, $h, $type, $link, $align, $resize, $dpi, $palign, false, $imgmask);
  6998. }
  6999. /**
  7000. * Get the GD-corrected PNG gamma value from alpha color
  7001. * @param $img (int) GD image Resource ID.
  7002. * @param $c (int) alpha color
  7003. * @protected
  7004. * @since 4.3.007 (2008-12-04)
  7005. */
  7006. protected function getGDgamma($img, $c) {
  7007. if (!isset($this->gdgammacache['#'.$c])) {
  7008. $colors = imagecolorsforindex($img, $c);
  7009. // GD alpha is only 7 bit (0 -> 127)
  7010. $this->gdgammacache['#'.$c] = (((127 - $colors['alpha']) / 127) * 255);
  7011. // correct gamma
  7012. $this->gdgammacache['#'.$c] = (pow(($this->gdgammacache['#'.$c] / 255), 2.2) * 255);
  7013. // store the latest values on cache to improve performances
  7014. if (count($this->gdgammacache) > 8) {
  7015. // remove one element from the cache array
  7016. array_shift($this->gdgammacache);
  7017. }
  7018. }
  7019. return $this->gdgammacache['#'.$c];
  7020. }
  7021. /**
  7022. * Performs a line break.
  7023. * The current abscissa goes back to the left margin and the ordinate increases by the amount passed in parameter.
  7024. * @param $h (float) The height of the break. By default, the value equals the height of the last printed cell.
  7025. * @param $cell (boolean) if true add the current left (or right o for RTL) padding to the X coordinate
  7026. * @public
  7027. * @since 1.0
  7028. * @see Cell()
  7029. */
  7030. public function Ln($h='', $cell=false) {
  7031. 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'])) {
  7032. // revove vertical space from the top of the column
  7033. return;
  7034. }
  7035. if ($cell) {
  7036. if ($this->rtl) {
  7037. $cellpadding = $this->cell_padding['R'];
  7038. } else {
  7039. $cellpadding = $this->cell_padding['L'];
  7040. }
  7041. } else {
  7042. $cellpadding = 0;
  7043. }
  7044. if ($this->rtl) {
  7045. $this->x = $this->w - $this->rMargin - $cellpadding;
  7046. } else {
  7047. $this->x = $this->lMargin + $cellpadding;
  7048. }
  7049. if (is_string($h)) {
  7050. $h = $this->lasth;
  7051. }
  7052. $this->y += $h;
  7053. $this->newline = true;
  7054. }
  7055. /**
  7056. * Returns the relative X value of current position.
  7057. * The value is relative to the left border for LTR languages and to the right border for RTL languages.
  7058. * @return float
  7059. * @public
  7060. * @since 1.2
  7061. * @see SetX(), GetY(), SetY()
  7062. */
  7063. public function GetX() {
  7064. //Get x position
  7065. if ($this->rtl) {
  7066. return ($this->w - $this->x);
  7067. } else {
  7068. return $this->x;
  7069. }
  7070. }
  7071. /**
  7072. * Returns the absolute X value of current position.
  7073. * @return float
  7074. * @public
  7075. * @since 1.2
  7076. * @see SetX(), GetY(), SetY()
  7077. */
  7078. public function GetAbsX() {
  7079. return $this->x;
  7080. }
  7081. /**
  7082. * Returns the ordinate of the current position.
  7083. * @return float
  7084. * @public
  7085. * @since 1.0
  7086. * @see SetY(), GetX(), SetX()
  7087. */
  7088. public function GetY() {
  7089. return $this->y;
  7090. }
  7091. /**
  7092. * Defines the abscissa of the current position.
  7093. * If the passed value is negative, it is relative to the right of the page (or left if language is RTL).
  7094. * @param $x (float) The value of the abscissa in user units.
  7095. * @param $rtloff (boolean) if true always uses the page top-left corner as origin of axis.
  7096. * @public
  7097. * @since 1.2
  7098. * @see GetX(), GetY(), SetY(), SetXY()
  7099. */
  7100. public function SetX($x, $rtloff=false) {
  7101. $x = floatval($x);
  7102. if (!$rtloff AND $this->rtl) {
  7103. if ($x >= 0) {
  7104. $this->x = $this->w - $x;
  7105. } else {
  7106. $this->x = abs($x);
  7107. }
  7108. } else {
  7109. if ($x >= 0) {
  7110. $this->x = $x;
  7111. } else {
  7112. $this->x = $this->w + $x;
  7113. }
  7114. }
  7115. if ($this->x < 0) {
  7116. $this->x = 0;
  7117. }
  7118. if ($this->x > $this->w) {
  7119. $this->x = $this->w;
  7120. }
  7121. }
  7122. /**
  7123. * Moves the current abscissa back to the left margin and sets the ordinate.
  7124. * If the passed value is negative, it is relative to the bottom of the page.
  7125. * @param $y (float) The value of the ordinate in user units.
  7126. * @param $resetx (bool) if true (default) reset the X position.
  7127. * @param $rtloff (boolean) if true always uses the page top-left corner as origin of axis.
  7128. * @public
  7129. * @since 1.0
  7130. * @see GetX(), GetY(), SetY(), SetXY()
  7131. */
  7132. public function SetY($y, $resetx=true, $rtloff=false) {
  7133. $y = floatval($y);
  7134. if ($resetx) {
  7135. //reset x
  7136. if (!$rtloff AND $this->rtl) {
  7137. $this->x = $this->w - $this->rMargin;
  7138. } else {
  7139. $this->x = $this->lMargin;
  7140. }
  7141. }
  7142. if ($y >= 0) {
  7143. $this->y = $y;
  7144. } else {
  7145. $this->y = $this->h + $y;
  7146. }
  7147. if ($this->y < 0) {
  7148. $this->y = 0;
  7149. }
  7150. if ($this->y > $this->h) {
  7151. $this->y = $this->h;
  7152. }
  7153. }
  7154. /**
  7155. * Defines the abscissa and ordinate of the current position.
  7156. * If the passed values are negative, they are relative respectively to the right and bottom of the page.
  7157. * @param $x (float) The value of the abscissa.
  7158. * @param $y (float) The value of the ordinate.
  7159. * @param $rtloff (boolean) if true always uses the page top-left corner as origin of axis.
  7160. * @public
  7161. * @since 1.2
  7162. * @see SetX(), SetY()
  7163. */
  7164. public function SetXY($x, $y, $rtloff=false) {
  7165. $this->SetY($y, false, $rtloff);
  7166. $this->SetX($x, $rtloff);
  7167. }
  7168. /**
  7169. * Set the absolute X coordinate of the current pointer.
  7170. * @param $x (float) The value of the abscissa in user units.
  7171. * @public
  7172. * @since 5.9.186 (2012-09-13)
  7173. * @see setAbsX(), setAbsY(), SetAbsXY()
  7174. */
  7175. public function SetAbsX($x) {
  7176. $this->x = floatval($x);
  7177. }
  7178. /**
  7179. * Set the absolute Y coordinate of the current pointer.
  7180. * @param $y (float) (float) The value of the ordinate in user units.
  7181. * @public
  7182. * @since 5.9.186 (2012-09-13)
  7183. * @see setAbsX(), setAbsY(), SetAbsXY()
  7184. */
  7185. public function SetAbsY($y) {
  7186. $this->y = floatval($y);
  7187. }
  7188. /**
  7189. * Set the absolute X and Y coordinates of the current pointer.
  7190. * @param $x (float) The value of the abscissa in user units.
  7191. * @param $y (float) (float) The value of the ordinate in user units.
  7192. * @public
  7193. * @since 5.9.186 (2012-09-13)
  7194. * @see setAbsX(), setAbsY(), SetAbsXY()
  7195. */
  7196. public function SetAbsXY($x, $y) {
  7197. $this->SetAbsX($x);
  7198. $this->SetAbsY($y);
  7199. }
  7200. /**
  7201. * Send the document to a given destination: string, local file or browser.
  7202. * In the last case, the plug-in may be used (if present) or a download ("Save as" dialog box) may be forced.<br />
  7203. * The method first calls Close() if necessary to terminate the document.
  7204. * @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.
  7205. * @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>
  7206. * @return string
  7207. * @public
  7208. * @since 1.0
  7209. * @see Close()
  7210. */
  7211. public function Output($name='doc.pdf', $dest='I') {
  7212. //Output PDF to some destination
  7213. //Finish document if necessary
  7214. if ($this->state < 3) {
  7215. $this->Close();
  7216. }
  7217. //Normalize parameters
  7218. if (is_bool($dest)) {
  7219. $dest = $dest ? 'D' : 'F';
  7220. }
  7221. $dest = strtoupper($dest);
  7222. if ($dest[0] != 'F') {
  7223. $name = preg_replace('/[\s]+/', '_', $name);
  7224. $name = preg_replace('/[^a-zA-Z0-9_\.-]/', '', $name);
  7225. }
  7226. if ($this->sign) {
  7227. // *** apply digital signature to the document ***
  7228. // get the document content
  7229. $pdfdoc = $this->getBuffer();
  7230. // remove last newline
  7231. $pdfdoc = substr($pdfdoc, 0, -1);
  7232. // remove filler space
  7233. $byterange_string_len = strlen(TCPDF_STATIC::$byterange_string);
  7234. // define the ByteRange
  7235. $byte_range = array();
  7236. $byte_range[0] = 0;
  7237. $byte_range[1] = strpos($pdfdoc, TCPDF_STATIC::$byterange_string) + $byterange_string_len + 10;
  7238. $byte_range[2] = $byte_range[1] + $this->signature_max_length + 2;
  7239. $byte_range[3] = strlen($pdfdoc) - $byte_range[2];
  7240. $pdfdoc = substr($pdfdoc, 0, $byte_range[1]).substr($pdfdoc, $byte_range[2]);
  7241. // replace the ByteRange
  7242. $byterange = sprintf('/ByteRange[0 %u %u %u]', $byte_range[1], $byte_range[2], $byte_range[3]);
  7243. $byterange .= str_repeat(' ', ($byterange_string_len - strlen($byterange)));
  7244. $pdfdoc = str_replace(TCPDF_STATIC::$byterange_string, $byterange, $pdfdoc);
  7245. // write the document to a temporary folder
  7246. $tempdoc = TCPDF_STATIC::getObjFilename('doc', $this->file_id);
  7247. $f = TCPDF_STATIC::fopenLocal($tempdoc, 'wb');
  7248. if (!$f) {
  7249. $this->Error('Unable to create temporary file: '.$tempdoc);
  7250. }
  7251. $pdfdoc_length = strlen($pdfdoc);
  7252. fwrite($f, $pdfdoc, $pdfdoc_length);
  7253. fclose($f);
  7254. // get digital signature via openssl library
  7255. $tempsign = TCPDF_STATIC::getObjFilename('sig', $this->file_id);
  7256. if (empty($this->signature_data['extracerts'])) {
  7257. openssl_pkcs7_sign($tempdoc, $tempsign, $this->signature_data['signcert'], array($this->signature_data['privkey'], $this->signature_data['password']), array(), PKCS7_BINARY | PKCS7_DETACHED);
  7258. } else {
  7259. 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']);
  7260. }
  7261. // read signature
  7262. $signature = file_get_contents($tempsign);
  7263. // extract signature
  7264. $signature = substr($signature, $pdfdoc_length);
  7265. $signature = substr($signature, (strpos($signature, "%%EOF\n\n------") + 13));
  7266. $tmparr = explode("\n\n", $signature);
  7267. $signature = $tmparr[1];
  7268. // decode signature
  7269. $signature = base64_decode(trim($signature));
  7270. // add TSA timestamp to signature
  7271. $signature = $this->applyTSA($signature);
  7272. // convert signature to hex
  7273. $signature = current(unpack('H*', $signature));
  7274. $signature = str_pad($signature, $this->signature_max_length, '0');
  7275. // Add signature to the document
  7276. $this->buffer = substr($pdfdoc, 0, $byte_range[1]).'<'.$signature.'>'.substr($pdfdoc, $byte_range[1]);
  7277. $this->bufferlen = strlen($this->buffer);
  7278. }
  7279. switch($dest) {
  7280. case 'I': {
  7281. // Send PDF to the standard output
  7282. if (ob_get_contents()) {
  7283. $this->Error('Some data has already been output, can\'t send PDF file');
  7284. }
  7285. if (php_sapi_name() != 'cli') {
  7286. // send output to a browser
  7287. header('Content-Type: application/pdf');
  7288. if (headers_sent()) {
  7289. $this->Error('Some data has already been output to browser, can\'t send PDF file');
  7290. }
  7291. header('Cache-Control: private, must-revalidate, post-check=0, pre-check=0, max-age=1');
  7292. //header('Cache-Control: public, must-revalidate, max-age=0'); // HTTP/1.1
  7293. header('Pragma: public');
  7294. header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
  7295. header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
  7296. header('Content-Disposition: inline; filename="'.basename($name).'"');
  7297. TCPDF_STATIC::sendOutputData($this->getBuffer(), $this->bufferlen);
  7298. } else {
  7299. echo $this->getBuffer();
  7300. }
  7301. break;
  7302. }
  7303. case 'D': {
  7304. // download PDF as file
  7305. if (ob_get_contents()) {
  7306. $this->Error('Some data has already been output, can\'t send PDF file');
  7307. }
  7308. header('Content-Description: File Transfer');
  7309. if (headers_sent()) {
  7310. $this->Error('Some data has already been output to browser, can\'t send PDF file');
  7311. }
  7312. header('Cache-Control: private, must-revalidate, post-check=0, pre-check=0, max-age=1');
  7313. //header('Cache-Control: public, must-revalidate, max-age=0'); // HTTP/1.1
  7314. header('Pragma: public');
  7315. header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
  7316. header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
  7317. // force download dialog
  7318. if (strpos(php_sapi_name(), 'cgi') === false) {
  7319. header('Content-Type: application/force-download');
  7320. header('Content-Type: application/octet-stream', false);
  7321. header('Content-Type: application/download', false);
  7322. header('Content-Type: application/pdf', false);
  7323. } else {
  7324. header('Content-Type: application/pdf');
  7325. }
  7326. // use the Content-Disposition header to supply a recommended filename
  7327. header('Content-Disposition: attachment; filename="'.basename($name).'"');
  7328. header('Content-Transfer-Encoding: binary');
  7329. TCPDF_STATIC::sendOutputData($this->getBuffer(), $this->bufferlen);
  7330. break;
  7331. }
  7332. case 'F':
  7333. case 'FI':
  7334. case 'FD': {
  7335. // save PDF to a local file
  7336. $f = TCPDF_STATIC::fopenLocal($name, 'wb');
  7337. if (!$f) {
  7338. $this->Error('Unable to create output file: '.$name);
  7339. }
  7340. fwrite($f, $this->getBuffer(), $this->bufferlen);
  7341. fclose($f);
  7342. if ($dest == 'FI') {
  7343. // send headers to browser
  7344. header('Content-Type: application/pdf');
  7345. header('Cache-Control: private, must-revalidate, post-check=0, pre-check=0, max-age=1');
  7346. //header('Cache-Control: public, must-revalidate, max-age=0'); // HTTP/1.1
  7347. header('Pragma: public');
  7348. header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
  7349. header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
  7350. header('Content-Disposition: inline; filename="'.basename($name).'"');
  7351. TCPDF_STATIC::sendOutputData(file_get_contents($name), filesize($name));
  7352. } elseif ($dest == 'FD') {
  7353. // send headers to browser
  7354. if (ob_get_contents()) {
  7355. $this->Error('Some data has already been output, can\'t send PDF file');
  7356. }
  7357. header('Content-Description: File Transfer');
  7358. if (headers_sent()) {
  7359. $this->Error('Some data has already been output to browser, can\'t send PDF file');
  7360. }
  7361. header('Cache-Control: private, must-revalidate, post-check=0, pre-check=0, max-age=1');
  7362. header('Pragma: public');
  7363. header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
  7364. header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
  7365. // force download dialog
  7366. if (strpos(php_sapi_name(), 'cgi') === false) {
  7367. header('Content-Type: application/force-download');
  7368. header('Content-Type: application/octet-stream', false);
  7369. header('Content-Type: application/download', false);
  7370. header('Content-Type: application/pdf', false);
  7371. } else {
  7372. header('Content-Type: application/pdf');
  7373. }
  7374. // use the Content-Disposition header to supply a recommended filename
  7375. header('Content-Disposition: attachment; filename="'.basename($name).'"');
  7376. header('Content-Transfer-Encoding: binary');
  7377. TCPDF_STATIC::sendOutputData(file_get_contents($name), filesize($name));
  7378. }
  7379. break;
  7380. }
  7381. case 'E': {
  7382. // return PDF as base64 mime multi-part email attachment (RFC 2045)
  7383. $retval = 'Content-Type: application/pdf;'."\r\n";
  7384. $retval .= ' name="'.$name.'"'."\r\n";
  7385. $retval .= 'Content-Transfer-Encoding: base64'."\r\n";
  7386. $retval .= 'Content-Disposition: attachment;'."\r\n";
  7387. $retval .= ' filename="'.$name.'"'."\r\n\r\n";
  7388. $retval .= chunk_split(base64_encode($this->getBuffer()), 76, "\r\n");
  7389. return $retval;
  7390. }
  7391. case 'S': {
  7392. // returns PDF as a string
  7393. return $this->getBuffer();
  7394. }
  7395. default: {
  7396. $this->Error('Incorrect output destination: '.$dest);
  7397. }
  7398. }
  7399. return '';
  7400. }
  7401. protected static $cleaned_ids = array();
  7402. /**
  7403. * Unset all class variables except the following critical variables.
  7404. * @param $destroyall (boolean) if true destroys all class variables, otherwise preserves critical variables.
  7405. * @param $preserve_objcopy (boolean) if true preserves the objcopy variable
  7406. * @public
  7407. * @since 4.5.016 (2009-02-24)
  7408. */
  7409. public function _destroy($destroyall=false, $preserve_objcopy=false) {
  7410. if (isset(self::$cleaned_ids[$this->file_id])) {
  7411. $destroyall = false;
  7412. }
  7413. if ($destroyall AND !$preserve_objcopy && isset($this->file_id)) {
  7414. self::$cleaned_ids[$this->file_id] = true;
  7415. // remove all temporary files
  7416. if ($handle = @opendir(K_PATH_CACHE)) {
  7417. while ( false !== ( $file_name = readdir( $handle ) ) ) {
  7418. if (strpos($file_name, '__tcpdf_'.$this->file_id.'_') === 0) {
  7419. unlink(K_PATH_CACHE.$file_name);
  7420. }
  7421. }
  7422. closedir($handle);
  7423. }
  7424. if (isset($this->imagekeys)) {
  7425. foreach($this->imagekeys as $file) {
  7426. if (strpos($file, K_PATH_CACHE) === 0 && TCPDF_STATIC::file_exists($file)) {
  7427. @unlink($file);
  7428. }
  7429. }
  7430. }
  7431. }
  7432. $preserve = array(
  7433. 'file_id',
  7434. 'state',
  7435. 'bufferlen',
  7436. 'buffer',
  7437. 'cached_files',
  7438. 'imagekeys',
  7439. 'sign',
  7440. 'signature_data',
  7441. 'signature_max_length',
  7442. 'byterange_string',
  7443. 'tsa_timestamp',
  7444. 'tsa_data'
  7445. );
  7446. foreach (array_keys(get_object_vars($this)) as $val) {
  7447. if ($destroyall OR !in_array($val, $preserve)) {
  7448. if ((!$preserve_objcopy OR ($val != 'objcopy')) AND ($val != 'file_id') AND isset($this->$val)) {
  7449. unset($this->$val);
  7450. }
  7451. }
  7452. }
  7453. }
  7454. /**
  7455. * Check for locale-related bug
  7456. * @protected
  7457. */
  7458. protected function _dochecks() {
  7459. //Check for locale-related bug
  7460. if (1.1 == 1) {
  7461. $this->Error('Don\'t alter the locale before including class file');
  7462. }
  7463. //Check for decimal separator
  7464. if (sprintf('%.1F', 1.0) != '1.0') {
  7465. setlocale(LC_NUMERIC, 'C');
  7466. }
  7467. }
  7468. /**
  7469. * Return an array containing variations for the basic page number alias.
  7470. * @param $a (string) Base alias.
  7471. * @return array of page number aliases
  7472. * @protected
  7473. */
  7474. protected function getInternalPageNumberAliases($a= '') {
  7475. $alias = array();
  7476. // build array of Unicode + ASCII variants (the order is important)
  7477. $alias = array('u' => array(), 'a' => array());
  7478. $u = '{'.$a.'}';
  7479. $alias['u'][] = TCPDF_STATIC::_escape($u);
  7480. if ($this->isunicode) {
  7481. $alias['u'][] = TCPDF_STATIC::_escape(TCPDF_FONTS::UTF8ToLatin1($u, $this->isunicode, $this->CurrentFont));
  7482. $alias['u'][] = TCPDF_STATIC::_escape(TCPDF_FONTS::utf8StrRev($u, false, $this->tmprtl, $this->isunicode, $this->CurrentFont));
  7483. $alias['a'][] = TCPDF_STATIC::_escape(TCPDF_FONTS::UTF8ToLatin1($a, $this->isunicode, $this->CurrentFont));
  7484. $alias['a'][] = TCPDF_STATIC::_escape(TCPDF_FONTS::utf8StrRev($a, false, $this->tmprtl, $this->isunicode, $this->CurrentFont));
  7485. }
  7486. $alias['a'][] = TCPDF_STATIC::_escape($a);
  7487. return $alias;
  7488. }
  7489. /**
  7490. * Return an array containing all internal page aliases.
  7491. * @return array of page number aliases
  7492. * @protected
  7493. */
  7494. protected function getAllInternalPageNumberAliases() {
  7495. $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);
  7496. $pnalias = array();
  7497. foreach($basic_alias as $k => $a) {
  7498. $pnalias[$k] = $this->getInternalPageNumberAliases($a);
  7499. }
  7500. return $pnalias;
  7501. }
  7502. /**
  7503. * Replace right shift page number aliases with spaces to correct right alignment.
  7504. * This works perfectly only when using monospaced fonts.
  7505. * @param $page (string) Page content.
  7506. * @param $aliases (array) Array of page aliases.
  7507. * @param $diff (int) initial difference to add.
  7508. * @return replaced page content.
  7509. * @protected
  7510. */
  7511. protected function replaceRightShiftPageNumAliases($page, $aliases, $diff) {
  7512. foreach ($aliases as $type => $alias) {
  7513. foreach ($alias as $a) {
  7514. // find position of compensation factor
  7515. $startnum = (strpos($a, ':') + 1);
  7516. $a = substr($a, 0, $startnum);
  7517. if (($pos = strpos($page, $a)) !== false) {
  7518. // end of alias
  7519. $endnum = strpos($page, '}', $pos);
  7520. // string to be replaced
  7521. $aa = substr($page, $pos, ($endnum - $pos + 1));
  7522. // get compensation factor
  7523. $ratio = substr($page, ($pos + $startnum), ($endnum - $pos - $startnum));
  7524. $ratio = preg_replace('/[^0-9\.]/', '', $ratio);
  7525. $ratio = floatval($ratio);
  7526. if ($type == 'u') {
  7527. $chrdiff = floor(($diff + 12) * $ratio);
  7528. $shift = str_repeat(' ', $chrdiff);
  7529. $shift = TCPDF_FONTS::UTF8ToUTF16BE($shift, false, $this->isunicode, $this->CurrentFont);
  7530. } else {
  7531. $chrdiff = floor(($diff + 11) * $ratio);
  7532. $shift = str_repeat(' ', $chrdiff);
  7533. }
  7534. $page = str_replace($aa, $shift, $page);
  7535. }
  7536. }
  7537. }
  7538. return $page;
  7539. }
  7540. /**
  7541. * Set page boxes to be included on page descriptions.
  7542. * @param $boxes (array) Array of page boxes to set on document: ('MediaBox', 'CropBox', 'BleedBox', 'TrimBox', 'ArtBox').
  7543. * @protected
  7544. */
  7545. protected function setPageBoxTypes($boxes) {
  7546. $this->page_boxes = array();
  7547. foreach ($boxes as $box) {
  7548. if (in_array($box, TCPDF_STATIC::$pageboxes)) {
  7549. $this->page_boxes[] = $box;
  7550. }
  7551. }
  7552. }
  7553. /**
  7554. * Output pages (and replace page number aliases).
  7555. * @protected
  7556. */
  7557. protected function _putpages() {
  7558. $filter = ($this->compress) ? '/Filter /FlateDecode ' : '';
  7559. // get internal aliases for page numbers
  7560. $pnalias = $this->getAllInternalPageNumberAliases();
  7561. $num_pages = $this->numpages;
  7562. $ptpa = TCPDF_STATIC::formatPageNumber(($this->starting_page_number + $num_pages - 1));
  7563. $ptpu = TCPDF_FONTS::UTF8ToUTF16BE($ptpa, false, $this->isunicode, $this->CurrentFont);
  7564. $ptp_num_chars = $this->GetNumChars($ptpa);
  7565. $pagegroupnum = 0;
  7566. $groupnum = 0;
  7567. $ptgu = 1;
  7568. $ptga = 1;
  7569. $ptg_num_chars = 1;
  7570. for ($n = 1; $n <= $num_pages; ++$n) {
  7571. // get current page
  7572. $temppage = $this->getPageBuffer($n);
  7573. $pagelen = strlen($temppage);
  7574. // set replacements for total pages number
  7575. $pnpa = TCPDF_STATIC::formatPageNumber(($this->starting_page_number + $n - 1));
  7576. $pnpu = TCPDF_FONTS::UTF8ToUTF16BE($pnpa, false, $this->isunicode, $this->CurrentFont);
  7577. $pnp_num_chars = $this->GetNumChars($pnpa);
  7578. $pdiff = 0; // difference used for right shift alignment of page numbers
  7579. $gdiff = 0; // difference used for right shift alignment of page group numbers
  7580. if (!empty($this->pagegroups)) {
  7581. if (isset($this->newpagegroup[$n])) {
  7582. $pagegroupnum = 0;
  7583. ++$groupnum;
  7584. $ptga = TCPDF_STATIC::formatPageNumber($this->pagegroups[$groupnum]);
  7585. $ptgu = TCPDF_FONTS::UTF8ToUTF16BE($ptga, false, $this->isunicode, $this->CurrentFont);
  7586. $ptg_num_chars = $this->GetNumChars($ptga);
  7587. }
  7588. ++$pagegroupnum;
  7589. $pnga = TCPDF_STATIC::formatPageNumber($pagegroupnum);
  7590. $pngu = TCPDF_FONTS::UTF8ToUTF16BE($pnga, false, $this->isunicode, $this->CurrentFont);
  7591. $png_num_chars = $this->GetNumChars($pnga);
  7592. // replace page numbers
  7593. $replace = array();
  7594. $replace[] = array($ptgu, $ptg_num_chars, 9, $pnalias[2]['u']);
  7595. $replace[] = array($ptga, $ptg_num_chars, 7, $pnalias[2]['a']);
  7596. $replace[] = array($pngu, $png_num_chars, 9, $pnalias[3]['u']);
  7597. $replace[] = array($pnga, $png_num_chars, 7, $pnalias[3]['a']);
  7598. list($temppage, $gdiff) = TCPDF_STATIC::replacePageNumAliases($temppage, $replace, $gdiff);
  7599. }
  7600. // replace page numbers
  7601. $replace = array();
  7602. $replace[] = array($ptpu, $ptp_num_chars, 9, $pnalias[0]['u']);
  7603. $replace[] = array($ptpa, $ptp_num_chars, 7, $pnalias[0]['a']);
  7604. $replace[] = array($pnpu, $pnp_num_chars, 9, $pnalias[1]['u']);
  7605. $replace[] = array($pnpa, $pnp_num_chars, 7, $pnalias[1]['a']);
  7606. list($temppage, $pdiff) = TCPDF_STATIC::replacePageNumAliases($temppage, $replace, $pdiff);
  7607. // replace right shift alias
  7608. $temppage = $this->replaceRightShiftPageNumAliases($temppage, $pnalias[4], max($pdiff, $gdiff));
  7609. // replace EPS marker
  7610. $temppage = str_replace($this->epsmarker, '', $temppage);
  7611. //Page
  7612. $this->page_obj_id[$n] = $this->_newobj();
  7613. $out = '<<';
  7614. $out .= ' /Type /Page';
  7615. $out .= ' /Parent 1 0 R';
  7616. if (empty($this->signature_data['approval']) OR ($this->signature_data['approval'] != 'A')) {
  7617. $out .= ' /LastModified '.$this->_datestring(0, $this->doc_modification_timestamp);
  7618. }
  7619. $out .= ' /Resources 2 0 R';
  7620. foreach ($this->page_boxes as $box) {
  7621. $out .= ' /'.$box;
  7622. $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']);
  7623. }
  7624. if (isset($this->pagedim[$n]['BoxColorInfo']) AND !empty($this->pagedim[$n]['BoxColorInfo'])) {
  7625. $out .= ' /BoxColorInfo <<';
  7626. foreach ($this->page_boxes as $box) {
  7627. if (isset($this->pagedim[$n]['BoxColorInfo'][$box])) {
  7628. $out .= ' /'.$box.' <<';
  7629. if (isset($this->pagedim[$n]['BoxColorInfo'][$box]['C'])) {
  7630. $color = $this->pagedim[$n]['BoxColorInfo'][$box]['C'];
  7631. $out .= ' /C [';
  7632. $out .= sprintf(' %F %F %F', ($color[0] / 255), ($color[1] / 255), ($color[2] / 255));
  7633. $out .= ' ]';
  7634. }
  7635. if (isset($this->pagedim[$n]['BoxColorInfo'][$box]['W'])) {
  7636. $out .= ' /W '.($this->pagedim[$n]['BoxColorInfo'][$box]['W'] * $this->k);
  7637. }
  7638. if (isset($this->pagedim[$n]['BoxColorInfo'][$box]['S'])) {
  7639. $out .= ' /S /'.$this->pagedim[$n]['BoxColorInfo'][$box]['S'];
  7640. }
  7641. if (isset($this->pagedim[$n]['BoxColorInfo'][$box]['D'])) {
  7642. $dashes = $this->pagedim[$n]['BoxColorInfo'][$box]['D'];
  7643. $out .= ' /D [';
  7644. foreach ($dashes as $dash) {
  7645. $out .= sprintf(' %F', ($dash * $this->k));
  7646. }
  7647. $out .= ' ]';
  7648. }
  7649. $out .= ' >>';
  7650. }
  7651. }
  7652. $out .= ' >>';
  7653. }
  7654. $out .= ' /Contents '.($this->n + 1).' 0 R';
  7655. $out .= ' /Rotate '.$this->pagedim[$n]['Rotate'];
  7656. if (!$this->pdfa_mode) {
  7657. $out .= ' /Group << /Type /Group /S /Transparency /CS /DeviceRGB >>';
  7658. }
  7659. if (isset($this->pagedim[$n]['trans']) AND !empty($this->pagedim[$n]['trans'])) {
  7660. // page transitions
  7661. if (isset($this->pagedim[$n]['trans']['Dur'])) {
  7662. $out .= ' /Dur '.$this->pagedim[$n]['trans']['Dur'];
  7663. }
  7664. $out .= ' /Trans <<';
  7665. $out .= ' /Type /Trans';
  7666. if (isset($this->pagedim[$n]['trans']['S'])) {
  7667. $out .= ' /S /'.$this->pagedim[$n]['trans']['S'];
  7668. }
  7669. if (isset($this->pagedim[$n]['trans']['D'])) {
  7670. $out .= ' /D '.$this->pagedim[$n]['trans']['D'];
  7671. }
  7672. if (isset($this->pagedim[$n]['trans']['Dm'])) {
  7673. $out .= ' /Dm /'.$this->pagedim[$n]['trans']['Dm'];
  7674. }
  7675. if (isset($this->pagedim[$n]['trans']['M'])) {
  7676. $out .= ' /M /'.$this->pagedim[$n]['trans']['M'];
  7677. }
  7678. if (isset($this->pagedim[$n]['trans']['Di'])) {
  7679. $out .= ' /Di '.$this->pagedim[$n]['trans']['Di'];
  7680. }
  7681. if (isset($this->pagedim[$n]['trans']['SS'])) {
  7682. $out .= ' /SS '.$this->pagedim[$n]['trans']['SS'];
  7683. }
  7684. if (isset($this->pagedim[$n]['trans']['B'])) {
  7685. $out .= ' /B '.$this->pagedim[$n]['trans']['B'];
  7686. }
  7687. $out .= ' >>';
  7688. }
  7689. $out .= $this->_getannotsrefs($n);
  7690. $out .= ' /PZ '.$this->pagedim[$n]['PZ'];
  7691. $out .= ' >>';
  7692. $out .= "\n".'endobj';
  7693. $this->_out($out);
  7694. //Page content
  7695. $p = ($this->compress) ? gzcompress($temppage) : $temppage;
  7696. $this->_newobj();
  7697. $p = $this->_getrawstream($p);
  7698. $this->_out('<<'.$filter.'/Length '.strlen($p).'>> stream'."\n".$p."\n".'endstream'."\n".'endobj');
  7699. }
  7700. //Pages root
  7701. $out = $this->_getobj(1)."\n";
  7702. $out .= '<< /Type /Pages /Kids [';
  7703. foreach($this->page_obj_id as $page_obj) {
  7704. $out .= ' '.$page_obj.' 0 R';
  7705. }
  7706. $out .= ' ] /Count '.$num_pages.' >>';
  7707. $out .= "\n".'endobj';
  7708. $this->_out($out);
  7709. }
  7710. /**
  7711. * Get references to page annotations.
  7712. * @param $n (int) page number
  7713. * @return string
  7714. * @protected
  7715. * @author Nicola Asuni
  7716. * @since 5.0.010 (2010-05-17)
  7717. */
  7718. protected function _getannotsrefs($n) {
  7719. if (!(isset($this->PageAnnots[$n]) OR ($this->sign AND isset($this->signature_data['cert_type'])))) {
  7720. return '';
  7721. }
  7722. $out = ' /Annots [';
  7723. if (isset($this->PageAnnots[$n])) {
  7724. foreach ($this->PageAnnots[$n] as $key => $val) {
  7725. if (!in_array($val['n'], $this->radio_groups)) {
  7726. $out .= ' '.$val['n'].' 0 R';
  7727. }
  7728. }
  7729. // add radiobutton groups
  7730. if (isset($this->radiobutton_groups[$n])) {
  7731. foreach ($this->radiobutton_groups[$n] as $key => $data) {
  7732. if (isset($data['n'])) {
  7733. $out .= ' '.$data['n'].' 0 R';
  7734. }
  7735. }
  7736. }
  7737. }
  7738. if ($this->sign AND ($n == $this->signature_appearance['page']) AND isset($this->signature_data['cert_type'])) {
  7739. // set reference for signature object
  7740. $out .= ' '.$this->sig_obj_id.' 0 R';
  7741. }
  7742. if (!empty($this->empty_signature_appearance)) {
  7743. foreach ($this->empty_signature_appearance as $esa) {
  7744. if ($esa['page'] == $n) {
  7745. // set reference for empty signature objects
  7746. $out .= ' '.$esa['objid'].' 0 R';
  7747. }
  7748. }
  7749. }
  7750. $out .= ' ]';
  7751. return $out;
  7752. }
  7753. /**
  7754. * Output annotations objects for all pages.
  7755. * !!! THIS METHOD IS NOT YET COMPLETED !!!
  7756. * See section 12.5 of PDF 32000_2008 reference.
  7757. * @protected
  7758. * @author Nicola Asuni
  7759. * @since 4.0.018 (2008-08-06)
  7760. */
  7761. protected function _putannotsobjs() {
  7762. // reset object counter
  7763. for ($n=1; $n <= $this->numpages; ++$n) {
  7764. if (isset($this->PageAnnots[$n])) {
  7765. // set page annotations
  7766. foreach ($this->PageAnnots[$n] as $key => $pl) {
  7767. $annot_obj_id = $this->PageAnnots[$n][$key]['n'];
  7768. // create annotation object for grouping radiobuttons
  7769. if (isset($this->radiobutton_groups[$n][$pl['txt']]) AND is_array($this->radiobutton_groups[$n][$pl['txt']])) {
  7770. $radio_button_obj_id = $this->radiobutton_groups[$n][$pl['txt']]['n'];
  7771. $annots = '<<';
  7772. $annots .= ' /Type /Annot';
  7773. $annots .= ' /Subtype /Widget';
  7774. $annots .= ' /Rect [0 0 0 0]';
  7775. if ($this->radiobutton_groups[$n][$pl['txt']]['#readonly#']) {
  7776. // read only
  7777. $annots .= ' /F 68';
  7778. $annots .= ' /Ff 49153';
  7779. } else {
  7780. $annots .= ' /F 4'; // default print for PDF/A
  7781. $annots .= ' /Ff 49152';
  7782. }
  7783. $annots .= ' /T '.$this->_datastring($pl['txt'], $radio_button_obj_id);
  7784. if (isset($pl['opt']['tu']) AND is_string($pl['opt']['tu'])) {
  7785. $annots .= ' /TU '.$this->_datastring($pl['opt']['tu'], $radio_button_obj_id);
  7786. }
  7787. $annots .= ' /FT /Btn';
  7788. $annots .= ' /Kids [';
  7789. $defval = '';
  7790. foreach ($this->radiobutton_groups[$n][$pl['txt']] as $key => $data) {
  7791. if (isset($data['kid'])) {
  7792. $annots .= ' '.$data['kid'].' 0 R';
  7793. if ($data['def'] !== 'Off') {
  7794. $defval = $data['def'];
  7795. }
  7796. }
  7797. }
  7798. $annots .= ' ]';
  7799. if (!empty($defval)) {
  7800. $annots .= ' /V /'.$defval;
  7801. }
  7802. $annots .= ' >>';
  7803. $this->_out($this->_getobj($radio_button_obj_id)."\n".$annots."\n".'endobj');
  7804. $this->form_obj_id[] = $radio_button_obj_id;
  7805. // store object id to be used on Parent entry of Kids
  7806. $this->radiobutton_groups[$n][$pl['txt']] = $radio_button_obj_id;
  7807. }
  7808. $formfield = false;
  7809. $pl['opt'] = array_change_key_case($pl['opt'], CASE_LOWER);
  7810. $a = $pl['x'] * $this->k;
  7811. $b = $this->pagedim[$n]['h'] - (($pl['y'] + $pl['h']) * $this->k);
  7812. $c = $pl['w'] * $this->k;
  7813. $d = $pl['h'] * $this->k;
  7814. $rect = sprintf('%F %F %F %F', $a, $b, $a+$c, $b+$d);
  7815. // create new annotation object
  7816. $annots = '<</Type /Annot';
  7817. $annots .= ' /Subtype /'.$pl['opt']['subtype'];
  7818. $annots .= ' /Rect ['.$rect.']';
  7819. $ft = array('Btn', 'Tx', 'Ch', 'Sig');
  7820. if (isset($pl['opt']['ft']) AND in_array($pl['opt']['ft'], $ft)) {
  7821. $annots .= ' /FT /'.$pl['opt']['ft'];
  7822. $formfield = true;
  7823. }
  7824. if ($pl['opt']['subtype'] !== 'Link') {
  7825. $annots .= ' /Contents '.$this->_textstring($pl['txt'], $annot_obj_id);
  7826. }
  7827. $annots .= ' /P '.$this->page_obj_id[$n].' 0 R';
  7828. $annots .= ' /NM '.$this->_datastring(sprintf('%04u-%04u', $n, $key), $annot_obj_id);
  7829. $annots .= ' /M '.$this->_datestring($annot_obj_id, $this->doc_modification_timestamp);
  7830. if (isset($pl['opt']['f'])) {
  7831. $fval = 0;
  7832. if (is_array($pl['opt']['f'])) {
  7833. foreach ($pl['opt']['f'] as $f) {
  7834. switch (strtolower($f)) {
  7835. case 'invisible': {
  7836. $fval += 1 << 0;
  7837. break;
  7838. }
  7839. case 'hidden': {
  7840. $fval += 1 << 1;
  7841. break;
  7842. }
  7843. case 'print': {
  7844. $fval += 1 << 2;
  7845. break;
  7846. }
  7847. case 'nozoom': {
  7848. $fval += 1 << 3;
  7849. break;
  7850. }
  7851. case 'norotate': {
  7852. $fval += 1 << 4;
  7853. break;
  7854. }
  7855. case 'noview': {
  7856. $fval += 1 << 5;
  7857. break;
  7858. }
  7859. case 'readonly': {
  7860. $fval += 1 << 6;
  7861. break;
  7862. }
  7863. case 'locked': {
  7864. $fval += 1 << 8;
  7865. break;
  7866. }
  7867. case 'togglenoview': {
  7868. $fval += 1 << 9;
  7869. break;
  7870. }
  7871. case 'lockedcontents': {
  7872. $fval += 1 << 10;
  7873. break;
  7874. }
  7875. default: {
  7876. break;
  7877. }
  7878. }
  7879. }
  7880. } else {
  7881. $fval = intval($pl['opt']['f']);
  7882. }
  7883. } else {
  7884. $fval = 4;
  7885. }
  7886. if ($this->pdfa_mode) {
  7887. // force print flag for PDF/A mode
  7888. $fval |= 4;
  7889. }
  7890. $annots .= ' /F '.intval($fval);
  7891. if (isset($pl['opt']['as']) AND is_string($pl['opt']['as'])) {
  7892. $annots .= ' /AS /'.$pl['opt']['as'];
  7893. }
  7894. if (isset($pl['opt']['ap'])) {
  7895. // appearance stream
  7896. $annots .= ' /AP <<';
  7897. if (is_array($pl['opt']['ap'])) {
  7898. foreach ($pl['opt']['ap'] as $apmode => $apdef) {
  7899. // $apmode can be: n = normal; r = rollover; d = down;
  7900. $annots .= ' /'.strtoupper($apmode);
  7901. if (is_array($apdef)) {
  7902. $annots .= ' <<';
  7903. foreach ($apdef as $apstate => $stream) {
  7904. // reference to XObject that define the appearance for this mode-state
  7905. $apsobjid = $this->_putAPXObject($c, $d, $stream);
  7906. $annots .= ' /'.$apstate.' '.$apsobjid.' 0 R';
  7907. }
  7908. $annots .= ' >>';
  7909. } else {
  7910. // reference to XObject that define the appearance for this mode
  7911. $apsobjid = $this->_putAPXObject($c, $d, $apdef);
  7912. $annots .= ' '.$apsobjid.' 0 R';
  7913. }
  7914. }
  7915. } else {
  7916. $annots .= $pl['opt']['ap'];
  7917. }
  7918. $annots .= ' >>';
  7919. }
  7920. if (isset($pl['opt']['bs']) AND (is_array($pl['opt']['bs']))) {
  7921. $annots .= ' /BS <<';
  7922. $annots .= ' /Type /Border';
  7923. if (isset($pl['opt']['bs']['w'])) {
  7924. $annots .= ' /W '.intval($pl['opt']['bs']['w']);
  7925. }
  7926. $bstyles = array('S', 'D', 'B', 'I', 'U');
  7927. if (isset($pl['opt']['bs']['s']) AND in_array($pl['opt']['bs']['s'], $bstyles)) {
  7928. $annots .= ' /S /'.$pl['opt']['bs']['s'];
  7929. }
  7930. if (isset($pl['opt']['bs']['d']) AND (is_array($pl['opt']['bs']['d']))) {
  7931. $annots .= ' /D [';
  7932. foreach ($pl['opt']['bs']['d'] as $cord) {
  7933. $annots .= ' '.intval($cord);
  7934. }
  7935. $annots .= ']';
  7936. }
  7937. $annots .= ' >>';
  7938. } else {
  7939. $annots .= ' /Border [';
  7940. if (isset($pl['opt']['border']) AND (count($pl['opt']['border']) >= 3)) {
  7941. $annots .= intval($pl['opt']['border'][0]).' ';
  7942. $annots .= intval($pl['opt']['border'][1]).' ';
  7943. $annots .= intval($pl['opt']['border'][2]);
  7944. if (isset($pl['opt']['border'][3]) AND is_array($pl['opt']['border'][3])) {
  7945. $annots .= ' [';
  7946. foreach ($pl['opt']['border'][3] as $dash) {
  7947. $annots .= intval($dash).' ';
  7948. }
  7949. $annots .= ']';
  7950. }
  7951. } else {
  7952. $annots .= '0 0 0';
  7953. }
  7954. $annots .= ']';
  7955. }
  7956. if (isset($pl['opt']['be']) AND (is_array($pl['opt']['be']))) {
  7957. $annots .= ' /BE <<';
  7958. $bstyles = array('S', 'C');
  7959. if (isset($pl['opt']['be']['s']) AND in_array($pl['opt']['be']['s'], $bstyles)) {
  7960. $annots .= ' /S /'.$pl['opt']['bs']['s'];
  7961. } else {
  7962. $annots .= ' /S /S';
  7963. }
  7964. if (isset($pl['opt']['be']['i']) AND ($pl['opt']['be']['i'] >= 0) AND ($pl['opt']['be']['i'] <= 2)) {
  7965. $annots .= ' /I '.sprintf(' %F', $pl['opt']['be']['i']);
  7966. }
  7967. $annots .= '>>';
  7968. }
  7969. if (isset($pl['opt']['c']) AND (is_array($pl['opt']['c'])) AND !empty($pl['opt']['c'])) {
  7970. $annots .= ' /C '.TCPDF_COLORS::getColorStringFromArray($pl['opt']['c']);
  7971. }
  7972. //$annots .= ' /StructParent ';
  7973. //$annots .= ' /OC ';
  7974. $markups = array('text', 'freetext', 'line', 'square', 'circle', 'polygon', 'polyline', 'highlight', 'underline', 'squiggly', 'strikeout', 'stamp', 'caret', 'ink', 'fileattachment', 'sound');
  7975. if (in_array(strtolower($pl['opt']['subtype']), $markups)) {
  7976. // this is a markup type
  7977. if (isset($pl['opt']['t']) AND is_string($pl['opt']['t'])) {
  7978. $annots .= ' /T '.$this->_textstring($pl['opt']['t'], $annot_obj_id);
  7979. }
  7980. //$annots .= ' /Popup ';
  7981. if (isset($pl['opt']['ca'])) {
  7982. $annots .= ' /CA '.sprintf('%F', floatval($pl['opt']['ca']));
  7983. }
  7984. if (isset($pl['opt']['rc'])) {
  7985. $annots .= ' /RC '.$this->_textstring($pl['opt']['rc'], $annot_obj_id);
  7986. }
  7987. $annots .= ' /CreationDate '.$this->_datestring($annot_obj_id, $this->doc_creation_timestamp);
  7988. //$annots .= ' /IRT ';
  7989. if (isset($pl['opt']['subj'])) {
  7990. $annots .= ' /Subj '.$this->_textstring($pl['opt']['subj'], $annot_obj_id);
  7991. }
  7992. //$annots .= ' /RT ';
  7993. //$annots .= ' /IT ';
  7994. //$annots .= ' /ExData ';
  7995. }
  7996. $lineendings = array('Square', 'Circle', 'Diamond', 'OpenArrow', 'ClosedArrow', 'None', 'Butt', 'ROpenArrow', 'RClosedArrow', 'Slash');
  7997. // Annotation types
  7998. switch (strtolower($pl['opt']['subtype'])) {
  7999. case 'text': {
  8000. if (isset($pl['opt']['open'])) {
  8001. $annots .= ' /Open '. (strtolower($pl['opt']['open']) == 'true' ? 'true' : 'false');
  8002. }
  8003. $iconsapp = array('Comment', 'Help', 'Insert', 'Key', 'NewParagraph', 'Note', 'Paragraph');
  8004. if (isset($pl['opt']['name']) AND in_array($pl['opt']['name'], $iconsapp)) {
  8005. $annots .= ' /Name /'.$pl['opt']['name'];
  8006. } else {
  8007. $annots .= ' /Name /Note';
  8008. }
  8009. $statemodels = array('Marked', 'Review');
  8010. if (isset($pl['opt']['statemodel']) AND in_array($pl['opt']['statemodel'], $statemodels)) {
  8011. $annots .= ' /StateModel /'.$pl['opt']['statemodel'];
  8012. } else {
  8013. $pl['opt']['statemodel'] = 'Marked';
  8014. $annots .= ' /StateModel /'.$pl['opt']['statemodel'];
  8015. }
  8016. if ($pl['opt']['statemodel'] == 'Marked') {
  8017. $states = array('Accepted', 'Unmarked');
  8018. } else {
  8019. $states = array('Accepted', 'Rejected', 'Cancelled', 'Completed', 'None');
  8020. }
  8021. if (isset($pl['opt']['state']) AND in_array($pl['opt']['state'], $states)) {
  8022. $annots .= ' /State /'.$pl['opt']['state'];
  8023. } else {
  8024. if ($pl['opt']['statemodel'] == 'Marked') {
  8025. $annots .= ' /State /Unmarked';
  8026. } else {
  8027. $annots .= ' /State /None';
  8028. }
  8029. }
  8030. break;
  8031. }
  8032. case 'link': {
  8033. if (is_string($pl['txt']) && !empty($pl['txt'])) {
  8034. if ($pl['txt'][0] == '#') {
  8035. // internal destination
  8036. $annots .= ' /A <</S /GoTo /D '.TCPDF_STATIC::encodeNameObject(substr($pl['txt'], 1)).'>>';
  8037. } elseif ($pl['txt'][0] == '%') {
  8038. // embedded PDF file
  8039. $filename = basename(substr($pl['txt'], 1));
  8040. $annots .= ' /A << /S /GoToE /D [0 /Fit] /NewWindow true /T << /R /C /P '.($n - 1).' /A '.$this->embeddedfiles[$filename]['a'].' >> >>';
  8041. } elseif ($pl['txt'][0] == '*') {
  8042. // embedded generic file
  8043. $filename = basename(substr($pl['txt'], 1));
  8044. $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});';
  8045. $annots .= ' /A << /S /JavaScript /JS '.$this->_textstring($jsa, $annot_obj_id).'>>';
  8046. } else {
  8047. $parsedUrl = parse_url($pl['txt']);
  8048. if (empty($parsedUrl['scheme']) AND (!empty($parsedUrl['path']) && strtolower(substr($parsedUrl['path'], -4)) == '.pdf')) {
  8049. // relative link to a PDF file
  8050. $dest = '[0 /Fit]'; // default page 0
  8051. if (!empty($parsedUrl['fragment'])) {
  8052. // check for named destination
  8053. $tmp = explode('=', $parsedUrl['fragment']);
  8054. $dest = '('.((count($tmp) == 2) ? $tmp[1] : $tmp[0]).')';
  8055. }
  8056. $annots .= ' /A <</S /GoToR /D '.$dest.' /F '.$this->_datastring($this->unhtmlentities($parsedUrl['path']), $annot_obj_id).' /NewWindow true>>';
  8057. } else {
  8058. // external URI link
  8059. $annots .= ' /A <</S /URI /URI '.$this->_datastring($this->unhtmlentities($pl['txt']), $annot_obj_id).'>>';
  8060. }
  8061. }
  8062. } elseif (isset($this->links[$pl['txt']])) {
  8063. // internal link ID
  8064. $l = $this->links[$pl['txt']];
  8065. if (isset($this->page_obj_id[($l['p'])])) {
  8066. $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)));
  8067. }
  8068. }
  8069. $hmodes = array('N', 'I', 'O', 'P');
  8070. if (isset($pl['opt']['h']) AND in_array($pl['opt']['h'], $hmodes)) {
  8071. $annots .= ' /H /'.$pl['opt']['h'];
  8072. } else {
  8073. $annots .= ' /H /I';
  8074. }
  8075. //$annots .= ' /PA ';
  8076. //$annots .= ' /Quadpoints ';
  8077. break;
  8078. }
  8079. case 'freetext': {
  8080. if (isset($pl['opt']['da']) AND !empty($pl['opt']['da'])) {
  8081. $annots .= ' /DA ('.$pl['opt']['da'].')';
  8082. }
  8083. if (isset($pl['opt']['q']) AND ($pl['opt']['q'] >= 0) AND ($pl['opt']['q'] <= 2)) {
  8084. $annots .= ' /Q '.intval($pl['opt']['q']);
  8085. }
  8086. if (isset($pl['opt']['rc'])) {
  8087. $annots .= ' /RC '.$this->_textstring($pl['opt']['rc'], $annot_obj_id);
  8088. }
  8089. if (isset($pl['opt']['ds'])) {
  8090. $annots .= ' /DS '.$this->_textstring($pl['opt']['ds'], $annot_obj_id);
  8091. }
  8092. if (isset($pl['opt']['cl']) AND is_array($pl['opt']['cl'])) {
  8093. $annots .= ' /CL [';
  8094. foreach ($pl['opt']['cl'] as $cl) {
  8095. $annots .= sprintf('%F ', $cl * $this->k);
  8096. }
  8097. $annots .= ']';
  8098. }
  8099. $tfit = array('FreeText', 'FreeTextCallout', 'FreeTextTypeWriter');
  8100. if (isset($pl['opt']['it']) AND in_array($pl['opt']['it'], $tfit)) {
  8101. $annots .= ' /IT /'.$pl['opt']['it'];
  8102. }
  8103. if (isset($pl['opt']['rd']) AND is_array($pl['opt']['rd'])) {
  8104. $l = $pl['opt']['rd'][0] * $this->k;
  8105. $r = $pl['opt']['rd'][1] * $this->k;
  8106. $t = $pl['opt']['rd'][2] * $this->k;
  8107. $b = $pl['opt']['rd'][3] * $this->k;
  8108. $annots .= ' /RD ['.sprintf('%F %F %F %F', $l, $r, $t, $b).']';
  8109. }
  8110. if (isset($pl['opt']['le']) AND in_array($pl['opt']['le'], $lineendings)) {
  8111. $annots .= ' /LE /'.$pl['opt']['le'];
  8112. }
  8113. break;
  8114. }
  8115. case 'line': {
  8116. break;
  8117. }
  8118. case 'square': {
  8119. break;
  8120. }
  8121. case 'circle': {
  8122. break;
  8123. }
  8124. case 'polygon': {
  8125. break;
  8126. }
  8127. case 'polyline': {
  8128. break;
  8129. }
  8130. case 'highlight': {
  8131. break;
  8132. }
  8133. case 'underline': {
  8134. break;
  8135. }
  8136. case 'squiggly': {
  8137. break;
  8138. }
  8139. case 'strikeout': {
  8140. break;
  8141. }
  8142. case 'stamp': {
  8143. break;
  8144. }
  8145. case 'caret': {
  8146. break;
  8147. }
  8148. case 'ink': {
  8149. break;
  8150. }
  8151. case 'popup': {
  8152. break;
  8153. }
  8154. case 'fileattachment': {
  8155. if ($this->pdfa_mode && $this->pdfa_version != 3) {
  8156. // embedded files are not allowed in PDF/A mode version 1 and 2
  8157. break;
  8158. }
  8159. if (!isset($pl['opt']['fs'])) {
  8160. break;
  8161. }
  8162. $filename = basename($pl['opt']['fs']);
  8163. if (isset($this->embeddedfiles[$filename]['f'])) {
  8164. $annots .= ' /FS '.$this->embeddedfiles[$filename]['f'].' 0 R';
  8165. $iconsapp = array('Graph', 'Paperclip', 'PushPin', 'Tag');
  8166. if (isset($pl['opt']['name']) AND in_array($pl['opt']['name'], $iconsapp)) {
  8167. $annots .= ' /Name /'.$pl['opt']['name'];
  8168. } else {
  8169. $annots .= ' /Name /PushPin';
  8170. }
  8171. // index (zero-based) of the annotation in the Annots array of this page
  8172. $this->embeddedfiles[$filename]['a'] = $key;
  8173. }
  8174. break;
  8175. }
  8176. case 'sound': {
  8177. if (!isset($pl['opt']['fs'])) {
  8178. break;
  8179. }
  8180. $filename = basename($pl['opt']['fs']);
  8181. if (isset($this->embeddedfiles[$filename]['f'])) {
  8182. // ... TO BE COMPLETED ...
  8183. // /R /C /B /E /CO /CP
  8184. $annots .= ' /Sound '.$this->embeddedfiles[$filename]['f'].' 0 R';
  8185. $iconsapp = array('Speaker', 'Mic');
  8186. if (isset($pl['opt']['name']) AND in_array($pl['opt']['name'], $iconsapp)) {
  8187. $annots .= ' /Name /'.$pl['opt']['name'];
  8188. } else {
  8189. $annots .= ' /Name /Speaker';
  8190. }
  8191. }
  8192. break;
  8193. }
  8194. case 'movie': {
  8195. break;
  8196. }
  8197. case 'widget': {
  8198. $hmode = array('N', 'I', 'O', 'P', 'T');
  8199. if (isset($pl['opt']['h']) AND in_array($pl['opt']['h'], $hmode)) {
  8200. $annots .= ' /H /'.$pl['opt']['h'];
  8201. }
  8202. if (isset($pl['opt']['mk']) AND (is_array($pl['opt']['mk'])) AND !empty($pl['opt']['mk'])) {
  8203. $annots .= ' /MK <<';
  8204. if (isset($pl['opt']['mk']['r'])) {
  8205. $annots .= ' /R '.$pl['opt']['mk']['r'];
  8206. }
  8207. if (isset($pl['opt']['mk']['bc']) AND (is_array($pl['opt']['mk']['bc']))) {
  8208. $annots .= ' /BC '.TCPDF_COLORS::getColorStringFromArray($pl['opt']['mk']['bc']);
  8209. }
  8210. if (isset($pl['opt']['mk']['bg']) AND (is_array($pl['opt']['mk']['bg']))) {
  8211. $annots .= ' /BG '.TCPDF_COLORS::getColorStringFromArray($pl['opt']['mk']['bg']);
  8212. }
  8213. if (isset($pl['opt']['mk']['ca'])) {
  8214. $annots .= ' /CA '.$pl['opt']['mk']['ca'];
  8215. }
  8216. if (isset($pl['opt']['mk']['rc'])) {
  8217. $annots .= ' /RC '.$pl['opt']['mk']['rc'];
  8218. }
  8219. if (isset($pl['opt']['mk']['ac'])) {
  8220. $annots .= ' /AC '.$pl['opt']['mk']['ac'];
  8221. }
  8222. if (isset($pl['opt']['mk']['i'])) {
  8223. $info = $this->getImageBuffer($pl['opt']['mk']['i']);
  8224. if ($info !== false) {
  8225. $annots .= ' /I '.$info['n'].' 0 R';
  8226. }
  8227. }
  8228. if (isset($pl['opt']['mk']['ri'])) {
  8229. $info = $this->getImageBuffer($pl['opt']['mk']['ri']);
  8230. if ($info !== false) {
  8231. $annots .= ' /RI '.$info['n'].' 0 R';
  8232. }
  8233. }
  8234. if (isset($pl['opt']['mk']['ix'])) {
  8235. $info = $this->getImageBuffer($pl['opt']['mk']['ix']);
  8236. if ($info !== false) {
  8237. $annots .= ' /IX '.$info['n'].' 0 R';
  8238. }
  8239. }
  8240. if (isset($pl['opt']['mk']['if']) AND (is_array($pl['opt']['mk']['if'])) AND !empty($pl['opt']['mk']['if'])) {
  8241. $annots .= ' /IF <<';
  8242. $if_sw = array('A', 'B', 'S', 'N');
  8243. if (isset($pl['opt']['mk']['if']['sw']) AND in_array($pl['opt']['mk']['if']['sw'], $if_sw)) {
  8244. $annots .= ' /SW /'.$pl['opt']['mk']['if']['sw'];
  8245. }
  8246. $if_s = array('A', 'P');
  8247. if (isset($pl['opt']['mk']['if']['s']) AND in_array($pl['opt']['mk']['if']['s'], $if_s)) {
  8248. $annots .= ' /S /'.$pl['opt']['mk']['if']['s'];
  8249. }
  8250. if (isset($pl['opt']['mk']['if']['a']) AND (is_array($pl['opt']['mk']['if']['a'])) AND !empty($pl['opt']['mk']['if']['a'])) {
  8251. $annots .= sprintf(' /A [%F %F]', $pl['opt']['mk']['if']['a'][0], $pl['opt']['mk']['if']['a'][1]);
  8252. }
  8253. if (isset($pl['opt']['mk']['if']['fb']) AND ($pl['opt']['mk']['if']['fb'])) {
  8254. $annots .= ' /FB true';
  8255. }
  8256. $annots .= '>>';
  8257. }
  8258. if (isset($pl['opt']['mk']['tp']) AND ($pl['opt']['mk']['tp'] >= 0) AND ($pl['opt']['mk']['tp'] <= 6)) {
  8259. $annots .= ' /TP '.intval($pl['opt']['mk']['tp']);
  8260. }
  8261. $annots .= '>>';
  8262. } // end MK
  8263. // --- Entries for field dictionaries ---
  8264. if (isset($this->radiobutton_groups[$n][$pl['txt']])) {
  8265. // set parent
  8266. $annots .= ' /Parent '.$this->radiobutton_groups[$n][$pl['txt']].' 0 R';
  8267. }
  8268. if (isset($pl['opt']['t']) AND is_string($pl['opt']['t'])) {
  8269. $annots .= ' /T '.$this->_datastring($pl['opt']['t'], $annot_obj_id);
  8270. }
  8271. if (isset($pl['opt']['tu']) AND is_string($pl['opt']['tu'])) {
  8272. $annots .= ' /TU '.$this->_datastring($pl['opt']['tu'], $annot_obj_id);
  8273. }
  8274. if (isset($pl['opt']['tm']) AND is_string($pl['opt']['tm'])) {
  8275. $annots .= ' /TM '.$this->_datastring($pl['opt']['tm'], $annot_obj_id);
  8276. }
  8277. if (isset($pl['opt']['ff'])) {
  8278. if (is_array($pl['opt']['ff'])) {
  8279. // array of bit settings
  8280. $flag = 0;
  8281. foreach($pl['opt']['ff'] as $val) {
  8282. $flag += 1 << ($val - 1);
  8283. }
  8284. } else {
  8285. $flag = intval($pl['opt']['ff']);
  8286. }
  8287. $annots .= ' /Ff '.$flag;
  8288. }
  8289. if (isset($pl['opt']['maxlen'])) {
  8290. $annots .= ' /MaxLen '.intval($pl['opt']['maxlen']);
  8291. }
  8292. if (isset($pl['opt']['v'])) {
  8293. $annots .= ' /V';
  8294. if (is_array($pl['opt']['v'])) {
  8295. foreach ($pl['opt']['v'] AS $optval) {
  8296. if (is_float($optval)) {
  8297. $optval = sprintf('%F', $optval);
  8298. }
  8299. $annots .= ' '.$optval;
  8300. }
  8301. } else {
  8302. $annots .= ' '.$this->_textstring($pl['opt']['v'], $annot_obj_id);
  8303. }
  8304. }
  8305. if (isset($pl['opt']['dv'])) {
  8306. $annots .= ' /DV';
  8307. if (is_array($pl['opt']['dv'])) {
  8308. foreach ($pl['opt']['dv'] AS $optval) {
  8309. if (is_float($optval)) {
  8310. $optval = sprintf('%F', $optval);
  8311. }
  8312. $annots .= ' '.$optval;
  8313. }
  8314. } else {
  8315. $annots .= ' '.$this->_textstring($pl['opt']['dv'], $annot_obj_id);
  8316. }
  8317. }
  8318. if (isset($pl['opt']['rv'])) {
  8319. $annots .= ' /RV';
  8320. if (is_array($pl['opt']['rv'])) {
  8321. foreach ($pl['opt']['rv'] AS $optval) {
  8322. if (is_float($optval)) {
  8323. $optval = sprintf('%F', $optval);
  8324. }
  8325. $annots .= ' '.$optval;
  8326. }
  8327. } else {
  8328. $annots .= ' '.$this->_textstring($pl['opt']['rv'], $annot_obj_id);
  8329. }
  8330. }
  8331. if (isset($pl['opt']['a']) AND !empty($pl['opt']['a'])) {
  8332. $annots .= ' /A << '.$pl['opt']['a'].' >>';
  8333. }
  8334. if (isset($pl['opt']['aa']) AND !empty($pl['opt']['aa'])) {
  8335. $annots .= ' /AA << '.$pl['opt']['aa'].' >>';
  8336. }
  8337. if (isset($pl['opt']['da']) AND !empty($pl['opt']['da'])) {
  8338. $annots .= ' /DA ('.$pl['opt']['da'].')';
  8339. }
  8340. if (isset($pl['opt']['q']) AND ($pl['opt']['q'] >= 0) AND ($pl['opt']['q'] <= 2)) {
  8341. $annots .= ' /Q '.intval($pl['opt']['q']);
  8342. }
  8343. if (isset($pl['opt']['opt']) AND (is_array($pl['opt']['opt'])) AND !empty($pl['opt']['opt'])) {
  8344. $annots .= ' /Opt [';
  8345. foreach($pl['opt']['opt'] AS $copt) {
  8346. if (is_array($copt)) {
  8347. $annots .= ' ['.$this->_textstring($copt[0], $annot_obj_id).' '.$this->_textstring($copt[1], $annot_obj_id).']';
  8348. } else {
  8349. $annots .= ' '.$this->_textstring($copt, $annot_obj_id);
  8350. }
  8351. }
  8352. $annots .= ']';
  8353. }
  8354. if (isset($pl['opt']['ti'])) {
  8355. $annots .= ' /TI '.intval($pl['opt']['ti']);
  8356. }
  8357. if (isset($pl['opt']['i']) AND (is_array($pl['opt']['i'])) AND !empty($pl['opt']['i'])) {
  8358. $annots .= ' /I [';
  8359. foreach($pl['opt']['i'] AS $copt) {
  8360. $annots .= intval($copt).' ';
  8361. }
  8362. $annots .= ']';
  8363. }
  8364. break;
  8365. }
  8366. case 'screen': {
  8367. break;
  8368. }
  8369. case 'printermark': {
  8370. break;
  8371. }
  8372. case 'trapnet': {
  8373. break;
  8374. }
  8375. case 'watermark': {
  8376. break;
  8377. }
  8378. case '3d': {
  8379. break;
  8380. }
  8381. default: {
  8382. break;
  8383. }
  8384. }
  8385. $annots .= '>>';
  8386. // create new annotation object
  8387. $this->_out($this->_getobj($annot_obj_id)."\n".$annots."\n".'endobj');
  8388. if ($formfield AND !isset($this->radiobutton_groups[$n][$pl['txt']])) {
  8389. // store reference of form object
  8390. $this->form_obj_id[] = $annot_obj_id;
  8391. }
  8392. }
  8393. }
  8394. } // end for each page
  8395. }
  8396. /**
  8397. * Put appearance streams XObject used to define annotation's appearance states.
  8398. * @param $w (int) annotation width
  8399. * @param $h (int) annotation height
  8400. * @param $stream (string) appearance stream
  8401. * @return int object ID
  8402. * @protected
  8403. * @since 4.8.001 (2009-09-09)
  8404. */
  8405. protected function _putAPXObject($w=0, $h=0, $stream='') {
  8406. $stream = trim($stream);
  8407. $out = $this->_getobj()."\n";
  8408. $this->xobjects['AX'.$this->n] = array('n' => $this->n);
  8409. $out .= '<<';
  8410. $out .= ' /Type /XObject';
  8411. $out .= ' /Subtype /Form';
  8412. $out .= ' /FormType 1';
  8413. if ($this->compress) {
  8414. $stream = gzcompress($stream);
  8415. $out .= ' /Filter /FlateDecode';
  8416. }
  8417. $rect = sprintf('%F %F', $w, $h);
  8418. $out .= ' /BBox [0 0 '.$rect.']';
  8419. $out .= ' /Matrix [1 0 0 1 0 0]';
  8420. $out .= ' /Resources 2 0 R';
  8421. $stream = $this->_getrawstream($stream);
  8422. $out .= ' /Length '.strlen($stream);
  8423. $out .= ' >>';
  8424. $out .= ' stream'."\n".$stream."\n".'endstream';
  8425. $out .= "\n".'endobj';
  8426. $this->_out($out);
  8427. return $this->n;
  8428. }
  8429. /**
  8430. * Output fonts.
  8431. * @author Nicola Asuni
  8432. * @protected
  8433. */
  8434. protected function _putfonts() {
  8435. $nf = $this->n;
  8436. foreach ($this->diffs as $diff) {
  8437. //Encodings
  8438. $this->_newobj();
  8439. $this->_out('<< /Type /Encoding /BaseEncoding /WinAnsiEncoding /Differences ['.$diff.'] >>'."\n".'endobj');
  8440. }
  8441. $mqr = TCPDF_STATIC::get_mqr();
  8442. TCPDF_STATIC::set_mqr(false);
  8443. foreach ($this->FontFiles as $file => $info) {
  8444. // search and get font file to embedd
  8445. $fontfile = TCPDF_FONTS::getFontFullPath($file, $info['fontdir']);
  8446. if (!TCPDF_STATIC::empty_string($fontfile)) {
  8447. $font = file_get_contents($fontfile);
  8448. $compressed = (substr($file, -2) == '.z');
  8449. if ((!$compressed) AND (isset($info['length2']))) {
  8450. $header = (ord($font[0]) == 128);
  8451. if ($header) {
  8452. // strip first binary header
  8453. $font = substr($font, 6);
  8454. }
  8455. if ($header AND (ord($font[$info['length1']]) == 128)) {
  8456. // strip second binary header
  8457. $font = substr($font, 0, $info['length1']).substr($font, ($info['length1'] + 6));
  8458. }
  8459. } elseif ($info['subset'] AND ((!$compressed) OR ($compressed AND function_exists('gzcompress')))) {
  8460. if ($compressed) {
  8461. // uncompress font
  8462. $font = gzuncompress($font);
  8463. }
  8464. // merge subset characters
  8465. $subsetchars = array(); // used chars
  8466. foreach ($info['fontkeys'] as $fontkey) {
  8467. $fontinfo = $this->getFontBuffer($fontkey);
  8468. $subsetchars += $fontinfo['subsetchars'];
  8469. }
  8470. // rebuild a font subset
  8471. $font = TCPDF_FONTS::_getTrueTypeFontSubset($font, $subsetchars);
  8472. // calculate new font length
  8473. $info['length1'] = strlen($font);
  8474. if ($compressed) {
  8475. // recompress font
  8476. $font = gzcompress($font);
  8477. }
  8478. }
  8479. $this->_newobj();
  8480. $this->FontFiles[$file]['n'] = $this->n;
  8481. $stream = $this->_getrawstream($font);
  8482. $out = '<< /Length '.strlen($stream);
  8483. if ($compressed) {
  8484. $out .= ' /Filter /FlateDecode';
  8485. }
  8486. $out .= ' /Length1 '.$info['length1'];
  8487. if (isset($info['length2'])) {
  8488. $out .= ' /Length2 '.$info['length2'].' /Length3 0';
  8489. }
  8490. $out .= ' >>';
  8491. $out .= ' stream'."\n".$stream."\n".'endstream';
  8492. $out .= "\n".'endobj';
  8493. $this->_out($out);
  8494. }
  8495. }
  8496. TCPDF_STATIC::set_mqr($mqr);
  8497. foreach ($this->fontkeys as $k) {
  8498. //Font objects
  8499. $font = $this->getFontBuffer($k);
  8500. $type = $font['type'];
  8501. $name = $font['name'];
  8502. if ($type == 'core') {
  8503. // standard core font
  8504. $out = $this->_getobj($this->font_obj_ids[$k])."\n";
  8505. $out .= '<</Type /Font';
  8506. $out .= ' /Subtype /Type1';
  8507. $out .= ' /BaseFont /'.$name;
  8508. $out .= ' /Name /F'.$font['i'];
  8509. if ((strtolower($name) != 'symbol') AND (strtolower($name) != 'zapfdingbats')) {
  8510. $out .= ' /Encoding /WinAnsiEncoding';
  8511. }
  8512. if ($k == 'helvetica') {
  8513. // add default font for annotations
  8514. $this->annotation_fonts[$k] = $font['i'];
  8515. }
  8516. $out .= ' >>';
  8517. $out .= "\n".'endobj';
  8518. $this->_out($out);
  8519. } elseif (($type == 'Type1') OR ($type == 'TrueType')) {
  8520. // additional Type1 or TrueType font
  8521. $out = $this->_getobj($this->font_obj_ids[$k])."\n";
  8522. $out .= '<</Type /Font';
  8523. $out .= ' /Subtype /'.$type;
  8524. $out .= ' /BaseFont /'.$name;
  8525. $out .= ' /Name /F'.$font['i'];
  8526. $out .= ' /FirstChar 32 /LastChar 255';
  8527. $out .= ' /Widths '.($this->n + 1).' 0 R';
  8528. $out .= ' /FontDescriptor '.($this->n + 2).' 0 R';
  8529. if ($font['enc']) {
  8530. if (isset($font['diff'])) {
  8531. $out .= ' /Encoding '.($nf + $font['diff']).' 0 R';
  8532. } else {
  8533. $out .= ' /Encoding /WinAnsiEncoding';
  8534. }
  8535. }
  8536. $out .= ' >>';
  8537. $out .= "\n".'endobj';
  8538. $this->_out($out);
  8539. // Widths
  8540. $this->_newobj();
  8541. $s = '[';
  8542. for ($i = 32; $i < 256; ++$i) {
  8543. if (isset($font['cw'][$i])) {
  8544. $s .= $font['cw'][$i].' ';
  8545. } else {
  8546. $s .= $font['dw'].' ';
  8547. }
  8548. }
  8549. $s .= ']';
  8550. $s .= "\n".'endobj';
  8551. $this->_out($s);
  8552. //Descriptor
  8553. $this->_newobj();
  8554. $s = '<</Type /FontDescriptor /FontName /'.$name;
  8555. foreach ($font['desc'] as $fdk => $fdv) {
  8556. if (is_float($fdv)) {
  8557. $fdv = sprintf('%F', $fdv);
  8558. }
  8559. $s .= ' /'.$fdk.' '.$fdv.'';
  8560. }
  8561. if (!TCPDF_STATIC::empty_string($font['file'])) {
  8562. $s .= ' /FontFile'.($type == 'Type1' ? '' : '2').' '.$this->FontFiles[$font['file']]['n'].' 0 R';
  8563. }
  8564. $s .= '>>';
  8565. $s .= "\n".'endobj';
  8566. $this->_out($s);
  8567. } else {
  8568. // additional types
  8569. $mtd = '_put'.strtolower($type);
  8570. if (!method_exists($this, $mtd)) {
  8571. $this->Error('Unsupported font type: '.$type);
  8572. }
  8573. $this->$mtd($font);
  8574. }
  8575. }
  8576. }
  8577. /**
  8578. * Adds unicode fonts.<br>
  8579. * Based on PDF Reference 1.3 (section 5)
  8580. * @param $font (array) font data
  8581. * @protected
  8582. * @author Nicola Asuni
  8583. * @since 1.52.0.TC005 (2005-01-05)
  8584. */
  8585. protected function _puttruetypeunicode($font) {
  8586. $fontname = '';
  8587. if ($font['subset']) {
  8588. // change name for font subsetting
  8589. $subtag = sprintf('%06u', $font['i']);
  8590. $subtag = strtr($subtag, '0123456789', 'ABCDEFGHIJ');
  8591. $fontname .= $subtag.'+';
  8592. }
  8593. $fontname .= $font['name'];
  8594. // Type0 Font
  8595. // A composite font composed of other fonts, organized hierarchically
  8596. $out = $this->_getobj($this->font_obj_ids[$font['fontkey']])."\n";
  8597. $out .= '<< /Type /Font';
  8598. $out .= ' /Subtype /Type0';
  8599. $out .= ' /BaseFont /'.$fontname;
  8600. $out .= ' /Name /F'.$font['i'];
  8601. $out .= ' /Encoding /'.$font['enc'];
  8602. $out .= ' /ToUnicode '.($this->n + 1).' 0 R';
  8603. $out .= ' /DescendantFonts ['.($this->n + 2).' 0 R]';
  8604. $out .= ' >>';
  8605. $out .= "\n".'endobj';
  8606. $this->_out($out);
  8607. // ToUnicode map for Identity-H
  8608. $stream = TCPDF_FONT_DATA::$uni_identity_h;
  8609. // ToUnicode Object
  8610. $this->_newobj();
  8611. $stream = ($this->compress) ? gzcompress($stream) : $stream;
  8612. $filter = ($this->compress) ? '/Filter /FlateDecode ' : '';
  8613. $stream = $this->_getrawstream($stream);
  8614. $this->_out('<<'.$filter.'/Length '.strlen($stream).'>> stream'."\n".$stream."\n".'endstream'."\n".'endobj');
  8615. // CIDFontType2
  8616. // A CIDFont whose glyph descriptions are based on TrueType font technology
  8617. $oid = $this->_newobj();
  8618. $out = '<< /Type /Font';
  8619. $out .= ' /Subtype /CIDFontType2';
  8620. $out .= ' /BaseFont /'.$fontname;
  8621. // A dictionary containing entries that define the character collection of the CIDFont.
  8622. $cidinfo = '/Registry '.$this->_datastring($font['cidinfo']['Registry'], $oid);
  8623. $cidinfo .= ' /Ordering '.$this->_datastring($font['cidinfo']['Ordering'], $oid);
  8624. $cidinfo .= ' /Supplement '.$font['cidinfo']['Supplement'];
  8625. $out .= ' /CIDSystemInfo << '.$cidinfo.' >>';
  8626. $out .= ' /FontDescriptor '.($this->n + 1).' 0 R';
  8627. $out .= ' /DW '.$font['dw']; // default width
  8628. $out .= "\n".TCPDF_FONTS::_putfontwidths($font, 0);
  8629. if (isset($font['ctg']) AND (!TCPDF_STATIC::empty_string($font['ctg']))) {
  8630. $out .= "\n".'/CIDToGIDMap '.($this->n + 2).' 0 R';
  8631. }
  8632. $out .= ' >>';
  8633. $out .= "\n".'endobj';
  8634. $this->_out($out);
  8635. // Font descriptor
  8636. // A font descriptor describing the CIDFont default metrics other than its glyph widths
  8637. $this->_newobj();
  8638. $out = '<< /Type /FontDescriptor';
  8639. $out .= ' /FontName /'.$fontname;
  8640. foreach ($font['desc'] as $key => $value) {
  8641. if (is_float($value)) {
  8642. $value = sprintf('%F', $value);
  8643. }
  8644. $out .= ' /'.$key.' '.$value;
  8645. }
  8646. $fontdir = false;
  8647. if (!TCPDF_STATIC::empty_string($font['file'])) {
  8648. // A stream containing a TrueType font
  8649. $out .= ' /FontFile2 '.$this->FontFiles[$font['file']]['n'].' 0 R';
  8650. $fontdir = $this->FontFiles[$font['file']]['fontdir'];
  8651. }
  8652. $out .= ' >>';
  8653. $out .= "\n".'endobj';
  8654. $this->_out($out);
  8655. if (isset($font['ctg']) AND (!TCPDF_STATIC::empty_string($font['ctg']))) {
  8656. $this->_newobj();
  8657. // Embed CIDToGIDMap
  8658. // A specification of the mapping from CIDs to glyph indices
  8659. // search and get CTG font file to embedd
  8660. $ctgfile = strtolower($font['ctg']);
  8661. // search and get ctg font file to embedd
  8662. $fontfile = TCPDF_FONTS::getFontFullPath($ctgfile, $fontdir);
  8663. if (TCPDF_STATIC::empty_string($fontfile)) {
  8664. $this->Error('Font file not found: '.$ctgfile);
  8665. }
  8666. $stream = $this->_getrawstream(file_get_contents($fontfile));
  8667. $out = '<< /Length '.strlen($stream).'';
  8668. if (substr($fontfile, -2) == '.z') { // check file extension
  8669. // Decompresses data encoded using the public-domain
  8670. // zlib/deflate compression method, reproducing the
  8671. // original text or binary data
  8672. $out .= ' /Filter /FlateDecode';
  8673. }
  8674. $out .= ' >>';
  8675. $out .= ' stream'."\n".$stream."\n".'endstream';
  8676. $out .= "\n".'endobj';
  8677. $this->_out($out);
  8678. }
  8679. }
  8680. /**
  8681. * Output CID-0 fonts.
  8682. * A Type 0 CIDFont contains glyph descriptions based on the Adobe Type 1 font format
  8683. * @param $font (array) font data
  8684. * @protected
  8685. * @author Andrew Whitehead, Nicola Asuni, Yukihiro Nakadaira
  8686. * @since 3.2.000 (2008-06-23)
  8687. */
  8688. protected function _putcidfont0($font) {
  8689. $cidoffset = 0;
  8690. if (!isset($font['cw'][1])) {
  8691. $cidoffset = 31;
  8692. }
  8693. if (isset($font['cidinfo']['uni2cid'])) {
  8694. // convert unicode to cid.
  8695. $uni2cid = $font['cidinfo']['uni2cid'];
  8696. $cw = array();
  8697. foreach ($font['cw'] as $uni => $width) {
  8698. if (isset($uni2cid[$uni])) {
  8699. $cw[($uni2cid[$uni] + $cidoffset)] = $width;
  8700. } elseif ($uni < 256) {
  8701. $cw[$uni] = $width;
  8702. } // else unknown character
  8703. }
  8704. $font = array_merge($font, array('cw' => $cw));
  8705. }
  8706. $name = $font['name'];
  8707. $enc = $font['enc'];
  8708. if ($enc) {
  8709. $longname = $name.'-'.$enc;
  8710. } else {
  8711. $longname = $name;
  8712. }
  8713. $out = $this->_getobj($this->font_obj_ids[$font['fontkey']])."\n";
  8714. $out .= '<</Type /Font';
  8715. $out .= ' /Subtype /Type0';
  8716. $out .= ' /BaseFont /'.$longname;
  8717. $out .= ' /Name /F'.$font['i'];
  8718. if ($enc) {
  8719. $out .= ' /Encoding /'.$enc;
  8720. }
  8721. $out .= ' /DescendantFonts ['.($this->n + 1).' 0 R]';
  8722. $out .= ' >>';
  8723. $out .= "\n".'endobj';
  8724. $this->_out($out);
  8725. $oid = $this->_newobj();
  8726. $out = '<</Type /Font';
  8727. $out .= ' /Subtype /CIDFontType0';
  8728. $out .= ' /BaseFont /'.$name;
  8729. $cidinfo = '/Registry '.$this->_datastring($font['cidinfo']['Registry'], $oid);
  8730. $cidinfo .= ' /Ordering '.$this->_datastring($font['cidinfo']['Ordering'], $oid);
  8731. $cidinfo .= ' /Supplement '.$font['cidinfo']['Supplement'];
  8732. $out .= ' /CIDSystemInfo <<'.$cidinfo.'>>';
  8733. $out .= ' /FontDescriptor '.($this->n + 1).' 0 R';
  8734. $out .= ' /DW '.$font['dw'];
  8735. $out .= "\n".TCPDF_FONTS::_putfontwidths($font, $cidoffset);
  8736. $out .= ' >>';
  8737. $out .= "\n".'endobj';
  8738. $this->_out($out);
  8739. $this->_newobj();
  8740. $s = '<</Type /FontDescriptor /FontName /'.$name;
  8741. foreach ($font['desc'] as $k => $v) {
  8742. if ($k != 'Style') {
  8743. if (is_float($v)) {
  8744. $v = sprintf('%F', $v);
  8745. }
  8746. $s .= ' /'.$k.' '.$v.'';
  8747. }
  8748. }
  8749. $s .= '>>';
  8750. $s .= "\n".'endobj';
  8751. $this->_out($s);
  8752. }
  8753. /**
  8754. * Output images.
  8755. * @protected
  8756. */
  8757. protected function _putimages() {
  8758. $filter = ($this->compress) ? '/Filter /FlateDecode ' : '';
  8759. foreach ($this->imagekeys as $file) {
  8760. $info = $this->getImageBuffer($file);
  8761. // set object for alternate images array
  8762. if ((!$this->pdfa_mode) AND isset($info['altimgs']) AND !empty($info['altimgs'])) {
  8763. $altoid = $this->_newobj();
  8764. $out = '[';
  8765. foreach ($info['altimgs'] as $altimage) {
  8766. if (isset($this->xobjects['I'.$altimage[0]]['n'])) {
  8767. $out .= ' << /Image '.$this->xobjects['I'.$altimage[0]]['n'].' 0 R';
  8768. $out .= ' /DefaultForPrinting';
  8769. if ($altimage[1] === true) {
  8770. $out .= ' true';
  8771. } else {
  8772. $out .= ' false';
  8773. }
  8774. $out .= ' >>';
  8775. }
  8776. }
  8777. $out .= ' ]';
  8778. $out .= "\n".'endobj';
  8779. $this->_out($out);
  8780. }
  8781. // set image object
  8782. $oid = $this->_newobj();
  8783. $this->xobjects['I'.$info['i']] = array('n' => $oid);
  8784. $this->setImageSubBuffer($file, 'n', $this->n);
  8785. $out = '<</Type /XObject';
  8786. $out .= ' /Subtype /Image';
  8787. $out .= ' /Width '.$info['w'];
  8788. $out .= ' /Height '.$info['h'];
  8789. if (array_key_exists('masked', $info)) {
  8790. $out .= ' /SMask '.($this->n - 1).' 0 R';
  8791. }
  8792. // set color space
  8793. $icc = false;
  8794. if (isset($info['icc']) AND ($info['icc'] !== false)) {
  8795. // ICC Colour Space
  8796. $icc = true;
  8797. $out .= ' /ColorSpace [/ICCBased '.($this->n + 1).' 0 R]';
  8798. } elseif ($info['cs'] == 'Indexed') {
  8799. // Indexed Colour Space
  8800. $out .= ' /ColorSpace [/Indexed /DeviceRGB '.((strlen($info['pal']) / 3) - 1).' '.($this->n + 1).' 0 R]';
  8801. } else {
  8802. // Device Colour Space
  8803. $out .= ' /ColorSpace /'.$info['cs'];
  8804. }
  8805. if ($info['cs'] == 'DeviceCMYK') {
  8806. $out .= ' /Decode [1 0 1 0 1 0 1 0]';
  8807. }
  8808. $out .= ' /BitsPerComponent '.$info['bpc'];
  8809. if (isset($altoid) AND ($altoid > 0)) {
  8810. // reference to alternate images dictionary
  8811. $out .= ' /Alternates '.$altoid.' 0 R';
  8812. }
  8813. if (isset($info['exurl']) AND !empty($info['exurl'])) {
  8814. // external stream
  8815. $out .= ' /Length 0';
  8816. $out .= ' /F << /FS /URL /F '.$this->_datastring($info['exurl'], $oid).' >>';
  8817. if (isset($info['f'])) {
  8818. $out .= ' /FFilter /'.$info['f'];
  8819. }
  8820. $out .= ' >>';
  8821. $out .= ' stream'."\n".'endstream';
  8822. } else {
  8823. if (isset($info['f'])) {
  8824. $out .= ' /Filter /'.$info['f'];
  8825. }
  8826. if (isset($info['parms'])) {
  8827. $out .= ' '.$info['parms'];
  8828. }
  8829. if (isset($info['trns']) AND is_array($info['trns'])) {
  8830. $trns = '';
  8831. $count_info = count($info['trns']);
  8832. if ($info['cs'] == 'Indexed') {
  8833. $maxval =(pow(2, $info['bpc']) - 1);
  8834. for ($i = 0; $i < $count_info; ++$i) {
  8835. if (($info['trns'][$i] != 0) AND ($info['trns'][$i] != $maxval)) {
  8836. // this is not a binary type mask @TODO: create a SMask
  8837. $trns = '';
  8838. break;
  8839. } elseif (empty($trns) AND ($info['trns'][$i] == 0)) {
  8840. // store the first fully transparent value
  8841. $trns .= $i.' '.$i.' ';
  8842. }
  8843. }
  8844. } else {
  8845. // grayscale or RGB
  8846. for ($i = 0; $i < $count_info; ++$i) {
  8847. if ($info['trns'][$i] == 0) {
  8848. $trns .= $info['trns'][$i].' '.$info['trns'][$i].' ';
  8849. }
  8850. }
  8851. }
  8852. // Colour Key Masking
  8853. if (!empty($trns)) {
  8854. $out .= ' /Mask ['.$trns.']';
  8855. }
  8856. }
  8857. $stream = $this->_getrawstream($info['data']);
  8858. $out .= ' /Length '.strlen($stream).' >>';
  8859. $out .= ' stream'."\n".$stream."\n".'endstream';
  8860. }
  8861. $out .= "\n".'endobj';
  8862. $this->_out($out);
  8863. if ($icc) {
  8864. // ICC colour profile
  8865. $this->_newobj();
  8866. $icc = ($this->compress) ? gzcompress($info['icc']) : $info['icc'];
  8867. $icc = $this->_getrawstream($icc);
  8868. $this->_out('<</N '.$info['ch'].' /Alternate /'.$info['cs'].' '.$filter.'/Length '.strlen($icc).'>> stream'."\n".$icc."\n".'endstream'."\n".'endobj');
  8869. } elseif ($info['cs'] == 'Indexed') {
  8870. // colour palette
  8871. $this->_newobj();
  8872. $pal = ($this->compress) ? gzcompress($info['pal']) : $info['pal'];
  8873. $pal = $this->_getrawstream($pal);
  8874. $this->_out('<<'.$filter.'/Length '.strlen($pal).'>> stream'."\n".$pal."\n".'endstream'."\n".'endobj');
  8875. }
  8876. }
  8877. }
  8878. /**
  8879. * Output Form XObjects Templates.
  8880. * @author Nicola Asuni
  8881. * @since 5.8.017 (2010-08-24)
  8882. * @protected
  8883. * @see startTemplate(), endTemplate(), printTemplate()
  8884. */
  8885. protected function _putxobjects() {
  8886. foreach ($this->xobjects as $key => $data) {
  8887. if (isset($data['outdata'])) {
  8888. $stream = str_replace($this->epsmarker, '', trim($data['outdata']));
  8889. $out = $this->_getobj($data['n'])."\n";
  8890. $out .= '<<';
  8891. $out .= ' /Type /XObject';
  8892. $out .= ' /Subtype /Form';
  8893. $out .= ' /FormType 1';
  8894. if ($this->compress) {
  8895. $stream = gzcompress($stream);
  8896. $out .= ' /Filter /FlateDecode';
  8897. }
  8898. $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));
  8899. $out .= ' /Matrix [1 0 0 1 0 0]';
  8900. $out .= ' /Resources <<';
  8901. $out .= ' /ProcSet [/PDF /Text /ImageB /ImageC /ImageI]';
  8902. if (!$this->pdfa_mode) {
  8903. // transparency
  8904. if (isset($data['extgstates']) AND !empty($data['extgstates'])) {
  8905. $out .= ' /ExtGState <<';
  8906. foreach ($data['extgstates'] as $k => $extgstate) {
  8907. if (isset($this->extgstates[$k]['name'])) {
  8908. $out .= ' /'.$this->extgstates[$k]['name'];
  8909. } else {
  8910. $out .= ' /GS'.$k;
  8911. }
  8912. $out .= ' '.$this->extgstates[$k]['n'].' 0 R';
  8913. }
  8914. $out .= ' >>';
  8915. }
  8916. if (isset($data['gradients']) AND !empty($data['gradients'])) {
  8917. $gp = '';
  8918. $gs = '';
  8919. foreach ($data['gradients'] as $id => $grad) {
  8920. // gradient patterns
  8921. $gp .= ' /p'.$id.' '.$this->gradients[$id]['pattern'].' 0 R';
  8922. // gradient shadings
  8923. $gs .= ' /Sh'.$id.' '.$this->gradients[$id]['id'].' 0 R';
  8924. }
  8925. $out .= ' /Pattern <<'.$gp.' >>';
  8926. $out .= ' /Shading <<'.$gs.' >>';
  8927. }
  8928. }
  8929. // spot colors
  8930. if (isset($data['spot_colors']) AND !empty($data['spot_colors'])) {
  8931. $out .= ' /ColorSpace <<';
  8932. foreach ($data['spot_colors'] as $name => $color) {
  8933. $out .= ' /CS'.$color['i'].' '.$this->spot_colors[$name]['n'].' 0 R';
  8934. }
  8935. $out .= ' >>';
  8936. }
  8937. // fonts
  8938. if (!empty($data['fonts'])) {
  8939. $out .= ' /Font <<';
  8940. foreach ($data['fonts'] as $fontkey => $fontid) {
  8941. $out .= ' /F'.$fontid.' '.$this->font_obj_ids[$fontkey].' 0 R';
  8942. }
  8943. $out .= ' >>';
  8944. }
  8945. // images or nested xobjects
  8946. if (!empty($data['images']) OR !empty($data['xobjects'])) {
  8947. $out .= ' /XObject <<';
  8948. foreach ($data['images'] as $imgid) {
  8949. $out .= ' /I'.$imgid.' '.$this->xobjects['I'.$imgid]['n'].' 0 R';
  8950. }
  8951. foreach ($data['xobjects'] as $sub_id => $sub_objid) {
  8952. $out .= ' /'.$sub_id.' '.$sub_objid['n'].' 0 R';
  8953. }
  8954. $out .= ' >>';
  8955. }
  8956. $out .= ' >>'; //end resources
  8957. if (isset($data['group']) AND ($data['group'] !== false)) {
  8958. // set transparency group
  8959. $out .= ' /Group << /Type /Group /S /Transparency';
  8960. if (is_array($data['group'])) {
  8961. if (isset($data['group']['CS']) AND !empty($data['group']['CS'])) {
  8962. $out .= ' /CS /'.$data['group']['CS'];
  8963. }
  8964. if (isset($data['group']['I'])) {
  8965. $out .= ' /I /'.($data['group']['I']===true?'true':'false');
  8966. }
  8967. if (isset($data['group']['K'])) {
  8968. $out .= ' /K /'.($data['group']['K']===true?'true':'false');
  8969. }
  8970. }
  8971. $out .= ' >>';
  8972. }
  8973. $stream = $this->_getrawstream($stream, $data['n']);
  8974. $out .= ' /Length '.strlen($stream);
  8975. $out .= ' >>';
  8976. $out .= ' stream'."\n".$stream."\n".'endstream';
  8977. $out .= "\n".'endobj';
  8978. $this->_out($out);
  8979. }
  8980. }
  8981. }
  8982. /**
  8983. * Output Spot Colors Resources.
  8984. * @protected
  8985. * @since 4.0.024 (2008-09-12)
  8986. */
  8987. protected function _putspotcolors() {
  8988. foreach ($this->spot_colors as $name => $color) {
  8989. $this->_newobj();
  8990. $this->spot_colors[$name]['n'] = $this->n;
  8991. $out = '[/Separation /'.str_replace(' ', '#20', $name);
  8992. $out .= ' /DeviceCMYK <<';
  8993. $out .= ' /Range [0 1 0 1 0 1 0 1] /C0 [0 0 0 0]';
  8994. $out .= ' '.sprintf('/C1 [%F %F %F %F] ', ($color['C'] / 100), ($color['M'] / 100), ($color['Y'] / 100), ($color['K'] / 100));
  8995. $out .= ' /FunctionType 2 /Domain [0 1] /N 1>>]';
  8996. $out .= "\n".'endobj';
  8997. $this->_out($out);
  8998. }
  8999. }
  9000. /**
  9001. * Return XObjects Dictionary.
  9002. * @return string XObjects dictionary
  9003. * @protected
  9004. * @since 5.8.014 (2010-08-23)
  9005. */
  9006. protected function _getxobjectdict() {
  9007. $out = '';
  9008. foreach ($this->xobjects as $id => $objid) {
  9009. $out .= ' /'.$id.' '.$objid['n'].' 0 R';
  9010. }
  9011. return $out;
  9012. }
  9013. /**
  9014. * Output Resources Dictionary.
  9015. * @protected
  9016. */
  9017. protected function _putresourcedict() {
  9018. $out = $this->_getobj(2)."\n";
  9019. $out .= '<< /ProcSet [/PDF /Text /ImageB /ImageC /ImageI]';
  9020. $out .= ' /Font <<';
  9021. foreach ($this->fontkeys as $fontkey) {
  9022. $font = $this->getFontBuffer($fontkey);
  9023. $out .= ' /F'.$font['i'].' '.$font['n'].' 0 R';
  9024. }
  9025. $out .= ' >>';
  9026. $out .= ' /XObject <<';
  9027. $out .= $this->_getxobjectdict();
  9028. $out .= ' >>';
  9029. // layers
  9030. if (!empty($this->pdflayers)) {
  9031. $out .= ' /Properties <<';
  9032. foreach ($this->pdflayers as $layer) {
  9033. $out .= ' /'.$layer['layer'].' '.$layer['objid'].' 0 R';
  9034. }
  9035. $out .= ' >>';
  9036. }
  9037. if (!$this->pdfa_mode) {
  9038. // transparency
  9039. if (isset($this->extgstates) AND !empty($this->extgstates)) {
  9040. $out .= ' /ExtGState <<';
  9041. foreach ($this->extgstates as $k => $extgstate) {
  9042. if (isset($extgstate['name'])) {
  9043. $out .= ' /'.$extgstate['name'];
  9044. } else {
  9045. $out .= ' /GS'.$k;
  9046. }
  9047. $out .= ' '.$extgstate['n'].' 0 R';
  9048. }
  9049. $out .= ' >>';
  9050. }
  9051. if (isset($this->gradients) AND !empty($this->gradients)) {
  9052. $gp = '';
  9053. $gs = '';
  9054. foreach ($this->gradients as $id => $grad) {
  9055. // gradient patterns
  9056. $gp .= ' /p'.$id.' '.$grad['pattern'].' 0 R';
  9057. // gradient shadings
  9058. $gs .= ' /Sh'.$id.' '.$grad['id'].' 0 R';
  9059. }
  9060. $out .= ' /Pattern <<'.$gp.' >>';
  9061. $out .= ' /Shading <<'.$gs.' >>';
  9062. }
  9063. }
  9064. // spot colors
  9065. if (isset($this->spot_colors) AND !empty($this->spot_colors)) {
  9066. $out .= ' /ColorSpace <<';
  9067. foreach ($this->spot_colors as $color) {
  9068. $out .= ' /CS'.$color['i'].' '.$color['n'].' 0 R';
  9069. }
  9070. $out .= ' >>';
  9071. }
  9072. $out .= ' >>';
  9073. $out .= "\n".'endobj';
  9074. $this->_out($out);
  9075. }
  9076. /**
  9077. * Output Resources.
  9078. * @protected
  9079. */
  9080. protected function _putresources() {
  9081. $this->_putextgstates();
  9082. $this->_putocg();
  9083. $this->_putfonts();
  9084. $this->_putimages();
  9085. $this->_putspotcolors();
  9086. $this->_putshaders();
  9087. $this->_putxobjects();
  9088. $this->_putresourcedict();
  9089. $this->_putdests();
  9090. $this->_putEmbeddedFiles();
  9091. $this->_putannotsobjs();
  9092. $this->_putjavascript();
  9093. $this->_putbookmarks();
  9094. $this->_putencryption();
  9095. }
  9096. /**
  9097. * Adds some Metadata information (Document Information Dictionary)
  9098. * (see Chapter 14.3.3 Document Information Dictionary of PDF32000_2008.pdf Reference)
  9099. * @return int object id
  9100. * @protected
  9101. */
  9102. protected function _putinfo() {
  9103. $oid = $this->_newobj();
  9104. $out = '<<';
  9105. // store current isunicode value
  9106. $prev_isunicode = $this->isunicode;
  9107. if ($this->docinfounicode) {
  9108. $this->isunicode = true;
  9109. }
  9110. if (!TCPDF_STATIC::empty_string($this->title)) {
  9111. // The document's title.
  9112. $out .= ' /Title '.$this->_textstring($this->title, $oid);
  9113. }
  9114. if (!TCPDF_STATIC::empty_string($this->author)) {
  9115. // The name of the person who created the document.
  9116. $out .= ' /Author '.$this->_textstring($this->author, $oid);
  9117. }
  9118. if (!TCPDF_STATIC::empty_string($this->subject)) {
  9119. // The subject of the document.
  9120. $out .= ' /Subject '.$this->_textstring($this->subject, $oid);
  9121. }
  9122. if (!TCPDF_STATIC::empty_string($this->keywords)) {
  9123. // Keywords associated with the document.
  9124. $out .= ' /Keywords '.$this->_textstring($this->keywords, $oid);
  9125. }
  9126. if (!TCPDF_STATIC::empty_string($this->creator)) {
  9127. // 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.
  9128. $out .= ' /Creator '.$this->_textstring($this->creator, $oid);
  9129. }
  9130. // restore previous isunicode value
  9131. $this->isunicode = $prev_isunicode;
  9132. // default producer
  9133. $out .= ' /Producer '.$this->_textstring(TCPDF_STATIC::getTCPDFProducer(), $oid);
  9134. // The date and time the document was created, in human-readable form
  9135. $out .= ' /CreationDate '.$this->_datestring(0, $this->doc_creation_timestamp);
  9136. // The date and time the document was most recently modified, in human-readable form
  9137. $out .= ' /ModDate '.$this->_datestring(0, $this->doc_modification_timestamp);
  9138. // A name object indicating whether the document has been modified to include trapping information
  9139. $out .= ' /Trapped /False';
  9140. $out .= ' >>';
  9141. $out .= "\n".'endobj';
  9142. $this->_out($out);
  9143. return $oid;
  9144. }
  9145. /**
  9146. * Set additional XMP data to be added on the default XMP data just before the end of "x:xmpmeta" tag.
  9147. * IMPORTANT: This data is added as-is without controls, so you have to validate your data before using this method!
  9148. * @param $xmp (string) Custom XMP data.
  9149. * @since 5.9.128 (2011-10-06)
  9150. * @public
  9151. */
  9152. public function setExtraXMP($xmp) {
  9153. $this->custom_xmp = $xmp;
  9154. }
  9155. /**
  9156. * Set additional XMP data to be added on the default XMP data just before the end of "rdf:RDF" tag.
  9157. * IMPORTANT: This data is added as-is without controls, so you have to validate your data before using this method!
  9158. * @param $xmp (string) Custom XMP RDF data.
  9159. * @since 6.3.0 (2019-09-19)
  9160. * @public
  9161. */
  9162. public function setExtraXMPRDF($xmp) {
  9163. $this->custom_xmp_rdf = $xmp;
  9164. }
  9165. /**
  9166. * Put XMP data object and return ID.
  9167. * @return (int) The object ID.
  9168. * @since 5.9.121 (2011-09-28)
  9169. * @protected
  9170. */
  9171. protected function _putXMP() {
  9172. $oid = $this->_newobj();
  9173. // store current isunicode value
  9174. $prev_isunicode = $this->isunicode;
  9175. $this->isunicode = true;
  9176. $prev_encrypted = $this->encrypted;
  9177. $this->encrypted = false;
  9178. // set XMP data
  9179. $xmp = '<?xpacket begin="'.TCPDF_FONTS::unichr(0xfeff, $this->isunicode).'" id="W5M0MpCehiHzreSzNTczkc9d"?>'."\n";
  9180. $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";
  9181. $xmp .= "\t".'<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">'."\n";
  9182. $xmp .= "\t\t".'<rdf:Description rdf:about="" xmlns:dc="http://purl.org/dc/elements/1.1/">'."\n";
  9183. $xmp .= "\t\t\t".'<dc:format>application/pdf</dc:format>'."\n";
  9184. $xmp .= "\t\t\t".'<dc:title>'."\n";
  9185. $xmp .= "\t\t\t\t".'<rdf:Alt>'."\n";
  9186. $xmp .= "\t\t\t\t\t".'<rdf:li xml:lang="x-default">'.TCPDF_STATIC::_escapeXML($this->title).'</rdf:li>'."\n";
  9187. $xmp .= "\t\t\t\t".'</rdf:Alt>'."\n";
  9188. $xmp .= "\t\t\t".'</dc:title>'."\n";
  9189. $xmp .= "\t\t\t".'<dc:creator>'."\n";
  9190. $xmp .= "\t\t\t\t".'<rdf:Seq>'."\n";
  9191. $xmp .= "\t\t\t\t\t".'<rdf:li>'.TCPDF_STATIC::_escapeXML($this->author).'</rdf:li>'."\n";
  9192. $xmp .= "\t\t\t\t".'</rdf:Seq>'."\n";
  9193. $xmp .= "\t\t\t".'</dc:creator>'."\n";
  9194. $xmp .= "\t\t\t".'<dc:description>'."\n";
  9195. $xmp .= "\t\t\t\t".'<rdf:Alt>'."\n";
  9196. $xmp .= "\t\t\t\t\t".'<rdf:li xml:lang="x-default">'.TCPDF_STATIC::_escapeXML($this->subject).'</rdf:li>'."\n";
  9197. $xmp .= "\t\t\t\t".'</rdf:Alt>'."\n";
  9198. $xmp .= "\t\t\t".'</dc:description>'."\n";
  9199. $xmp .= "\t\t\t".'<dc:subject>'."\n";
  9200. $xmp .= "\t\t\t\t".'<rdf:Bag>'."\n";
  9201. $xmp .= "\t\t\t\t\t".'<rdf:li>'.TCPDF_STATIC::_escapeXML($this->keywords).'</rdf:li>'."\n";
  9202. $xmp .= "\t\t\t\t".'</rdf:Bag>'."\n";
  9203. $xmp .= "\t\t\t".'</dc:subject>'."\n";
  9204. $xmp .= "\t\t".'</rdf:Description>'."\n";
  9205. // convert doc creation date format
  9206. $dcdate = TCPDF_STATIC::getFormattedDate($this->doc_creation_timestamp);
  9207. $doccreationdate = substr($dcdate, 0, 4).'-'.substr($dcdate, 4, 2).'-'.substr($dcdate, 6, 2);
  9208. $doccreationdate .= 'T'.substr($dcdate, 8, 2).':'.substr($dcdate, 10, 2).':'.substr($dcdate, 12, 2);
  9209. $doccreationdate .= substr($dcdate, 14, 3).':'.substr($dcdate, 18, 2);
  9210. $doccreationdate = TCPDF_STATIC::_escapeXML($doccreationdate);
  9211. // convert doc modification date format
  9212. $dmdate = TCPDF_STATIC::getFormattedDate($this->doc_modification_timestamp);
  9213. $docmoddate = substr($dmdate, 0, 4).'-'.substr($dmdate, 4, 2).'-'.substr($dmdate, 6, 2);
  9214. $docmoddate .= 'T'.substr($dmdate, 8, 2).':'.substr($dmdate, 10, 2).':'.substr($dmdate, 12, 2);
  9215. $docmoddate .= substr($dmdate, 14, 3).':'.substr($dmdate, 18, 2);
  9216. $docmoddate = TCPDF_STATIC::_escapeXML($docmoddate);
  9217. $xmp .= "\t\t".'<rdf:Description rdf:about="" xmlns:xmp="http://ns.adobe.com/xap/1.0/">'."\n";
  9218. $xmp .= "\t\t\t".'<xmp:CreateDate>'.$doccreationdate.'</xmp:CreateDate>'."\n";
  9219. $xmp .= "\t\t\t".'<xmp:CreatorTool>'.$this->creator.'</xmp:CreatorTool>'."\n";
  9220. $xmp .= "\t\t\t".'<xmp:ModifyDate>'.$docmoddate.'</xmp:ModifyDate>'."\n";
  9221. $xmp .= "\t\t\t".'<xmp:MetadataDate>'.$doccreationdate.'</xmp:MetadataDate>'."\n";
  9222. $xmp .= "\t\t".'</rdf:Description>'."\n";
  9223. $xmp .= "\t\t".'<rdf:Description rdf:about="" xmlns:pdf="http://ns.adobe.com/pdf/1.3/">'."\n";
  9224. $xmp .= "\t\t\t".'<pdf:Keywords>'.TCPDF_STATIC::_escapeXML($this->keywords).'</pdf:Keywords>'."\n";
  9225. $xmp .= "\t\t\t".'<pdf:Producer>'.TCPDF_STATIC::_escapeXML(TCPDF_STATIC::getTCPDFProducer()).'</pdf:Producer>'."\n";
  9226. $xmp .= "\t\t".'</rdf:Description>'."\n";
  9227. $xmp .= "\t\t".'<rdf:Description rdf:about="" xmlns:xmpMM="http://ns.adobe.com/xap/1.0/mm/">'."\n";
  9228. $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);
  9229. $xmp .= "\t\t\t".'<xmpMM:DocumentID>'.$uuid.'</xmpMM:DocumentID>'."\n";
  9230. $xmp .= "\t\t\t".'<xmpMM:InstanceID>'.$uuid.'</xmpMM:InstanceID>'."\n";
  9231. $xmp .= "\t\t".'</rdf:Description>'."\n";
  9232. if ($this->pdfa_mode) {
  9233. $xmp .= "\t\t".'<rdf:Description rdf:about="" xmlns:pdfaid="http://www.aiim.org/pdfa/ns/id/">'."\n";
  9234. $xmp .= "\t\t\t".'<pdfaid:part>'.$this->pdfa_version.'</pdfaid:part>'."\n";
  9235. $xmp .= "\t\t\t".'<pdfaid:conformance>B</pdfaid:conformance>'."\n";
  9236. $xmp .= "\t\t".'</rdf:Description>'."\n";
  9237. }
  9238. // XMP extension schemas
  9239. $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";
  9240. $xmp .= "\t\t\t".'<pdfaExtension:schemas>'."\n";
  9241. $xmp .= "\t\t\t\t".'<rdf:Bag>'."\n";
  9242. $xmp .= "\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
  9243. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:namespaceURI>http://ns.adobe.com/pdf/1.3/</pdfaSchema:namespaceURI>'."\n";
  9244. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:prefix>pdf</pdfaSchema:prefix>'."\n";
  9245. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:schema>Adobe PDF Schema</pdfaSchema:schema>'."\n";
  9246. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:property>'."\n";
  9247. $xmp .= "\t\t\t\t\t\t\t".'<rdf:Seq>'."\n";
  9248. $xmp .= "\t\t\t\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
  9249. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:category>internal</pdfaProperty:category>'."\n";
  9250. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:description>Adobe PDF Schema</pdfaProperty:description>'."\n";
  9251. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:name>InstanceID</pdfaProperty:name>'."\n";
  9252. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:valueType>URI</pdfaProperty:valueType>'."\n";
  9253. $xmp .= "\t\t\t\t\t\t\t\t".'</rdf:li>'."\n";
  9254. $xmp .= "\t\t\t\t\t\t\t".'</rdf:Seq>'."\n";
  9255. $xmp .= "\t\t\t\t\t\t".'</pdfaSchema:property>'."\n";
  9256. $xmp .= "\t\t\t\t\t".'</rdf:li>'."\n";
  9257. $xmp .= "\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
  9258. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:namespaceURI>http://ns.adobe.com/xap/1.0/mm/</pdfaSchema:namespaceURI>'."\n";
  9259. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:prefix>xmpMM</pdfaSchema:prefix>'."\n";
  9260. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:schema>XMP Media Management Schema</pdfaSchema:schema>'."\n";
  9261. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:property>'."\n";
  9262. $xmp .= "\t\t\t\t\t\t\t".'<rdf:Seq>'."\n";
  9263. $xmp .= "\t\t\t\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
  9264. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:category>internal</pdfaProperty:category>'."\n";
  9265. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:description>UUID based identifier for specific incarnation of a document</pdfaProperty:description>'."\n";
  9266. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:name>InstanceID</pdfaProperty:name>'."\n";
  9267. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:valueType>URI</pdfaProperty:valueType>'."\n";
  9268. $xmp .= "\t\t\t\t\t\t\t\t".'</rdf:li>'."\n";
  9269. $xmp .= "\t\t\t\t\t\t\t".'</rdf:Seq>'."\n";
  9270. $xmp .= "\t\t\t\t\t\t".'</pdfaSchema:property>'."\n";
  9271. $xmp .= "\t\t\t\t\t".'</rdf:li>'."\n";
  9272. $xmp .= "\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
  9273. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:namespaceURI>http://www.aiim.org/pdfa/ns/id/</pdfaSchema:namespaceURI>'."\n";
  9274. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:prefix>pdfaid</pdfaSchema:prefix>'."\n";
  9275. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:schema>PDF/A ID Schema</pdfaSchema:schema>'."\n";
  9276. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:property>'."\n";
  9277. $xmp .= "\t\t\t\t\t\t\t".'<rdf:Seq>'."\n";
  9278. $xmp .= "\t\t\t\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
  9279. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:category>internal</pdfaProperty:category>'."\n";
  9280. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:description>Part of PDF/A standard</pdfaProperty:description>'."\n";
  9281. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:name>part</pdfaProperty:name>'."\n";
  9282. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:valueType>Integer</pdfaProperty:valueType>'."\n";
  9283. $xmp .= "\t\t\t\t\t\t\t\t".'</rdf:li>'."\n";
  9284. $xmp .= "\t\t\t\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
  9285. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:category>internal</pdfaProperty:category>'."\n";
  9286. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:description>Amendment of PDF/A standard</pdfaProperty:description>'."\n";
  9287. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:name>amd</pdfaProperty:name>'."\n";
  9288. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:valueType>Text</pdfaProperty:valueType>'."\n";
  9289. $xmp .= "\t\t\t\t\t\t\t\t".'</rdf:li>'."\n";
  9290. $xmp .= "\t\t\t\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
  9291. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:category>internal</pdfaProperty:category>'."\n";
  9292. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:description>Conformance level of PDF/A standard</pdfaProperty:description>'."\n";
  9293. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:name>conformance</pdfaProperty:name>'."\n";
  9294. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:valueType>Text</pdfaProperty:valueType>'."\n";
  9295. $xmp .= "\t\t\t\t\t\t\t\t".'</rdf:li>'."\n";
  9296. $xmp .= "\t\t\t\t\t\t\t".'</rdf:Seq>'."\n";
  9297. $xmp .= "\t\t\t\t\t\t".'</pdfaSchema:property>'."\n";
  9298. $xmp .= "\t\t\t\t\t".'</rdf:li>'."\n";
  9299. $xmp .= "\t\t\t\t".'</rdf:Bag>'."\n";
  9300. $xmp .= "\t\t\t".'</pdfaExtension:schemas>'."\n";
  9301. $xmp .= "\t\t".'</rdf:Description>'."\n";
  9302. $xmp .= $this->custom_xmp_rdf;
  9303. $xmp .= "\t".'</rdf:RDF>'."\n";
  9304. $xmp .= $this->custom_xmp;
  9305. $xmp .= '</x:xmpmeta>'."\n";
  9306. $xmp .= '<?xpacket end="w"?>';
  9307. $out = '<< /Type /Metadata /Subtype /XML /Length '.strlen($xmp).' >> stream'."\n".$xmp."\n".'endstream'."\n".'endobj';
  9308. // restore previous isunicode value
  9309. $this->isunicode = $prev_isunicode;
  9310. $this->encrypted = $prev_encrypted;
  9311. $this->_out($out);
  9312. return $oid;
  9313. }
  9314. /**
  9315. * Output Catalog.
  9316. * @return int object id
  9317. * @protected
  9318. */
  9319. protected function _putcatalog() {
  9320. // put XMP
  9321. $xmpobj = $this->_putXMP();
  9322. // if required, add standard sRGB ICC colour profile
  9323. if ($this->pdfa_mode OR $this->force_srgb) {
  9324. $iccobj = $this->_newobj();
  9325. $icc = file_get_contents(dirname(__FILE__).'/include/sRGB.icc');
  9326. $filter = '';
  9327. if ($this->compress) {
  9328. $filter = ' /Filter /FlateDecode';
  9329. $icc = gzcompress($icc);
  9330. }
  9331. $icc = $this->_getrawstream($icc);
  9332. $this->_out('<</N 3 '.$filter.'/Length '.strlen($icc).'>> stream'."\n".$icc."\n".'endstream'."\n".'endobj');
  9333. }
  9334. // start catalog
  9335. $oid = $this->_newobj();
  9336. $out = '<< /Type /Catalog';
  9337. $out .= ' /Version /'.$this->PDFVersion;
  9338. //$out .= ' /Extensions <<>>';
  9339. $out .= ' /Pages 1 0 R';
  9340. //$out .= ' /PageLabels ' //...;
  9341. $out .= ' /Names <<';
  9342. if ((!$this->pdfa_mode) AND !empty($this->n_js)) {
  9343. $out .= ' /JavaScript '.$this->n_js;
  9344. }
  9345. if (!empty($this->efnames)) {
  9346. $out .= ' /EmbeddedFiles <</Names [';
  9347. foreach ($this->efnames AS $fn => $fref) {
  9348. $out .= ' '.$this->_datastring($fn).' '.$fref;
  9349. }
  9350. $out .= ' ]>>';
  9351. }
  9352. $out .= ' >>';
  9353. if (!empty($this->dests)) {
  9354. $out .= ' /Dests '.($this->n_dests).' 0 R';
  9355. }
  9356. $out .= $this->_putviewerpreferences();
  9357. if (isset($this->LayoutMode) AND (!TCPDF_STATIC::empty_string($this->LayoutMode))) {
  9358. $out .= ' /PageLayout /'.$this->LayoutMode;
  9359. }
  9360. if (isset($this->PageMode) AND (!TCPDF_STATIC::empty_string($this->PageMode))) {
  9361. $out .= ' /PageMode /'.$this->PageMode;
  9362. }
  9363. if (count($this->outlines) > 0) {
  9364. $out .= ' /Outlines '.$this->OutlineRoot.' 0 R';
  9365. $out .= ' /PageMode /UseOutlines';
  9366. }
  9367. //$out .= ' /Threads []';
  9368. if ($this->ZoomMode == 'fullpage') {
  9369. $out .= ' /OpenAction ['.$this->page_obj_id[1].' 0 R /Fit]';
  9370. } elseif ($this->ZoomMode == 'fullwidth') {
  9371. $out .= ' /OpenAction ['.$this->page_obj_id[1].' 0 R /FitH null]';
  9372. } elseif ($this->ZoomMode == 'real') {
  9373. $out .= ' /OpenAction ['.$this->page_obj_id[1].' 0 R /XYZ null null 1]';
  9374. } elseif (!is_string($this->ZoomMode)) {
  9375. $out .= sprintf(' /OpenAction ['.$this->page_obj_id[1].' 0 R /XYZ null null %F]', ($this->ZoomMode / 100));
  9376. }
  9377. //$out .= ' /AA <<>>';
  9378. //$out .= ' /URI <<>>';
  9379. $out .= ' /Metadata '.$xmpobj.' 0 R';
  9380. //$out .= ' /StructTreeRoot <<>>';
  9381. //$out .= ' /MarkInfo <<>>';
  9382. if (isset($this->l['a_meta_language'])) {
  9383. $out .= ' /Lang '.$this->_textstring($this->l['a_meta_language'], $oid);
  9384. }
  9385. //$out .= ' /SpiderInfo <<>>';
  9386. // set OutputIntent to sRGB IEC61966-2.1 if required
  9387. if ($this->pdfa_mode OR $this->force_srgb) {
  9388. $out .= ' /OutputIntents [<<';
  9389. $out .= ' /Type /OutputIntent';
  9390. $out .= ' /S /GTS_PDFA1';
  9391. $out .= ' /OutputCondition '.$this->_textstring('sRGB IEC61966-2.1', $oid);
  9392. $out .= ' /OutputConditionIdentifier '.$this->_textstring('sRGB IEC61966-2.1', $oid);
  9393. $out .= ' /RegistryName '.$this->_textstring('http://www.color.org', $oid);
  9394. $out .= ' /Info '.$this->_textstring('sRGB IEC61966-2.1', $oid);
  9395. $out .= ' /DestOutputProfile '.$iccobj.' 0 R';
  9396. $out .= ' >>]';
  9397. }
  9398. //$out .= ' /PieceInfo <<>>';
  9399. if (!empty($this->pdflayers)) {
  9400. $lyrobjs = '';
  9401. $lyrobjs_off = '';
  9402. $lyrobjs_lock = '';
  9403. foreach ($this->pdflayers as $layer) {
  9404. $layer_obj_ref = ' '.$layer['objid'].' 0 R';
  9405. $lyrobjs .= $layer_obj_ref;
  9406. if ($layer['view'] === false) {
  9407. $lyrobjs_off .= $layer_obj_ref;
  9408. }
  9409. if ($layer['lock']) {
  9410. $lyrobjs_lock .= $layer_obj_ref;
  9411. }
  9412. }
  9413. $out .= ' /OCProperties << /OCGs ['.$lyrobjs.']';
  9414. $out .= ' /D <<';
  9415. $out .= ' /Name '.$this->_textstring('Layers', $oid);
  9416. $out .= ' /Creator '.$this->_textstring('TCPDF', $oid);
  9417. $out .= ' /BaseState /ON';
  9418. $out .= ' /OFF ['.$lyrobjs_off.']';
  9419. $out .= ' /Locked ['.$lyrobjs_lock.']';
  9420. $out .= ' /Intent /View';
  9421. $out .= ' /AS [';
  9422. $out .= ' << /Event /Print /OCGs ['.$lyrobjs.'] /Category [/Print] >>';
  9423. $out .= ' << /Event /View /OCGs ['.$lyrobjs.'] /Category [/View] >>';
  9424. $out .= ' ]';
  9425. $out .= ' /Order ['.$lyrobjs.']';
  9426. $out .= ' /ListMode /AllPages';
  9427. //$out .= ' /RBGroups ['..']';
  9428. //$out .= ' /Locked ['..']';
  9429. $out .= ' >>';
  9430. $out .= ' >>';
  9431. }
  9432. // AcroForm
  9433. if (!empty($this->form_obj_id)
  9434. OR ($this->sign AND isset($this->signature_data['cert_type']))
  9435. OR !empty($this->empty_signature_appearance)) {
  9436. $out .= ' /AcroForm <<';
  9437. $objrefs = '';
  9438. if ($this->sign AND isset($this->signature_data['cert_type'])) {
  9439. // set reference for signature object
  9440. $objrefs .= $this->sig_obj_id.' 0 R';
  9441. }
  9442. if (!empty($this->empty_signature_appearance)) {
  9443. foreach ($this->empty_signature_appearance as $esa) {
  9444. // set reference for empty signature objects
  9445. $objrefs .= ' '.$esa['objid'].' 0 R';
  9446. }
  9447. }
  9448. if (!empty($this->form_obj_id)) {
  9449. foreach($this->form_obj_id as $objid) {
  9450. $objrefs .= ' '.$objid.' 0 R';
  9451. }
  9452. }
  9453. $out .= ' /Fields ['.$objrefs.']';
  9454. // It's better to turn off this value and set the appearance stream for each annotation (/AP) to avoid conflicts with signature fields.
  9455. if (empty($this->signature_data['approval']) OR ($this->signature_data['approval'] != 'A')) {
  9456. $out .= ' /NeedAppearances false';
  9457. }
  9458. if ($this->sign AND isset($this->signature_data['cert_type'])) {
  9459. if ($this->signature_data['cert_type'] > 0) {
  9460. $out .= ' /SigFlags 3';
  9461. } else {
  9462. $out .= ' /SigFlags 1';
  9463. }
  9464. }
  9465. //$out .= ' /CO ';
  9466. if (isset($this->annotation_fonts) AND !empty($this->annotation_fonts)) {
  9467. $out .= ' /DR <<';
  9468. $out .= ' /Font <<';
  9469. foreach ($this->annotation_fonts as $fontkey => $fontid) {
  9470. $out .= ' /F'.$fontid.' '.$this->font_obj_ids[$fontkey].' 0 R';
  9471. }
  9472. $out .= ' >> >>';
  9473. }
  9474. $font = $this->getFontBuffer('helvetica');
  9475. $out .= ' /DA (/F'.$font['i'].' 0 Tf 0 g)';
  9476. $out .= ' /Q '.(($this->rtl)?'2':'0');
  9477. //$out .= ' /XFA ';
  9478. $out .= ' >>';
  9479. // signatures
  9480. if ($this->sign AND isset($this->signature_data['cert_type'])
  9481. AND (empty($this->signature_data['approval']) OR ($this->signature_data['approval'] != 'A'))) {
  9482. if ($this->signature_data['cert_type'] > 0) {
  9483. $out .= ' /Perms << /DocMDP '.($this->sig_obj_id + 1).' 0 R >>';
  9484. } else {
  9485. $out .= ' /Perms << /UR3 '.($this->sig_obj_id + 1).' 0 R >>';
  9486. }
  9487. }
  9488. }
  9489. //$out .= ' /Legal <<>>';
  9490. //$out .= ' /Requirements []';
  9491. //$out .= ' /Collection <<>>';
  9492. //$out .= ' /NeedsRendering true';
  9493. $out .= ' >>';
  9494. $out .= "\n".'endobj';
  9495. $this->_out($out);
  9496. return $oid;
  9497. }
  9498. /**
  9499. * Output viewer preferences.
  9500. * @return string for viewer preferences
  9501. * @author Nicola asuni
  9502. * @since 3.1.000 (2008-06-09)
  9503. * @protected
  9504. */
  9505. protected function _putviewerpreferences() {
  9506. $vp = $this->viewer_preferences;
  9507. $out = ' /ViewerPreferences <<';
  9508. if ($this->rtl) {
  9509. $out .= ' /Direction /R2L';
  9510. } else {
  9511. $out .= ' /Direction /L2R';
  9512. }
  9513. if (isset($vp['HideToolbar']) AND ($vp['HideToolbar'])) {
  9514. $out .= ' /HideToolbar true';
  9515. }
  9516. if (isset($vp['HideMenubar']) AND ($vp['HideMenubar'])) {
  9517. $out .= ' /HideMenubar true';
  9518. }
  9519. if (isset($vp['HideWindowUI']) AND ($vp['HideWindowUI'])) {
  9520. $out .= ' /HideWindowUI true';
  9521. }
  9522. if (isset($vp['FitWindow']) AND ($vp['FitWindow'])) {
  9523. $out .= ' /FitWindow true';
  9524. }
  9525. if (isset($vp['CenterWindow']) AND ($vp['CenterWindow'])) {
  9526. $out .= ' /CenterWindow true';
  9527. }
  9528. if (isset($vp['DisplayDocTitle']) AND ($vp['DisplayDocTitle'])) {
  9529. $out .= ' /DisplayDocTitle true';
  9530. }
  9531. if (isset($vp['NonFullScreenPageMode'])) {
  9532. $out .= ' /NonFullScreenPageMode /'.$vp['NonFullScreenPageMode'];
  9533. }
  9534. if (isset($vp['ViewArea'])) {
  9535. $out .= ' /ViewArea /'.$vp['ViewArea'];
  9536. }
  9537. if (isset($vp['ViewClip'])) {
  9538. $out .= ' /ViewClip /'.$vp['ViewClip'];
  9539. }
  9540. if (isset($vp['PrintArea'])) {
  9541. $out .= ' /PrintArea /'.$vp['PrintArea'];
  9542. }
  9543. if (isset($vp['PrintClip'])) {
  9544. $out .= ' /PrintClip /'.$vp['PrintClip'];
  9545. }
  9546. if (isset($vp['PrintScaling'])) {
  9547. $out .= ' /PrintScaling /'.$vp['PrintScaling'];
  9548. }
  9549. if (isset($vp['Duplex']) AND (!TCPDF_STATIC::empty_string($vp['Duplex']))) {
  9550. $out .= ' /Duplex /'.$vp['Duplex'];
  9551. }
  9552. if (isset($vp['PickTrayByPDFSize'])) {
  9553. if ($vp['PickTrayByPDFSize']) {
  9554. $out .= ' /PickTrayByPDFSize true';
  9555. } else {
  9556. $out .= ' /PickTrayByPDFSize false';
  9557. }
  9558. }
  9559. if (isset($vp['PrintPageRange'])) {
  9560. $PrintPageRangeNum = '';
  9561. foreach ($vp['PrintPageRange'] as $k => $v) {
  9562. $PrintPageRangeNum .= ' '.($v - 1).'';
  9563. }
  9564. $out .= ' /PrintPageRange ['.substr($PrintPageRangeNum,1).']';
  9565. }
  9566. if (isset($vp['NumCopies'])) {
  9567. $out .= ' /NumCopies '.intval($vp['NumCopies']);
  9568. }
  9569. $out .= ' >>';
  9570. return $out;
  9571. }
  9572. /**
  9573. * Output PDF File Header (7.5.2).
  9574. * @protected
  9575. */
  9576. protected function _putheader() {
  9577. $this->_out('%PDF-'.$this->PDFVersion);
  9578. $this->_out('%'.chr(0xe2).chr(0xe3).chr(0xcf).chr(0xd3));
  9579. }
  9580. /**
  9581. * Output end of document (EOF).
  9582. * @protected
  9583. */
  9584. protected function _enddoc() {
  9585. if (isset($this->CurrentFont['fontkey']) AND isset($this->CurrentFont['subsetchars'])) {
  9586. // save subset chars of the previous font
  9587. $this->setFontSubBuffer($this->CurrentFont['fontkey'], 'subsetchars', $this->CurrentFont['subsetchars']);
  9588. }
  9589. $this->state = 1;
  9590. $this->_putheader();
  9591. $this->_putpages();
  9592. $this->_putresources();
  9593. // empty signature fields
  9594. if (!empty($this->empty_signature_appearance)) {
  9595. foreach ($this->empty_signature_appearance as $key => $esa) {
  9596. // widget annotation for empty signature
  9597. $out = $this->_getobj($esa['objid'])."\n";
  9598. $out .= '<< /Type /Annot';
  9599. $out .= ' /Subtype /Widget';
  9600. $out .= ' /Rect ['.$esa['rect'].']';
  9601. $out .= ' /P '.$this->page_obj_id[($esa['page'])].' 0 R'; // link to signature appearance page
  9602. $out .= ' /F 4';
  9603. $out .= ' /FT /Sig';
  9604. $signame = $esa['name'].sprintf(' [%03d]', ($key + 1));
  9605. $out .= ' /T '.$this->_textstring($signame, $esa['objid']);
  9606. $out .= ' /Ff 0';
  9607. $out .= ' >>';
  9608. $out .= "\n".'endobj';
  9609. $this->_out($out);
  9610. }
  9611. }
  9612. // Signature
  9613. if ($this->sign AND isset($this->signature_data['cert_type'])) {
  9614. // widget annotation for signature
  9615. $out = $this->_getobj($this->sig_obj_id)."\n";
  9616. $out .= '<< /Type /Annot';
  9617. $out .= ' /Subtype /Widget';
  9618. $out .= ' /Rect ['.$this->signature_appearance['rect'].']';
  9619. $out .= ' /P '.$this->page_obj_id[($this->signature_appearance['page'])].' 0 R'; // link to signature appearance page
  9620. $out .= ' /F 4';
  9621. $out .= ' /FT /Sig';
  9622. $out .= ' /T '.$this->_textstring($this->signature_appearance['name'], $this->sig_obj_id);
  9623. $out .= ' /Ff 0';
  9624. $out .= ' /V '.($this->sig_obj_id + 1).' 0 R';
  9625. $out .= ' >>';
  9626. $out .= "\n".'endobj';
  9627. $this->_out($out);
  9628. // signature
  9629. $this->_putsignature();
  9630. }
  9631. // Info
  9632. $objid_info = $this->_putinfo();
  9633. // Catalog
  9634. $objid_catalog = $this->_putcatalog();
  9635. // Cross-ref
  9636. $o = $this->bufferlen;
  9637. // XREF section
  9638. $this->_out('xref');
  9639. $this->_out('0 '.($this->n + 1));
  9640. $this->_out('0000000000 65535 f ');
  9641. $freegen = ($this->n + 2);
  9642. for ($i=1; $i <= $this->n; ++$i) {
  9643. if (!isset($this->offsets[$i]) AND ($i > 1)) {
  9644. $this->_out(sprintf('0000000000 %05d f ', $freegen));
  9645. ++$freegen;
  9646. } else {
  9647. $this->_out(sprintf('%010d 00000 n ', $this->offsets[$i]));
  9648. }
  9649. }
  9650. // TRAILER
  9651. $out = 'trailer'."\n";
  9652. $out .= '<<';
  9653. $out .= ' /Size '.($this->n + 1);
  9654. $out .= ' /Root '.$objid_catalog.' 0 R';
  9655. $out .= ' /Info '.$objid_info.' 0 R';
  9656. if ($this->encrypted) {
  9657. $out .= ' /Encrypt '.$this->encryptdata['objid'].' 0 R';
  9658. }
  9659. $out .= ' /ID [ <'.$this->file_id.'> <'.$this->file_id.'> ]';
  9660. $out .= ' >>';
  9661. $this->_out($out);
  9662. $this->_out('startxref');
  9663. $this->_out($o);
  9664. $this->_out('%%EOF');
  9665. $this->state = 3; // end-of-doc
  9666. }
  9667. /**
  9668. * Initialize a new page.
  9669. * @param $orientation (string) page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
  9670. * @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().
  9671. * @protected
  9672. * @see getPageSizeFromFormat(), setPageFormat()
  9673. */
  9674. protected function _beginpage($orientation='', $format='') {
  9675. ++$this->page;
  9676. $this->pageobjects[$this->page] = array();
  9677. $this->setPageBuffer($this->page, '');
  9678. // initialize array for graphics tranformation positions inside a page buffer
  9679. $this->transfmrk[$this->page] = array();
  9680. $this->state = 2;
  9681. if (TCPDF_STATIC::empty_string($orientation)) {
  9682. if (isset($this->CurOrientation)) {
  9683. $orientation = $this->CurOrientation;
  9684. } elseif ($this->fwPt > $this->fhPt) {
  9685. // landscape
  9686. $orientation = 'L';
  9687. } else {
  9688. // portrait
  9689. $orientation = 'P';
  9690. }
  9691. }
  9692. if (TCPDF_STATIC::empty_string($format)) {
  9693. $this->pagedim[$this->page] = $this->pagedim[($this->page - 1)];
  9694. $this->setPageOrientation($orientation);
  9695. } else {
  9696. $this->setPageFormat($format, $orientation);
  9697. }
  9698. if ($this->rtl) {
  9699. $this->x = $this->w - $this->rMargin;
  9700. } else {
  9701. $this->x = $this->lMargin;
  9702. }
  9703. $this->y = $this->tMargin;
  9704. if (isset($this->newpagegroup[$this->page])) {
  9705. // start a new group
  9706. $this->currpagegroup = $this->newpagegroup[$this->page];
  9707. $this->pagegroups[$this->currpagegroup] = 1;
  9708. } elseif (isset($this->currpagegroup) AND ($this->currpagegroup > 0)) {
  9709. ++$this->pagegroups[$this->currpagegroup];
  9710. }
  9711. }
  9712. /**
  9713. * Mark end of page.
  9714. * @protected
  9715. */
  9716. protected function _endpage() {
  9717. $this->setVisibility('all');
  9718. $this->state = 1;
  9719. }
  9720. /**
  9721. * Begin a new object and return the object number.
  9722. * @return int object number
  9723. * @protected
  9724. */
  9725. protected function _newobj() {
  9726. $this->_out($this->_getobj());
  9727. return $this->n;
  9728. }
  9729. /**
  9730. * Return the starting object string for the selected object ID.
  9731. * @param $objid (int) Object ID (leave empty to get a new ID).
  9732. * @return string the starting object string
  9733. * @protected
  9734. * @since 5.8.009 (2010-08-20)
  9735. */
  9736. protected function _getobj($objid='') {
  9737. if ($objid === '') {
  9738. ++$this->n;
  9739. $objid = $this->n;
  9740. }
  9741. $this->offsets[$objid] = $this->bufferlen;
  9742. $this->pageobjects[$this->page][] = $objid;
  9743. return $objid.' 0 obj';
  9744. }
  9745. /**
  9746. * Underline text.
  9747. * @param $x (int) X coordinate
  9748. * @param $y (int) Y coordinate
  9749. * @param $txt (string) text to underline
  9750. * @protected
  9751. */
  9752. protected function _dounderline($x, $y, $txt) {
  9753. $w = $this->GetStringWidth($txt);
  9754. return $this->_dounderlinew($x, $y, $w);
  9755. }
  9756. /**
  9757. * Underline for rectangular text area.
  9758. * @param $x (int) X coordinate
  9759. * @param $y (int) Y coordinate
  9760. * @param $w (int) width to underline
  9761. * @protected
  9762. * @since 4.8.008 (2009-09-29)
  9763. */
  9764. protected function _dounderlinew($x, $y, $w) {
  9765. $linew = - $this->CurrentFont['ut'] / 1000 * $this->FontSizePt;
  9766. return sprintf('%F %F %F %F re f', $x * $this->k, ((($this->h - $y) * $this->k) + $linew), $w * $this->k, $linew);
  9767. }
  9768. /**
  9769. * Line through text.
  9770. * @param $x (int) X coordinate
  9771. * @param $y (int) Y coordinate
  9772. * @param $txt (string) text to linethrough
  9773. * @protected
  9774. */
  9775. protected function _dolinethrough($x, $y, $txt) {
  9776. $w = $this->GetStringWidth($txt);
  9777. return $this->_dolinethroughw($x, $y, $w);
  9778. }
  9779. /**
  9780. * Line through for rectangular text area.
  9781. * @param $x (int) X coordinate
  9782. * @param $y (int) Y coordinate
  9783. * @param $w (int) line length (width)
  9784. * @protected
  9785. * @since 4.9.008 (2009-09-29)
  9786. */
  9787. protected function _dolinethroughw($x, $y, $w) {
  9788. $linew = - $this->CurrentFont['ut'] / 1000 * $this->FontSizePt;
  9789. return sprintf('%F %F %F %F re f', $x * $this->k, ((($this->h - $y) * $this->k) + $linew + ($this->FontSizePt / 3)), $w * $this->k, $linew);
  9790. }
  9791. /**
  9792. * Overline text.
  9793. * @param $x (int) X coordinate
  9794. * @param $y (int) Y coordinate
  9795. * @param $txt (string) text to overline
  9796. * @protected
  9797. * @since 4.9.015 (2010-04-19)
  9798. */
  9799. protected function _dooverline($x, $y, $txt) {
  9800. $w = $this->GetStringWidth($txt);
  9801. return $this->_dooverlinew($x, $y, $w);
  9802. }
  9803. /**
  9804. * Overline for rectangular text area.
  9805. * @param $x (int) X coordinate
  9806. * @param $y (int) Y coordinate
  9807. * @param $w (int) width to overline
  9808. * @protected
  9809. * @since 4.9.015 (2010-04-19)
  9810. */
  9811. protected function _dooverlinew($x, $y, $w) {
  9812. $linew = - $this->CurrentFont['ut'] / 1000 * $this->FontSizePt;
  9813. return sprintf('%F %F %F %F re f', $x * $this->k, (($this->h - $y + $this->FontAscent) * $this->k) - $linew, $w * $this->k, $linew);
  9814. }
  9815. /**
  9816. * Format a data string for meta information
  9817. * @param $s (string) data string to escape.
  9818. * @param $n (int) object ID
  9819. * @return string escaped string.
  9820. * @protected
  9821. */
  9822. protected function _datastring($s, $n=0) {
  9823. if ($n == 0) {
  9824. $n = $this->n;
  9825. }
  9826. $s = $this->_encrypt_data($n, $s);
  9827. return '('. TCPDF_STATIC::_escape($s).')';
  9828. }
  9829. /**
  9830. * Set the document creation timestamp
  9831. * @param $time (mixed) Document creation timestamp in seconds or date-time string.
  9832. * @public
  9833. * @since 5.9.152 (2012-03-23)
  9834. */
  9835. public function setDocCreationTimestamp($time) {
  9836. if (is_string($time)) {
  9837. $time = TCPDF_STATIC::getTimestamp($time);
  9838. }
  9839. $this->doc_creation_timestamp = intval($time);
  9840. }
  9841. /**
  9842. * Set the document modification timestamp
  9843. * @param $time (mixed) Document modification timestamp in seconds or date-time string.
  9844. * @public
  9845. * @since 5.9.152 (2012-03-23)
  9846. */
  9847. public function setDocModificationTimestamp($time) {
  9848. if (is_string($time)) {
  9849. $time = TCPDF_STATIC::getTimestamp($time);
  9850. }
  9851. $this->doc_modification_timestamp = intval($time);
  9852. }
  9853. /**
  9854. * Returns document creation timestamp in seconds.
  9855. * @return (int) Creation timestamp in seconds.
  9856. * @public
  9857. * @since 5.9.152 (2012-03-23)
  9858. */
  9859. public function getDocCreationTimestamp() {
  9860. return $this->doc_creation_timestamp;
  9861. }
  9862. /**
  9863. * Returns document modification timestamp in seconds.
  9864. * @return (int) Modfication timestamp in seconds.
  9865. * @public
  9866. * @since 5.9.152 (2012-03-23)
  9867. */
  9868. public function getDocModificationTimestamp() {
  9869. return $this->doc_modification_timestamp;
  9870. }
  9871. /**
  9872. * Returns a formatted date for meta information
  9873. * @param $n (int) Object ID.
  9874. * @param $timestamp (int) Timestamp to convert.
  9875. * @return string escaped date string.
  9876. * @protected
  9877. * @since 4.6.028 (2009-08-25)
  9878. */
  9879. protected function _datestring($n=0, $timestamp=0) {
  9880. if ((empty($timestamp)) OR ($timestamp < 0)) {
  9881. $timestamp = $this->doc_creation_timestamp;
  9882. }
  9883. return $this->_datastring('D:'.TCPDF_STATIC::getFormattedDate($timestamp), $n);
  9884. }
  9885. /**
  9886. * Format a text string for meta information
  9887. * @param $s (string) string to escape.
  9888. * @param $n (int) object ID
  9889. * @return string escaped string.
  9890. * @protected
  9891. */
  9892. protected function _textstring($s, $n=0) {
  9893. if ($this->isunicode) {
  9894. //Convert string to UTF-16BE
  9895. $s = TCPDF_FONTS::UTF8ToUTF16BE($s, true, $this->isunicode, $this->CurrentFont);
  9896. }
  9897. return $this->_datastring($s, $n);
  9898. }
  9899. /**
  9900. * get raw output stream.
  9901. * @param $s (string) string to output.
  9902. * @param $n (int) object reference for encryption mode
  9903. * @protected
  9904. * @author Nicola Asuni
  9905. * @since 5.5.000 (2010-06-22)
  9906. */
  9907. protected function _getrawstream($s, $n=0) {
  9908. if ($n <= 0) {
  9909. // default to current object
  9910. $n = $this->n;
  9911. }
  9912. return $this->_encrypt_data($n, $s);
  9913. }
  9914. /**
  9915. * Output a string to the document.
  9916. * @param $s (string) string to output.
  9917. * @protected
  9918. */
  9919. protected function _out($s) {
  9920. if ($this->state == 2) {
  9921. if ($this->inxobj) {
  9922. // we are inside an XObject template
  9923. $this->xobjects[$this->xobjid]['outdata'] .= $s."\n";
  9924. } elseif ((!$this->InFooter) AND isset($this->footerlen[$this->page]) AND ($this->footerlen[$this->page] > 0)) {
  9925. // puts data before page footer
  9926. $pagebuff = $this->getPageBuffer($this->page);
  9927. $page = substr($pagebuff, 0, -$this->footerlen[$this->page]);
  9928. $footer = substr($pagebuff, -$this->footerlen[$this->page]);
  9929. $this->setPageBuffer($this->page, $page.$s."\n".$footer);
  9930. // update footer position
  9931. $this->footerpos[$this->page] += strlen($s."\n");
  9932. } else {
  9933. // set page data
  9934. $this->setPageBuffer($this->page, $s."\n", true);
  9935. }
  9936. } elseif ($this->state > 0) {
  9937. // set general data
  9938. $this->setBuffer($s."\n");
  9939. }
  9940. }
  9941. /**
  9942. * Set header font.
  9943. * @param $font (array) Array describing the basic font parameters: (family, style, size).
  9944. * @public
  9945. * @since 1.1
  9946. */
  9947. public function setHeaderFont($font) {
  9948. $this->header_font = $font;
  9949. }
  9950. /**
  9951. * Get header font.
  9952. * @return array() Array describing the basic font parameters: (family, style, size).
  9953. * @public
  9954. * @since 4.0.012 (2008-07-24)
  9955. */
  9956. public function getHeaderFont() {
  9957. return $this->header_font;
  9958. }
  9959. /**
  9960. * Set footer font.
  9961. * @param $font (array) Array describing the basic font parameters: (family, style, size).
  9962. * @public
  9963. * @since 1.1
  9964. */
  9965. public function setFooterFont($font) {
  9966. $this->footer_font = $font;
  9967. }
  9968. /**
  9969. * Get Footer font.
  9970. * @return array() Array describing the basic font parameters: (family, style, size).
  9971. * @public
  9972. * @since 4.0.012 (2008-07-24)
  9973. */
  9974. public function getFooterFont() {
  9975. return $this->footer_font;
  9976. }
  9977. /**
  9978. * Set language array.
  9979. * @param $language (array)
  9980. * @public
  9981. * @since 1.1
  9982. */
  9983. public function setLanguageArray($language) {
  9984. $this->l = $language;
  9985. if (isset($this->l['a_meta_dir'])) {
  9986. $this->rtl = $this->l['a_meta_dir']=='rtl' ? true : false;
  9987. } else {
  9988. $this->rtl = false;
  9989. }
  9990. }
  9991. /**
  9992. * Returns the PDF data.
  9993. * @public
  9994. */
  9995. public function getPDFData() {
  9996. if ($this->state < 3) {
  9997. $this->Close();
  9998. }
  9999. return $this->buffer;
  10000. }
  10001. /**
  10002. * Output anchor link.
  10003. * @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;)
  10004. * @param $name (string) link name
  10005. * @param $fill (boolean) Indicates if the cell background must be painted (true) or transparent (false).
  10006. * @param $firstline (boolean) if true prints only the first line and return the remaining string.
  10007. * @param $color (array) array of RGB text color
  10008. * @param $style (string) font style (U, D, B, I)
  10009. * @param $firstblock (boolean) if true the string is the starting of a line.
  10010. * @return the number of cells used or the remaining text if $firstline = true;
  10011. * @public
  10012. */
  10013. public function addHtmlLink($url, $name, $fill=false, $firstline=false, $color='', $style=-1, $firstblock=false) {
  10014. if (isset($url[1]) AND ($url[0] == '#') AND is_numeric($url[1])) {
  10015. // convert url to internal link
  10016. $lnkdata = explode(',', $url);
  10017. if (isset($lnkdata[0]) ) {
  10018. $page = substr($lnkdata[0], 1);
  10019. if (isset($lnkdata[1]) AND (strlen($lnkdata[1]) > 0)) {
  10020. $lnky = floatval($lnkdata[1]);
  10021. } else {
  10022. $lnky = 0;
  10023. }
  10024. $url = $this->AddLink();
  10025. $this->SetLink($url, $lnky, $page);
  10026. }
  10027. }
  10028. // store current settings
  10029. $prevcolor = $this->fgcolor;
  10030. $prevstyle = $this->FontStyle;
  10031. if (empty($color)) {
  10032. $this->SetTextColorArray($this->htmlLinkColorArray);
  10033. } else {
  10034. $this->SetTextColorArray($color);
  10035. }
  10036. if ($style == -1) {
  10037. $this->SetFont('', $this->FontStyle.$this->htmlLinkFontStyle);
  10038. } else {
  10039. $this->SetFont('', $this->FontStyle.$style);
  10040. }
  10041. $ret = $this->Write($this->lasth, $name, $url, $fill, '', false, 0, $firstline, $firstblock, 0);
  10042. // restore settings
  10043. $this->SetFont('', $prevstyle);
  10044. $this->SetTextColorArray($prevcolor);
  10045. return $ret;
  10046. }
  10047. /**
  10048. * Converts pixels to User's Units.
  10049. * @param $px (int) pixels
  10050. * @return float value in user's unit
  10051. * @public
  10052. * @see setImageScale(), getImageScale()
  10053. */
  10054. public function pixelsToUnits($px) {
  10055. return ($px / ($this->imgscale * $this->k));
  10056. }
  10057. /**
  10058. * Reverse function for htmlentities.
  10059. * Convert entities in UTF-8.
  10060. * @param $text_to_convert (string) Text to convert.
  10061. * @return string converted text string
  10062. * @public
  10063. */
  10064. public function unhtmlentities($text_to_convert) {
  10065. return @html_entity_decode($text_to_convert, ENT_QUOTES, $this->encoding);
  10066. }
  10067. // ENCRYPTION METHODS ----------------------------------
  10068. /**
  10069. * Compute encryption key depending on object number where the encrypted data is stored.
  10070. * This is used for all strings and streams without crypt filter specifier.
  10071. * @param $n (int) object number
  10072. * @return int object key
  10073. * @protected
  10074. * @author Nicola Asuni
  10075. * @since 2.0.000 (2008-01-02)
  10076. */
  10077. protected function _objectkey($n) {
  10078. $objkey = $this->encryptdata['key'].pack('VXxx', $n);
  10079. if ($this->encryptdata['mode'] == 2) { // AES-128
  10080. // AES padding
  10081. $objkey .= "\x73\x41\x6C\x54"; // sAlT
  10082. }
  10083. $objkey = substr(TCPDF_STATIC::_md5_16($objkey), 0, (($this->encryptdata['Length'] / 8) + 5));
  10084. $objkey = substr($objkey, 0, 16);
  10085. return $objkey;
  10086. }
  10087. /**
  10088. * Encrypt the input string.
  10089. * @param $n (int) object number
  10090. * @param $s (string) data string to encrypt
  10091. * @return encrypted string
  10092. * @protected
  10093. * @author Nicola Asuni
  10094. * @since 5.0.005 (2010-05-11)
  10095. */
  10096. protected function _encrypt_data($n, $s) {
  10097. if (!$this->encrypted) {
  10098. return $s;
  10099. }
  10100. switch ($this->encryptdata['mode']) {
  10101. case 0: // RC4-40
  10102. case 1: { // RC4-128
  10103. $s = TCPDF_STATIC::_RC4($this->_objectkey($n), $s, $this->last_enc_key, $this->last_enc_key_c);
  10104. break;
  10105. }
  10106. case 2: { // AES-128
  10107. $s = TCPDF_STATIC::_AES($this->_objectkey($n), $s);
  10108. break;
  10109. }
  10110. case 3: { // AES-256
  10111. $s = TCPDF_STATIC::_AES($this->encryptdata['key'], $s);
  10112. break;
  10113. }
  10114. }
  10115. return $s;
  10116. }
  10117. /**
  10118. * Put encryption on PDF document.
  10119. * @protected
  10120. * @author Nicola Asuni
  10121. * @since 2.0.000 (2008-01-02)
  10122. */
  10123. protected function _putencryption() {
  10124. if (!$this->encrypted) {
  10125. return;
  10126. }
  10127. $this->encryptdata['objid'] = $this->_newobj();
  10128. $out = '<<';
  10129. if (!isset($this->encryptdata['Filter']) OR empty($this->encryptdata['Filter'])) {
  10130. $this->encryptdata['Filter'] = 'Standard';
  10131. }
  10132. $out .= ' /Filter /'.$this->encryptdata['Filter'];
  10133. if (isset($this->encryptdata['SubFilter']) AND !empty($this->encryptdata['SubFilter'])) {
  10134. $out .= ' /SubFilter /'.$this->encryptdata['SubFilter'];
  10135. }
  10136. if (!isset($this->encryptdata['V']) OR empty($this->encryptdata['V'])) {
  10137. $this->encryptdata['V'] = 1;
  10138. }
  10139. // V is a code specifying the algorithm to be used in encrypting and decrypting the document
  10140. $out .= ' /V '.$this->encryptdata['V'];
  10141. if (isset($this->encryptdata['Length']) AND !empty($this->encryptdata['Length'])) {
  10142. // The length of the encryption key, in bits. The value shall be a multiple of 8, in the range 40 to 256
  10143. $out .= ' /Length '.$this->encryptdata['Length'];
  10144. } else {
  10145. $out .= ' /Length 40';
  10146. }
  10147. if ($this->encryptdata['V'] >= 4) {
  10148. if (!isset($this->encryptdata['StmF']) OR empty($this->encryptdata['StmF'])) {
  10149. $this->encryptdata['StmF'] = 'Identity';
  10150. }
  10151. if (!isset($this->encryptdata['StrF']) OR empty($this->encryptdata['StrF'])) {
  10152. // The name of the crypt filter that shall be used when decrypting all strings in the document.
  10153. $this->encryptdata['StrF'] = 'Identity';
  10154. }
  10155. // A dictionary whose keys shall be crypt filter names and whose values shall be the corresponding crypt filter dictionaries.
  10156. if (isset($this->encryptdata['CF']) AND !empty($this->encryptdata['CF'])) {
  10157. $out .= ' /CF <<';
  10158. $out .= ' /'.$this->encryptdata['StmF'].' <<';
  10159. $out .= ' /Type /CryptFilter';
  10160. if (isset($this->encryptdata['CF']['CFM']) AND !empty($this->encryptdata['CF']['CFM'])) {
  10161. // The method used
  10162. $out .= ' /CFM /'.$this->encryptdata['CF']['CFM'];
  10163. if ($this->encryptdata['pubkey']) {
  10164. $out .= ' /Recipients [';
  10165. foreach ($this->encryptdata['Recipients'] as $rec) {
  10166. $out .= ' <'.$rec.'>';
  10167. }
  10168. $out .= ' ]';
  10169. if (isset($this->encryptdata['CF']['EncryptMetadata']) AND (!$this->encryptdata['CF']['EncryptMetadata'])) {
  10170. $out .= ' /EncryptMetadata false';
  10171. } else {
  10172. $out .= ' /EncryptMetadata true';
  10173. }
  10174. }
  10175. } else {
  10176. $out .= ' /CFM /None';
  10177. }
  10178. if (isset($this->encryptdata['CF']['AuthEvent']) AND !empty($this->encryptdata['CF']['AuthEvent'])) {
  10179. // The event to be used to trigger the authorization that is required to access encryption keys used by this filter.
  10180. $out .= ' /AuthEvent /'.$this->encryptdata['CF']['AuthEvent'];
  10181. } else {
  10182. $out .= ' /AuthEvent /DocOpen';
  10183. }
  10184. if (isset($this->encryptdata['CF']['Length']) AND !empty($this->encryptdata['CF']['Length'])) {
  10185. // The bit length of the encryption key.
  10186. $out .= ' /Length '.$this->encryptdata['CF']['Length'];
  10187. }
  10188. $out .= ' >> >>';
  10189. }
  10190. // The name of the crypt filter that shall be used by default when decrypting streams.
  10191. $out .= ' /StmF /'.$this->encryptdata['StmF'];
  10192. // The name of the crypt filter that shall be used when decrypting all strings in the document.
  10193. $out .= ' /StrF /'.$this->encryptdata['StrF'];
  10194. if (isset($this->encryptdata['EFF']) AND !empty($this->encryptdata['EFF'])) {
  10195. // The name of the crypt filter that shall be used when encrypting embedded file streams that do not have their own crypt filter specifier.
  10196. $out .= ' /EFF /'.$this->encryptdata[''];
  10197. }
  10198. }
  10199. // Additional encryption dictionary entries for the standard security handler
  10200. if ($this->encryptdata['pubkey']) {
  10201. if (($this->encryptdata['V'] < 4) AND isset($this->encryptdata['Recipients']) AND !empty($this->encryptdata['Recipients'])) {
  10202. $out .= ' /Recipients [';
  10203. foreach ($this->encryptdata['Recipients'] as $rec) {
  10204. $out .= ' <'.$rec.'>';
  10205. }
  10206. $out .= ' ]';
  10207. }
  10208. } else {
  10209. $out .= ' /R';
  10210. if ($this->encryptdata['V'] == 5) { // AES-256
  10211. $out .= ' 5';
  10212. $out .= ' /OE ('.TCPDF_STATIC::_escape($this->encryptdata['OE']).')';
  10213. $out .= ' /UE ('.TCPDF_STATIC::_escape($this->encryptdata['UE']).')';
  10214. $out .= ' /Perms ('.TCPDF_STATIC::_escape($this->encryptdata['perms']).')';
  10215. } elseif ($this->encryptdata['V'] == 4) { // AES-128
  10216. $out .= ' 4';
  10217. } elseif ($this->encryptdata['V'] < 2) { // RC-40
  10218. $out .= ' 2';
  10219. } else { // RC-128
  10220. $out .= ' 3';
  10221. }
  10222. $out .= ' /O ('.TCPDF_STATIC::_escape($this->encryptdata['O']).')';
  10223. $out .= ' /U ('.TCPDF_STATIC::_escape($this->encryptdata['U']).')';
  10224. $out .= ' /P '.$this->encryptdata['P'];
  10225. if (isset($this->encryptdata['EncryptMetadata']) AND (!$this->encryptdata['EncryptMetadata'])) {
  10226. $out .= ' /EncryptMetadata false';
  10227. } else {
  10228. $out .= ' /EncryptMetadata true';
  10229. }
  10230. }
  10231. $out .= ' >>';
  10232. $out .= "\n".'endobj';
  10233. $this->_out($out);
  10234. }
  10235. /**
  10236. * Compute U value (used for encryption)
  10237. * @return string U value
  10238. * @protected
  10239. * @since 2.0.000 (2008-01-02)
  10240. * @author Nicola Asuni
  10241. */
  10242. protected function _Uvalue() {
  10243. if ($this->encryptdata['mode'] == 0) { // RC4-40
  10244. return TCPDF_STATIC::_RC4($this->encryptdata['key'], TCPDF_STATIC::$enc_padding, $this->last_enc_key, $this->last_enc_key_c);
  10245. } elseif ($this->encryptdata['mode'] < 3) { // RC4-128, AES-128
  10246. $tmp = TCPDF_STATIC::_md5_16(TCPDF_STATIC::$enc_padding.$this->encryptdata['fileid']);
  10247. $enc = TCPDF_STATIC::_RC4($this->encryptdata['key'], $tmp, $this->last_enc_key, $this->last_enc_key_c);
  10248. $len = strlen($tmp);
  10249. for ($i = 1; $i <= 19; ++$i) {
  10250. $ek = '';
  10251. for ($j = 0; $j < $len; ++$j) {
  10252. $ek .= chr(ord($this->encryptdata['key'][$j]) ^ $i);
  10253. }
  10254. $enc = TCPDF_STATIC::_RC4($ek, $enc, $this->last_enc_key, $this->last_enc_key_c);
  10255. }
  10256. $enc .= str_repeat("\x00", 16);
  10257. return substr($enc, 0, 32);
  10258. } elseif ($this->encryptdata['mode'] == 3) { // AES-256
  10259. $seed = TCPDF_STATIC::_md5_16(TCPDF_STATIC::getRandomSeed());
  10260. // User Validation Salt
  10261. $this->encryptdata['UVS'] = substr($seed, 0, 8);
  10262. // User Key Salt
  10263. $this->encryptdata['UKS'] = substr($seed, 8, 16);
  10264. return hash('sha256', $this->encryptdata['user_password'].$this->encryptdata['UVS'], true).$this->encryptdata['UVS'].$this->encryptdata['UKS'];
  10265. }
  10266. }
  10267. /**
  10268. * Compute UE value (used for encryption)
  10269. * @return string UE value
  10270. * @protected
  10271. * @since 5.9.006 (2010-10-19)
  10272. * @author Nicola Asuni
  10273. */
  10274. protected function _UEvalue() {
  10275. $hashkey = hash('sha256', $this->encryptdata['user_password'].$this->encryptdata['UKS'], true);
  10276. return TCPDF_STATIC::_AESnopad($hashkey, $this->encryptdata['key']);
  10277. }
  10278. /**
  10279. * Compute O value (used for encryption)
  10280. * @return string O value
  10281. * @protected
  10282. * @since 2.0.000 (2008-01-02)
  10283. * @author Nicola Asuni
  10284. */
  10285. protected function _Ovalue() {
  10286. if ($this->encryptdata['mode'] < 3) { // RC4-40, RC4-128, AES-128
  10287. $tmp = TCPDF_STATIC::_md5_16($this->encryptdata['owner_password']);
  10288. if ($this->encryptdata['mode'] > 0) {
  10289. for ($i = 0; $i < 50; ++$i) {
  10290. $tmp = TCPDF_STATIC::_md5_16($tmp);
  10291. }
  10292. }
  10293. $owner_key = substr($tmp, 0, ($this->encryptdata['Length'] / 8));
  10294. $enc = TCPDF_STATIC::_RC4($owner_key, $this->encryptdata['user_password'], $this->last_enc_key, $this->last_enc_key_c);
  10295. if ($this->encryptdata['mode'] > 0) {
  10296. $len = strlen($owner_key);
  10297. for ($i = 1; $i <= 19; ++$i) {
  10298. $ek = '';
  10299. for ($j = 0; $j < $len; ++$j) {
  10300. $ek .= chr(ord($owner_key[$j]) ^ $i);
  10301. }
  10302. $enc = TCPDF_STATIC::_RC4($ek, $enc, $this->last_enc_key, $this->last_enc_key_c);
  10303. }
  10304. }
  10305. return $enc;
  10306. } elseif ($this->encryptdata['mode'] == 3) { // AES-256
  10307. $seed = TCPDF_STATIC::_md5_16(TCPDF_STATIC::getRandomSeed());
  10308. // Owner Validation Salt
  10309. $this->encryptdata['OVS'] = substr($seed, 0, 8);
  10310. // Owner Key Salt
  10311. $this->encryptdata['OKS'] = substr($seed, 8, 16);
  10312. return hash('sha256', $this->encryptdata['owner_password'].$this->encryptdata['OVS'].$this->encryptdata['U'], true).$this->encryptdata['OVS'].$this->encryptdata['OKS'];
  10313. }
  10314. }
  10315. /**
  10316. * Compute OE value (used for encryption)
  10317. * @return string OE value
  10318. * @protected
  10319. * @since 5.9.006 (2010-10-19)
  10320. * @author Nicola Asuni
  10321. */
  10322. protected function _OEvalue() {
  10323. $hashkey = hash('sha256', $this->encryptdata['owner_password'].$this->encryptdata['OKS'].$this->encryptdata['U'], true);
  10324. return TCPDF_STATIC::_AESnopad($hashkey, $this->encryptdata['key']);
  10325. }
  10326. /**
  10327. * Convert password for AES-256 encryption mode
  10328. * @param $password (string) password
  10329. * @return string password
  10330. * @protected
  10331. * @since 5.9.006 (2010-10-19)
  10332. * @author Nicola Asuni
  10333. */
  10334. protected function _fixAES256Password($password) {
  10335. $psw = ''; // password to be returned
  10336. $psw_array = TCPDF_FONTS::utf8Bidi(TCPDF_FONTS::UTF8StringToArray($password, $this->isunicode, $this->CurrentFont), $password, $this->rtl, $this->isunicode, $this->CurrentFont);
  10337. foreach ($psw_array as $c) {
  10338. $psw .= TCPDF_FONTS::unichr($c, $this->isunicode);
  10339. }
  10340. return substr($psw, 0, 127);
  10341. }
  10342. /**
  10343. * Compute encryption key
  10344. * @protected
  10345. * @since 2.0.000 (2008-01-02)
  10346. * @author Nicola Asuni
  10347. */
  10348. protected function _generateencryptionkey() {
  10349. $keybytelen = ($this->encryptdata['Length'] / 8);
  10350. if (!$this->encryptdata['pubkey']) { // standard mode
  10351. if ($this->encryptdata['mode'] == 3) { // AES-256
  10352. // generate 256 bit random key
  10353. $this->encryptdata['key'] = substr(hash('sha256', TCPDF_STATIC::getRandomSeed(), true), 0, $keybytelen);
  10354. // truncate passwords
  10355. $this->encryptdata['user_password'] = $this->_fixAES256Password($this->encryptdata['user_password']);
  10356. $this->encryptdata['owner_password'] = $this->_fixAES256Password($this->encryptdata['owner_password']);
  10357. // Compute U value
  10358. $this->encryptdata['U'] = $this->_Uvalue();
  10359. // Compute UE value
  10360. $this->encryptdata['UE'] = $this->_UEvalue();
  10361. // Compute O value
  10362. $this->encryptdata['O'] = $this->_Ovalue();
  10363. // Compute OE value
  10364. $this->encryptdata['OE'] = $this->_OEvalue();
  10365. // Compute P value
  10366. $this->encryptdata['P'] = $this->encryptdata['protection'];
  10367. // Computing the encryption dictionary's Perms (permissions) value
  10368. $perms = TCPDF_STATIC::getEncPermissionsString($this->encryptdata['protection']); // bytes 0-3
  10369. $perms .= chr(255).chr(255).chr(255).chr(255); // bytes 4-7
  10370. if (isset($this->encryptdata['CF']['EncryptMetadata']) AND (!$this->encryptdata['CF']['EncryptMetadata'])) { // byte 8
  10371. $perms .= 'F';
  10372. } else {
  10373. $perms .= 'T';
  10374. }
  10375. $perms .= 'adb'; // bytes 9-11
  10376. $perms .= 'nick'; // bytes 12-15
  10377. $this->encryptdata['perms'] = TCPDF_STATIC::_AESnopad($this->encryptdata['key'], $perms);
  10378. } else { // RC4-40, RC4-128, AES-128
  10379. // Pad passwords
  10380. $this->encryptdata['user_password'] = substr($this->encryptdata['user_password'].TCPDF_STATIC::$enc_padding, 0, 32);
  10381. $this->encryptdata['owner_password'] = substr($this->encryptdata['owner_password'].TCPDF_STATIC::$enc_padding, 0, 32);
  10382. // Compute O value
  10383. $this->encryptdata['O'] = $this->_Ovalue();
  10384. // get default permissions (reverse byte order)
  10385. $permissions = TCPDF_STATIC::getEncPermissionsString($this->encryptdata['protection']);
  10386. // Compute encryption key
  10387. $tmp = TCPDF_STATIC::_md5_16($this->encryptdata['user_password'].$this->encryptdata['O'].$permissions.$this->encryptdata['fileid']);
  10388. if ($this->encryptdata['mode'] > 0) {
  10389. for ($i = 0; $i < 50; ++$i) {
  10390. $tmp = TCPDF_STATIC::_md5_16(substr($tmp, 0, $keybytelen));
  10391. }
  10392. }
  10393. $this->encryptdata['key'] = substr($tmp, 0, $keybytelen);
  10394. // Compute U value
  10395. $this->encryptdata['U'] = $this->_Uvalue();
  10396. // Compute P value
  10397. $this->encryptdata['P'] = $this->encryptdata['protection'];
  10398. }
  10399. } else { // Public-Key mode
  10400. // random 20-byte seed
  10401. $seed = sha1(TCPDF_STATIC::getRandomSeed(), true);
  10402. $recipient_bytes = '';
  10403. foreach ($this->encryptdata['pubkeys'] as $pubkey) {
  10404. // for each public certificate
  10405. if (isset($pubkey['p'])) {
  10406. $pkprotection = TCPDF_STATIC::getUserPermissionCode($pubkey['p'], $this->encryptdata['mode']);
  10407. } else {
  10408. $pkprotection = $this->encryptdata['protection'];
  10409. }
  10410. // get default permissions (reverse byte order)
  10411. $pkpermissions = TCPDF_STATIC::getEncPermissionsString($pkprotection);
  10412. // envelope data
  10413. $envelope = $seed.$pkpermissions;
  10414. // write the envelope data to a temporary file
  10415. $tempkeyfile = TCPDF_STATIC::getObjFilename('key', $this->file_id);
  10416. $f = TCPDF_STATIC::fopenLocal($tempkeyfile, 'wb');
  10417. if (!$f) {
  10418. $this->Error('Unable to create temporary key file: '.$tempkeyfile);
  10419. }
  10420. $envelope_length = strlen($envelope);
  10421. fwrite($f, $envelope, $envelope_length);
  10422. fclose($f);
  10423. $tempencfile = TCPDF_STATIC::getObjFilename('enc', $this->file_id);
  10424. if (!openssl_pkcs7_encrypt($tempkeyfile, $tempencfile, $pubkey['c'], array(), PKCS7_BINARY | PKCS7_DETACHED)) {
  10425. $this->Error('Unable to encrypt the file: '.$tempkeyfile);
  10426. }
  10427. // read encryption signature
  10428. $signature = file_get_contents($tempencfile, false, null, $envelope_length);
  10429. // extract signature
  10430. $signature = substr($signature, strpos($signature, 'Content-Disposition'));
  10431. $tmparr = explode("\n\n", $signature);
  10432. $signature = trim($tmparr[1]);
  10433. unset($tmparr);
  10434. // decode signature
  10435. $signature = base64_decode($signature);
  10436. // convert signature to hex
  10437. $hexsignature = current(unpack('H*', $signature));
  10438. // store signature on recipients array
  10439. $this->encryptdata['Recipients'][] = $hexsignature;
  10440. // The bytes of each item in the Recipients array of PKCS#7 objects in the order in which they appear in the array
  10441. $recipient_bytes .= $signature;
  10442. }
  10443. // calculate encryption key
  10444. if ($this->encryptdata['mode'] == 3) { // AES-256
  10445. $this->encryptdata['key'] = substr(hash('sha256', $seed.$recipient_bytes, true), 0, $keybytelen);
  10446. } else { // RC4-40, RC4-128, AES-128
  10447. $this->encryptdata['key'] = substr(sha1($seed.$recipient_bytes, true), 0, $keybytelen);
  10448. }
  10449. }
  10450. }
  10451. /**
  10452. * Set document protection
  10453. * Remark: the protection against modification is for people who have the full Acrobat product.
  10454. * 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.
  10455. * 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.
  10456. * @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>
  10457. * @param $user_pass (String) user password. Empty by default.
  10458. * @param $owner_pass (String) owner password. If not specified, a random value is used.
  10459. * @param $mode (int) encryption strength: 0 = RC4 40 bit; 1 = RC4 128 bit; 2 = AES 128 bit; 3 = AES 256 bit.
  10460. * @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')))
  10461. * @public
  10462. * @since 2.0.000 (2008-01-02)
  10463. * @author Nicola Asuni
  10464. */
  10465. 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) {
  10466. if ($this->pdfa_mode) {
  10467. // encryption is not allowed in PDF/A mode
  10468. return;
  10469. }
  10470. $this->encryptdata['protection'] = TCPDF_STATIC::getUserPermissionCode($permissions, $mode);
  10471. if (($pubkeys !== null) AND (is_array($pubkeys))) {
  10472. // public-key mode
  10473. $this->encryptdata['pubkeys'] = $pubkeys;
  10474. if ($mode == 0) {
  10475. // public-Key Security requires at least 128 bit
  10476. $mode = 1;
  10477. }
  10478. if (!function_exists('openssl_pkcs7_encrypt')) {
  10479. $this->Error('Public-Key Security requires openssl library.');
  10480. }
  10481. // Set Public-Key filter (available are: Entrust.PPKEF, Adobe.PPKLite, Adobe.PubSec)
  10482. $this->encryptdata['pubkey'] = true;
  10483. $this->encryptdata['Filter'] = 'Adobe.PubSec';
  10484. $this->encryptdata['StmF'] = 'DefaultCryptFilter';
  10485. $this->encryptdata['StrF'] = 'DefaultCryptFilter';
  10486. } else {
  10487. // standard mode (password mode)
  10488. $this->encryptdata['pubkey'] = false;
  10489. $this->encryptdata['Filter'] = 'Standard';
  10490. $this->encryptdata['StmF'] = 'StdCF';
  10491. $this->encryptdata['StrF'] = 'StdCF';
  10492. }
  10493. if ($mode > 1) { // AES
  10494. if (!extension_loaded('openssl') && !extension_loaded('mcrypt')) {
  10495. $this->Error('AES encryption requires openssl or mcrypt extension (http://www.php.net/manual/en/mcrypt.requirements.php).');
  10496. }
  10497. if (extension_loaded('openssl') && !in_array('aes-256-cbc', openssl_get_cipher_methods())) {
  10498. $this->Error('AES encryption requires openssl/aes-256-cbc cypher.');
  10499. }
  10500. if (extension_loaded('mcrypt') && mcrypt_get_cipher_name(MCRYPT_RIJNDAEL_128) === false) {
  10501. $this->Error('AES encryption requires MCRYPT_RIJNDAEL_128 cypher.');
  10502. }
  10503. if (($mode == 3) AND !function_exists('hash')) {
  10504. // the Hash extension requires no external libraries and is enabled by default as of PHP 5.1.2.
  10505. $this->Error('AES 256 encryption requires HASH Message Digest Framework (http://www.php.net/manual/en/book.hash.php).');
  10506. }
  10507. }
  10508. if ($owner_pass === null) {
  10509. $owner_pass = md5(TCPDF_STATIC::getRandomSeed());
  10510. }
  10511. $this->encryptdata['user_password'] = $user_pass;
  10512. $this->encryptdata['owner_password'] = $owner_pass;
  10513. $this->encryptdata['mode'] = $mode;
  10514. switch ($mode) {
  10515. case 0: { // RC4 40 bit
  10516. $this->encryptdata['V'] = 1;
  10517. $this->encryptdata['Length'] = 40;
  10518. $this->encryptdata['CF']['CFM'] = 'V2';
  10519. break;
  10520. }
  10521. case 1: { // RC4 128 bit
  10522. $this->encryptdata['V'] = 2;
  10523. $this->encryptdata['Length'] = 128;
  10524. $this->encryptdata['CF']['CFM'] = 'V2';
  10525. if ($this->encryptdata['pubkey']) {
  10526. $this->encryptdata['SubFilter'] = 'adbe.pkcs7.s4';
  10527. $this->encryptdata['Recipients'] = array();
  10528. }
  10529. break;
  10530. }
  10531. case 2: { // AES 128 bit
  10532. $this->encryptdata['V'] = 4;
  10533. $this->encryptdata['Length'] = 128;
  10534. $this->encryptdata['CF']['CFM'] = 'AESV2';
  10535. $this->encryptdata['CF']['Length'] = 128;
  10536. if ($this->encryptdata['pubkey']) {
  10537. $this->encryptdata['SubFilter'] = 'adbe.pkcs7.s5';
  10538. $this->encryptdata['Recipients'] = array();
  10539. }
  10540. break;
  10541. }
  10542. case 3: { // AES 256 bit
  10543. $this->encryptdata['V'] = 5;
  10544. $this->encryptdata['Length'] = 256;
  10545. $this->encryptdata['CF']['CFM'] = 'AESV3';
  10546. $this->encryptdata['CF']['Length'] = 256;
  10547. if ($this->encryptdata['pubkey']) {
  10548. $this->encryptdata['SubFilter'] = 'adbe.pkcs7.s5';
  10549. $this->encryptdata['Recipients'] = array();
  10550. }
  10551. break;
  10552. }
  10553. }
  10554. $this->encrypted = true;
  10555. $this->encryptdata['fileid'] = TCPDF_STATIC::convertHexStringToString($this->file_id);
  10556. $this->_generateencryptionkey();
  10557. }
  10558. // END OF ENCRYPTION FUNCTIONS -------------------------
  10559. // START TRANSFORMATIONS SECTION -----------------------
  10560. /**
  10561. * Starts a 2D tranformation saving current graphic state.
  10562. * This function must be called before scaling, mirroring, translation, rotation and skewing.
  10563. * Use StartTransform() before, and StopTransform() after the transformations to restore the normal behavior.
  10564. * @public
  10565. * @since 2.1.000 (2008-01-07)
  10566. * @see StartTransform(), StopTransform()
  10567. */
  10568. public function StartTransform() {
  10569. if ($this->state != 2) {
  10570. return;
  10571. }
  10572. $this->_outSaveGraphicsState();
  10573. if ($this->inxobj) {
  10574. // we are inside an XObject template
  10575. $this->xobjects[$this->xobjid]['transfmrk'][] = strlen($this->xobjects[$this->xobjid]['outdata']);
  10576. } else {
  10577. $this->transfmrk[$this->page][] = $this->pagelen[$this->page];
  10578. }
  10579. ++$this->transfmatrix_key;
  10580. $this->transfmatrix[$this->transfmatrix_key] = array();
  10581. }
  10582. /**
  10583. * Stops a 2D tranformation restoring previous graphic state.
  10584. * This function must be called after scaling, mirroring, translation, rotation and skewing.
  10585. * Use StartTransform() before, and StopTransform() after the transformations to restore the normal behavior.
  10586. * @public
  10587. * @since 2.1.000 (2008-01-07)
  10588. * @see StartTransform(), StopTransform()
  10589. */
  10590. public function StopTransform() {
  10591. if ($this->state != 2) {
  10592. return;
  10593. }
  10594. $this->_outRestoreGraphicsState();
  10595. if (isset($this->transfmatrix[$this->transfmatrix_key])) {
  10596. array_pop($this->transfmatrix[$this->transfmatrix_key]);
  10597. --$this->transfmatrix_key;
  10598. }
  10599. if ($this->inxobj) {
  10600. // we are inside an XObject template
  10601. array_pop($this->xobjects[$this->xobjid]['transfmrk']);
  10602. } else {
  10603. array_pop($this->transfmrk[$this->page]);
  10604. }
  10605. }
  10606. /**
  10607. * Horizontal Scaling.
  10608. * @param $s_x (float) scaling factor for width as percent. 0 is not allowed.
  10609. * @param $x (int) abscissa of the scaling center. Default is current x position
  10610. * @param $y (int) ordinate of the scaling center. Default is current y position
  10611. * @public
  10612. * @since 2.1.000 (2008-01-07)
  10613. * @see StartTransform(), StopTransform()
  10614. */
  10615. public function ScaleX($s_x, $x='', $y='') {
  10616. $this->Scale($s_x, 100, $x, $y);
  10617. }
  10618. /**
  10619. * Vertical Scaling.
  10620. * @param $s_y (float) scaling factor for height as percent. 0 is not allowed.
  10621. * @param $x (int) abscissa of the scaling center. Default is current x position
  10622. * @param $y (int) ordinate of the scaling center. Default is current y position
  10623. * @public
  10624. * @since 2.1.000 (2008-01-07)
  10625. * @see StartTransform(), StopTransform()
  10626. */
  10627. public function ScaleY($s_y, $x='', $y='') {
  10628. $this->Scale(100, $s_y, $x, $y);
  10629. }
  10630. /**
  10631. * Vertical and horizontal proportional Scaling.
  10632. * @param $s (float) scaling factor for width and height as percent. 0 is not allowed.
  10633. * @param $x (int) abscissa of the scaling center. Default is current x position
  10634. * @param $y (int) ordinate of the scaling center. Default is current y position
  10635. * @public
  10636. * @since 2.1.000 (2008-01-07)
  10637. * @see StartTransform(), StopTransform()
  10638. */
  10639. public function ScaleXY($s, $x='', $y='') {
  10640. $this->Scale($s, $s, $x, $y);
  10641. }
  10642. /**
  10643. * Vertical and horizontal non-proportional Scaling.
  10644. * @param $s_x (float) scaling factor for width as percent. 0 is not allowed.
  10645. * @param $s_y (float) scaling factor for height as percent. 0 is not allowed.
  10646. * @param $x (int) abscissa of the scaling center. Default is current x position
  10647. * @param $y (int) ordinate of the scaling center. Default is current y position
  10648. * @public
  10649. * @since 2.1.000 (2008-01-07)
  10650. * @see StartTransform(), StopTransform()
  10651. */
  10652. public function Scale($s_x, $s_y, $x='', $y='') {
  10653. if ($x === '') {
  10654. $x = $this->x;
  10655. }
  10656. if ($y === '') {
  10657. $y = $this->y;
  10658. }
  10659. if (($s_x == 0) OR ($s_y == 0)) {
  10660. $this->Error('Please do not use values equal to zero for scaling');
  10661. }
  10662. $y = ($this->h - $y) * $this->k;
  10663. $x *= $this->k;
  10664. //calculate elements of transformation matrix
  10665. $s_x /= 100;
  10666. $s_y /= 100;
  10667. $tm = array();
  10668. $tm[0] = $s_x;
  10669. $tm[1] = 0;
  10670. $tm[2] = 0;
  10671. $tm[3] = $s_y;
  10672. $tm[4] = $x * (1 - $s_x);
  10673. $tm[5] = $y * (1 - $s_y);
  10674. //scale the coordinate system
  10675. $this->Transform($tm);
  10676. }
  10677. /**
  10678. * Horizontal Mirroring.
  10679. * @param $x (int) abscissa of the point. Default is current x position
  10680. * @public
  10681. * @since 2.1.000 (2008-01-07)
  10682. * @see StartTransform(), StopTransform()
  10683. */
  10684. public function MirrorH($x='') {
  10685. $this->Scale(-100, 100, $x);
  10686. }
  10687. /**
  10688. * Verical Mirroring.
  10689. * @param $y (int) ordinate of the point. Default is current y position
  10690. * @public
  10691. * @since 2.1.000 (2008-01-07)
  10692. * @see StartTransform(), StopTransform()
  10693. */
  10694. public function MirrorV($y='') {
  10695. $this->Scale(100, -100, '', $y);
  10696. }
  10697. /**
  10698. * Point reflection mirroring.
  10699. * @param $x (int) abscissa of the point. Default is current x position
  10700. * @param $y (int) ordinate of the point. Default is current y position
  10701. * @public
  10702. * @since 2.1.000 (2008-01-07)
  10703. * @see StartTransform(), StopTransform()
  10704. */
  10705. public function MirrorP($x='',$y='') {
  10706. $this->Scale(-100, -100, $x, $y);
  10707. }
  10708. /**
  10709. * Reflection against a straight line through point (x, y) with the gradient angle (angle).
  10710. * @param $angle (float) gradient angle of the straight line. Default is 0 (horizontal line).
  10711. * @param $x (int) abscissa of the point. Default is current x position
  10712. * @param $y (int) ordinate of the point. Default is current y position
  10713. * @public
  10714. * @since 2.1.000 (2008-01-07)
  10715. * @see StartTransform(), StopTransform()
  10716. */
  10717. public function MirrorL($angle=0, $x='',$y='') {
  10718. $this->Scale(-100, 100, $x, $y);
  10719. $this->Rotate(-2*($angle-90), $x, $y);
  10720. }
  10721. /**
  10722. * Translate graphic object horizontally.
  10723. * @param $t_x (int) movement to the right (or left for RTL)
  10724. * @public
  10725. * @since 2.1.000 (2008-01-07)
  10726. * @see StartTransform(), StopTransform()
  10727. */
  10728. public function TranslateX($t_x) {
  10729. $this->Translate($t_x, 0);
  10730. }
  10731. /**
  10732. * Translate graphic object vertically.
  10733. * @param $t_y (int) movement to the bottom
  10734. * @public
  10735. * @since 2.1.000 (2008-01-07)
  10736. * @see StartTransform(), StopTransform()
  10737. */
  10738. public function TranslateY($t_y) {
  10739. $this->Translate(0, $t_y);
  10740. }
  10741. /**
  10742. * Translate graphic object horizontally and vertically.
  10743. * @param $t_x (int) movement to the right
  10744. * @param $t_y (int) movement to the bottom
  10745. * @public
  10746. * @since 2.1.000 (2008-01-07)
  10747. * @see StartTransform(), StopTransform()
  10748. */
  10749. public function Translate($t_x, $t_y) {
  10750. //calculate elements of transformation matrix
  10751. $tm = array();
  10752. $tm[0] = 1;
  10753. $tm[1] = 0;
  10754. $tm[2] = 0;
  10755. $tm[3] = 1;
  10756. $tm[4] = $t_x * $this->k;
  10757. $tm[5] = -$t_y * $this->k;
  10758. //translate the coordinate system
  10759. $this->Transform($tm);
  10760. }
  10761. /**
  10762. * Rotate object.
  10763. * @param $angle (float) angle in degrees for counter-clockwise rotation
  10764. * @param $x (int) abscissa of the rotation center. Default is current x position
  10765. * @param $y (int) ordinate of the rotation center. Default is current y position
  10766. * @public
  10767. * @since 2.1.000 (2008-01-07)
  10768. * @see StartTransform(), StopTransform()
  10769. */
  10770. public function Rotate($angle, $x='', $y='') {
  10771. if ($x === '') {
  10772. $x = $this->x;
  10773. }
  10774. if ($y === '') {
  10775. $y = $this->y;
  10776. }
  10777. $y = ($this->h - $y) * $this->k;
  10778. $x *= $this->k;
  10779. //calculate elements of transformation matrix
  10780. $tm = array();
  10781. $tm[0] = cos(deg2rad($angle));
  10782. $tm[1] = sin(deg2rad($angle));
  10783. $tm[2] = -$tm[1];
  10784. $tm[3] = $tm[0];
  10785. $tm[4] = $x + ($tm[1] * $y) - ($tm[0] * $x);
  10786. $tm[5] = $y - ($tm[0] * $y) - ($tm[1] * $x);
  10787. //rotate the coordinate system around ($x,$y)
  10788. $this->Transform($tm);
  10789. }
  10790. /**
  10791. * Skew horizontally.
  10792. * @param $angle_x (float) angle in degrees between -90 (skew to the left) and 90 (skew to the right)
  10793. * @param $x (int) abscissa of the skewing center. default is current x position
  10794. * @param $y (int) ordinate of the skewing center. default is current y position
  10795. * @public
  10796. * @since 2.1.000 (2008-01-07)
  10797. * @see StartTransform(), StopTransform()
  10798. */
  10799. public function SkewX($angle_x, $x='', $y='') {
  10800. $this->Skew($angle_x, 0, $x, $y);
  10801. }
  10802. /**
  10803. * Skew vertically.
  10804. * @param $angle_y (float) angle in degrees between -90 (skew to the bottom) and 90 (skew to the top)
  10805. * @param $x (int) abscissa of the skewing center. default is current x position
  10806. * @param $y (int) ordinate of the skewing center. default is current y position
  10807. * @public
  10808. * @since 2.1.000 (2008-01-07)
  10809. * @see StartTransform(), StopTransform()
  10810. */
  10811. public function SkewY($angle_y, $x='', $y='') {
  10812. $this->Skew(0, $angle_y, $x, $y);
  10813. }
  10814. /**
  10815. * Skew.
  10816. * @param $angle_x (float) angle in degrees between -90 (skew to the left) and 90 (skew to the right)
  10817. * @param $angle_y (float) angle in degrees between -90 (skew to the bottom) and 90 (skew to the top)
  10818. * @param $x (int) abscissa of the skewing center. default is current x position
  10819. * @param $y (int) ordinate of the skewing center. default is current y position
  10820. * @public
  10821. * @since 2.1.000 (2008-01-07)
  10822. * @see StartTransform(), StopTransform()
  10823. */
  10824. public function Skew($angle_x, $angle_y, $x='', $y='') {
  10825. if ($x === '') {
  10826. $x = $this->x;
  10827. }
  10828. if ($y === '') {
  10829. $y = $this->y;
  10830. }
  10831. if (($angle_x <= -90) OR ($angle_x >= 90) OR ($angle_y <= -90) OR ($angle_y >= 90)) {
  10832. $this->Error('Please use values between -90 and +90 degrees for Skewing.');
  10833. }
  10834. $x *= $this->k;
  10835. $y = ($this->h - $y) * $this->k;
  10836. //calculate elements of transformation matrix
  10837. $tm = array();
  10838. $tm[0] = 1;
  10839. $tm[1] = tan(deg2rad($angle_y));
  10840. $tm[2] = tan(deg2rad($angle_x));
  10841. $tm[3] = 1;
  10842. $tm[4] = -$tm[2] * $y;
  10843. $tm[5] = -$tm[1] * $x;
  10844. //skew the coordinate system
  10845. $this->Transform($tm);
  10846. }
  10847. /**
  10848. * Apply graphic transformations.
  10849. * @param $tm (array) transformation matrix
  10850. * @protected
  10851. * @since 2.1.000 (2008-01-07)
  10852. * @see StartTransform(), StopTransform()
  10853. */
  10854. protected function Transform($tm) {
  10855. if ($this->state != 2) {
  10856. return;
  10857. }
  10858. $this->_out(sprintf('%F %F %F %F %F %F cm', $tm[0], $tm[1], $tm[2], $tm[3], $tm[4], $tm[5]));
  10859. // add tranformation matrix
  10860. $this->transfmatrix[$this->transfmatrix_key][] = array('a' => $tm[0], 'b' => $tm[1], 'c' => $tm[2], 'd' => $tm[3], 'e' => $tm[4], 'f' => $tm[5]);
  10861. // update transformation mark
  10862. if ($this->inxobj) {
  10863. // we are inside an XObject template
  10864. if (end($this->xobjects[$this->xobjid]['transfmrk']) !== false) {
  10865. $key = key($this->xobjects[$this->xobjid]['transfmrk']);
  10866. $this->xobjects[$this->xobjid]['transfmrk'][$key] = strlen($this->xobjects[$this->xobjid]['outdata']);
  10867. }
  10868. } elseif (end($this->transfmrk[$this->page]) !== false) {
  10869. $key = key($this->transfmrk[$this->page]);
  10870. $this->transfmrk[$this->page][$key] = $this->pagelen[$this->page];
  10871. }
  10872. }
  10873. // END TRANSFORMATIONS SECTION -------------------------
  10874. // START GRAPHIC FUNCTIONS SECTION ---------------------
  10875. // The following section is based on the code provided by David Hernandez Sanz
  10876. /**
  10877. * 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.
  10878. * @param $width (float) The width.
  10879. * @public
  10880. * @since 1.0
  10881. * @see Line(), Rect(), Cell(), MultiCell()
  10882. */
  10883. public function SetLineWidth($width) {
  10884. //Set line width
  10885. $this->LineWidth = $width;
  10886. $this->linestyleWidth = sprintf('%F w', ($width * $this->k));
  10887. if ($this->state == 2) {
  10888. $this->_out($this->linestyleWidth);
  10889. }
  10890. }
  10891. /**
  10892. * Returns the current the line width.
  10893. * @return int Line width
  10894. * @public
  10895. * @since 2.1.000 (2008-01-07)
  10896. * @see Line(), SetLineWidth()
  10897. */
  10898. public function GetLineWidth() {
  10899. return $this->LineWidth;
  10900. }
  10901. /**
  10902. * Set line style.
  10903. * @param $style (array) Line style. Array with keys among the following:
  10904. * <ul>
  10905. * <li>width (float): Width of the line in user units.</li>
  10906. * <li>cap (string): Type of cap to put on the line. Possible values are:
  10907. * butt, round, square. The difference between "square" and "butt" is that
  10908. * "square" projects a flat end past the end of the line.</li>
  10909. * <li>join (string): Type of join. Possible values are: miter, round,
  10910. * bevel.</li>
  10911. * <li>dash (mixed): Dash pattern. Is 0 (without dash) or string with
  10912. * series of length values, which are the lengths of the on and off dashes.
  10913. * For example: "2" represents 2 on, 2 off, 2 on, 2 off, ...; "2,1" is 2 on,
  10914. * 1 off, 2 on, 1 off, ...</li>
  10915. * <li>phase (integer): Modifier on the dash pattern which is used to shift
  10916. * the point at which the pattern starts.</li>
  10917. * <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>
  10918. * </ul>
  10919. * @param $ret (boolean) if true do not send the command.
  10920. * @return string the PDF command
  10921. * @public
  10922. * @since 2.1.000 (2008-01-08)
  10923. */
  10924. public function SetLineStyle($style, $ret=false) {
  10925. $s = ''; // string to be returned
  10926. if (!is_array($style)) {
  10927. return;
  10928. }
  10929. if (isset($style['width'])) {
  10930. $this->LineWidth = $style['width'];
  10931. $this->linestyleWidth = sprintf('%F w', ($style['width'] * $this->k));
  10932. $s .= $this->linestyleWidth.' ';
  10933. }
  10934. if (isset($style['cap'])) {
  10935. $ca = array('butt' => 0, 'round'=> 1, 'square' => 2);
  10936. if (isset($ca[$style['cap']])) {
  10937. $this->linestyleCap = $ca[$style['cap']].' J';
  10938. $s .= $this->linestyleCap.' ';
  10939. }
  10940. }
  10941. if (isset($style['join'])) {
  10942. $ja = array('miter' => 0, 'round' => 1, 'bevel' => 2);
  10943. if (isset($ja[$style['join']])) {
  10944. $this->linestyleJoin = $ja[$style['join']].' j';
  10945. $s .= $this->linestyleJoin.' ';
  10946. }
  10947. }
  10948. if (isset($style['dash'])) {
  10949. $dash_string = '';
  10950. if ($style['dash']) {
  10951. if (preg_match('/^.+,/', $style['dash']) > 0) {
  10952. $tab = explode(',', $style['dash']);
  10953. } else {
  10954. $tab = array($style['dash']);
  10955. }
  10956. $dash_string = '';
  10957. foreach ($tab as $i => $v) {
  10958. if ($i) {
  10959. $dash_string .= ' ';
  10960. }
  10961. $dash_string .= sprintf('%F', $v);
  10962. }
  10963. }
  10964. if (!isset($style['phase']) OR !$style['dash']) {
  10965. $style['phase'] = 0;
  10966. }
  10967. $this->linestyleDash = sprintf('[%s] %F d', $dash_string, $style['phase']);
  10968. $s .= $this->linestyleDash.' ';
  10969. }
  10970. if (isset($style['color'])) {
  10971. $s .= $this->SetDrawColorArray($style['color'], true).' ';
  10972. }
  10973. if (!$ret AND ($this->state == 2)) {
  10974. $this->_out($s);
  10975. }
  10976. return $s;
  10977. }
  10978. /**
  10979. * Begin a new subpath by moving the current point to coordinates (x, y), omitting any connecting line segment.
  10980. * @param $x (float) Abscissa of point.
  10981. * @param $y (float) Ordinate of point.
  10982. * @protected
  10983. * @since 2.1.000 (2008-01-08)
  10984. */
  10985. protected function _outPoint($x, $y) {
  10986. if ($this->state == 2) {
  10987. $this->_out(sprintf('%F %F m', ($x * $this->k), (($this->h - $y) * $this->k)));
  10988. }
  10989. }
  10990. /**
  10991. * Append a straight line segment from the current point to the point (x, y).
  10992. * The new current point shall be (x, y).
  10993. * @param $x (float) Abscissa of end point.
  10994. * @param $y (float) Ordinate of end point.
  10995. * @protected
  10996. * @since 2.1.000 (2008-01-08)
  10997. */
  10998. protected function _outLine($x, $y) {
  10999. if ($this->state == 2) {
  11000. $this->_out(sprintf('%F %F l', ($x * $this->k), (($this->h - $y) * $this->k)));
  11001. }
  11002. }
  11003. /**
  11004. * Append a rectangle to the current path as a complete subpath, with lower-left corner (x, y) and dimensions widthand height in user space.
  11005. * @param $x (float) Abscissa of upper-left corner.
  11006. * @param $y (float) Ordinate of upper-left corner.
  11007. * @param $w (float) Width.
  11008. * @param $h (float) Height.
  11009. * @param $op (string) options
  11010. * @protected
  11011. * @since 2.1.000 (2008-01-08)
  11012. */
  11013. protected function _outRect($x, $y, $w, $h, $op) {
  11014. if ($this->state == 2) {
  11015. $this->_out(sprintf('%F %F %F %F re %s', ($x * $this->k), (($this->h - $y) * $this->k), ($w * $this->k), (-$h * $this->k), $op));
  11016. }
  11017. }
  11018. /**
  11019. * 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.
  11020. * The new current point shall be (x3, y3).
  11021. * @param $x1 (float) Abscissa of control point 1.
  11022. * @param $y1 (float) Ordinate of control point 1.
  11023. * @param $x2 (float) Abscissa of control point 2.
  11024. * @param $y2 (float) Ordinate of control point 2.
  11025. * @param $x3 (float) Abscissa of end point.
  11026. * @param $y3 (float) Ordinate of end point.
  11027. * @protected
  11028. * @since 2.1.000 (2008-01-08)
  11029. */
  11030. protected function _outCurve($x1, $y1, $x2, $y2, $x3, $y3) {
  11031. if ($this->state == 2) {
  11032. $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)));
  11033. }
  11034. }
  11035. /**
  11036. * 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.
  11037. * The new current point shall be (x3, y3).
  11038. * @param $x2 (float) Abscissa of control point 2.
  11039. * @param $y2 (float) Ordinate of control point 2.
  11040. * @param $x3 (float) Abscissa of end point.
  11041. * @param $y3 (float) Ordinate of end point.
  11042. * @protected
  11043. * @since 4.9.019 (2010-04-26)
  11044. */
  11045. protected function _outCurveV($x2, $y2, $x3, $y3) {
  11046. if ($this->state == 2) {
  11047. $this->_out(sprintf('%F %F %F %F v', ($x2 * $this->k), (($this->h - $y2) * $this->k), ($x3 * $this->k), (($this->h - $y3) * $this->k)));
  11048. }
  11049. }
  11050. /**
  11051. * 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.
  11052. * The new current point shall be (x3, y3).
  11053. * @param $x1 (float) Abscissa of control point 1.
  11054. * @param $y1 (float) Ordinate of control point 1.
  11055. * @param $x3 (float) Abscissa of end point.
  11056. * @param $y3 (float) Ordinate of end point.
  11057. * @protected
  11058. * @since 2.1.000 (2008-01-08)
  11059. */
  11060. protected function _outCurveY($x1, $y1, $x3, $y3) {
  11061. if ($this->state == 2) {
  11062. $this->_out(sprintf('%F %F %F %F y', ($x1 * $this->k), (($this->h - $y1) * $this->k), ($x3 * $this->k), (($this->h - $y3) * $this->k)));
  11063. }
  11064. }
  11065. /**
  11066. * Draws a line between two points.
  11067. * @param $x1 (float) Abscissa of first point.
  11068. * @param $y1 (float) Ordinate of first point.
  11069. * @param $x2 (float) Abscissa of second point.
  11070. * @param $y2 (float) Ordinate of second point.
  11071. * @param $style (array) Line style. Array like for SetLineStyle(). Default value: default line style (empty array).
  11072. * @public
  11073. * @since 1.0
  11074. * @see SetLineWidth(), SetDrawColor(), SetLineStyle()
  11075. */
  11076. public function Line($x1, $y1, $x2, $y2, $style=array()) {
  11077. if ($this->state != 2) {
  11078. return;
  11079. }
  11080. if (is_array($style)) {
  11081. $this->SetLineStyle($style);
  11082. }
  11083. $this->_outPoint($x1, $y1);
  11084. $this->_outLine($x2, $y2);
  11085. $this->_out('S');
  11086. }
  11087. /**
  11088. * Draws a rectangle.
  11089. * @param $x (float) Abscissa of upper-left corner.
  11090. * @param $y (float) Ordinate of upper-left corner.
  11091. * @param $w (float) Width.
  11092. * @param $h (float) Height.
  11093. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  11094. * @param $border_style (array) Border style of rectangle. Array with keys among the following:
  11095. * <ul>
  11096. * <li>all: Line style of all borders. Array like for SetLineStyle().</li>
  11097. * <li>L, T, R, B or combinations: Line style of left, top, right or bottom border. Array like for SetLineStyle().</li>
  11098. * </ul>
  11099. * If a key is not present or is null, the correspondent border is not drawn. Default value: default line style (empty array).
  11100. * @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).
  11101. * @public
  11102. * @since 1.0
  11103. * @see SetLineStyle()
  11104. */
  11105. public function Rect($x, $y, $w, $h, $style='', $border_style=array(), $fill_color=array()) {
  11106. if ($this->state != 2) {
  11107. return;
  11108. }
  11109. if (empty($style)) {
  11110. $style = 'S';
  11111. }
  11112. if (!(strpos($style, 'F') === false) AND !empty($fill_color)) {
  11113. // set background color
  11114. $this->SetFillColorArray($fill_color);
  11115. }
  11116. if (!empty($border_style)) {
  11117. if (isset($border_style['all']) AND !empty($border_style['all'])) {
  11118. //set global style for border
  11119. $this->SetLineStyle($border_style['all']);
  11120. $border_style = array();
  11121. } else {
  11122. // remove stroke operator from style
  11123. $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*' );
  11124. if (isset($opnostroke[$style])) {
  11125. $style = $opnostroke[$style];
  11126. }
  11127. }
  11128. }
  11129. if (!empty($style)) {
  11130. $op = TCPDF_STATIC::getPathPaintOperator($style);
  11131. $this->_outRect($x, $y, $w, $h, $op);
  11132. }
  11133. if (!empty($border_style)) {
  11134. $border_style2 = array();
  11135. foreach ($border_style as $line => $value) {
  11136. $length = strlen($line);
  11137. for ($i = 0; $i < $length; ++$i) {
  11138. $border_style2[$line[$i]] = $value;
  11139. }
  11140. }
  11141. $border_style = $border_style2;
  11142. if (isset($border_style['L']) AND $border_style['L']) {
  11143. $this->Line($x, $y, $x, $y + $h, $border_style['L']);
  11144. }
  11145. if (isset($border_style['T']) AND $border_style['T']) {
  11146. $this->Line($x, $y, $x + $w, $y, $border_style['T']);
  11147. }
  11148. if (isset($border_style['R']) AND $border_style['R']) {
  11149. $this->Line($x + $w, $y, $x + $w, $y + $h, $border_style['R']);
  11150. }
  11151. if (isset($border_style['B']) AND $border_style['B']) {
  11152. $this->Line($x, $y + $h, $x + $w, $y + $h, $border_style['B']);
  11153. }
  11154. }
  11155. }
  11156. /**
  11157. * Draws a Bezier curve.
  11158. * The Bezier curve is a tangent to the line between the control points at
  11159. * either end of the curve.
  11160. * @param $x0 (float) Abscissa of start point.
  11161. * @param $y0 (float) Ordinate of start point.
  11162. * @param $x1 (float) Abscissa of control point 1.
  11163. * @param $y1 (float) Ordinate of control point 1.
  11164. * @param $x2 (float) Abscissa of control point 2.
  11165. * @param $y2 (float) Ordinate of control point 2.
  11166. * @param $x3 (float) Abscissa of end point.
  11167. * @param $y3 (float) Ordinate of end point.
  11168. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  11169. * @param $line_style (array) Line style of curve. Array like for SetLineStyle(). Default value: default line style (empty array).
  11170. * @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).
  11171. * @public
  11172. * @see SetLineStyle()
  11173. * @since 2.1.000 (2008-01-08)
  11174. */
  11175. public function Curve($x0, $y0, $x1, $y1, $x2, $y2, $x3, $y3, $style='', $line_style=array(), $fill_color=array()) {
  11176. if ($this->state != 2) {
  11177. return;
  11178. }
  11179. if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
  11180. $this->SetFillColorArray($fill_color);
  11181. }
  11182. $op = TCPDF_STATIC::getPathPaintOperator($style);
  11183. if ($line_style) {
  11184. $this->SetLineStyle($line_style);
  11185. }
  11186. $this->_outPoint($x0, $y0);
  11187. $this->_outCurve($x1, $y1, $x2, $y2, $x3, $y3);
  11188. $this->_out($op);
  11189. }
  11190. /**
  11191. * Draws a poly-Bezier curve.
  11192. * Each Bezier curve segment is a tangent to the line between the control points at
  11193. * either end of the curve.
  11194. * @param $x0 (float) Abscissa of start point.
  11195. * @param $y0 (float) Ordinate of start point.
  11196. * @param $segments (float) An array of bezier descriptions. Format: array(x1, y1, x2, y2, x3, y3).
  11197. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  11198. * @param $line_style (array) Line style of curve. Array like for SetLineStyle(). Default value: default line style (empty array).
  11199. * @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).
  11200. * @public
  11201. * @see SetLineStyle()
  11202. * @since 3.0008 (2008-05-12)
  11203. */
  11204. public function Polycurve($x0, $y0, $segments, $style='', $line_style=array(), $fill_color=array()) {
  11205. if ($this->state != 2) {
  11206. return;
  11207. }
  11208. if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
  11209. $this->SetFillColorArray($fill_color);
  11210. }
  11211. $op = TCPDF_STATIC::getPathPaintOperator($style);
  11212. if ($op == 'f') {
  11213. $line_style = array();
  11214. }
  11215. if ($line_style) {
  11216. $this->SetLineStyle($line_style);
  11217. }
  11218. $this->_outPoint($x0, $y0);
  11219. foreach ($segments as $segment) {
  11220. list($x1, $y1, $x2, $y2, $x3, $y3) = $segment;
  11221. $this->_outCurve($x1, $y1, $x2, $y2, $x3, $y3);
  11222. }
  11223. $this->_out($op);
  11224. }
  11225. /**
  11226. * Draws an ellipse.
  11227. * An ellipse is formed from n Bezier curves.
  11228. * @param $x0 (float) Abscissa of center point.
  11229. * @param $y0 (float) Ordinate of center point.
  11230. * @param $rx (float) Horizontal radius.
  11231. * @param $ry (float) Vertical radius (if ry = 0 then is a circle, see Circle()). Default value: 0.
  11232. * @param $angle: (float) Angle oriented (anti-clockwise). Default value: 0.
  11233. * @param $astart: (float) Angle start of draw line. Default value: 0.
  11234. * @param $afinish: (float) Angle finish of draw line. Default value: 360.
  11235. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  11236. * @param $line_style (array) Line style of ellipse. Array like for SetLineStyle(). Default value: default line style (empty array).
  11237. * @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).
  11238. * @param $nc (integer) Number of curves used to draw a 90 degrees portion of ellipse.
  11239. * @author Nicola Asuni
  11240. * @public
  11241. * @since 2.1.000 (2008-01-08)
  11242. */
  11243. public function Ellipse($x0, $y0, $rx, $ry='', $angle=0, $astart=0, $afinish=360, $style='', $line_style=array(), $fill_color=array(), $nc=2) {
  11244. if ($this->state != 2) {
  11245. return;
  11246. }
  11247. if (TCPDF_STATIC::empty_string($ry) OR ($ry == 0)) {
  11248. $ry = $rx;
  11249. }
  11250. if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
  11251. $this->SetFillColorArray($fill_color);
  11252. }
  11253. $op = TCPDF_STATIC::getPathPaintOperator($style);
  11254. if ($op == 'f') {
  11255. $line_style = array();
  11256. }
  11257. if ($line_style) {
  11258. $this->SetLineStyle($line_style);
  11259. }
  11260. $this->_outellipticalarc($x0, $y0, $rx, $ry, $angle, $astart, $afinish, false, $nc, true, true, false);
  11261. $this->_out($op);
  11262. }
  11263. /**
  11264. * Append an elliptical arc to the current path.
  11265. * An ellipse is formed from n Bezier curves.
  11266. * @param $xc (float) Abscissa of center point.
  11267. * @param $yc (float) Ordinate of center point.
  11268. * @param $rx (float) Horizontal radius.
  11269. * @param $ry (float) Vertical radius (if ry = 0 then is a circle, see Circle()). Default value: 0.
  11270. * @param $xang: (float) Angle between the X-axis and the major axis of the ellipse. Default value: 0.
  11271. * @param $angs: (float) Angle start of draw line. Default value: 0.
  11272. * @param $angf: (float) Angle finish of draw line. Default value: 360.
  11273. * @param $pie (boolean) if true do not mark the border point (used to draw pie sectors).
  11274. * @param $nc (integer) Number of curves used to draw a 90 degrees portion of ellipse.
  11275. * @param $startpoint (boolean) if true output a starting point.
  11276. * @param $ccw (boolean) if true draws in counter-clockwise.
  11277. * @param $svg (boolean) if true the angles are in svg mode (already calculated).
  11278. * @return array bounding box coordinates (x min, y min, x max, y max)
  11279. * @author Nicola Asuni
  11280. * @protected
  11281. * @since 4.9.019 (2010-04-26)
  11282. */
  11283. protected function _outellipticalarc($xc, $yc, $rx, $ry, $xang=0, $angs=0, $angf=360, $pie=false, $nc=2, $startpoint=true, $ccw=true, $svg=false) {
  11284. if (($rx <= 0) OR ($ry < 0)) {
  11285. return;
  11286. }
  11287. $k = $this->k;
  11288. if ($nc < 2) {
  11289. $nc = 2;
  11290. }
  11291. $xmin = 2147483647;
  11292. $ymin = 2147483647;
  11293. $xmax = 0;
  11294. $ymax = 0;
  11295. if ($pie) {
  11296. // center of the arc
  11297. $this->_outPoint($xc, $yc);
  11298. }
  11299. $xang = deg2rad((float) $xang);
  11300. $angs = deg2rad((float) $angs);
  11301. $angf = deg2rad((float) $angf);
  11302. if ($svg) {
  11303. $as = $angs;
  11304. $af = $angf;
  11305. } else {
  11306. $as = atan2((sin($angs) / $ry), (cos($angs) / $rx));
  11307. $af = atan2((sin($angf) / $ry), (cos($angf) / $rx));
  11308. }
  11309. if ($as < 0) {
  11310. $as += (2 * M_PI);
  11311. }
  11312. if ($af < 0) {
  11313. $af += (2 * M_PI);
  11314. }
  11315. if ($ccw AND ($as > $af)) {
  11316. // reverse rotation
  11317. $as -= (2 * M_PI);
  11318. } elseif (!$ccw AND ($as < $af)) {
  11319. // reverse rotation
  11320. $af -= (2 * M_PI);
  11321. }
  11322. $total_angle = ($af - $as);
  11323. if ($nc < 2) {
  11324. $nc = 2;
  11325. }
  11326. // total arcs to draw
  11327. $nc *= (2 * abs($total_angle) / M_PI);
  11328. $nc = round($nc) + 1;
  11329. // angle of each arc
  11330. $arcang = ($total_angle / $nc);
  11331. // center point in PDF coordinates
  11332. $x0 = $xc;
  11333. $y0 = ($this->h - $yc);
  11334. // starting angle
  11335. $ang = $as;
  11336. $alpha = sin($arcang) * ((sqrt(4 + (3 * pow(tan(($arcang) / 2), 2))) - 1) / 3);
  11337. $cos_xang = cos($xang);
  11338. $sin_xang = sin($xang);
  11339. $cos_ang = cos($ang);
  11340. $sin_ang = sin($ang);
  11341. // first arc point
  11342. $px1 = $x0 + ($rx * $cos_xang * $cos_ang) - ($ry * $sin_xang * $sin_ang);
  11343. $py1 = $y0 + ($rx * $sin_xang * $cos_ang) + ($ry * $cos_xang * $sin_ang);
  11344. // first Bezier control point
  11345. $qx1 = ($alpha * ((-$rx * $cos_xang * $sin_ang) - ($ry * $sin_xang * $cos_ang)));
  11346. $qy1 = ($alpha * ((-$rx * $sin_xang * $sin_ang) + ($ry * $cos_xang * $cos_ang)));
  11347. if ($pie) {
  11348. // line from center to arc starting point
  11349. $this->_outLine($px1, $this->h - $py1);
  11350. } elseif ($startpoint) {
  11351. // arc starting point
  11352. $this->_outPoint($px1, $this->h - $py1);
  11353. }
  11354. // draw arcs
  11355. for ($i = 1; $i <= $nc; ++$i) {
  11356. // starting angle
  11357. $ang = $as + ($i * $arcang);
  11358. if ($i == $nc) {
  11359. $ang = $af;
  11360. }
  11361. $cos_ang = cos($ang);
  11362. $sin_ang = sin($ang);
  11363. // second arc point
  11364. $px2 = $x0 + ($rx * $cos_xang * $cos_ang) - ($ry * $sin_xang * $sin_ang);
  11365. $py2 = $y0 + ($rx * $sin_xang * $cos_ang) + ($ry * $cos_xang * $sin_ang);
  11366. // second Bezier control point
  11367. $qx2 = ($alpha * ((-$rx * $cos_xang * $sin_ang) - ($ry * $sin_xang * $cos_ang)));
  11368. $qy2 = ($alpha * ((-$rx * $sin_xang * $sin_ang) + ($ry * $cos_xang * $cos_ang)));
  11369. // draw arc
  11370. $cx1 = ($px1 + $qx1);
  11371. $cy1 = ($this->h - ($py1 + $qy1));
  11372. $cx2 = ($px2 - $qx2);
  11373. $cy2 = ($this->h - ($py2 - $qy2));
  11374. $cx3 = $px2;
  11375. $cy3 = ($this->h - $py2);
  11376. $this->_outCurve($cx1, $cy1, $cx2, $cy2, $cx3, $cy3);
  11377. // get bounding box coordinates
  11378. $xmin = min($xmin, $cx1, $cx2, $cx3);
  11379. $ymin = min($ymin, $cy1, $cy2, $cy3);
  11380. $xmax = max($xmax, $cx1, $cx2, $cx3);
  11381. $ymax = max($ymax, $cy1, $cy2, $cy3);
  11382. // move to next point
  11383. $px1 = $px2;
  11384. $py1 = $py2;
  11385. $qx1 = $qx2;
  11386. $qy1 = $qy2;
  11387. }
  11388. if ($pie) {
  11389. $this->_outLine($xc, $yc);
  11390. // get bounding box coordinates
  11391. $xmin = min($xmin, $xc);
  11392. $ymin = min($ymin, $yc);
  11393. $xmax = max($xmax, $xc);
  11394. $ymax = max($ymax, $yc);
  11395. }
  11396. return array($xmin, $ymin, $xmax, $ymax);
  11397. }
  11398. /**
  11399. * Draws a circle.
  11400. * A circle is formed from n Bezier curves.
  11401. * @param $x0 (float) Abscissa of center point.
  11402. * @param $y0 (float) Ordinate of center point.
  11403. * @param $r (float) Radius.
  11404. * @param $angstr: (float) Angle start of draw line. Default value: 0.
  11405. * @param $angend: (float) Angle finish of draw line. Default value: 360.
  11406. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  11407. * @param $line_style (array) Line style of circle. Array like for SetLineStyle(). Default value: default line style (empty array).
  11408. * @param $fill_color (array) Fill color. Format: array(red, green, blue). Default value: default color (empty array).
  11409. * @param $nc (integer) Number of curves used to draw a 90 degrees portion of circle.
  11410. * @public
  11411. * @since 2.1.000 (2008-01-08)
  11412. */
  11413. public function Circle($x0, $y0, $r, $angstr=0, $angend=360, $style='', $line_style=array(), $fill_color=array(), $nc=2) {
  11414. $this->Ellipse($x0, $y0, $r, $r, 0, $angstr, $angend, $style, $line_style, $fill_color, $nc);
  11415. }
  11416. /**
  11417. * Draws a polygonal line
  11418. * @param $p (array) Points 0 to ($np - 1). Array with values (x0, y0, x1, y1,..., x(np-1), y(np - 1))
  11419. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  11420. * @param $line_style (array) Line style of polygon. Array with keys among the following:
  11421. * <ul>
  11422. * <li>all: Line style of all lines. Array like for SetLineStyle().</li>
  11423. * <li>0 to ($np - 1): Line style of each line. Array like for SetLineStyle().</li>
  11424. * </ul>
  11425. * If a key is not present or is null, not draws the line. Default value is default line style (empty array).
  11426. * @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).
  11427. * @since 4.8.003 (2009-09-15)
  11428. * @public
  11429. */
  11430. public function PolyLine($p, $style='', $line_style=array(), $fill_color=array()) {
  11431. $this->Polygon($p, $style, $line_style, $fill_color, false);
  11432. }
  11433. /**
  11434. * Draws a polygon.
  11435. * @param $p (array) Points 0 to ($np - 1). Array with values (x0, y0, x1, y1,..., x(np-1), y(np - 1))
  11436. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  11437. * @param $line_style (array) Line style of polygon. Array with keys among the following:
  11438. * <ul>
  11439. * <li>all: Line style of all lines. Array like for SetLineStyle().</li>
  11440. * <li>0 to ($np - 1): Line style of each line. Array like for SetLineStyle().</li>
  11441. * </ul>
  11442. * If a key is not present or is null, not draws the line. Default value is default line style (empty array).
  11443. * @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).
  11444. * @param $closed (boolean) if true the polygon is closes, otherwise will remain open
  11445. * @public
  11446. * @since 2.1.000 (2008-01-08)
  11447. */
  11448. public function Polygon($p, $style='', $line_style=array(), $fill_color=array(), $closed=true) {
  11449. if ($this->state != 2) {
  11450. return;
  11451. }
  11452. $nc = count($p); // number of coordinates
  11453. $np = $nc / 2; // number of points
  11454. if ($closed) {
  11455. // close polygon by adding the first 2 points at the end (one line)
  11456. for ($i = 0; $i < 4; ++$i) {
  11457. $p[$nc + $i] = $p[$i];
  11458. }
  11459. // copy style for the last added line
  11460. if (isset($line_style[0])) {
  11461. $line_style[$np] = $line_style[0];
  11462. }
  11463. $nc += 4;
  11464. }
  11465. if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
  11466. $this->SetFillColorArray($fill_color);
  11467. }
  11468. $op = TCPDF_STATIC::getPathPaintOperator($style);
  11469. if ($op == 'f') {
  11470. $line_style = array();
  11471. }
  11472. $draw = true;
  11473. if ($line_style) {
  11474. if (isset($line_style['all'])) {
  11475. $this->SetLineStyle($line_style['all']);
  11476. } else {
  11477. $draw = false;
  11478. if ($op == 'B') {
  11479. // draw fill
  11480. $op = 'f';
  11481. $this->_outPoint($p[0], $p[1]);
  11482. for ($i = 2; $i < $nc; $i = $i + 2) {
  11483. $this->_outLine($p[$i], $p[$i + 1]);
  11484. }
  11485. $this->_out($op);
  11486. }
  11487. // draw outline
  11488. $this->_outPoint($p[0], $p[1]);
  11489. for ($i = 2; $i < $nc; $i = $i + 2) {
  11490. $line_num = ($i / 2) - 1;
  11491. if (isset($line_style[$line_num])) {
  11492. if ($line_style[$line_num] != 0) {
  11493. if (is_array($line_style[$line_num])) {
  11494. $this->_out('S');
  11495. $this->SetLineStyle($line_style[$line_num]);
  11496. $this->_outPoint($p[$i - 2], $p[$i - 1]);
  11497. $this->_outLine($p[$i], $p[$i + 1]);
  11498. $this->_out('S');
  11499. $this->_outPoint($p[$i], $p[$i + 1]);
  11500. } else {
  11501. $this->_outLine($p[$i], $p[$i + 1]);
  11502. }
  11503. }
  11504. } else {
  11505. $this->_outLine($p[$i], $p[$i + 1]);
  11506. }
  11507. }
  11508. $this->_out($op);
  11509. }
  11510. }
  11511. if ($draw) {
  11512. $this->_outPoint($p[0], $p[1]);
  11513. for ($i = 2; $i < $nc; $i = $i + 2) {
  11514. $this->_outLine($p[$i], $p[$i + 1]);
  11515. }
  11516. $this->_out($op);
  11517. }
  11518. }
  11519. /**
  11520. * Draws a regular polygon.
  11521. * @param $x0 (float) Abscissa of center point.
  11522. * @param $y0 (float) Ordinate of center point.
  11523. * @param $r: (float) Radius of inscribed circle.
  11524. * @param $ns (integer) Number of sides.
  11525. * @param $angle (float) Angle oriented (anti-clockwise). Default value: 0.
  11526. * @param $draw_circle (boolean) Draw inscribed circle or not. Default value: false.
  11527. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  11528. * @param $line_style (array) Line style of polygon sides. Array with keys among the following:
  11529. * <ul>
  11530. * <li>all: Line style of all sides. Array like for SetLineStyle().</li>
  11531. * <li>0 to ($ns - 1): Line style of each side. Array like for SetLineStyle().</li>
  11532. * </ul>
  11533. * If a key is not present or is null, not draws the side. Default value is default line style (empty array).
  11534. * @param $fill_color (array) Fill color. Format: array(red, green, blue). Default value: default color (empty array).
  11535. * @param $circle_style (string) Style of rendering of inscribed circle (if draws). Possible values are:
  11536. * <ul>
  11537. * <li>D or empty string: Draw (default).</li>
  11538. * <li>F: Fill.</li>
  11539. * <li>DF or FD: Draw and fill.</li>
  11540. * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
  11541. * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
  11542. * </ul>
  11543. * @param $circle_outLine_style (array) Line style of inscribed circle (if draws). Array like for SetLineStyle(). Default value: default line style (empty array).
  11544. * @param $circle_fill_color (array) Fill color of inscribed circle (if draws). Format: array(red, green, blue). Default value: default color (empty array).
  11545. * @public
  11546. * @since 2.1.000 (2008-01-08)
  11547. */
  11548. 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()) {
  11549. if (3 > $ns) {
  11550. $ns = 3;
  11551. }
  11552. if ($draw_circle) {
  11553. $this->Circle($x0, $y0, $r, 0, 360, $circle_style, $circle_outLine_style, $circle_fill_color);
  11554. }
  11555. $p = array();
  11556. for ($i = 0; $i < $ns; ++$i) {
  11557. $a = $angle + ($i * 360 / $ns);
  11558. $a_rad = deg2rad((float) $a);
  11559. $p[] = $x0 + ($r * sin($a_rad));
  11560. $p[] = $y0 + ($r * cos($a_rad));
  11561. }
  11562. $this->Polygon($p, $style, $line_style, $fill_color);
  11563. }
  11564. /**
  11565. * Draws a star polygon
  11566. * @param $x0 (float) Abscissa of center point.
  11567. * @param $y0 (float) Ordinate of center point.
  11568. * @param $r (float) Radius of inscribed circle.
  11569. * @param $nv (integer) Number of vertices.
  11570. * @param $ng (integer) Number of gap (if ($ng % $nv = 1) then is a regular polygon).
  11571. * @param $angle: (float) Angle oriented (anti-clockwise). Default value: 0.
  11572. * @param $draw_circle: (boolean) Draw inscribed circle or not. Default value is false.
  11573. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  11574. * @param $line_style (array) Line style of polygon sides. Array with keys among the following:
  11575. * <ul>
  11576. * <li>all: Line style of all sides. Array like for
  11577. * SetLineStyle().</li>
  11578. * <li>0 to (n - 1): Line style of each side. Array like for SetLineStyle().</li>
  11579. * </ul>
  11580. * If a key is not present or is null, not draws the side. Default value is default line style (empty array).
  11581. * @param $fill_color (array) Fill color. Format: array(red, green, blue). Default value: default color (empty array).
  11582. * @param $circle_style (string) Style of rendering of inscribed circle (if draws). Possible values are:
  11583. * <ul>
  11584. * <li>D or empty string: Draw (default).</li>
  11585. * <li>F: Fill.</li>
  11586. * <li>DF or FD: Draw and fill.</li>
  11587. * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
  11588. * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
  11589. * </ul>
  11590. * @param $circle_outLine_style (array) Line style of inscribed circle (if draws). Array like for SetLineStyle(). Default value: default line style (empty array).
  11591. * @param $circle_fill_color (array) Fill color of inscribed circle (if draws). Format: array(red, green, blue). Default value: default color (empty array).
  11592. * @public
  11593. * @since 2.1.000 (2008-01-08)
  11594. */
  11595. 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()) {
  11596. if ($nv < 2) {
  11597. $nv = 2;
  11598. }
  11599. if ($draw_circle) {
  11600. $this->Circle($x0, $y0, $r, 0, 360, $circle_style, $circle_outLine_style, $circle_fill_color);
  11601. }
  11602. $p2 = array();
  11603. $visited = array();
  11604. for ($i = 0; $i < $nv; ++$i) {
  11605. $a = $angle + ($i * 360 / $nv);
  11606. $a_rad = deg2rad((float) $a);
  11607. $p2[] = $x0 + ($r * sin($a_rad));
  11608. $p2[] = $y0 + ($r * cos($a_rad));
  11609. $visited[] = false;
  11610. }
  11611. $p = array();
  11612. $i = 0;
  11613. do {
  11614. $p[] = $p2[$i * 2];
  11615. $p[] = $p2[($i * 2) + 1];
  11616. $visited[$i] = true;
  11617. $i += $ng;
  11618. $i %= $nv;
  11619. } while (!$visited[$i]);
  11620. $this->Polygon($p, $style, $line_style, $fill_color);
  11621. }
  11622. /**
  11623. * Draws a rounded rectangle.
  11624. * @param $x (float) Abscissa of upper-left corner.
  11625. * @param $y (float) Ordinate of upper-left corner.
  11626. * @param $w (float) Width.
  11627. * @param $h (float) Height.
  11628. * @param $r (float) the radius of the circle used to round off the corners of the rectangle.
  11629. * @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").
  11630. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  11631. * @param $border_style (array) Border style of rectangle. Array like for SetLineStyle(). Default value: default line style (empty array).
  11632. * @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).
  11633. * @public
  11634. * @since 2.1.000 (2008-01-08)
  11635. */
  11636. public function RoundedRect($x, $y, $w, $h, $r, $round_corner='1111', $style='', $border_style=array(), $fill_color=array()) {
  11637. $this->RoundedRectXY($x, $y, $w, $h, $r, $r, $round_corner, $style, $border_style, $fill_color);
  11638. }
  11639. /**
  11640. * Draws a rounded rectangle.
  11641. * @param $x (float) Abscissa of upper-left corner.
  11642. * @param $y (float) Ordinate of upper-left corner.
  11643. * @param $w (float) Width.
  11644. * @param $h (float) Height.
  11645. * @param $rx (float) the x-axis radius of the ellipse used to round off the corners of the rectangle.
  11646. * @param $ry (float) the y-axis radius of the ellipse used to round off the corners of the rectangle.
  11647. * @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").
  11648. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  11649. * @param $border_style (array) Border style of rectangle. Array like for SetLineStyle(). Default value: default line style (empty array).
  11650. * @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).
  11651. * @public
  11652. * @since 4.9.019 (2010-04-22)
  11653. */
  11654. public function RoundedRectXY($x, $y, $w, $h, $rx, $ry, $round_corner='1111', $style='', $border_style=array(), $fill_color=array()) {
  11655. if ($this->state != 2) {
  11656. return;
  11657. }
  11658. if (($round_corner == '0000') OR (($rx == $ry) AND ($rx == 0))) {
  11659. // Not rounded
  11660. $this->Rect($x, $y, $w, $h, $style, $border_style, $fill_color);
  11661. return;
  11662. }
  11663. // Rounded
  11664. if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
  11665. $this->SetFillColorArray($fill_color);
  11666. }
  11667. $op = TCPDF_STATIC::getPathPaintOperator($style);
  11668. if ($op == 'f') {
  11669. $border_style = array();
  11670. }
  11671. if ($border_style) {
  11672. $this->SetLineStyle($border_style);
  11673. }
  11674. $MyArc = 4 / 3 * (sqrt(2) - 1);
  11675. $this->_outPoint($x + $rx, $y);
  11676. $xc = $x + $w - $rx;
  11677. $yc = $y + $ry;
  11678. $this->_outLine($xc, $y);
  11679. if ($round_corner[0]) {
  11680. $this->_outCurve($xc + ($rx * $MyArc), $yc - $ry, $xc + $rx, $yc - ($ry * $MyArc), $xc + $rx, $yc);
  11681. } else {
  11682. $this->_outLine($x + $w, $y);
  11683. }
  11684. $xc = $x + $w - $rx;
  11685. $yc = $y + $h - $ry;
  11686. $this->_outLine($x + $w, $yc);
  11687. if ($round_corner[1]) {
  11688. $this->_outCurve($xc + $rx, $yc + ($ry * $MyArc), $xc + ($rx * $MyArc), $yc + $ry, $xc, $yc + $ry);
  11689. } else {
  11690. $this->_outLine($x + $w, $y + $h);
  11691. }
  11692. $xc = $x + $rx;
  11693. $yc = $y + $h - $ry;
  11694. $this->_outLine($xc, $y + $h);
  11695. if ($round_corner[2]) {
  11696. $this->_outCurve($xc - ($rx * $MyArc), $yc + $ry, $xc - $rx, $yc + ($ry * $MyArc), $xc - $rx, $yc);
  11697. } else {
  11698. $this->_outLine($x, $y + $h);
  11699. }
  11700. $xc = $x + $rx;
  11701. $yc = $y + $ry;
  11702. $this->_outLine($x, $yc);
  11703. if ($round_corner[3]) {
  11704. $this->_outCurve($xc - $rx, $yc - ($ry * $MyArc), $xc - ($rx * $MyArc), $yc - $ry, $xc, $yc - $ry);
  11705. } else {
  11706. $this->_outLine($x, $y);
  11707. $this->_outLine($x + $rx, $y);
  11708. }
  11709. $this->_out($op);
  11710. }
  11711. /**
  11712. * Draws a grahic arrow.
  11713. * @param $x0 (float) Abscissa of first point.
  11714. * @param $y0 (float) Ordinate of first point.
  11715. * @param $x1 (float) Abscissa of second point.
  11716. * @param $y1 (float) Ordinate of second point.
  11717. * @param $head_style (int) (0 = draw only arrowhead arms, 1 = draw closed arrowhead, but no fill, 2 = closed and filled arrowhead, 3 = filled arrowhead)
  11718. * @param $arm_size (float) length of arrowhead arms
  11719. * @param $arm_angle (int) angle between an arm and the shaft
  11720. * @author Piotr Galecki, Nicola Asuni, Andy Meier
  11721. * @since 4.6.018 (2009-07-10)
  11722. */
  11723. public function Arrow($x0, $y0, $x1, $y1, $head_style=0, $arm_size=5, $arm_angle=15) {
  11724. // getting arrow direction angle
  11725. // 0 deg angle is when both arms go along X axis. angle grows clockwise.
  11726. $dir_angle = atan2(($y0 - $y1), ($x0 - $x1));
  11727. if ($dir_angle < 0) {
  11728. $dir_angle += (2 * M_PI);
  11729. }
  11730. $arm_angle = deg2rad($arm_angle);
  11731. $sx1 = $x1;
  11732. $sy1 = $y1;
  11733. if ($head_style > 0) {
  11734. // calculate the stopping point for the arrow shaft
  11735. $sx1 = $x1 + (($arm_size - $this->LineWidth) * cos($dir_angle));
  11736. $sy1 = $y1 + (($arm_size - $this->LineWidth) * sin($dir_angle));
  11737. }
  11738. // main arrow line / shaft
  11739. $this->Line($x0, $y0, $sx1, $sy1);
  11740. // left arrowhead arm tip
  11741. $x2L = $x1 + ($arm_size * cos($dir_angle + $arm_angle));
  11742. $y2L = $y1 + ($arm_size * sin($dir_angle + $arm_angle));
  11743. // right arrowhead arm tip
  11744. $x2R = $x1 + ($arm_size * cos($dir_angle - $arm_angle));
  11745. $y2R = $y1 + ($arm_size * sin($dir_angle - $arm_angle));
  11746. $mode = 'D';
  11747. $style = array();
  11748. switch ($head_style) {
  11749. case 0: {
  11750. // draw only arrowhead arms
  11751. $mode = 'D';
  11752. $style = array(1, 1, 0);
  11753. break;
  11754. }
  11755. case 1: {
  11756. // draw closed arrowhead, but no fill
  11757. $mode = 'D';
  11758. break;
  11759. }
  11760. case 2: {
  11761. // closed and filled arrowhead
  11762. $mode = 'DF';
  11763. break;
  11764. }
  11765. case 3: {
  11766. // filled arrowhead
  11767. $mode = 'F';
  11768. break;
  11769. }
  11770. }
  11771. $this->Polygon(array($x2L, $y2L, $x1, $y1, $x2R, $y2R), $mode, $style, array());
  11772. }
  11773. // END GRAPHIC FUNCTIONS SECTION -----------------------
  11774. /**
  11775. * Add a Named Destination.
  11776. * NOTE: destination names are unique, so only last entry will be saved.
  11777. * @param $name (string) Destination name.
  11778. * @param $y (float) Y position in user units of the destiantion on the selected page (default = -1 = current position; 0 = page start;).
  11779. * @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.
  11780. * @param $x (float) X position in user units of the destiantion on the selected page (default = -1 = current position;).
  11781. * @return (string) Stripped named destination identifier or false in case of error.
  11782. * @public
  11783. * @author Christian Deligant, Nicola Asuni
  11784. * @since 5.9.097 (2011-06-23)
  11785. */
  11786. public function setDestination($name, $y=-1, $page='', $x=-1) {
  11787. // remove unsupported characters
  11788. $name = TCPDF_STATIC::encodeNameObject($name);
  11789. if (TCPDF_STATIC::empty_string($name)) {
  11790. return false;
  11791. }
  11792. if ($y == -1) {
  11793. $y = $this->GetY();
  11794. } elseif ($y < 0) {
  11795. $y = 0;
  11796. } elseif ($y > $this->h) {
  11797. $y = $this->h;
  11798. }
  11799. if ($x == -1) {
  11800. $x = $this->GetX();
  11801. } elseif ($x < 0) {
  11802. $x = 0;
  11803. } elseif ($x > $this->w) {
  11804. $x = $this->w;
  11805. }
  11806. $fixed = false;
  11807. if (!empty($page) AND (substr($page, 0, 1) == '*')) {
  11808. $page = intval(substr($page, 1));
  11809. // this page number will not be changed when moving/add/deleting pages
  11810. $fixed = true;
  11811. }
  11812. if (empty($page)) {
  11813. $page = $this->PageNo();
  11814. if (empty($page)) {
  11815. return;
  11816. }
  11817. }
  11818. $this->dests[$name] = array('x' => $x, 'y' => $y, 'p' => $page, 'f' => $fixed);
  11819. return $name;
  11820. }
  11821. /**
  11822. * Return the Named Destination array.
  11823. * @return (array) Named Destination array.
  11824. * @public
  11825. * @author Nicola Asuni
  11826. * @since 5.9.097 (2011-06-23)
  11827. */
  11828. public function getDestination() {
  11829. return $this->dests;
  11830. }
  11831. /**
  11832. * Insert Named Destinations.
  11833. * @protected
  11834. * @author Johannes G\FCntert, Nicola Asuni
  11835. * @since 5.9.098 (2011-06-23)
  11836. */
  11837. protected function _putdests() {
  11838. if (empty($this->dests)) {
  11839. return;
  11840. }
  11841. $this->n_dests = $this->_newobj();
  11842. $out = ' <<';
  11843. foreach($this->dests as $name => $o) {
  11844. $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)));
  11845. }
  11846. $out .= ' >>';
  11847. $out .= "\n".'endobj';
  11848. $this->_out($out);
  11849. }
  11850. /**
  11851. * Adds a bookmark - alias for Bookmark().
  11852. * @param $txt (string) Bookmark description.
  11853. * @param $level (int) Bookmark level (minimum value is 0).
  11854. * @param $y (float) Y position in user units of the bookmark on the selected page (default = -1 = current position; 0 = page start;).
  11855. * @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.
  11856. * @param $style (string) Font style: B = Bold, I = Italic, BI = Bold + Italic.
  11857. * @param $color (array) RGB color array (values from 0 to 255).
  11858. * @param $x (float) X position in user units of the bookmark on the selected page (default = -1 = current position;).
  11859. * @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).
  11860. * @public
  11861. */
  11862. public function setBookmark($txt, $level=0, $y=-1, $page='', $style='', $color=array(0,0,0), $x=-1, $link='') {
  11863. $this->Bookmark($txt, $level, $y, $page, $style, $color, $x, $link);
  11864. }
  11865. /**
  11866. * Adds a bookmark.
  11867. * @param $txt (string) Bookmark description.
  11868. * @param $level (int) Bookmark level (minimum value is 0).
  11869. * @param $y (float) Y position in user units of the bookmark on the selected page (default = -1 = current position; 0 = page start;).
  11870. * @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.
  11871. * @param $style (string) Font style: B = Bold, I = Italic, BI = Bold + Italic.
  11872. * @param $color (array) RGB color array (values from 0 to 255).
  11873. * @param $x (float) X position in user units of the bookmark on the selected page (default = -1 = current position;).
  11874. * @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).
  11875. * @public
  11876. * @since 2.1.002 (2008-02-12)
  11877. */
  11878. public function Bookmark($txt, $level=0, $y=-1, $page='', $style='', $color=array(0,0,0), $x=-1, $link='') {
  11879. if ($level < 0) {
  11880. $level = 0;
  11881. }
  11882. if (isset($this->outlines[0])) {
  11883. $lastoutline = end($this->outlines);
  11884. $maxlevel = $lastoutline['l'] + 1;
  11885. } else {
  11886. $maxlevel = 0;
  11887. }
  11888. if ($level > $maxlevel) {
  11889. $level = $maxlevel;
  11890. }
  11891. if ($y == -1) {
  11892. $y = $this->GetY();
  11893. } elseif ($y < 0) {
  11894. $y = 0;
  11895. } elseif ($y > $this->h) {
  11896. $y = $this->h;
  11897. }
  11898. if ($x == -1) {
  11899. $x = $this->GetX();
  11900. } elseif ($x < 0) {
  11901. $x = 0;
  11902. } elseif ($x > $this->w) {
  11903. $x = $this->w;
  11904. }
  11905. $fixed = false;
  11906. $pageAsString = (string) $page;
  11907. if ($pageAsString && $pageAsString[0] == '*') {
  11908. $page = intval(substr($page, 1));
  11909. // this page number will not be changed when moving/add/deleting pages
  11910. $fixed = true;
  11911. }
  11912. if (empty($page)) {
  11913. $page = $this->PageNo();
  11914. if (empty($page)) {
  11915. return;
  11916. }
  11917. }
  11918. $this->outlines[] = array('t' => $txt, 'l' => $level, 'x' => $x, 'y' => $y, 'p' => $page, 'f' => $fixed, 's' => strtoupper($style), 'c' => $color, 'u' => $link);
  11919. }
  11920. /**
  11921. * Sort bookmarks for page and key.
  11922. * @protected
  11923. * @since 5.9.119 (2011-09-19)
  11924. */
  11925. protected function sortBookmarks() {
  11926. // get sorting columns
  11927. $outline_p = array();
  11928. $outline_y = array();
  11929. foreach ($this->outlines as $key => $row) {
  11930. $outline_p[$key] = $row['p'];
  11931. $outline_k[$key] = $key;
  11932. }
  11933. // sort outlines by page and original position
  11934. array_multisort($outline_p, SORT_NUMERIC, SORT_ASC, $outline_k, SORT_NUMERIC, SORT_ASC, $this->outlines);
  11935. }
  11936. /**
  11937. * Create a bookmark PDF string.
  11938. * @protected
  11939. * @author Olivier Plathey, Nicola Asuni
  11940. * @since 2.1.002 (2008-02-12)
  11941. */
  11942. protected function _putbookmarks() {
  11943. $nb = count($this->outlines);
  11944. if ($nb == 0) {
  11945. return;
  11946. }
  11947. // sort bookmarks
  11948. $this->sortBookmarks();
  11949. $lru = array();
  11950. $level = 0;
  11951. foreach ($this->outlines as $i => $o) {
  11952. if ($o['l'] > 0) {
  11953. $parent = $lru[($o['l'] - 1)];
  11954. //Set parent and last pointers
  11955. $this->outlines[$i]['parent'] = $parent;
  11956. $this->outlines[$parent]['last'] = $i;
  11957. if ($o['l'] > $level) {
  11958. //Level increasing: set first pointer
  11959. $this->outlines[$parent]['first'] = $i;
  11960. }
  11961. } else {
  11962. $this->outlines[$i]['parent'] = $nb;
  11963. }
  11964. if (($o['l'] <= $level) AND ($i > 0)) {
  11965. //Set prev and next pointers
  11966. $prev = $lru[$o['l']];
  11967. $this->outlines[$prev]['next'] = $i;
  11968. $this->outlines[$i]['prev'] = $prev;
  11969. }
  11970. $lru[$o['l']] = $i;
  11971. $level = $o['l'];
  11972. }
  11973. //Outline items
  11974. $n = $this->n + 1;
  11975. $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';
  11976. foreach ($this->outlines as $i => $o) {
  11977. $oid = $this->_newobj();
  11978. // covert HTML title to string
  11979. $title = preg_replace($nltags, "\n", $o['t']);
  11980. $title = preg_replace("/[\r]+/si", '', $title);
  11981. $title = preg_replace("/[\n]+/si", "\n", $title);
  11982. $title = strip_tags($title);
  11983. $title = $this->stringTrim($title);
  11984. $out = '<</Title '.$this->_textstring($title, $oid);
  11985. $out .= ' /Parent '.($n + $o['parent']).' 0 R';
  11986. if (isset($o['prev'])) {
  11987. $out .= ' /Prev '.($n + $o['prev']).' 0 R';
  11988. }
  11989. if (isset($o['next'])) {
  11990. $out .= ' /Next '.($n + $o['next']).' 0 R';
  11991. }
  11992. if (isset($o['first'])) {
  11993. $out .= ' /First '.($n + $o['first']).' 0 R';
  11994. }
  11995. if (isset($o['last'])) {
  11996. $out .= ' /Last '.($n + $o['last']).' 0 R';
  11997. }
  11998. if (isset($o['u']) AND !empty($o['u'])) {
  11999. // link
  12000. if (is_string($o['u'])) {
  12001. if ($o['u'][0] == '#') {
  12002. // internal destination
  12003. $out .= ' /Dest /'.TCPDF_STATIC::encodeNameObject(substr($o['u'], 1));
  12004. } elseif ($o['u'][0] == '%') {
  12005. // embedded PDF file
  12006. $filename = basename(substr($o['u'], 1));
  12007. $out .= ' /A <</S /GoToE /D [0 /Fit] /NewWindow true /T << /R /C /P '.($o['p'] - 1).' /A '.$this->embeddedfiles[$filename]['a'].' >> >>';
  12008. } elseif ($o['u'][0] == '*') {
  12009. // embedded generic file
  12010. $filename = basename(substr($o['u'], 1));
  12011. $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});';
  12012. $out .= ' /A <</S /JavaScript /JS '.$this->_textstring($jsa, $oid).'>>';
  12013. } else {
  12014. // external URI link
  12015. $out .= ' /A <</S /URI /URI '.$this->_datastring($this->unhtmlentities($o['u']), $oid).'>>';
  12016. }
  12017. } elseif (isset($this->links[$o['u']])) {
  12018. // internal link ID
  12019. $l = $this->links[$o['u']];
  12020. if (isset($this->page_obj_id[($l['p'])])) {
  12021. $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)));
  12022. }
  12023. }
  12024. } elseif (isset($this->page_obj_id[($o['p'])])) {
  12025. // link to a page
  12026. $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)));
  12027. }
  12028. // set font style
  12029. $style = 0;
  12030. if (!empty($o['s'])) {
  12031. // bold
  12032. if (strpos($o['s'], 'B') !== false) {
  12033. $style |= 2;
  12034. }
  12035. // oblique
  12036. if (strpos($o['s'], 'I') !== false) {
  12037. $style |= 1;
  12038. }
  12039. }
  12040. $out .= sprintf(' /F %d', $style);
  12041. // set bookmark color
  12042. if (isset($o['c']) AND is_array($o['c']) AND (count($o['c']) == 3)) {
  12043. $color = array_values($o['c']);
  12044. $out .= sprintf(' /C [%F %F %F]', ($color[0] / 255), ($color[1] / 255), ($color[2] / 255));
  12045. } else {
  12046. // black
  12047. $out .= ' /C [0.0 0.0 0.0]';
  12048. }
  12049. $out .= ' /Count 0'; // normally closed item
  12050. $out .= ' >>';
  12051. $out .= "\n".'endobj';
  12052. $this->_out($out);
  12053. }
  12054. //Outline root
  12055. $this->OutlineRoot = $this->_newobj();
  12056. $this->_out('<< /Type /Outlines /First '.$n.' 0 R /Last '.($n + $lru[0]).' 0 R >>'."\n".'endobj');
  12057. }
  12058. // --- JAVASCRIPT ------------------------------------------------------
  12059. /**
  12060. * Adds a javascript
  12061. * @param $script (string) Javascript code
  12062. * @public
  12063. * @author Johannes G\FCntert, Nicola Asuni
  12064. * @since 2.1.002 (2008-02-12)
  12065. */
  12066. public function IncludeJS($script) {
  12067. $this->javascript .= $script;
  12068. }
  12069. /**
  12070. * Adds a javascript object and return object ID
  12071. * @param $script (string) Javascript code
  12072. * @param $onload (boolean) if true executes this object when opening the document
  12073. * @return int internal object ID
  12074. * @public
  12075. * @author Nicola Asuni
  12076. * @since 4.8.000 (2009-09-07)
  12077. */
  12078. public function addJavascriptObject($script, $onload=false) {
  12079. if ($this->pdfa_mode) {
  12080. // javascript is not allowed in PDF/A mode
  12081. return false;
  12082. }
  12083. ++$this->n;
  12084. $this->js_objects[$this->n] = array('n' => $this->n, 'js' => $script, 'onload' => $onload);
  12085. return $this->n;
  12086. }
  12087. /**
  12088. * Create a javascript PDF string.
  12089. * @protected
  12090. * @author Johannes G\FCntert, Nicola Asuni
  12091. * @since 2.1.002 (2008-02-12)
  12092. */
  12093. protected function _putjavascript() {
  12094. if ($this->pdfa_mode OR (empty($this->javascript) AND empty($this->js_objects))) {
  12095. return;
  12096. }
  12097. if (strpos($this->javascript, 'this.addField') > 0) {
  12098. if (!$this->ur['enabled']) {
  12099. //$this->setUserRights();
  12100. }
  12101. // the following two lines are used to avoid form fields duplication after saving
  12102. // The addField method only works when releasing user rights (UR3)
  12103. $jsa = sprintf("ftcpdfdocsaved=this.addField('%s','%s',%d,[%F,%F,%F,%F]);", 'tcpdfdocsaved', 'text', 0, 0, 1, 0, 1);
  12104. $jsb = "getField('tcpdfdocsaved').value='saved';";
  12105. $this->javascript = $jsa."\n".$this->javascript."\n".$jsb;
  12106. }
  12107. // name tree for javascript
  12108. $this->n_js = '<< /Names [';
  12109. if (!empty($this->javascript)) {
  12110. $this->n_js .= ' (EmbeddedJS) '.($this->n + 1).' 0 R';
  12111. }
  12112. if (!empty($this->js_objects)) {
  12113. foreach ($this->js_objects as $key => $val) {
  12114. if ($val['onload']) {
  12115. $this->n_js .= ' (JS'.$key.') '.$key.' 0 R';
  12116. }
  12117. }
  12118. }
  12119. $this->n_js .= ' ] >>';
  12120. // default Javascript object
  12121. if (!empty($this->javascript)) {
  12122. $obj_id = $this->_newobj();
  12123. $out = '<< /S /JavaScript';
  12124. $out .= ' /JS '.$this->_textstring($this->javascript, $obj_id);
  12125. $out .= ' >>';
  12126. $out .= "\n".'endobj';
  12127. $this->_out($out);
  12128. }
  12129. // additional Javascript objects
  12130. if (!empty($this->js_objects)) {
  12131. foreach ($this->js_objects as $key => $val) {
  12132. $out = $this->_getobj($key)."\n".' << /S /JavaScript /JS '.$this->_textstring($val['js'], $key).' >>'."\n".'endobj';
  12133. $this->_out($out);
  12134. }
  12135. }
  12136. }
  12137. /**
  12138. * Adds a javascript form field.
  12139. * @param $type (string) field type
  12140. * @param $name (string) field name
  12141. * @param $x (int) horizontal position
  12142. * @param $y (int) vertical position
  12143. * @param $w (int) width
  12144. * @param $h (int) height
  12145. * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
  12146. * @protected
  12147. * @author Denis Van Nuffelen, Nicola Asuni
  12148. * @since 2.1.002 (2008-02-12)
  12149. */
  12150. protected function _addfield($type, $name, $x, $y, $w, $h, $prop) {
  12151. if ($this->rtl) {
  12152. $x = $x - $w;
  12153. }
  12154. // the followind avoid fields duplication after saving the document
  12155. $this->javascript .= "if (getField('tcpdfdocsaved').value != 'saved') {";
  12156. $k = $this->k;
  12157. $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";
  12158. $this->javascript .= 'f'.$name.'.textSize='.$this->FontSizePt.";\n";
  12159. foreach($prop as $key => $val) {
  12160. if (strcmp(substr($key, -5), 'Color') == 0) {
  12161. $val = TCPDF_COLORS::_JScolor($val);
  12162. } else {
  12163. $val = "'".$val."'";
  12164. }
  12165. $this->javascript .= 'f'.$name.'.'.$key.'='.$val.";\n";
  12166. }
  12167. if ($this->rtl) {
  12168. $this->x -= $w;
  12169. } else {
  12170. $this->x += $w;
  12171. }
  12172. $this->javascript .= '}';
  12173. }
  12174. // --- FORM FIELDS -----------------------------------------------------
  12175. /**
  12176. * Set default properties for form fields.
  12177. * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
  12178. * @public
  12179. * @author Nicola Asuni
  12180. * @since 4.8.000 (2009-09-06)
  12181. */
  12182. public function setFormDefaultProp($prop=array()) {
  12183. $this->default_form_prop = $prop;
  12184. }
  12185. /**
  12186. * Return the default properties for form fields.
  12187. * @return array $prop javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
  12188. * @public
  12189. * @author Nicola Asuni
  12190. * @since 4.8.000 (2009-09-06)
  12191. */
  12192. public function getFormDefaultProp() {
  12193. return $this->default_form_prop;
  12194. }
  12195. /**
  12196. * Creates a text field
  12197. * @param $name (string) field name
  12198. * @param $w (float) Width of the rectangle
  12199. * @param $h (float) Height of the rectangle
  12200. * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
  12201. * @param $opt (array) annotation parameters. Possible values are described on official PDF32000_2008 reference.
  12202. * @param $x (float) Abscissa of the upper-left corner of the rectangle
  12203. * @param $y (float) Ordinate of the upper-left corner of the rectangle
  12204. * @param $js (boolean) if true put the field using JavaScript (requires Acrobat Writer to be rendered).
  12205. * @public
  12206. * @author Nicola Asuni
  12207. * @since 4.8.000 (2009-09-07)
  12208. */
  12209. public function TextField($name, $w, $h, $prop=array(), $opt=array(), $x='', $y='', $js=false) {
  12210. if ($x === '') {
  12211. $x = $this->x;
  12212. }
  12213. if ($y === '') {
  12214. $y = $this->y;
  12215. }
  12216. // check page for no-write regions and adapt page margins if necessary
  12217. list($x, $y) = $this->checkPageRegions($h, $x, $y);
  12218. if ($js) {
  12219. $this->_addfield('text', $name, $x, $y, $w, $h, $prop);
  12220. return;
  12221. }
  12222. // get default style
  12223. $prop = array_merge($this->getFormDefaultProp(), $prop);
  12224. // get annotation data
  12225. $popt = TCPDF_STATIC::getAnnotOptFromJSProp($prop, $this->spot_colors, $this->rtl);
  12226. // set default appearance stream
  12227. $this->annotation_fonts[$this->CurrentFont['fontkey']] = $this->CurrentFont['i'];
  12228. $fontstyle = sprintf('/F%d %F Tf %s', $this->CurrentFont['i'], $this->FontSizePt, $this->TextColor);
  12229. $popt['da'] = $fontstyle;
  12230. // build appearance stream
  12231. $popt['ap'] = array();
  12232. $popt['ap']['n'] = '/Tx BMC q '.$fontstyle.' ';
  12233. $text = '';
  12234. if (isset($prop['value']) AND !empty($prop['value'])) {
  12235. $text = $prop['value'];
  12236. } elseif (isset($opt['v']) AND !empty($opt['v'])) {
  12237. $text = $opt['v'];
  12238. }
  12239. $tmpid = $this->startTemplate($w, $h, false);
  12240. $align = '';
  12241. if (isset($popt['q'])) {
  12242. switch ($popt['q']) {
  12243. case 0: {
  12244. $align = 'L';
  12245. break;
  12246. }
  12247. case 1: {
  12248. $align = 'C';
  12249. break;
  12250. }
  12251. case 2: {
  12252. $align = 'R';
  12253. break;
  12254. }
  12255. default: {
  12256. $align = '';
  12257. break;
  12258. }
  12259. }
  12260. }
  12261. $this->MultiCell($w, $h, $text, 0, $align, false, 0, 0, 0, true, 0, false, true, 0, 'T', false);
  12262. $this->endTemplate();
  12263. --$this->n;
  12264. $popt['ap']['n'] .= $this->xobjects[$tmpid]['outdata'];
  12265. unset($this->xobjects[$tmpid]);
  12266. $popt['ap']['n'] .= 'Q EMC';
  12267. // merge options
  12268. $opt = array_merge($popt, $opt);
  12269. // remove some conflicting options
  12270. unset($opt['bs']);
  12271. // set remaining annotation data
  12272. $opt['Subtype'] = 'Widget';
  12273. $opt['ft'] = 'Tx';
  12274. $opt['t'] = $name;
  12275. // Additional annotation's parameters (check _putannotsobj() method):
  12276. //$opt['f']
  12277. //$opt['as']
  12278. //$opt['bs']
  12279. //$opt['be']
  12280. //$opt['c']
  12281. //$opt['border']
  12282. //$opt['h']
  12283. //$opt['mk'];
  12284. //$opt['mk']['r']
  12285. //$opt['mk']['bc'];
  12286. //$opt['mk']['bg'];
  12287. unset($opt['mk']['ca']);
  12288. unset($opt['mk']['rc']);
  12289. unset($opt['mk']['ac']);
  12290. unset($opt['mk']['i']);
  12291. unset($opt['mk']['ri']);
  12292. unset($opt['mk']['ix']);
  12293. unset($opt['mk']['if']);
  12294. //$opt['mk']['if']['sw'];
  12295. //$opt['mk']['if']['s'];
  12296. //$opt['mk']['if']['a'];
  12297. //$opt['mk']['if']['fb'];
  12298. unset($opt['mk']['tp']);
  12299. //$opt['tu']
  12300. //$opt['tm']
  12301. //$opt['ff']
  12302. //$opt['v']
  12303. //$opt['dv']
  12304. //$opt['a']
  12305. //$opt['aa']
  12306. //$opt['q']
  12307. $this->Annotation($x, $y, $w, $h, $name, $opt, 0);
  12308. if ($this->rtl) {
  12309. $this->x -= $w;
  12310. } else {
  12311. $this->x += $w;
  12312. }
  12313. }
  12314. /**
  12315. * Creates a RadioButton field.
  12316. * @param $name (string) Field name.
  12317. * @param $w (int) Width of the radio button.
  12318. * @param $prop (array) Javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
  12319. * @param $opt (array) Annotation parameters. Possible values are described on official PDF32000_2008 reference.
  12320. * @param $onvalue (string) Value to be returned if selected.
  12321. * @param $checked (boolean) Define the initial state.
  12322. * @param $x (float) Abscissa of the upper-left corner of the rectangle
  12323. * @param $y (float) Ordinate of the upper-left corner of the rectangle
  12324. * @param $js (boolean) If true put the field using JavaScript (requires Acrobat Writer to be rendered).
  12325. * @public
  12326. * @author Nicola Asuni
  12327. * @since 4.8.000 (2009-09-07)
  12328. */
  12329. public function RadioButton($name, $w, $prop=array(), $opt=array(), $onvalue='On', $checked=false, $x='', $y='', $js=false) {
  12330. if ($x === '') {
  12331. $x = $this->x;
  12332. }
  12333. if ($y === '') {
  12334. $y = $this->y;
  12335. }
  12336. // check page for no-write regions and adapt page margins if necessary
  12337. list($x, $y) = $this->checkPageRegions($w, $x, $y);
  12338. if ($js) {
  12339. $this->_addfield('radiobutton', $name, $x, $y, $w, $w, $prop);
  12340. return;
  12341. }
  12342. if (TCPDF_STATIC::empty_string($onvalue)) {
  12343. $onvalue = 'On';
  12344. }
  12345. if ($checked) {
  12346. $defval = $onvalue;
  12347. } else {
  12348. $defval = 'Off';
  12349. }
  12350. // set font
  12351. $font = 'zapfdingbats';
  12352. if ($this->pdfa_mode) {
  12353. // all fonts must be embedded
  12354. $font = 'pdfa'.$font;
  12355. }
  12356. $this->AddFont($font);
  12357. $tmpfont = $this->getFontBuffer($font);
  12358. // set data for parent group
  12359. if (!isset($this->radiobutton_groups[$this->page])) {
  12360. $this->radiobutton_groups[$this->page] = array();
  12361. }
  12362. if (!isset($this->radiobutton_groups[$this->page][$name])) {
  12363. $this->radiobutton_groups[$this->page][$name] = array();
  12364. ++$this->n;
  12365. $this->radiobutton_groups[$this->page][$name]['n'] = $this->n;
  12366. $this->radio_groups[] = $this->n;
  12367. }
  12368. $kid = ($this->n + 1);
  12369. // save object ID to be added on Kids entry on parent object
  12370. $this->radiobutton_groups[$this->page][$name][] = array('kid' => $kid, 'def' => $defval);
  12371. // get default style
  12372. $prop = array_merge($this->getFormDefaultProp(), $prop);
  12373. $prop['NoToggleToOff'] = 'true';
  12374. $prop['Radio'] = 'true';
  12375. $prop['borderStyle'] = 'inset';
  12376. // get annotation data
  12377. $popt = TCPDF_STATIC::getAnnotOptFromJSProp($prop, $this->spot_colors, $this->rtl);
  12378. // set additional default options
  12379. $this->annotation_fonts[$tmpfont['fontkey']] = $tmpfont['i'];
  12380. $fontstyle = sprintf('/F%d %F Tf %s', $tmpfont['i'], $this->FontSizePt, $this->TextColor);
  12381. $popt['da'] = $fontstyle;
  12382. // build appearance stream
  12383. $popt['ap'] = array();
  12384. $popt['ap']['n'] = array();
  12385. $fx = ((($w - $this->getAbsFontMeasure($tmpfont['cw'][108])) / 2) * $this->k);
  12386. $fy = (($w - ((($tmpfont['desc']['Ascent'] - $tmpfont['desc']['Descent']) * $this->FontSizePt / 1000) / $this->k)) * $this->k);
  12387. $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);
  12388. $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);
  12389. if (!isset($popt['mk'])) {
  12390. $popt['mk'] = array();
  12391. }
  12392. $popt['mk']['ca'] = '(l)';
  12393. // merge options
  12394. $opt = array_merge($popt, $opt);
  12395. // set remaining annotation data
  12396. $opt['Subtype'] = 'Widget';
  12397. $opt['ft'] = 'Btn';
  12398. if ($checked) {
  12399. $opt['v'] = array('/'.$onvalue);
  12400. $opt['as'] = $onvalue;
  12401. } else {
  12402. $opt['as'] = 'Off';
  12403. }
  12404. // store readonly flag
  12405. if (!isset($this->radiobutton_groups[$this->page][$name]['#readonly#'])) {
  12406. $this->radiobutton_groups[$this->page][$name]['#readonly#'] = false;
  12407. }
  12408. $this->radiobutton_groups[$this->page][$name]['#readonly#'] |= ($opt['f'] & 64);
  12409. $this->Annotation($x, $y, $w, $w, $name, $opt, 0);
  12410. if ($this->rtl) {
  12411. $this->x -= $w;
  12412. } else {
  12413. $this->x += $w;
  12414. }
  12415. }
  12416. /**
  12417. * Creates a List-box field
  12418. * @param $name (string) field name
  12419. * @param $w (int) width
  12420. * @param $h (int) height
  12421. * @param $values (array) array containing the list of values.
  12422. * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
  12423. * @param $opt (array) annotation parameters. Possible values are described on official PDF32000_2008 reference.
  12424. * @param $x (float) Abscissa of the upper-left corner of the rectangle
  12425. * @param $y (float) Ordinate of the upper-left corner of the rectangle
  12426. * @param $js (boolean) if true put the field using JavaScript (requires Acrobat Writer to be rendered).
  12427. * @public
  12428. * @author Nicola Asuni
  12429. * @since 4.8.000 (2009-09-07)
  12430. */
  12431. public function ListBox($name, $w, $h, $values, $prop=array(), $opt=array(), $x='', $y='', $js=false) {
  12432. if ($x === '') {
  12433. $x = $this->x;
  12434. }
  12435. if ($y === '') {
  12436. $y = $this->y;
  12437. }
  12438. // check page for no-write regions and adapt page margins if necessary
  12439. list($x, $y) = $this->checkPageRegions($h, $x, $y);
  12440. if ($js) {
  12441. $this->_addfield('listbox', $name, $x, $y, $w, $h, $prop);
  12442. $s = '';
  12443. foreach ($values as $value) {
  12444. if (is_array($value)) {
  12445. $s .= ',[\''.addslashes($value[1]).'\',\''.addslashes($value[0]).'\']';
  12446. } else {
  12447. $s .= ',[\''.addslashes($value).'\',\''.addslashes($value).'\']';
  12448. }
  12449. }
  12450. $this->javascript .= 'f'.$name.'.setItems('.substr($s, 1).');'."\n";
  12451. return;
  12452. }
  12453. // get default style
  12454. $prop = array_merge($this->getFormDefaultProp(), $prop);
  12455. // get annotation data
  12456. $popt = TCPDF_STATIC::getAnnotOptFromJSProp($prop, $this->spot_colors, $this->rtl);
  12457. // set additional default values
  12458. $this->annotation_fonts[$this->CurrentFont['fontkey']] = $this->CurrentFont['i'];
  12459. $fontstyle = sprintf('/F%d %F Tf %s', $this->CurrentFont['i'], $this->FontSizePt, $this->TextColor);
  12460. $popt['da'] = $fontstyle;
  12461. // build appearance stream
  12462. $popt['ap'] = array();
  12463. $popt['ap']['n'] = '/Tx BMC q '.$fontstyle.' ';
  12464. $text = '';
  12465. foreach($values as $item) {
  12466. if (is_array($item)) {
  12467. $text .= $item[1]."\n";
  12468. } else {
  12469. $text .= $item."\n";
  12470. }
  12471. }
  12472. $tmpid = $this->startTemplate($w, $h, false);
  12473. $this->MultiCell($w, $h, $text, 0, '', false, 0, 0, 0, true, 0, false, true, 0, 'T', false);
  12474. $this->endTemplate();
  12475. --$this->n;
  12476. $popt['ap']['n'] .= $this->xobjects[$tmpid]['outdata'];
  12477. unset($this->xobjects[$tmpid]);
  12478. $popt['ap']['n'] .= 'Q EMC';
  12479. // merge options
  12480. $opt = array_merge($popt, $opt);
  12481. // set remaining annotation data
  12482. $opt['Subtype'] = 'Widget';
  12483. $opt['ft'] = 'Ch';
  12484. $opt['t'] = $name;
  12485. $opt['opt'] = $values;
  12486. unset($opt['mk']['ca']);
  12487. unset($opt['mk']['rc']);
  12488. unset($opt['mk']['ac']);
  12489. unset($opt['mk']['i']);
  12490. unset($opt['mk']['ri']);
  12491. unset($opt['mk']['ix']);
  12492. unset($opt['mk']['if']);
  12493. unset($opt['mk']['tp']);
  12494. $this->Annotation($x, $y, $w, $h, $name, $opt, 0);
  12495. if ($this->rtl) {
  12496. $this->x -= $w;
  12497. } else {
  12498. $this->x += $w;
  12499. }
  12500. }
  12501. /**
  12502. * Creates a Combo-box field
  12503. * @param $name (string) field name
  12504. * @param $w (int) width
  12505. * @param $h (int) height
  12506. * @param $values (array) array containing the list of values.
  12507. * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
  12508. * @param $opt (array) annotation parameters. Possible values are described on official PDF32000_2008 reference.
  12509. * @param $x (float) Abscissa of the upper-left corner of the rectangle
  12510. * @param $y (float) Ordinate of the upper-left corner of the rectangle
  12511. * @param $js (boolean) if true put the field using JavaScript (requires Acrobat Writer to be rendered).
  12512. * @public
  12513. * @author Nicola Asuni
  12514. * @since 4.8.000 (2009-09-07)
  12515. */
  12516. public function ComboBox($name, $w, $h, $values, $prop=array(), $opt=array(), $x='', $y='', $js=false) {
  12517. if ($x === '') {
  12518. $x = $this->x;
  12519. }
  12520. if ($y === '') {
  12521. $y = $this->y;
  12522. }
  12523. // check page for no-write regions and adapt page margins if necessary
  12524. list($x, $y) = $this->checkPageRegions($h, $x, $y);
  12525. if ($js) {
  12526. $this->_addfield('combobox', $name, $x, $y, $w, $h, $prop);
  12527. $s = '';
  12528. foreach ($values as $value) {
  12529. if (is_array($value)) {
  12530. $s .= ',[\''.addslashes($value[1]).'\',\''.addslashes($value[0]).'\']';
  12531. } else {
  12532. $s .= ',[\''.addslashes($value).'\',\''.addslashes($value).'\']';
  12533. }
  12534. }
  12535. $this->javascript .= 'f'.$name.'.setItems('.substr($s, 1).');'."\n";
  12536. return;
  12537. }
  12538. // get default style
  12539. $prop = array_merge($this->getFormDefaultProp(), $prop);
  12540. $prop['Combo'] = true;
  12541. // get annotation data
  12542. $popt = TCPDF_STATIC::getAnnotOptFromJSProp($prop, $this->spot_colors, $this->rtl);
  12543. // set additional default options
  12544. $this->annotation_fonts[$this->CurrentFont['fontkey']] = $this->CurrentFont['i'];
  12545. $fontstyle = sprintf('/F%d %F Tf %s', $this->CurrentFont['i'], $this->FontSizePt, $this->TextColor);
  12546. $popt['da'] = $fontstyle;
  12547. // build appearance stream
  12548. $popt['ap'] = array();
  12549. $popt['ap']['n'] = '/Tx BMC q '.$fontstyle.' ';
  12550. $text = '';
  12551. foreach($values as $item) {
  12552. if (is_array($item)) {
  12553. $text .= $item[1]."\n";
  12554. } else {
  12555. $text .= $item."\n";
  12556. }
  12557. }
  12558. $tmpid = $this->startTemplate($w, $h, false);
  12559. $this->MultiCell($w, $h, $text, 0, '', false, 0, 0, 0, true, 0, false, true, 0, 'T', false);
  12560. $this->endTemplate();
  12561. --$this->n;
  12562. $popt['ap']['n'] .= $this->xobjects[$tmpid]['outdata'];
  12563. unset($this->xobjects[$tmpid]);
  12564. $popt['ap']['n'] .= 'Q EMC';
  12565. // merge options
  12566. $opt = array_merge($popt, $opt);
  12567. // set remaining annotation data
  12568. $opt['Subtype'] = 'Widget';
  12569. $opt['ft'] = 'Ch';
  12570. $opt['t'] = $name;
  12571. $opt['opt'] = $values;
  12572. unset($opt['mk']['ca']);
  12573. unset($opt['mk']['rc']);
  12574. unset($opt['mk']['ac']);
  12575. unset($opt['mk']['i']);
  12576. unset($opt['mk']['ri']);
  12577. unset($opt['mk']['ix']);
  12578. unset($opt['mk']['if']);
  12579. unset($opt['mk']['tp']);
  12580. $this->Annotation($x, $y, $w, $h, $name, $opt, 0);
  12581. if ($this->rtl) {
  12582. $this->x -= $w;
  12583. } else {
  12584. $this->x += $w;
  12585. }
  12586. }
  12587. /**
  12588. * Creates a CheckBox field
  12589. * @param $name (string) field name
  12590. * @param $w (int) width
  12591. * @param $checked (boolean) define the initial state.
  12592. * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
  12593. * @param $opt (array) annotation parameters. Possible values are described on official PDF32000_2008 reference.
  12594. * @param $onvalue (string) value to be returned if selected.
  12595. * @param $x (float) Abscissa of the upper-left corner of the rectangle
  12596. * @param $y (float) Ordinate of the upper-left corner of the rectangle
  12597. * @param $js (boolean) if true put the field using JavaScript (requires Acrobat Writer to be rendered).
  12598. * @public
  12599. * @author Nicola Asuni
  12600. * @since 4.8.000 (2009-09-07)
  12601. */
  12602. public function CheckBox($name, $w, $checked=false, $prop=array(), $opt=array(), $onvalue='Yes', $x='', $y='', $js=false) {
  12603. if ($x === '') {
  12604. $x = $this->x;
  12605. }
  12606. if ($y === '') {
  12607. $y = $this->y;
  12608. }
  12609. // check page for no-write regions and adapt page margins if necessary
  12610. list($x, $y) = $this->checkPageRegions($w, $x, $y);
  12611. if ($js) {
  12612. $this->_addfield('checkbox', $name, $x, $y, $w, $w, $prop);
  12613. return;
  12614. }
  12615. if (!isset($prop['value'])) {
  12616. $prop['value'] = array('Yes');
  12617. }
  12618. // get default style
  12619. $prop = array_merge($this->getFormDefaultProp(), $prop);
  12620. $prop['borderStyle'] = 'inset';
  12621. // get annotation data
  12622. $popt = TCPDF_STATIC::getAnnotOptFromJSProp($prop, $this->spot_colors, $this->rtl);
  12623. // set additional default options
  12624. $font = 'zapfdingbats';
  12625. if ($this->pdfa_mode) {
  12626. // all fonts must be embedded
  12627. $font = 'pdfa'.$font;
  12628. }
  12629. $this->AddFont($font);
  12630. $tmpfont = $this->getFontBuffer($font);
  12631. $this->annotation_fonts[$tmpfont['fontkey']] = $tmpfont['i'];
  12632. $fontstyle = sprintf('/F%d %F Tf %s', $tmpfont['i'], $this->FontSizePt, $this->TextColor);
  12633. $popt['da'] = $fontstyle;
  12634. // build appearance stream
  12635. $popt['ap'] = array();
  12636. $popt['ap']['n'] = array();
  12637. $fx = ((($w - $this->getAbsFontMeasure($tmpfont['cw'][110])) / 2) * $this->k);
  12638. $fy = (($w - ((($tmpfont['desc']['Ascent'] - $tmpfont['desc']['Descent']) * $this->FontSizePt / 1000) / $this->k)) * $this->k);
  12639. $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);
  12640. $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);
  12641. // merge options
  12642. $opt = array_merge($popt, $opt);
  12643. // set remaining annotation data
  12644. $opt['Subtype'] = 'Widget';
  12645. $opt['ft'] = 'Btn';
  12646. $opt['t'] = $name;
  12647. if (TCPDF_STATIC::empty_string($onvalue)) {
  12648. $onvalue = 'Yes';
  12649. }
  12650. $opt['opt'] = array($onvalue);
  12651. if ($checked) {
  12652. $opt['v'] = array('/Yes');
  12653. $opt['as'] = 'Yes';
  12654. } else {
  12655. $opt['v'] = array('/Off');
  12656. $opt['as'] = 'Off';
  12657. }
  12658. $this->Annotation($x, $y, $w, $w, $name, $opt, 0);
  12659. if ($this->rtl) {
  12660. $this->x -= $w;
  12661. } else {
  12662. $this->x += $w;
  12663. }
  12664. }
  12665. /**
  12666. * Creates a button field
  12667. * @param $name (string) field name
  12668. * @param $w (int) width
  12669. * @param $h (int) height
  12670. * @param $caption (string) caption.
  12671. * @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.
  12672. * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
  12673. * @param $opt (array) annotation parameters. Possible values are described on official PDF32000_2008 reference.
  12674. * @param $x (float) Abscissa of the upper-left corner of the rectangle
  12675. * @param $y (float) Ordinate of the upper-left corner of the rectangle
  12676. * @param $js (boolean) if true put the field using JavaScript (requires Acrobat Writer to be rendered).
  12677. * @public
  12678. * @author Nicola Asuni
  12679. * @since 4.8.000 (2009-09-07)
  12680. */
  12681. public function Button($name, $w, $h, $caption, $action, $prop=array(), $opt=array(), $x='', $y='', $js=false) {
  12682. if ($x === '') {
  12683. $x = $this->x;
  12684. }
  12685. if ($y === '') {
  12686. $y = $this->y;
  12687. }
  12688. // check page for no-write regions and adapt page margins if necessary
  12689. list($x, $y) = $this->checkPageRegions($h, $x, $y);
  12690. if ($js) {
  12691. $this->_addfield('button', $name, $this->x, $this->y, $w, $h, $prop);
  12692. $this->javascript .= 'f'.$name.".buttonSetCaption('".addslashes($caption)."');\n";
  12693. $this->javascript .= 'f'.$name.".setAction('MouseUp','".addslashes($action)."');\n";
  12694. $this->javascript .= 'f'.$name.".highlight='push';\n";
  12695. $this->javascript .= 'f'.$name.".print=false;\n";
  12696. return;
  12697. }
  12698. // get default style
  12699. $prop = array_merge($this->getFormDefaultProp(), $prop);
  12700. $prop['Pushbutton'] = 'true';
  12701. $prop['highlight'] = 'push';
  12702. $prop['display'] = 'display.noPrint';
  12703. // get annotation data
  12704. $popt = TCPDF_STATIC::getAnnotOptFromJSProp($prop, $this->spot_colors, $this->rtl);
  12705. $this->annotation_fonts[$this->CurrentFont['fontkey']] = $this->CurrentFont['i'];
  12706. $fontstyle = sprintf('/F%d %F Tf %s', $this->CurrentFont['i'], $this->FontSizePt, $this->TextColor);
  12707. $popt['da'] = $fontstyle;
  12708. // build appearance stream
  12709. $popt['ap'] = array();
  12710. $popt['ap']['n'] = '/Tx BMC q '.$fontstyle.' ';
  12711. $tmpid = $this->startTemplate($w, $h, false);
  12712. $bw = (2 / $this->k); // border width
  12713. $border = array(
  12714. 'L' => array('width' => $bw, 'cap' => 'square', 'join' => 'miter', 'dash' => 0, 'color' => array(231)),
  12715. 'R' => array('width' => $bw, 'cap' => 'square', 'join' => 'miter', 'dash' => 0, 'color' => array(51)),
  12716. 'T' => array('width' => $bw, 'cap' => 'square', 'join' => 'miter', 'dash' => 0, 'color' => array(231)),
  12717. 'B' => array('width' => $bw, 'cap' => 'square', 'join' => 'miter', 'dash' => 0, 'color' => array(51)));
  12718. $this->SetFillColor(204);
  12719. $this->Cell($w, $h, $caption, $border, 0, 'C', true, '', 1, false, 'T', 'M');
  12720. $this->endTemplate();
  12721. --$this->n;
  12722. $popt['ap']['n'] .= $this->xobjects[$tmpid]['outdata'];
  12723. unset($this->xobjects[$tmpid]);
  12724. $popt['ap']['n'] .= 'Q EMC';
  12725. // set additional default options
  12726. if (!isset($popt['mk'])) {
  12727. $popt['mk'] = array();
  12728. }
  12729. $ann_obj_id = ($this->n + 1);
  12730. if (!empty($action) AND !is_array($action)) {
  12731. $ann_obj_id = ($this->n + 2);
  12732. }
  12733. $popt['mk']['ca'] = $this->_textstring($caption, $ann_obj_id);
  12734. $popt['mk']['rc'] = $this->_textstring($caption, $ann_obj_id);
  12735. $popt['mk']['ac'] = $this->_textstring($caption, $ann_obj_id);
  12736. // merge options
  12737. $opt = array_merge($popt, $opt);
  12738. // set remaining annotation data
  12739. $opt['Subtype'] = 'Widget';
  12740. $opt['ft'] = 'Btn';
  12741. $opt['t'] = $caption;
  12742. $opt['v'] = $name;
  12743. if (!empty($action)) {
  12744. if (is_array($action)) {
  12745. // form action options as on section 12.7.5 of PDF32000_2008.
  12746. $opt['aa'] = '/D <<';
  12747. $bmode = array('SubmitForm', 'ResetForm', 'ImportData');
  12748. foreach ($action AS $key => $val) {
  12749. if (($key == 'S') AND in_array($val, $bmode)) {
  12750. $opt['aa'] .= ' /S /'.$val;
  12751. } elseif (($key == 'F') AND (!empty($val))) {
  12752. $opt['aa'] .= ' /F '.$this->_datastring($val, $ann_obj_id);
  12753. } elseif (($key == 'Fields') AND is_array($val) AND !empty($val)) {
  12754. $opt['aa'] .= ' /Fields [';
  12755. foreach ($val AS $field) {
  12756. $opt['aa'] .= ' '.$this->_textstring($field, $ann_obj_id);
  12757. }
  12758. $opt['aa'] .= ']';
  12759. } elseif (($key == 'Flags')) {
  12760. $ff = 0;
  12761. if (is_array($val)) {
  12762. foreach ($val AS $flag) {
  12763. switch ($flag) {
  12764. case 'Include/Exclude': {
  12765. $ff += 1 << 0;
  12766. break;
  12767. }
  12768. case 'IncludeNoValueFields': {
  12769. $ff += 1 << 1;
  12770. break;
  12771. }
  12772. case 'ExportFormat': {
  12773. $ff += 1 << 2;
  12774. break;
  12775. }
  12776. case 'GetMethod': {
  12777. $ff += 1 << 3;
  12778. break;
  12779. }
  12780. case 'SubmitCoordinates': {
  12781. $ff += 1 << 4;
  12782. break;
  12783. }
  12784. case 'XFDF': {
  12785. $ff += 1 << 5;
  12786. break;
  12787. }
  12788. case 'IncludeAppendSaves': {
  12789. $ff += 1 << 6;
  12790. break;
  12791. }
  12792. case 'IncludeAnnotations': {
  12793. $ff += 1 << 7;
  12794. break;
  12795. }
  12796. case 'SubmitPDF': {
  12797. $ff += 1 << 8;
  12798. break;
  12799. }
  12800. case 'CanonicalFormat': {
  12801. $ff += 1 << 9;
  12802. break;
  12803. }
  12804. case 'ExclNonUserAnnots': {
  12805. $ff += 1 << 10;
  12806. break;
  12807. }
  12808. case 'ExclFKey': {
  12809. $ff += 1 << 11;
  12810. break;
  12811. }
  12812. case 'EmbedForm': {
  12813. $ff += 1 << 13;
  12814. break;
  12815. }
  12816. }
  12817. }
  12818. } else {
  12819. $ff = intval($val);
  12820. }
  12821. $opt['aa'] .= ' /Flags '.$ff;
  12822. }
  12823. }
  12824. $opt['aa'] .= ' >>';
  12825. } else {
  12826. // Javascript action or raw action command
  12827. $js_obj_id = $this->addJavascriptObject($action);
  12828. $opt['aa'] = '/D '.$js_obj_id.' 0 R';
  12829. }
  12830. }
  12831. $this->Annotation($x, $y, $w, $h, $name, $opt, 0);
  12832. if ($this->rtl) {
  12833. $this->x -= $w;
  12834. } else {
  12835. $this->x += $w;
  12836. }
  12837. }
  12838. // --- END FORMS FIELDS ------------------------------------------------
  12839. /**
  12840. * Add certification signature (DocMDP or UR3)
  12841. * You can set only one signature type
  12842. * @protected
  12843. * @author Nicola Asuni
  12844. * @since 4.6.008 (2009-05-07)
  12845. */
  12846. protected function _putsignature() {
  12847. if ((!$this->sign) OR (!isset($this->signature_data['cert_type']))) {
  12848. return;
  12849. }
  12850. $sigobjid = ($this->sig_obj_id + 1);
  12851. $out = $this->_getobj($sigobjid)."\n";
  12852. $out .= '<< /Type /Sig';
  12853. $out .= ' /Filter /Adobe.PPKLite';
  12854. $out .= ' /SubFilter /adbe.pkcs7.detached';
  12855. $out .= ' '.TCPDF_STATIC::$byterange_string;
  12856. $out .= ' /Contents<'.str_repeat('0', $this->signature_max_length).'>';
  12857. if (empty($this->signature_data['approval']) OR ($this->signature_data['approval'] != 'A')) {
  12858. $out .= ' /Reference ['; // array of signature reference dictionaries
  12859. $out .= ' << /Type /SigRef';
  12860. if ($this->signature_data['cert_type'] > 0) {
  12861. $out .= ' /TransformMethod /DocMDP';
  12862. $out .= ' /TransformParams <<';
  12863. $out .= ' /Type /TransformParams';
  12864. $out .= ' /P '.$this->signature_data['cert_type'];
  12865. $out .= ' /V /1.2';
  12866. } else {
  12867. $out .= ' /TransformMethod /UR3';
  12868. $out .= ' /TransformParams <<';
  12869. $out .= ' /Type /TransformParams';
  12870. $out .= ' /V /2.2';
  12871. if (!TCPDF_STATIC::empty_string($this->ur['document'])) {
  12872. $out .= ' /Document['.$this->ur['document'].']';
  12873. }
  12874. if (!TCPDF_STATIC::empty_string($this->ur['form'])) {
  12875. $out .= ' /Form['.$this->ur['form'].']';
  12876. }
  12877. if (!TCPDF_STATIC::empty_string($this->ur['signature'])) {
  12878. $out .= ' /Signature['.$this->ur['signature'].']';
  12879. }
  12880. if (!TCPDF_STATIC::empty_string($this->ur['annots'])) {
  12881. $out .= ' /Annots['.$this->ur['annots'].']';
  12882. }
  12883. if (!TCPDF_STATIC::empty_string($this->ur['ef'])) {
  12884. $out .= ' /EF['.$this->ur['ef'].']';
  12885. }
  12886. if (!TCPDF_STATIC::empty_string($this->ur['formex'])) {
  12887. $out .= ' /FormEX['.$this->ur['formex'].']';
  12888. }
  12889. }
  12890. $out .= ' >>'; // close TransformParams
  12891. // optional digest data (values must be calculated and replaced later)
  12892. //$out .= ' /Data ********** 0 R';
  12893. //$out .= ' /DigestMethod/MD5';
  12894. //$out .= ' /DigestLocation[********** 34]';
  12895. //$out .= ' /DigestValue<********************************>';
  12896. $out .= ' >>';
  12897. $out .= ' ]'; // end of reference
  12898. }
  12899. if (isset($this->signature_data['info']['Name']) AND !TCPDF_STATIC::empty_string($this->signature_data['info']['Name'])) {
  12900. $out .= ' /Name '.$this->_textstring($this->signature_data['info']['Name'], $sigobjid);
  12901. }
  12902. if (isset($this->signature_data['info']['Location']) AND !TCPDF_STATIC::empty_string($this->signature_data['info']['Location'])) {
  12903. $out .= ' /Location '.$this->_textstring($this->signature_data['info']['Location'], $sigobjid);
  12904. }
  12905. if (isset($this->signature_data['info']['Reason']) AND !TCPDF_STATIC::empty_string($this->signature_data['info']['Reason'])) {
  12906. $out .= ' /Reason '.$this->_textstring($this->signature_data['info']['Reason'], $sigobjid);
  12907. }
  12908. if (isset($this->signature_data['info']['ContactInfo']) AND !TCPDF_STATIC::empty_string($this->signature_data['info']['ContactInfo'])) {
  12909. $out .= ' /ContactInfo '.$this->_textstring($this->signature_data['info']['ContactInfo'], $sigobjid);
  12910. }
  12911. $out .= ' /M '.$this->_datestring($sigobjid, $this->doc_modification_timestamp);
  12912. $out .= ' >>';
  12913. $out .= "\n".'endobj';
  12914. $this->_out($out);
  12915. }
  12916. /**
  12917. * Set User's Rights for PDF Reader
  12918. * WARNING: This is experimental and currently do not work.
  12919. * Check the PDF Reference 8.7.1 Transform Methods,
  12920. * Table 8.105 Entries in the UR transform parameters dictionary
  12921. * @param $enable (boolean) if true enable user's rights on PDF reader
  12922. * @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.
  12923. * @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.
  12924. * @param $form (string) Names specifying additional form-field-related usage rights for the document. Valid names are: /Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate
  12925. * @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.
  12926. * @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
  12927. Names specifying additional embedded-files-related usage rights for the document.
  12928. * @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.
  12929. * @public
  12930. * @author Nicola Asuni
  12931. * @since 2.9.000 (2008-03-26)
  12932. */
  12933. public function setUserRights(
  12934. $enable=true,
  12935. $document='/FullSave',
  12936. $annots='/Create/Delete/Modify/Copy/Import/Export',
  12937. $form='/Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate',
  12938. $signature='/Modify',
  12939. $ef='/Create/Delete/Modify/Import',
  12940. $formex='') {
  12941. $this->ur['enabled'] = $enable;
  12942. $this->ur['document'] = $document;
  12943. $this->ur['annots'] = $annots;
  12944. $this->ur['form'] = $form;
  12945. $this->ur['signature'] = $signature;
  12946. $this->ur['ef'] = $ef;
  12947. $this->ur['formex'] = $formex;
  12948. if (!$this->sign) {
  12949. $this->setSignature('', '', '', '', 0, array());
  12950. }
  12951. }
  12952. /**
  12953. * Enable document signature (requires the OpenSSL Library).
  12954. * The digital signature improve document authenticity and integrity and allows o enable extra features on Acrobat Reader.
  12955. * To create self-signed signature: openssl req -x509 -nodes -days 365000 -newkey rsa:1024 -keyout tcpdf.crt -out tcpdf.crt
  12956. * To export crt to p12: openssl pkcs12 -export -in tcpdf.crt -out tcpdf.p12
  12957. * To convert pfx certificate to pem: openssl pkcs12 -in tcpdf.pfx -out tcpdf.crt -nodes
  12958. * @param $signing_cert (mixed) signing certificate (string or filename prefixed with 'file://')
  12959. * @param $private_key (mixed) private key (string or filename prefixed with 'file://')
  12960. * @param $private_key_password (string) password
  12961. * @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.
  12962. * @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.
  12963. * @param $info (array) array of option information: Name, Location, Reason, ContactInfo.
  12964. * @param $approval (string) Enable approval signature eg. for PDF incremental update
  12965. * @public
  12966. * @author Nicola Asuni
  12967. * @since 4.6.005 (2009-04-24)
  12968. */
  12969. public function setSignature($signing_cert='', $private_key='', $private_key_password='', $extracerts='', $cert_type=2, $info=array(), $approval='') {
  12970. // to create self-signed signature: openssl req -x509 -nodes -days 365000 -newkey rsa:1024 -keyout tcpdf.crt -out tcpdf.crt
  12971. // to export crt to p12: openssl pkcs12 -export -in tcpdf.crt -out tcpdf.p12
  12972. // to convert pfx certificate to pem: openssl
  12973. // OpenSSL> pkcs12 -in <cert.pfx> -out <cert.crt> -nodes
  12974. $this->sign = true;
  12975. ++$this->n;
  12976. $this->sig_obj_id = $this->n; // signature widget
  12977. ++$this->n; // signature object ($this->sig_obj_id + 1)
  12978. $this->signature_data = array();
  12979. if (strlen($signing_cert) == 0) {
  12980. $this->Error('Please provide a certificate file and password!');
  12981. }
  12982. if (strlen($private_key) == 0) {
  12983. $private_key = $signing_cert;
  12984. }
  12985. $this->signature_data['signcert'] = $signing_cert;
  12986. $this->signature_data['privkey'] = $private_key;
  12987. $this->signature_data['password'] = $private_key_password;
  12988. $this->signature_data['extracerts'] = $extracerts;
  12989. $this->signature_data['cert_type'] = $cert_type;
  12990. $this->signature_data['info'] = $info;
  12991. $this->signature_data['approval'] = $approval;
  12992. }
  12993. /**
  12994. * Set the digital signature appearance (a cliccable rectangle area to get signature properties)
  12995. * @param $x (float) Abscissa of the upper-left corner.
  12996. * @param $y (float) Ordinate of the upper-left corner.
  12997. * @param $w (float) Width of the signature area.
  12998. * @param $h (float) Height of the signature area.
  12999. * @param $page (int) option page number (if < 0 the current page is used).
  13000. * @param $name (string) Name of the signature.
  13001. * @public
  13002. * @author Nicola Asuni
  13003. * @since 5.3.011 (2010-06-17)
  13004. */
  13005. public function setSignatureAppearance($x=0, $y=0, $w=0, $h=0, $page=-1, $name='') {
  13006. $this->signature_appearance = $this->getSignatureAppearanceArray($x, $y, $w, $h, $page, $name);
  13007. }
  13008. /**
  13009. * Add an empty digital signature appearance (a cliccable rectangle area to get signature properties)
  13010. * @param $x (float) Abscissa of the upper-left corner.
  13011. * @param $y (float) Ordinate of the upper-left corner.
  13012. * @param $w (float) Width of the signature area.
  13013. * @param $h (float) Height of the signature area.
  13014. * @param $page (int) option page number (if < 0 the current page is used).
  13015. * @param $name (string) Name of the signature.
  13016. * @public
  13017. * @author Nicola Asuni
  13018. * @since 5.9.101 (2011-07-06)
  13019. */
  13020. public function addEmptySignatureAppearance($x=0, $y=0, $w=0, $h=0, $page=-1, $name='') {
  13021. ++$this->n;
  13022. $this->empty_signature_appearance[] = array('objid' => $this->n) + $this->getSignatureAppearanceArray($x, $y, $w, $h, $page, $name);
  13023. }
  13024. /**
  13025. * Get the array that defines the signature appearance (page and rectangle coordinates).
  13026. * @param $x (float) Abscissa of the upper-left corner.
  13027. * @param $y (float) Ordinate of the upper-left corner.
  13028. * @param $w (float) Width of the signature area.
  13029. * @param $h (float) Height of the signature area.
  13030. * @param $page (int) option page number (if < 0 the current page is used).
  13031. * @param $name (string) Name of the signature.
  13032. * @return (array) Array defining page and rectangle coordinates of signature appearance.
  13033. * @protected
  13034. * @author Nicola Asuni
  13035. * @since 5.9.101 (2011-07-06)
  13036. */
  13037. protected function getSignatureAppearanceArray($x=0, $y=0, $w=0, $h=0, $page=-1, $name='') {
  13038. $sigapp = array();
  13039. if (($page < 1) OR ($page > $this->numpages)) {
  13040. $sigapp['page'] = $this->page;
  13041. } else {
  13042. $sigapp['page'] = intval($page);
  13043. }
  13044. if (empty($name)) {
  13045. $sigapp['name'] = 'Signature';
  13046. } else {
  13047. $sigapp['name'] = $name;
  13048. }
  13049. $a = $x * $this->k;
  13050. $b = $this->pagedim[($sigapp['page'])]['h'] - (($y + $h) * $this->k);
  13051. $c = $w * $this->k;
  13052. $d = $h * $this->k;
  13053. $sigapp['rect'] = sprintf('%F %F %F %F', $a, $b, ($a + $c), ($b + $d));
  13054. return $sigapp;
  13055. }
  13056. /**
  13057. * Enable document timestamping (requires the OpenSSL Library).
  13058. * The trusted timestamping improve document security that means that no one should be able to change the document once it has been recorded.
  13059. * Use with digital signature only!
  13060. * @param $tsa_host (string) Time Stamping Authority (TSA) server (prefixed with 'https://')
  13061. * @param $tsa_username (string) Specifies the username for TSA authorization (optional) OR specifies the TSA authorization PEM file (see: example_66.php, optional)
  13062. * @param $tsa_password (string) Specifies the password for TSA authorization (optional)
  13063. * @param $tsa_cert (string) Specifies the location of TSA certificate for authorization (optional for cURL)
  13064. * @public
  13065. * @author Richard Stockinger
  13066. * @since 6.0.090 (2014-06-16)
  13067. */
  13068. public function setTimeStamp($tsa_host='', $tsa_username='', $tsa_password='', $tsa_cert='') {
  13069. $this->tsa_data = array();
  13070. if (!function_exists('curl_init')) {
  13071. $this->Error('Please enable cURL PHP extension!');
  13072. }
  13073. if (strlen($tsa_host) == 0) {
  13074. $this->Error('Please specify the host of Time Stamping Authority (TSA)!');
  13075. }
  13076. $this->tsa_data['tsa_host'] = $tsa_host;
  13077. if (is_file($tsa_username)) {
  13078. $this->tsa_data['tsa_auth'] = $tsa_username;
  13079. } else {
  13080. $this->tsa_data['tsa_username'] = $tsa_username;
  13081. }
  13082. $this->tsa_data['tsa_password'] = $tsa_password;
  13083. $this->tsa_data['tsa_cert'] = $tsa_cert;
  13084. $this->tsa_timestamp = true;
  13085. }
  13086. /**
  13087. * NOT YET IMPLEMENTED
  13088. * Request TSA for a timestamp
  13089. * @param $signature (string) Digital signature as binary string
  13090. * @return (string) Timestamped digital signature
  13091. * @protected
  13092. * @author Richard Stockinger
  13093. * @since 6.0.090 (2014-06-16)
  13094. */
  13095. protected function applyTSA($signature) {
  13096. if (!$this->tsa_timestamp) {
  13097. return $signature;
  13098. }
  13099. //@TODO: implement this feature
  13100. return $signature;
  13101. }
  13102. /**
  13103. * Create a new page group.
  13104. * NOTE: call this function before calling AddPage()
  13105. * @param $page (int) starting group page (leave empty for next page).
  13106. * @public
  13107. * @since 3.0.000 (2008-03-27)
  13108. */
  13109. public function startPageGroup($page='') {
  13110. if (empty($page)) {
  13111. $page = $this->page + 1;
  13112. }
  13113. $this->newpagegroup[$page] = sizeof($this->newpagegroup) + 1;
  13114. }
  13115. /**
  13116. * Set the starting page number.
  13117. * @param $num (int) Starting page number.
  13118. * @since 5.9.093 (2011-06-16)
  13119. * @public
  13120. */
  13121. public function setStartingPageNumber($num=1) {
  13122. $this->starting_page_number = max(0, intval($num));
  13123. }
  13124. /**
  13125. * Returns the string alias used right align page numbers.
  13126. * If the current font is unicode type, the returned string wil contain an additional open curly brace.
  13127. * @return string
  13128. * @since 5.9.099 (2011-06-27)
  13129. * @public
  13130. */
  13131. public function getAliasRightShift() {
  13132. // calculate aproximatively the ratio between widths of aliases and replacements.
  13133. $ref = '{'.TCPDF_STATIC::$alias_right_shift.'}{'.TCPDF_STATIC::$alias_tot_pages.'}{'.TCPDF_STATIC::$alias_num_page.'}';
  13134. $rep = str_repeat(' ', $this->GetNumChars($ref));
  13135. $wrep = $this->GetStringWidth($rep);
  13136. if ($wrep > 0) {
  13137. $wdiff = max(1, ($this->GetStringWidth($ref) / $wrep));
  13138. } else {
  13139. $wdiff = 1;
  13140. }
  13141. $sdiff = sprintf('%F', $wdiff);
  13142. $alias = TCPDF_STATIC::$alias_right_shift.$sdiff.'}';
  13143. if ($this->isUnicodeFont()) {
  13144. $alias = '{'.$alias;
  13145. }
  13146. return $alias;
  13147. }
  13148. /**
  13149. * Returns the string alias used for the total number of pages.
  13150. * If the current font is unicode type, the returned string is surrounded by additional curly braces.
  13151. * This alias will be replaced by the total number of pages in the document.
  13152. * @return string
  13153. * @since 4.0.018 (2008-08-08)
  13154. * @public
  13155. */
  13156. public function getAliasNbPages() {
  13157. if ($this->isUnicodeFont()) {
  13158. return '{'.TCPDF_STATIC::$alias_tot_pages.'}';
  13159. }
  13160. return TCPDF_STATIC::$alias_tot_pages;
  13161. }
  13162. /**
  13163. * Returns the string alias used for the page number.
  13164. * If the current font is unicode type, the returned string is surrounded by additional curly braces.
  13165. * This alias will be replaced by the page number.
  13166. * @return string
  13167. * @since 4.5.000 (2009-01-02)
  13168. * @public
  13169. */
  13170. public function getAliasNumPage() {
  13171. if ($this->isUnicodeFont()) {
  13172. return '{'.TCPDF_STATIC::$alias_num_page.'}';
  13173. }
  13174. return TCPDF_STATIC::$alias_num_page;
  13175. }
  13176. /**
  13177. * Return the alias for the total number of pages in the current page group.
  13178. * If the current font is unicode type, the returned string is surrounded by additional curly braces.
  13179. * This alias will be replaced by the total number of pages in this group.
  13180. * @return alias of the current page group
  13181. * @public
  13182. * @since 3.0.000 (2008-03-27)
  13183. */
  13184. public function getPageGroupAlias() {
  13185. if ($this->isUnicodeFont()) {
  13186. return '{'.TCPDF_STATIC::$alias_group_tot_pages.'}';
  13187. }
  13188. return TCPDF_STATIC::$alias_group_tot_pages;
  13189. }
  13190. /**
  13191. * Return the alias for the page number on the current page group.
  13192. * If the current font is unicode type, the returned string is surrounded by additional curly braces.
  13193. * This alias will be replaced by the page number (relative to the belonging group).
  13194. * @return alias of the current page group
  13195. * @public
  13196. * @since 4.5.000 (2009-01-02)
  13197. */
  13198. public function getPageNumGroupAlias() {
  13199. if ($this->isUnicodeFont()) {
  13200. return '{'.TCPDF_STATIC::$alias_group_num_page.'}';
  13201. }
  13202. return TCPDF_STATIC::$alias_group_num_page;
  13203. }
  13204. /**
  13205. * Return the current page in the group.
  13206. * @return current page in the group
  13207. * @public
  13208. * @since 3.0.000 (2008-03-27)
  13209. */
  13210. public function getGroupPageNo() {
  13211. return $this->pagegroups[$this->currpagegroup];
  13212. }
  13213. /**
  13214. * Returns the current group page number formatted as a string.
  13215. * @public
  13216. * @since 4.3.003 (2008-11-18)
  13217. * @see PaneNo(), formatPageNumber()
  13218. */
  13219. public function getGroupPageNoFormatted() {
  13220. return TCPDF_STATIC::formatPageNumber($this->getGroupPageNo());
  13221. }
  13222. /**
  13223. * Returns the current page number formatted as a string.
  13224. * @public
  13225. * @since 4.2.005 (2008-11-06)
  13226. * @see PaneNo(), formatPageNumber()
  13227. */
  13228. public function PageNoFormatted() {
  13229. return TCPDF_STATIC::formatPageNumber($this->PageNo());
  13230. }
  13231. /**
  13232. * Put pdf layers.
  13233. * @protected
  13234. * @since 3.0.000 (2008-03-27)
  13235. */
  13236. protected function _putocg() {
  13237. if (empty($this->pdflayers)) {
  13238. return;
  13239. }
  13240. foreach ($this->pdflayers as $key => $layer) {
  13241. $this->pdflayers[$key]['objid'] = $this->_newobj();
  13242. $out = '<< /Type /OCG';
  13243. $out .= ' /Name '.$this->_textstring($layer['name'], $this->pdflayers[$key]['objid']);
  13244. $out .= ' /Usage <<';
  13245. if (isset($layer['print']) AND ($layer['print'] !== NULL)) {
  13246. $out .= ' /Print <</PrintState /'.($layer['print']?'ON':'OFF').'>>';
  13247. }
  13248. $out .= ' /View <</ViewState /'.($layer['view']?'ON':'OFF').'>>';
  13249. $out .= ' >> >>';
  13250. $out .= "\n".'endobj';
  13251. $this->_out($out);
  13252. }
  13253. }
  13254. /**
  13255. * Start a new pdf layer.
  13256. * @param $name (string) Layer name (only a-z letters and numbers). Leave empty for automatic name.
  13257. * @param $print (boolean|null) Set to TRUE to print this layer, FALSE to not print and NULL to not set this option
  13258. * @param $view (boolean) Set to true to view this layer.
  13259. * @param $lock (boolean) If true lock the layer
  13260. * @public
  13261. * @since 5.9.102 (2011-07-13)
  13262. */
  13263. public function startLayer($name='', $print=true, $view=true, $lock=true) {
  13264. if ($this->state != 2) {
  13265. return;
  13266. }
  13267. $layer = sprintf('LYR%03d', (count($this->pdflayers) + 1));
  13268. if (empty($name)) {
  13269. $name = $layer;
  13270. } else {
  13271. $name = preg_replace('/[^a-zA-Z0-9_\-]/', '', $name);
  13272. }
  13273. $this->pdflayers[] = array('layer' => $layer, 'name' => $name, 'print' => $print, 'view' => $view, 'lock' => $lock);
  13274. $this->openMarkedContent = true;
  13275. $this->_out('/OC /'.$layer.' BDC');
  13276. }
  13277. /**
  13278. * End the current PDF layer.
  13279. * @public
  13280. * @since 5.9.102 (2011-07-13)
  13281. */
  13282. public function endLayer() {
  13283. if ($this->state != 2) {
  13284. return;
  13285. }
  13286. if ($this->openMarkedContent) {
  13287. // close existing open marked-content layer
  13288. $this->_out('EMC');
  13289. $this->openMarkedContent = false;
  13290. }
  13291. }
  13292. /**
  13293. * Set the visibility of the successive elements.
  13294. * This can be useful, for instance, to put a background
  13295. * image or color that will show on screen but won't print.
  13296. * @param $v (string) visibility mode. Legal values are: all, print, screen or view.
  13297. * @public
  13298. * @since 3.0.000 (2008-03-27)
  13299. */
  13300. public function setVisibility($v) {
  13301. if ($this->state != 2) {
  13302. return;
  13303. }
  13304. $this->endLayer();
  13305. switch($v) {
  13306. case 'print': {
  13307. $this->startLayer('Print', true, false);
  13308. break;
  13309. }
  13310. case 'view':
  13311. case 'screen': {
  13312. $this->startLayer('View', false, true);
  13313. break;
  13314. }
  13315. case 'all': {
  13316. $this->_out('');
  13317. break;
  13318. }
  13319. default: {
  13320. $this->Error('Incorrect visibility: '.$v);
  13321. break;
  13322. }
  13323. }
  13324. }
  13325. /**
  13326. * Add transparency parameters to the current extgstate
  13327. * @param $parms (array) parameters
  13328. * @return the number of extgstates
  13329. * @protected
  13330. * @since 3.0.000 (2008-03-27)
  13331. */
  13332. protected function addExtGState($parms) {
  13333. if ($this->pdfa_mode) {
  13334. // transparencies are not allowed in PDF/A mode
  13335. return;
  13336. }
  13337. // check if this ExtGState already exist
  13338. foreach ($this->extgstates as $i => $ext) {
  13339. if ($ext['parms'] == $parms) {
  13340. if ($this->inxobj) {
  13341. // we are inside an XObject template
  13342. $this->xobjects[$this->xobjid]['extgstates'][$i] = $ext;
  13343. }
  13344. // return reference to existing ExtGState
  13345. return $i;
  13346. }
  13347. }
  13348. $n = (count($this->extgstates) + 1);
  13349. $this->extgstates[$n] = array('parms' => $parms);
  13350. if ($this->inxobj) {
  13351. // we are inside an XObject template
  13352. $this->xobjects[$this->xobjid]['extgstates'][$n] = $this->extgstates[$n];
  13353. }
  13354. return $n;
  13355. }
  13356. /**
  13357. * Add an extgstate
  13358. * @param $gs (array) extgstate
  13359. * @protected
  13360. * @since 3.0.000 (2008-03-27)
  13361. */
  13362. protected function setExtGState($gs) {
  13363. if ($this->pdfa_mode OR ($this->state != 2)) {
  13364. // transparency is not allowed in PDF/A mode
  13365. return;
  13366. }
  13367. $this->_out(sprintf('/GS%d gs', $gs));
  13368. }
  13369. /**
  13370. * Put extgstates for object transparency
  13371. * @protected
  13372. * @since 3.0.000 (2008-03-27)
  13373. */
  13374. protected function _putextgstates() {
  13375. foreach ($this->extgstates as $i => $ext) {
  13376. $this->extgstates[$i]['n'] = $this->_newobj();
  13377. $out = '<< /Type /ExtGState';
  13378. foreach ($ext['parms'] as $k => $v) {
  13379. if (is_float($v)) {
  13380. $v = sprintf('%F', $v);
  13381. } elseif ($v === true) {
  13382. $v = 'true';
  13383. } elseif ($v === false) {
  13384. $v = 'false';
  13385. }
  13386. $out .= ' /'.$k.' '.$v;
  13387. }
  13388. $out .= ' >>';
  13389. $out .= "\n".'endobj';
  13390. $this->_out($out);
  13391. }
  13392. }
  13393. /**
  13394. * Set overprint mode for stroking (OP) and non-stroking (op) painting operations.
  13395. * (Check the "Entries in a Graphics State Parameter Dictionary" on PDF 32000-1:2008).
  13396. * @param $stroking (boolean) If true apply overprint for stroking operations.
  13397. * @param $nonstroking (boolean) If true apply overprint for painting operations other than stroking.
  13398. * @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).
  13399. * @public
  13400. * @since 5.9.152 (2012-03-23)
  13401. */
  13402. public function setOverprint($stroking=true, $nonstroking='', $mode=0) {
  13403. if ($this->state != 2) {
  13404. return;
  13405. }
  13406. $stroking = $stroking ? true : false;
  13407. if (TCPDF_STATIC::empty_string($nonstroking)) {
  13408. // default value if not set
  13409. $nonstroking = $stroking;
  13410. } else {
  13411. $nonstroking = $nonstroking ? true : false;
  13412. }
  13413. if (($mode != 0) AND ($mode != 1)) {
  13414. $mode = 0;
  13415. }
  13416. $this->overprint = array('OP' => $stroking, 'op' => $nonstroking, 'OPM' => $mode);
  13417. $gs = $this->addExtGState($this->overprint);
  13418. $this->setExtGState($gs);
  13419. }
  13420. /**
  13421. * Get the overprint mode array (OP, op, OPM).
  13422. * (Check the "Entries in a Graphics State Parameter Dictionary" on PDF 32000-1:2008).
  13423. * @return array.
  13424. * @public
  13425. * @since 5.9.152 (2012-03-23)
  13426. */
  13427. public function getOverprint() {
  13428. return $this->overprint;
  13429. }
  13430. /**
  13431. * Set alpha for stroking (CA) and non-stroking (ca) operations.
  13432. * @param $stroking (float) Alpha value for stroking operations: real value from 0 (transparent) to 1 (opaque).
  13433. * @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
  13434. * @param $nonstroking (float) Alpha value for non-stroking operations: real value from 0 (transparent) to 1 (opaque).
  13435. * @param $ais (boolean)
  13436. * @public
  13437. * @since 3.0.000 (2008-03-27)
  13438. */
  13439. public function setAlpha($stroking=1, $bm='Normal', $nonstroking='', $ais=false) {
  13440. if ($this->pdfa_mode) {
  13441. // transparency is not allowed in PDF/A mode
  13442. return;
  13443. }
  13444. $stroking = floatval($stroking);
  13445. if (TCPDF_STATIC::empty_string($nonstroking)) {
  13446. // default value if not set
  13447. $nonstroking = $stroking;
  13448. } else {
  13449. $nonstroking = floatval($nonstroking);
  13450. }
  13451. if ($bm[0] == '/') {
  13452. // remove trailing slash
  13453. $bm = substr($bm, 1);
  13454. }
  13455. if (!in_array($bm, array('Normal', 'Multiply', 'Screen', 'Overlay', 'Darken', 'Lighten', 'ColorDodge', 'ColorBurn', 'HardLight', 'SoftLight', 'Difference', 'Exclusion', 'Hue', 'Saturation', 'Color', 'Luminosity'))) {
  13456. $bm = 'Normal';
  13457. }
  13458. $ais = $ais ? true : false;
  13459. $this->alpha = array('CA' => $stroking, 'ca' => $nonstroking, 'BM' => '/'.$bm, 'AIS' => $ais);
  13460. $gs = $this->addExtGState($this->alpha);
  13461. $this->setExtGState($gs);
  13462. }
  13463. /**
  13464. * Get the alpha mode array (CA, ca, BM, AIS).
  13465. * (Check the "Entries in a Graphics State Parameter Dictionary" on PDF 32000-1:2008).
  13466. * @return array.
  13467. * @public
  13468. * @since 5.9.152 (2012-03-23)
  13469. */
  13470. public function getAlpha() {
  13471. return $this->alpha;
  13472. }
  13473. /**
  13474. * Set the default JPEG compression quality (1-100)
  13475. * @param $quality (int) JPEG quality, integer between 1 and 100
  13476. * @public
  13477. * @since 3.0.000 (2008-03-27)
  13478. */
  13479. public function setJPEGQuality($quality) {
  13480. if (($quality < 1) OR ($quality > 100)) {
  13481. $quality = 75;
  13482. }
  13483. $this->jpeg_quality = intval($quality);
  13484. }
  13485. /**
  13486. * Set the default number of columns in a row for HTML tables.
  13487. * @param $cols (int) number of columns
  13488. * @public
  13489. * @since 3.0.014 (2008-06-04)
  13490. */
  13491. public function setDefaultTableColumns($cols=4) {
  13492. $this->default_table_columns = intval($cols);
  13493. }
  13494. /**
  13495. * Set the height of the cell (line height) respect the font height.
  13496. * @param $h (int) cell proportion respect font height (typical value = 1.25).
  13497. * @public
  13498. * @since 3.0.014 (2008-06-04)
  13499. */
  13500. public function setCellHeightRatio($h) {
  13501. $this->cell_height_ratio = $h;
  13502. }
  13503. /**
  13504. * return the height of cell repect font height.
  13505. * @public
  13506. * @since 4.0.012 (2008-07-24)
  13507. */
  13508. public function getCellHeightRatio() {
  13509. return $this->cell_height_ratio;
  13510. }
  13511. /**
  13512. * Set the PDF version (check PDF reference for valid values).
  13513. * @param $version (string) PDF document version.
  13514. * @public
  13515. * @since 3.1.000 (2008-06-09)
  13516. */
  13517. public function setPDFVersion($version='1.7') {
  13518. if ($this->pdfa_mode && $this->pdfa_version == 1 ) {
  13519. // PDF/A mode
  13520. $this->PDFVersion = '1.4';
  13521. } else {
  13522. $this->PDFVersion = $version;
  13523. }
  13524. }
  13525. /**
  13526. * Set the viewer preferences dictionary controlling the way the document is to be presented on the screen or in print.
  13527. * (see Section 8.1 of PDF reference, "Viewer Preferences").
  13528. * <ul><li>HideToolbar boolean (Optional) A flag specifying whether to hide the viewer application's tool bars when the document is active. Default value: false.</li><li>HideMenubar boolean (Optional) A flag specifying whether to hide the viewer application's menu bar when the document is active. Default value: false.</li><li>HideWindowUI boolean (Optional) A flag specifying whether to hide user interface elements in the document's window (such as scroll bars and navigation controls), leaving only the document's contents displayed. Default value: false.</li><li>FitWindow boolean (Optional) A flag specifying whether to resize the document's window to fit the size of the first displayed page. Default value: false.</li><li>CenterWindow boolean (Optional) A flag specifying whether to position the document's window in the center of the screen. Default value: false.</li><li>DisplayDocTitle boolean (Optional; PDF 1.4) A flag specifying whether the window's title bar should display the document title taken from the Title entry of the document information dictionary (see Section 10.2.1, "Document Information Dictionary"). If false, the title bar should instead display the name of the PDF file containing the document. Default value: false.</li><li>NonFullScreenPageMode name (Optional) The document's page mode, specifying how to display the document on exiting full-screen mode:<ul><li>UseNone Neither document outline nor thumbnail images visible</li><li>UseOutlines Document outline visible</li><li>UseThumbs Thumbnail images visible</li><li>UseOC Optional content group panel visible</li></ul>This entry is meaningful only if the value of the PageMode entry in the catalog dictionary (see Section 3.6.1, "Document Catalog") is FullScreen; it is ignored otherwise. Default value: UseNone.</li><li>ViewArea name (Optional; PDF 1.4) The name of the page boundary representing the area of a page to be displayed when viewing the document on the screen. Valid values are (see Section 10.10.1, "Page Boundaries").:<ul><li>MediaBox</li><li>CropBox (default)</li><li>BleedBox</li><li>TrimBox</li><li>ArtBox</li></ul></li><li>ViewClip name (Optional; PDF 1.4) The name of the page boundary to which the contents of a page are to be clipped when viewing the document on the screen. Valid values are (see Section 10.10.1, "Page Boundaries").:<ul><li>MediaBox</li><li>CropBox (default)</li><li>BleedBox</li><li>TrimBox</li><li>ArtBox</li></ul></li><li>PrintArea name (Optional; PDF 1.4) The name of the page boundary representing the area of a page to be rendered when printing the document. Valid values are (see Section 10.10.1, "Page Boundaries").:<ul><li>MediaBox</li><li>CropBox (default)</li><li>BleedBox</li><li>TrimBox</li><li>ArtBox</li></ul></li><li>PrintClip name (Optional; PDF 1.4) The name of the page boundary to which the contents of a page are to be clipped when printing the document. Valid values are (see Section 10.10.1, "Page Boundaries").:<ul><li>MediaBox</li><li>CropBox (default)</li><li>BleedBox</li><li>TrimBox</li><li>ArtBox</li></ul></li><li>PrintScaling name (Optional; PDF 1.6) The page scaling option to be selected when a print dialog is displayed for this document. Valid values are: <ul><li>None, which indicates that the print dialog should reflect no page scaling</li><li>AppDefault (default), which indicates that applications should use the current print scaling</li></ul></li><li>Duplex name (Optional; PDF 1.7) The paper handling option to use when printing the file from the print dialog. The following values are valid:<ul><li>Simplex - Print single-sided</li><li>DuplexFlipShortEdge - Duplex and flip on the short edge of the sheet</li><li>DuplexFlipLongEdge - Duplex and flip on the long edge of the sheet</li></ul>Default value: none</li><li>PickTrayByPDFSize boolean (Optional; PDF 1.7) A flag specifying whether the PDF page size is used to select the input paper tray. This setting influences only the preset values used to populate the print dialog presented by a PDF viewer application. If PickTrayByPDFSize is true, the check box in the print dialog associated with input paper tray is checked. Note: This setting has no effect on Mac OS systems, which do not provide the ability to pick the input tray by size.</li><li>PrintPageRange array (Optional; PDF 1.7) The page numbers used to initialize the print dialog box when the file is printed. The first page of the PDF file is denoted by 1. Each pair consists of the first and last pages in the sub-range. An odd number of integers causes this entry to be ignored. Negative numbers cause the entire array to be ignored. Default value: as defined by PDF viewer application</li><li>NumCopies integer (Optional; PDF 1.7) The number of copies to be printed when the print dialog is opened for this file. Supported values are the integers 2 through 5. Values outside this range are ignored. Default value: as defined by PDF viewer application, but typically 1</li></ul>
  13529. * @param $preferences (array) array of options.
  13530. * @author Nicola Asuni
  13531. * @public
  13532. * @since 3.1.000 (2008-06-09)
  13533. */
  13534. public function setViewerPreferences($preferences) {
  13535. $this->viewer_preferences = $preferences;
  13536. }
  13537. /**
  13538. * Paints color transition registration bars
  13539. * @param $x (float) abscissa of the top left corner of the rectangle.
  13540. * @param $y (float) ordinate of the top left corner of the rectangle.
  13541. * @param $w (float) width of the rectangle.
  13542. * @param $h (float) height of the rectangle.
  13543. * @param $transition (boolean) if true prints tcolor transitions to white.
  13544. * @param $vertical (boolean) if true prints bar vertically.
  13545. * @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.
  13546. * @author Nicola Asuni
  13547. * @since 4.9.000 (2010-03-26)
  13548. * @public
  13549. */
  13550. public function colorRegistrationBar($x, $y, $w, $h, $transition=true, $vertical=false, $colors='A,R,G,B,C,M,Y,K') {
  13551. if (strpos($colors, 'ALLSPOT') !== false) {
  13552. // expand spot colors
  13553. $spot_colors = '';
  13554. foreach ($this->spot_colors as $spot_color_name => $v) {
  13555. $spot_colors .= ','.$spot_color_name;
  13556. }
  13557. if (!empty($spot_colors)) {
  13558. $spot_colors = substr($spot_colors, 1);
  13559. $colors = str_replace('ALLSPOT', $spot_colors, $colors);
  13560. } else {
  13561. $colors = str_replace('ALLSPOT', 'NONE', $colors);
  13562. }
  13563. }
  13564. $bars = explode(',', $colors);
  13565. $numbars = count($bars); // number of bars to print
  13566. if ($numbars <= 0) {
  13567. return;
  13568. }
  13569. // set bar measures
  13570. if ($vertical) {
  13571. $coords = array(0, 0, 0, 1);
  13572. $wb = $w / $numbars; // bar width
  13573. $hb = $h; // bar height
  13574. $xd = $wb; // delta x
  13575. $yd = 0; // delta y
  13576. } else {
  13577. $coords = array(1, 0, 0, 0);
  13578. $wb = $w; // bar width
  13579. $hb = $h / $numbars; // bar height
  13580. $xd = 0; // delta x
  13581. $yd = $hb; // delta y
  13582. }
  13583. $xb = $x;
  13584. $yb = $y;
  13585. foreach ($bars as $col) {
  13586. switch ($col) {
  13587. // set transition colors
  13588. case 'A': { // BLACK (GRAYSCALE)
  13589. $col_a = array(255);
  13590. $col_b = array(0);
  13591. break;
  13592. }
  13593. case 'W': { // WHITE (GRAYSCALE)
  13594. $col_a = array(0);
  13595. $col_b = array(255);
  13596. break;
  13597. }
  13598. case 'R': { // RED (RGB)
  13599. $col_a = array(255,255,255);
  13600. $col_b = array(255,0,0);
  13601. break;
  13602. }
  13603. case 'G': { // GREEN (RGB)
  13604. $col_a = array(255,255,255);
  13605. $col_b = array(0,255,0);
  13606. break;
  13607. }
  13608. case 'B': { // BLUE (RGB)
  13609. $col_a = array(255,255,255);
  13610. $col_b = array(0,0,255);
  13611. break;
  13612. }
  13613. case 'C': { // CYAN (CMYK)
  13614. $col_a = array(0,0,0,0);
  13615. $col_b = array(100,0,0,0);
  13616. break;
  13617. }
  13618. case 'M': { // MAGENTA (CMYK)
  13619. $col_a = array(0,0,0,0);
  13620. $col_b = array(0,100,0,0);
  13621. break;
  13622. }
  13623. case 'Y': { // YELLOW (CMYK)
  13624. $col_a = array(0,0,0,0);
  13625. $col_b = array(0,0,100,0);
  13626. break;
  13627. }
  13628. case 'K': { // KEY - BLACK (CMYK)
  13629. $col_a = array(0,0,0,0);
  13630. $col_b = array(0,0,0,100);
  13631. break;
  13632. }
  13633. case 'RGB': { // BLACK REGISTRATION (RGB)
  13634. $col_a = array(255,255,255);
  13635. $col_b = array(0,0,0);
  13636. break;
  13637. }
  13638. case 'CMYK': { // BLACK REGISTRATION (CMYK)
  13639. $col_a = array(0,0,0,0);
  13640. $col_b = array(100,100,100,100);
  13641. break;
  13642. }
  13643. case 'ALL': { // SPOT COLOR REGISTRATION
  13644. $col_a = array(0,0,0,0,'None');
  13645. $col_b = array(100,100,100,100,'All');
  13646. break;
  13647. }
  13648. case 'NONE': { // SKIP THIS COLOR
  13649. $col_a = array(0,0,0,0,'None');
  13650. $col_b = array(0,0,0,0,'None');
  13651. break;
  13652. }
  13653. default: { // SPECIFIC SPOT COLOR NAME
  13654. $col_a = array(0,0,0,0,'None');
  13655. $col_b = TCPDF_COLORS::getSpotColor($col, $this->spot_colors);
  13656. if ($col_b === false) {
  13657. // in case of error defaults to the registration color
  13658. $col_b = array(100,100,100,100,'All');
  13659. }
  13660. break;
  13661. }
  13662. }
  13663. if ($col != 'NONE') {
  13664. if ($transition) {
  13665. // color gradient
  13666. $this->LinearGradient($xb, $yb, $wb, $hb, $col_a, $col_b, $coords);
  13667. } else {
  13668. $this->SetFillColorArray($col_b);
  13669. // colored rectangle
  13670. $this->Rect($xb, $yb, $wb, $hb, 'F', array());
  13671. }
  13672. $xb += $xd;
  13673. $yb += $yd;
  13674. }
  13675. }
  13676. }
  13677. /**
  13678. * Paints crop marks.
  13679. * @param $x (float) abscissa of the crop mark center.
  13680. * @param $y (float) ordinate of the crop mark center.
  13681. * @param $w (float) width of the crop mark.
  13682. * @param $h (float) height of the crop mark.
  13683. * @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.
  13684. * @param $color (array) crop mark color (default spot registration color).
  13685. * @author Nicola Asuni
  13686. * @since 4.9.000 (2010-03-26)
  13687. * @public
  13688. */
  13689. public function cropMark($x, $y, $w, $h, $type='T,R,B,L', $color=array(100,100,100,100,'All')) {
  13690. $this->SetLineStyle(array('width' => (0.5 / $this->k), 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => $color));
  13691. $type = strtoupper($type);
  13692. $type = preg_replace('/[^A-Z\-\,]*/', '', $type);
  13693. // split type in single components
  13694. $type = str_replace('-', ',', $type);
  13695. $type = str_replace('TL', 'T,L', $type);
  13696. $type = str_replace('TR', 'T,R', $type);
  13697. $type = str_replace('BL', 'F,L', $type);
  13698. $type = str_replace('BR', 'F,R', $type);
  13699. $type = str_replace('A', 'T,L', $type);
  13700. $type = str_replace('B', 'T,R', $type);
  13701. $type = str_replace('T,RO', 'BO', $type);
  13702. $type = str_replace('C', 'F,L', $type);
  13703. $type = str_replace('D', 'F,R', $type);
  13704. $crops = explode(',', strtoupper($type));
  13705. // remove duplicates
  13706. $crops = array_unique($crops);
  13707. $dw = ($w / 4); // horizontal space to leave before the intersection point
  13708. $dh = ($h / 4); // vertical space to leave before the intersection point
  13709. foreach ($crops as $crop) {
  13710. switch ($crop) {
  13711. case 'T':
  13712. case 'TOP': {
  13713. $x1 = $x;
  13714. $y1 = ($y - $h);
  13715. $x2 = $x;
  13716. $y2 = ($y - $dh);
  13717. break;
  13718. }
  13719. case 'F':
  13720. case 'BOTTOM': {
  13721. $x1 = $x;
  13722. $y1 = ($y + $dh);
  13723. $x2 = $x;
  13724. $y2 = ($y + $h);
  13725. break;
  13726. }
  13727. case 'L':
  13728. case 'LEFT': {
  13729. $x1 = ($x - $w);
  13730. $y1 = $y;
  13731. $x2 = ($x - $dw);
  13732. $y2 = $y;
  13733. break;
  13734. }
  13735. case 'R':
  13736. case 'RIGHT': {
  13737. $x1 = ($x + $dw);
  13738. $y1 = $y;
  13739. $x2 = ($x + $w);
  13740. $y2 = $y;
  13741. break;
  13742. }
  13743. }
  13744. $this->Line($x1, $y1, $x2, $y2);
  13745. }
  13746. }
  13747. /**
  13748. * Paints a registration mark
  13749. * @param $x (float) abscissa of the registration mark center.
  13750. * @param $y (float) ordinate of the registration mark center.
  13751. * @param $r (float) radius of the crop mark.
  13752. * @param $double (boolean) if true print two concentric crop marks.
  13753. * @param $cola (array) crop mark color (default spot registration color 'All').
  13754. * @param $colb (array) second crop mark color (default spot registration color 'None').
  13755. * @author Nicola Asuni
  13756. * @since 4.9.000 (2010-03-26)
  13757. * @public
  13758. */
  13759. public function registrationMark($x, $y, $r, $double=false, $cola=array(100,100,100,100,'All'), $colb=array(0,0,0,0,'None')) {
  13760. $line_style = array('width' => max((0.5 / $this->k),($r / 30)), 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => $cola);
  13761. $this->SetFillColorArray($cola);
  13762. $this->PieSector($x, $y, $r, 90, 180, 'F');
  13763. $this->PieSector($x, $y, $r, 270, 360, 'F');
  13764. $this->Circle($x, $y, $r, 0, 360, 'C', $line_style, array(), 8);
  13765. if ($double) {
  13766. $ri = $r * 0.5;
  13767. $this->SetFillColorArray($colb);
  13768. $this->PieSector($x, $y, $ri, 90, 180, 'F');
  13769. $this->PieSector($x, $y, $ri, 270, 360, 'F');
  13770. $this->SetFillColorArray($cola);
  13771. $this->PieSector($x, $y, $ri, 0, 90, 'F');
  13772. $this->PieSector($x, $y, $ri, 180, 270, 'F');
  13773. $this->Circle($x, $y, $ri, 0, 360, 'C', $line_style, array(), 8);
  13774. }
  13775. }
  13776. /**
  13777. * Paints a CMYK registration mark
  13778. * @param $x (float) abscissa of the registration mark center.
  13779. * @param $y (float) ordinate of the registration mark center.
  13780. * @param $r (float) radius of the crop mark.
  13781. * @author Nicola Asuni
  13782. * @since 6.0.038 (2013-09-30)
  13783. * @public
  13784. */
  13785. public function registrationMarkCMYK($x, $y, $r) {
  13786. // line width
  13787. $lw = max((0.5 / $this->k),($r / 8));
  13788. // internal radius
  13789. $ri = ($r * 0.6);
  13790. // external radius
  13791. $re = ($r * 1.3);
  13792. // Cyan
  13793. $this->SetFillColorArray(array(100,0,0,0));
  13794. $this->PieSector($x, $y, $ri, 270, 360, 'F');
  13795. // Magenta
  13796. $this->SetFillColorArray(array(0,100,0,0));
  13797. $this->PieSector($x, $y, $ri, 0, 90, 'F');
  13798. // Yellow
  13799. $this->SetFillColorArray(array(0,0,100,0));
  13800. $this->PieSector($x, $y, $ri, 90, 180, 'F');
  13801. // Key - black
  13802. $this->SetFillColorArray(array(0,0,0,100));
  13803. $this->PieSector($x, $y, $ri, 180, 270, 'F');
  13804. // registration color
  13805. $line_style = array('width' => $lw, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(100,100,100,100,'All'));
  13806. $this->SetFillColorArray(array(100,100,100,100,'All'));
  13807. // external circle
  13808. $this->Circle($x, $y, $r, 0, 360, 'C', $line_style, array(), 8);
  13809. // cross lines
  13810. $this->Line($x, ($y - $re), $x, ($y - $ri));
  13811. $this->Line($x, ($y + $ri), $x, ($y + $re));
  13812. $this->Line(($x - $re), $y, ($x - $ri), $y);
  13813. $this->Line(($x + $ri), $y, ($x + $re), $y);
  13814. }
  13815. /**
  13816. * Paints a linear colour gradient.
  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 (Grayscale, RGB or CMYK components).
  13822. * @param $col2 (array) second color (Grayscale, RGB or CMYK components).
  13823. * @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).
  13824. * @author Andreas W\FCrmser, Nicola Asuni
  13825. * @since 3.1.000 (2008-06-09)
  13826. * @public
  13827. */
  13828. public function LinearGradient($x, $y, $w, $h, $col1=array(), $col2=array(), $coords=array(0,0,1,0)) {
  13829. $this->Clip($x, $y, $w, $h);
  13830. $this->Gradient(2, $coords, array(array('color' => $col1, 'offset' => 0, 'exponent' => 1), array('color' => $col2, 'offset' => 1, 'exponent' => 1)), array(), false);
  13831. }
  13832. /**
  13833. * Paints a radial colour gradient.
  13834. * @param $x (float) abscissa of the top left corner of the rectangle.
  13835. * @param $y (float) ordinate of the top left corner of the rectangle.
  13836. * @param $w (float) width of the rectangle.
  13837. * @param $h (float) height of the rectangle.
  13838. * @param $col1 (array) first color (Grayscale, RGB or CMYK components).
  13839. * @param $col2 (array) second color (Grayscale, RGB or CMYK components).
  13840. * @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.
  13841. * @author Andreas W\FCrmser, Nicola Asuni
  13842. * @since 3.1.000 (2008-06-09)
  13843. * @public
  13844. */
  13845. public function RadialGradient($x, $y, $w, $h, $col1=array(), $col2=array(), $coords=array(0.5,0.5,0.5,0.5,1)) {
  13846. $this->Clip($x, $y, $w, $h);
  13847. $this->Gradient(3, $coords, array(array('color' => $col1, 'offset' => 0, 'exponent' => 1), array('color' => $col2, 'offset' => 1, 'exponent' => 1)), array(), false);
  13848. }
  13849. /**
  13850. * Paints a coons patch mesh.
  13851. * @param $x (float) abscissa of the top left corner of the rectangle.
  13852. * @param $y (float) ordinate of the top left corner of the rectangle.
  13853. * @param $w (float) width of the rectangle.
  13854. * @param $h (float) height of the rectangle.
  13855. * @param $col1 (array) first color (lower left corner) (RGB components).
  13856. * @param $col2 (array) second color (lower right corner) (RGB components).
  13857. * @param $col3 (array) third color (upper right corner) (RGB components).
  13858. * @param $col4 (array) fourth color (upper left corner) (RGB components).
  13859. * @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>
  13860. * @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
  13861. * @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
  13862. * @param $antialias (boolean) A flag indicating whether to filter the shading function to prevent aliasing artifacts.
  13863. * @author Andreas W\FCrmser, Nicola Asuni
  13864. * @since 3.1.000 (2008-06-09)
  13865. * @public
  13866. */
  13867. 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) {
  13868. if ($this->pdfa_mode OR ($this->state != 2)) {
  13869. return;
  13870. }
  13871. $this->Clip($x, $y, $w, $h);
  13872. $n = count($this->gradients) + 1;
  13873. $this->gradients[$n] = array();
  13874. $this->gradients[$n]['type'] = 6; //coons patch mesh
  13875. $this->gradients[$n]['coords'] = array();
  13876. $this->gradients[$n]['antialias'] = $antialias;
  13877. $this->gradients[$n]['colors'] = array();
  13878. $this->gradients[$n]['transparency'] = false;
  13879. //check the coords array if it is the simple array or the multi patch array
  13880. if (!isset($coords[0]['f'])) {
  13881. //simple array -> convert to multi patch array
  13882. if (!isset($col1[1])) {
  13883. $col1[1] = $col1[2] = $col1[0];
  13884. }
  13885. if (!isset($col2[1])) {
  13886. $col2[1] = $col2[2] = $col2[0];
  13887. }
  13888. if (!isset($col3[1])) {
  13889. $col3[1] = $col3[2] = $col3[0];
  13890. }
  13891. if (!isset($col4[1])) {
  13892. $col4[1] = $col4[2] = $col4[0];
  13893. }
  13894. $patch_array[0]['f'] = 0;
  13895. $patch_array[0]['points'] = $coords;
  13896. $patch_array[0]['colors'][0]['r'] = $col1[0];
  13897. $patch_array[0]['colors'][0]['g'] = $col1[1];
  13898. $patch_array[0]['colors'][0]['b'] = $col1[2];
  13899. $patch_array[0]['colors'][1]['r'] = $col2[0];
  13900. $patch_array[0]['colors'][1]['g'] = $col2[1];
  13901. $patch_array[0]['colors'][1]['b'] = $col2[2];
  13902. $patch_array[0]['colors'][2]['r'] = $col3[0];
  13903. $patch_array[0]['colors'][2]['g'] = $col3[1];
  13904. $patch_array[0]['colors'][2]['b'] = $col3[2];
  13905. $patch_array[0]['colors'][3]['r'] = $col4[0];
  13906. $patch_array[0]['colors'][3]['g'] = $col4[1];
  13907. $patch_array[0]['colors'][3]['b'] = $col4[2];
  13908. } else {
  13909. //multi patch array
  13910. $patch_array = $coords;
  13911. }
  13912. $bpcd = 65535; //16 bits per coordinate
  13913. //build the data stream
  13914. $this->gradients[$n]['stream'] = '';
  13915. $count_patch = count($patch_array);
  13916. for ($i=0; $i < $count_patch; ++$i) {
  13917. $this->gradients[$n]['stream'] .= chr($patch_array[$i]['f']); //start with the edge flag as 8 bit
  13918. $count_points = count($patch_array[$i]['points']);
  13919. for ($j=0; $j < $count_points; ++$j) {
  13920. //each point as 16 bit
  13921. $patch_array[$i]['points'][$j] = (($patch_array[$i]['points'][$j] - $coords_min) / ($coords_max - $coords_min)) * $bpcd;
  13922. if ($patch_array[$i]['points'][$j] < 0) {
  13923. $patch_array[$i]['points'][$j] = 0;
  13924. }
  13925. if ($patch_array[$i]['points'][$j] > $bpcd) {
  13926. $patch_array[$i]['points'][$j] = $bpcd;
  13927. }
  13928. $this->gradients[$n]['stream'] .= chr(floor($patch_array[$i]['points'][$j] / 256));
  13929. $this->gradients[$n]['stream'] .= chr(floor($patch_array[$i]['points'][$j] % 256));
  13930. }
  13931. $count_cols = count($patch_array[$i]['colors']);
  13932. for ($j=0; $j < $count_cols; ++$j) {
  13933. //each color component as 8 bit
  13934. $this->gradients[$n]['stream'] .= chr($patch_array[$i]['colors'][$j]['r']);
  13935. $this->gradients[$n]['stream'] .= chr($patch_array[$i]['colors'][$j]['g']);
  13936. $this->gradients[$n]['stream'] .= chr($patch_array[$i]['colors'][$j]['b']);
  13937. }
  13938. }
  13939. //paint the gradient
  13940. $this->_out('/Sh'.$n.' sh');
  13941. //restore previous Graphic State
  13942. $this->_outRestoreGraphicsState();
  13943. if ($this->inxobj) {
  13944. // we are inside an XObject template
  13945. $this->xobjects[$this->xobjid]['gradients'][$n] = $this->gradients[$n];
  13946. }
  13947. }
  13948. /**
  13949. * Set a rectangular clipping area.
  13950. * @param $x (float) abscissa of the top left corner of the rectangle (or top right corner for RTL mode).
  13951. * @param $y (float) ordinate of the top left corner of the rectangle.
  13952. * @param $w (float) width of the rectangle.
  13953. * @param $h (float) height of the rectangle.
  13954. * @author Andreas W\FCrmser, Nicola Asuni
  13955. * @since 3.1.000 (2008-06-09)
  13956. * @protected
  13957. */
  13958. protected function Clip($x, $y, $w, $h) {
  13959. if ($this->state != 2) {
  13960. return;
  13961. }
  13962. if ($this->rtl) {
  13963. $x = $this->w - $x - $w;
  13964. }
  13965. //save current Graphic State
  13966. $s = 'q';
  13967. //set clipping area
  13968. $s .= sprintf(' %F %F %F %F re W n', $x*$this->k, ($this->h-$y)*$this->k, $w*$this->k, -$h*$this->k);
  13969. //set up transformation matrix for gradient
  13970. $s .= sprintf(' %F 0 0 %F %F %F cm', $w*$this->k, $h*$this->k, $x*$this->k, ($this->h-($y+$h))*$this->k);
  13971. $this->_out($s);
  13972. }
  13973. /**
  13974. * Output gradient.
  13975. * @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)
  13976. * @param $coords (array) array of coordinates.
  13977. * @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).
  13978. * @param $background (array) An array of colour components appropriate to the colour space, specifying a single background colour value.
  13979. * @param $antialias (boolean) A flag indicating whether to filter the shading function to prevent aliasing artifacts.
  13980. * @author Nicola Asuni
  13981. * @since 3.1.000 (2008-06-09)
  13982. * @public
  13983. */
  13984. public function Gradient($type, $coords, $stops, $background=array(), $antialias=false) {
  13985. if ($this->pdfa_mode OR ($this->state != 2)) {
  13986. return;
  13987. }
  13988. $n = count($this->gradients) + 1;
  13989. $this->gradients[$n] = array();
  13990. $this->gradients[$n]['type'] = $type;
  13991. $this->gradients[$n]['coords'] = $coords;
  13992. $this->gradients[$n]['antialias'] = $antialias;
  13993. $this->gradients[$n]['colors'] = array();
  13994. $this->gradients[$n]['transparency'] = false;
  13995. // color space
  13996. $numcolspace = count($stops[0]['color']);
  13997. $bcolor = array_values($background);
  13998. switch($numcolspace) {
  13999. case 5: // SPOT
  14000. case 4: { // CMYK
  14001. $this->gradients[$n]['colspace'] = 'DeviceCMYK';
  14002. if (!empty($background)) {
  14003. $this->gradients[$n]['background'] = sprintf('%F %F %F %F', $bcolor[0]/100, $bcolor[1]/100, $bcolor[2]/100, $bcolor[3]/100);
  14004. }
  14005. break;
  14006. }
  14007. case 3: { // RGB
  14008. $this->gradients[$n]['colspace'] = 'DeviceRGB';
  14009. if (!empty($background)) {
  14010. $this->gradients[$n]['background'] = sprintf('%F %F %F', $bcolor[0]/255, $bcolor[1]/255, $bcolor[2]/255);
  14011. }
  14012. break;
  14013. }
  14014. case 1: { // GRAY SCALE
  14015. $this->gradients[$n]['colspace'] = 'DeviceGray';
  14016. if (!empty($background)) {
  14017. $this->gradients[$n]['background'] = sprintf('%F', $bcolor[0]/255);
  14018. }
  14019. break;
  14020. }
  14021. }
  14022. $num_stops = count($stops);
  14023. $last_stop_id = $num_stops - 1;
  14024. foreach ($stops as $key => $stop) {
  14025. $this->gradients[$n]['colors'][$key] = array();
  14026. // offset represents a location along the gradient vector
  14027. if (isset($stop['offset'])) {
  14028. $this->gradients[$n]['colors'][$key]['offset'] = $stop['offset'];
  14029. } else {
  14030. if ($key == 0) {
  14031. $this->gradients[$n]['colors'][$key]['offset'] = 0;
  14032. } elseif ($key == $last_stop_id) {
  14033. $this->gradients[$n]['colors'][$key]['offset'] = 1;
  14034. } else {
  14035. $offsetstep = (1 - $this->gradients[$n]['colors'][($key - 1)]['offset']) / ($num_stops - $key);
  14036. $this->gradients[$n]['colors'][$key]['offset'] = $this->gradients[$n]['colors'][($key - 1)]['offset'] + $offsetstep;
  14037. }
  14038. }
  14039. if (isset($stop['opacity'])) {
  14040. $this->gradients[$n]['colors'][$key]['opacity'] = $stop['opacity'];
  14041. if ((!$this->pdfa_mode) AND ($stop['opacity'] < 1)) {
  14042. $this->gradients[$n]['transparency'] = true;
  14043. }
  14044. } else {
  14045. $this->gradients[$n]['colors'][$key]['opacity'] = 1;
  14046. }
  14047. // exponent for the exponential interpolation function
  14048. if (isset($stop['exponent'])) {
  14049. $this->gradients[$n]['colors'][$key]['exponent'] = $stop['exponent'];
  14050. } else {
  14051. $this->gradients[$n]['colors'][$key]['exponent'] = 1;
  14052. }
  14053. // set colors
  14054. $color = array_values($stop['color']);
  14055. switch($numcolspace) {
  14056. case 5: // SPOT
  14057. case 4: { // CMYK
  14058. $this->gradients[$n]['colors'][$key]['color'] = sprintf('%F %F %F %F', $color[0]/100, $color[1]/100, $color[2]/100, $color[3]/100);
  14059. break;
  14060. }
  14061. case 3: { // RGB
  14062. $this->gradients[$n]['colors'][$key]['color'] = sprintf('%F %F %F', $color[0]/255, $color[1]/255, $color[2]/255);
  14063. break;
  14064. }
  14065. case 1: { // GRAY SCALE
  14066. $this->gradients[$n]['colors'][$key]['color'] = sprintf('%F', $color[0]/255);
  14067. break;
  14068. }
  14069. }
  14070. }
  14071. if ($this->gradients[$n]['transparency']) {
  14072. // paint luminosity gradient
  14073. $this->_out('/TGS'.$n.' gs');
  14074. }
  14075. //paint the gradient
  14076. $this->_out('/Sh'.$n.' sh');
  14077. //restore previous Graphic State
  14078. $this->_outRestoreGraphicsState();
  14079. if ($this->inxobj) {
  14080. // we are inside an XObject template
  14081. $this->xobjects[$this->xobjid]['gradients'][$n] = $this->gradients[$n];
  14082. }
  14083. }
  14084. /**
  14085. * Output gradient shaders.
  14086. * @author Nicola Asuni
  14087. * @since 3.1.000 (2008-06-09)
  14088. * @protected
  14089. */
  14090. function _putshaders() {
  14091. if ($this->pdfa_mode) {
  14092. return;
  14093. }
  14094. $idt = count($this->gradients); //index for transparency gradients
  14095. foreach ($this->gradients as $id => $grad) {
  14096. if (($grad['type'] == 2) OR ($grad['type'] == 3)) {
  14097. $fc = $this->_newobj();
  14098. $out = '<<';
  14099. $out .= ' /FunctionType 3';
  14100. $out .= ' /Domain [0 1]';
  14101. $functions = '';
  14102. $bounds = '';
  14103. $encode = '';
  14104. $i = 1;
  14105. $num_cols = count($grad['colors']);
  14106. $lastcols = $num_cols - 1;
  14107. for ($i = 1; $i < $num_cols; ++$i) {
  14108. $functions .= ($fc + $i).' 0 R ';
  14109. if ($i < $lastcols) {
  14110. $bounds .= sprintf('%F ', $grad['colors'][$i]['offset']);
  14111. }
  14112. $encode .= '0 1 ';
  14113. }
  14114. $out .= ' /Functions ['.trim($functions).']';
  14115. $out .= ' /Bounds ['.trim($bounds).']';
  14116. $out .= ' /Encode ['.trim($encode).']';
  14117. $out .= ' >>';
  14118. $out .= "\n".'endobj';
  14119. $this->_out($out);
  14120. for ($i = 1; $i < $num_cols; ++$i) {
  14121. $this->_newobj();
  14122. $out = '<<';
  14123. $out .= ' /FunctionType 2';
  14124. $out .= ' /Domain [0 1]';
  14125. $out .= ' /C0 ['.$grad['colors'][($i - 1)]['color'].']';
  14126. $out .= ' /C1 ['.$grad['colors'][$i]['color'].']';
  14127. $out .= ' /N '.$grad['colors'][$i]['exponent'];
  14128. $out .= ' >>';
  14129. $out .= "\n".'endobj';
  14130. $this->_out($out);
  14131. }
  14132. // set transparency functions
  14133. if ($grad['transparency']) {
  14134. $ft = $this->_newobj();
  14135. $out = '<<';
  14136. $out .= ' /FunctionType 3';
  14137. $out .= ' /Domain [0 1]';
  14138. $functions = '';
  14139. $i = 1;
  14140. $num_cols = count($grad['colors']);
  14141. for ($i = 1; $i < $num_cols; ++$i) {
  14142. $functions .= ($ft + $i).' 0 R ';
  14143. }
  14144. $out .= ' /Functions ['.trim($functions).']';
  14145. $out .= ' /Bounds ['.trim($bounds).']';
  14146. $out .= ' /Encode ['.trim($encode).']';
  14147. $out .= ' >>';
  14148. $out .= "\n".'endobj';
  14149. $this->_out($out);
  14150. for ($i = 1; $i < $num_cols; ++$i) {
  14151. $this->_newobj();
  14152. $out = '<<';
  14153. $out .= ' /FunctionType 2';
  14154. $out .= ' /Domain [0 1]';
  14155. $out .= ' /C0 ['.$grad['colors'][($i - 1)]['opacity'].']';
  14156. $out .= ' /C1 ['.$grad['colors'][$i]['opacity'].']';
  14157. $out .= ' /N '.$grad['colors'][$i]['exponent'];
  14158. $out .= ' >>';
  14159. $out .= "\n".'endobj';
  14160. $this->_out($out);
  14161. }
  14162. }
  14163. }
  14164. // set shading object
  14165. $this->_newobj();
  14166. $out = '<< /ShadingType '.$grad['type'];
  14167. if (isset($grad['colspace'])) {
  14168. $out .= ' /ColorSpace /'.$grad['colspace'];
  14169. } else {
  14170. $out .= ' /ColorSpace /DeviceRGB';
  14171. }
  14172. if (isset($grad['background']) AND !empty($grad['background'])) {
  14173. $out .= ' /Background ['.$grad['background'].']';
  14174. }
  14175. if (isset($grad['antialias']) AND ($grad['antialias'] === true)) {
  14176. $out .= ' /AntiAlias true';
  14177. }
  14178. if ($grad['type'] == 2) {
  14179. $out .= ' '.sprintf('/Coords [%F %F %F %F]', $grad['coords'][0], $grad['coords'][1], $grad['coords'][2], $grad['coords'][3]);
  14180. $out .= ' /Domain [0 1]';
  14181. $out .= ' /Function '.$fc.' 0 R';
  14182. $out .= ' /Extend [true true]';
  14183. $out .= ' >>';
  14184. } elseif ($grad['type'] == 3) {
  14185. //x0, y0, r0, x1, y1, r1
  14186. //at this this time radius of inner circle is 0
  14187. $out .= ' '.sprintf('/Coords [%F %F 0 %F %F %F]', $grad['coords'][0], $grad['coords'][1], $grad['coords'][2], $grad['coords'][3], $grad['coords'][4]);
  14188. $out .= ' /Domain [0 1]';
  14189. $out .= ' /Function '.$fc.' 0 R';
  14190. $out .= ' /Extend [true true]';
  14191. $out .= ' >>';
  14192. } elseif ($grad['type'] == 6) {
  14193. $out .= ' /BitsPerCoordinate 16';
  14194. $out .= ' /BitsPerComponent 8';
  14195. $out .= ' /Decode[0 1 0 1 0 1 0 1 0 1]';
  14196. $out .= ' /BitsPerFlag 8';
  14197. $stream = $this->_getrawstream($grad['stream']);
  14198. $out .= ' /Length '.strlen($stream);
  14199. $out .= ' >>';
  14200. $out .= ' stream'."\n".$stream."\n".'endstream';
  14201. }
  14202. $out .= "\n".'endobj';
  14203. $this->_out($out);
  14204. if ($grad['transparency']) {
  14205. $shading_transparency = preg_replace('/\/ColorSpace \/[^\s]+/si', '/ColorSpace /DeviceGray', $out);
  14206. $shading_transparency = preg_replace('/\/Function [0-9]+ /si', '/Function '.$ft.' ', $shading_transparency);
  14207. }
  14208. $this->gradients[$id]['id'] = $this->n;
  14209. // set pattern object
  14210. $this->_newobj();
  14211. $out = '<< /Type /Pattern /PatternType 2';
  14212. $out .= ' /Shading '.$this->gradients[$id]['id'].' 0 R';
  14213. $out .= ' >>';
  14214. $out .= "\n".'endobj';
  14215. $this->_out($out);
  14216. $this->gradients[$id]['pattern'] = $this->n;
  14217. // set shading and pattern for transparency mask
  14218. if ($grad['transparency']) {
  14219. // luminosity pattern
  14220. $idgs = $id + $idt;
  14221. $this->_newobj();
  14222. $this->_out($shading_transparency);
  14223. $this->gradients[$idgs]['id'] = $this->n;
  14224. $this->_newobj();
  14225. $out = '<< /Type /Pattern /PatternType 2';
  14226. $out .= ' /Shading '.$this->gradients[$idgs]['id'].' 0 R';
  14227. $out .= ' >>';
  14228. $out .= "\n".'endobj';
  14229. $this->_out($out);
  14230. $this->gradients[$idgs]['pattern'] = $this->n;
  14231. // luminosity XObject
  14232. $oid = $this->_newobj();
  14233. $this->xobjects['LX'.$oid] = array('n' => $oid);
  14234. $filter = '';
  14235. $stream = 'q /a0 gs /Pattern cs /p'.$idgs.' scn 0 0 '.$this->wPt.' '.$this->hPt.' re f Q';
  14236. if ($this->compress) {
  14237. $filter = ' /Filter /FlateDecode';
  14238. $stream = gzcompress($stream);
  14239. }
  14240. $stream = $this->_getrawstream($stream);
  14241. $out = '<< /Type /XObject /Subtype /Form /FormType 1'.$filter;
  14242. $out .= ' /Length '.strlen($stream);
  14243. $rect = sprintf('%F %F', $this->wPt, $this->hPt);
  14244. $out .= ' /BBox [0 0 '.$rect.']';
  14245. $out .= ' /Group << /Type /Group /S /Transparency /CS /DeviceGray >>';
  14246. $out .= ' /Resources <<';
  14247. $out .= ' /ExtGState << /a0 << /ca 1 /CA 1 >> >>';
  14248. $out .= ' /Pattern << /p'.$idgs.' '.$this->gradients[$idgs]['pattern'].' 0 R >>';
  14249. $out .= ' >>';
  14250. $out .= ' >> ';
  14251. $out .= ' stream'."\n".$stream."\n".'endstream';
  14252. $out .= "\n".'endobj';
  14253. $this->_out($out);
  14254. // SMask
  14255. $this->_newobj();
  14256. $out = '<< /Type /Mask /S /Luminosity /G '.($this->n - 1).' 0 R >>'."\n".'endobj';
  14257. $this->_out($out);
  14258. // ExtGState
  14259. $this->_newobj();
  14260. $out = '<< /Type /ExtGState /SMask '.($this->n - 1).' 0 R /AIS false >>'."\n".'endobj';
  14261. $this->_out($out);
  14262. $this->extgstates[] = array('n' => $this->n, 'name' => 'TGS'.$id);
  14263. }
  14264. }
  14265. }
  14266. /**
  14267. * Draw the sector of a circle.
  14268. * It can be used for instance to render pie charts.
  14269. * @param $xc (float) abscissa of the center.
  14270. * @param $yc (float) ordinate of the center.
  14271. * @param $r (float) radius.
  14272. * @param $a (float) start angle (in degrees).
  14273. * @param $b (float) end angle (in degrees).
  14274. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  14275. * @param $cw: (float) indicates whether to go clockwise (default: true).
  14276. * @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.
  14277. * @author Maxime Delorme, Nicola Asuni
  14278. * @since 3.1.000 (2008-06-09)
  14279. * @public
  14280. */
  14281. public function PieSector($xc, $yc, $r, $a, $b, $style='FD', $cw=true, $o=90) {
  14282. $this->PieSectorXY($xc, $yc, $r, $r, $a, $b, $style, $cw, $o);
  14283. }
  14284. /**
  14285. * Draw the sector of an ellipse.
  14286. * It can be used for instance to render pie charts.
  14287. * @param $xc (float) abscissa of the center.
  14288. * @param $yc (float) ordinate of the center.
  14289. * @param $rx (float) the x-axis radius.
  14290. * @param $ry (float) the y-axis radius.
  14291. * @param $a (float) start angle (in degrees).
  14292. * @param $b (float) end angle (in degrees).
  14293. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  14294. * @param $cw: (float) indicates whether to go clockwise.
  14295. * @param $o: (float) origin of angles (0 for 3 o'clock, 90 for noon, 180 for 9 o'clock, 270 for 6 o'clock).
  14296. * @param $nc (integer) Number of curves used to draw a 90 degrees portion of arc.
  14297. * @author Maxime Delorme, Nicola Asuni
  14298. * @since 3.1.000 (2008-06-09)
  14299. * @public
  14300. */
  14301. public function PieSectorXY($xc, $yc, $rx, $ry, $a, $b, $style='FD', $cw=false, $o=0, $nc=2) {
  14302. if ($this->state != 2) {
  14303. return;
  14304. }
  14305. if ($this->rtl) {
  14306. $xc = ($this->w - $xc);
  14307. }
  14308. $op = TCPDF_STATIC::getPathPaintOperator($style);
  14309. if ($op == 'f') {
  14310. $line_style = array();
  14311. }
  14312. if ($cw) {
  14313. $d = $b;
  14314. $b = (360 - $a + $o);
  14315. $a = (360 - $d + $o);
  14316. } else {
  14317. $b += $o;
  14318. $a += $o;
  14319. }
  14320. $this->_outellipticalarc($xc, $yc, $rx, $ry, 0, $a, $b, true, $nc);
  14321. $this->_out($op);
  14322. }
  14323. /**
  14324. * Embed vector-based Adobe Illustrator (AI) or AI-compatible EPS files.
  14325. * NOTE: EPS is not yet fully implemented, use the setRasterizeVectorImages() method to enable/disable rasterization of vector images using ImageMagick library.
  14326. * Only vector drawing is supported, not text or bitmap.
  14327. * 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).
  14328. * @param $file (string) Name of the file containing the image or a '@' character followed by the EPS/AI data string.
  14329. * @param $x (float) Abscissa of the upper-left corner.
  14330. * @param $y (float) Ordinate of the upper-left corner.
  14331. * @param $w (float) Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
  14332. * @param $h (float) Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
  14333. * @param $link (mixed) URL or identifier returned by AddLink().
  14334. * @param $useBoundingBox (boolean) specifies whether to position the bounding box (true) or the complete canvas (false) at location (x,y). Default value is true.
  14335. * @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>
  14336. * @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>
  14337. * @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)))
  14338. * @param $fitonpage (boolean) if true the image is resized to not exceed page dimensions.
  14339. * @param $fixoutvals (boolean) if true remove values outside the bounding box.
  14340. * @author Valentin Schmidt, Nicola Asuni
  14341. * @since 3.1.000 (2008-06-09)
  14342. * @public
  14343. */
  14344. public function ImageEps($file, $x='', $y='', $w=0, $h=0, $link='', $useBoundingBox=true, $align='', $palign='', $border=0, $fitonpage=false, $fixoutvals=false) {
  14345. if ($this->state != 2) {
  14346. return;
  14347. }
  14348. if ($this->rasterize_vector_images AND ($w > 0) AND ($h > 0)) {
  14349. // convert EPS to raster image using GD or ImageMagick libraries
  14350. return $this->Image($file, $x, $y, $w, $h, 'EPS', $link, $align, true, 300, $palign, false, false, $border, false, false, $fitonpage);
  14351. }
  14352. if ($x === '') {
  14353. $x = $this->x;
  14354. }
  14355. if ($y === '') {
  14356. $y = $this->y;
  14357. }
  14358. // check page for no-write regions and adapt page margins if necessary
  14359. list($x, $y) = $this->checkPageRegions($h, $x, $y);
  14360. $k = $this->k;
  14361. if ($file[0] === '@') { // image from string
  14362. $data = substr($file, 1);
  14363. } else { // EPS/AI file
  14364. $data = $this->getCachedFileContents($file);
  14365. }
  14366. if ($data === FALSE) {
  14367. $this->Error('EPS file not found: '.$file);
  14368. }
  14369. $regs = array();
  14370. // EPS/AI compatibility check (only checks files created by Adobe Illustrator!)
  14371. preg_match("/%%Creator:([^\r\n]+)/", $data, $regs); # find Creator
  14372. if (count($regs) > 1) {
  14373. $version_str = trim($regs[1]); # e.g. "Adobe Illustrator(R) 8.0"
  14374. if (strpos($version_str, 'Adobe Illustrator') !== false) {
  14375. $versexp = explode(' ', $version_str);
  14376. $version = (float)array_pop($versexp);
  14377. if ($version >= 9) {
  14378. $this->Error('This version of Adobe Illustrator file is not supported: '.$file);
  14379. }
  14380. }
  14381. }
  14382. // strip binary bytes in front of PS-header
  14383. $start = strpos($data, '%!PS-Adobe');
  14384. if ($start > 0) {
  14385. $data = substr($data, $start);
  14386. }
  14387. // find BoundingBox params
  14388. preg_match("/%%BoundingBox:([^\r\n]+)/", $data, $regs);
  14389. if (count($regs) > 1) {
  14390. list($x1, $y1, $x2, $y2) = explode(' ', trim($regs[1]));
  14391. } else {
  14392. $this->Error('No BoundingBox found in EPS/AI file: '.$file);
  14393. }
  14394. $start = strpos($data, '%%EndSetup');
  14395. if ($start === false) {
  14396. $start = strpos($data, '%%EndProlog');
  14397. }
  14398. if ($start === false) {
  14399. $start = strpos($data, '%%BoundingBox');
  14400. }
  14401. $data = substr($data, $start);
  14402. $end = strpos($data, '%%PageTrailer');
  14403. if ($end===false) {
  14404. $end = strpos($data, 'showpage');
  14405. }
  14406. if ($end) {
  14407. $data = substr($data, 0, $end);
  14408. }
  14409. // calculate image width and height on document
  14410. if (($w <= 0) AND ($h <= 0)) {
  14411. $w = ($x2 - $x1) / $k;
  14412. $h = ($y2 - $y1) / $k;
  14413. } elseif ($w <= 0) {
  14414. $w = ($x2-$x1) / $k * ($h / (($y2 - $y1) / $k));
  14415. } elseif ($h <= 0) {
  14416. $h = ($y2 - $y1) / $k * ($w / (($x2 - $x1) / $k));
  14417. }
  14418. // fit the image on available space
  14419. list($w, $h, $x, $y) = $this->fitBlock($w, $h, $x, $y, $fitonpage);
  14420. if ($this->rasterize_vector_images) {
  14421. // convert EPS to raster image using GD or ImageMagick libraries
  14422. return $this->Image($file, $x, $y, $w, $h, 'EPS', $link, $align, true, 300, $palign, false, false, $border, false, false, $fitonpage);
  14423. }
  14424. // set scaling factors
  14425. $scale_x = $w / (($x2 - $x1) / $k);
  14426. $scale_y = $h / (($y2 - $y1) / $k);
  14427. // set alignment
  14428. $this->img_rb_y = $y + $h;
  14429. // set alignment
  14430. if ($this->rtl) {
  14431. if ($palign == 'L') {
  14432. $ximg = $this->lMargin;
  14433. } elseif ($palign == 'C') {
  14434. $ximg = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
  14435. } elseif ($palign == 'R') {
  14436. $ximg = $this->w - $this->rMargin - $w;
  14437. } else {
  14438. $ximg = $x - $w;
  14439. }
  14440. $this->img_rb_x = $ximg;
  14441. } else {
  14442. if ($palign == 'L') {
  14443. $ximg = $this->lMargin;
  14444. } elseif ($palign == 'C') {
  14445. $ximg = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
  14446. } elseif ($palign == 'R') {
  14447. $ximg = $this->w - $this->rMargin - $w;
  14448. } else {
  14449. $ximg = $x;
  14450. }
  14451. $this->img_rb_x = $ximg + $w;
  14452. }
  14453. if ($useBoundingBox) {
  14454. $dx = $ximg * $k - $x1;
  14455. $dy = $y * $k - $y1;
  14456. } else {
  14457. $dx = $ximg * $k;
  14458. $dy = $y * $k;
  14459. }
  14460. // save the current graphic state
  14461. $this->_out('q'.$this->epsmarker);
  14462. // translate
  14463. $this->_out(sprintf('%F %F %F %F %F %F cm', 1, 0, 0, 1, $dx, $dy + ($this->hPt - (2 * $y * $k) - ($y2 - $y1))));
  14464. // scale
  14465. if (isset($scale_x)) {
  14466. $this->_out(sprintf('%F %F %F %F %F %F cm', $scale_x, 0, 0, $scale_y, $x1 * (1 - $scale_x), $y2 * (1 - $scale_y)));
  14467. }
  14468. // handle pc/unix/mac line endings
  14469. $lines = preg_split('/[\r\n]+/si', $data, -1, PREG_SPLIT_NO_EMPTY);
  14470. $u=0;
  14471. $cnt = count($lines);
  14472. for ($i=0; $i < $cnt; ++$i) {
  14473. $line = $lines[$i];
  14474. if (($line == '') OR ($line[0] == '%')) {
  14475. continue;
  14476. }
  14477. $len = strlen($line);
  14478. // check for spot color names
  14479. $color_name = '';
  14480. if (strcasecmp('x', substr(trim($line), -1)) == 0) {
  14481. if (preg_match('/\([^\)]*\)/', $line, $matches) > 0) {
  14482. // extract spot color name
  14483. $color_name = $matches[0];
  14484. // remove color name from string
  14485. $line = str_replace(' '.$color_name, '', $line);
  14486. // remove pharentesis from color name
  14487. $color_name = substr($color_name, 1, -1);
  14488. }
  14489. }
  14490. $chunks = explode(' ', $line);
  14491. $cmd = trim(array_pop($chunks));
  14492. // RGB
  14493. if (($cmd == 'Xa') OR ($cmd == 'XA')) {
  14494. $b = array_pop($chunks);
  14495. $g = array_pop($chunks);
  14496. $r = array_pop($chunks);
  14497. $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!
  14498. continue;
  14499. }
  14500. $skip = false;
  14501. if ($fixoutvals) {
  14502. // check for values outside the bounding box
  14503. switch ($cmd) {
  14504. case 'm':
  14505. case 'l':
  14506. case 'L': {
  14507. // skip values outside bounding box
  14508. foreach ($chunks as $key => $val) {
  14509. if ((($key % 2) == 0) AND (($val < $x1) OR ($val > $x2))) {
  14510. $skip = true;
  14511. } elseif ((($key % 2) != 0) AND (($val < $y1) OR ($val > $y2))) {
  14512. $skip = true;
  14513. }
  14514. }
  14515. }
  14516. }
  14517. }
  14518. switch ($cmd) {
  14519. case 'm':
  14520. case 'l':
  14521. case 'v':
  14522. case 'y':
  14523. case 'c':
  14524. case 'k':
  14525. case 'K':
  14526. case 'g':
  14527. case 'G':
  14528. case 's':
  14529. case 'S':
  14530. case 'J':
  14531. case 'j':
  14532. case 'w':
  14533. case 'M':
  14534. case 'd':
  14535. case 'n': {
  14536. if ($skip) {
  14537. break;
  14538. }
  14539. $this->_out($line);
  14540. break;
  14541. }
  14542. case 'x': {// custom fill color
  14543. if (empty($color_name)) {
  14544. // CMYK color
  14545. list($col_c, $col_m, $col_y, $col_k) = $chunks;
  14546. $this->_out(''.$col_c.' '.$col_m.' '.$col_y.' '.$col_k.' k');
  14547. } else {
  14548. // Spot Color (CMYK + tint)
  14549. list($col_c, $col_m, $col_y, $col_k, $col_t) = $chunks;
  14550. $this->AddSpotColor($color_name, ($col_c * 100), ($col_m * 100), ($col_y * 100), ($col_k * 100));
  14551. $color_cmd = sprintf('/CS%d cs %F scn', $this->spot_colors[$color_name]['i'], (1 - $col_t));
  14552. $this->_out($color_cmd);
  14553. }
  14554. break;
  14555. }
  14556. case 'X': { // custom stroke color
  14557. if (empty($color_name)) {
  14558. // CMYK color
  14559. list($col_c, $col_m, $col_y, $col_k) = $chunks;
  14560. $this->_out(''.$col_c.' '.$col_m.' '.$col_y.' '.$col_k.' K');
  14561. } else {
  14562. // Spot Color (CMYK + tint)
  14563. list($col_c, $col_m, $col_y, $col_k, $col_t) = $chunks;
  14564. $this->AddSpotColor($color_name, ($col_c * 100), ($col_m * 100), ($col_y * 100), ($col_k * 100));
  14565. $color_cmd = sprintf('/CS%d CS %F SCN', $this->spot_colors[$color_name]['i'], (1 - $col_t));
  14566. $this->_out($color_cmd);
  14567. }
  14568. break;
  14569. }
  14570. case 'Y':
  14571. case 'N':
  14572. case 'V':
  14573. case 'L':
  14574. case 'C': {
  14575. if ($skip) {
  14576. break;
  14577. }
  14578. $line[($len - 1)] = strtolower($cmd);
  14579. $this->_out($line);
  14580. break;
  14581. }
  14582. case 'b':
  14583. case 'B': {
  14584. $this->_out($cmd . '*');
  14585. break;
  14586. }
  14587. case 'f':
  14588. case 'F': {
  14589. if ($u > 0) {
  14590. $isU = false;
  14591. $max = min(($i + 5), $cnt);
  14592. for ($j = ($i + 1); $j < $max; ++$j) {
  14593. $isU = ($isU OR (($lines[$j] == 'U') OR ($lines[$j] == '*U')));
  14594. }
  14595. if ($isU) {
  14596. $this->_out('f*');
  14597. }
  14598. } else {
  14599. $this->_out('f*');
  14600. }
  14601. break;
  14602. }
  14603. case '*u': {
  14604. ++$u;
  14605. break;
  14606. }
  14607. case '*U': {
  14608. --$u;
  14609. break;
  14610. }
  14611. }
  14612. }
  14613. // restore previous graphic state
  14614. $this->_out($this->epsmarker.'Q');
  14615. if (!empty($border)) {
  14616. $bx = $this->x;
  14617. $by = $this->y;
  14618. $this->x = $ximg;
  14619. if ($this->rtl) {
  14620. $this->x += $w;
  14621. }
  14622. $this->y = $y;
  14623. $this->Cell($w, $h, '', $border, 0, '', 0, '', 0, true);
  14624. $this->x = $bx;
  14625. $this->y = $by;
  14626. }
  14627. if ($link) {
  14628. $this->Link($ximg, $y, $w, $h, $link, 0);
  14629. }
  14630. // set pointer to align the next text/objects
  14631. switch($align) {
  14632. case 'T':{
  14633. $this->y = $y;
  14634. $this->x = $this->img_rb_x;
  14635. break;
  14636. }
  14637. case 'M':{
  14638. $this->y = $y + round($h/2);
  14639. $this->x = $this->img_rb_x;
  14640. break;
  14641. }
  14642. case 'B':{
  14643. $this->y = $this->img_rb_y;
  14644. $this->x = $this->img_rb_x;
  14645. break;
  14646. }
  14647. case 'N':{
  14648. $this->SetY($this->img_rb_y);
  14649. break;
  14650. }
  14651. default:{
  14652. break;
  14653. }
  14654. }
  14655. $this->endlinex = $this->img_rb_x;
  14656. }
  14657. /**
  14658. * Set document barcode.
  14659. * @param $bc (string) barcode
  14660. * @public
  14661. */
  14662. public function setBarcode($bc='') {
  14663. $this->barcode = $bc;
  14664. }
  14665. /**
  14666. * Get current barcode.
  14667. * @return string
  14668. * @public
  14669. * @since 4.0.012 (2008-07-24)
  14670. */
  14671. public function getBarcode() {
  14672. return $this->barcode;
  14673. }
  14674. /**
  14675. * Print a Linear Barcode.
  14676. * @param $code (string) code to print
  14677. * @param $type (string) type of barcode (see tcpdf_barcodes_1d.php for supported formats).
  14678. * @param $x (int) x position in user units (empty string = current x position)
  14679. * @param $y (int) y position in user units (empty string = current y position)
  14680. * @param $w (int) width in user units (empty string = remaining page width)
  14681. * @param $h (int) height in user units (empty string = remaining page height)
  14682. * @param $xres (float) width of the smallest bar in user units (empty string = default value = 0.4mm)
  14683. * @param $style (array) array of options:<ul>
  14684. * <li>boolean $style['border'] if true prints a border</li>
  14685. * <li>int $style['padding'] padding to leave around the barcode in user units (set to 'auto' for automatic padding)</li>
  14686. * <li>int $style['hpadding'] horizontal padding in user units (set to 'auto' for automatic padding)</li>
  14687. * <li>int $style['vpadding'] vertical padding in user units (set to 'auto' for automatic padding)</li>
  14688. * <li>array $style['fgcolor'] color array for bars and text</li>
  14689. * <li>mixed $style['bgcolor'] color array for background (set to false for transparent)</li>
  14690. * <li>boolean $style['text'] if true prints text below the barcode</li>
  14691. * <li>string $style['label'] override default label</li>
  14692. * <li>string $style['font'] font name for text</li><li>int $style['fontsize'] font size for text</li>
  14693. * <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>
  14694. * <li>string $style['position'] horizontal position of the containing barcode cell on the page: L = left margin; C = center; R = right margin.</li>
  14695. * <li>string $style['align'] horizontal position of the barcode on the containing rectangle: L = left; C = center; R = right.</li>
  14696. * <li>string $style['stretch'] if true stretch the barcode to best fit the available width, otherwise uses $xres resolution for a single bar.</li>
  14697. * <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>
  14698. * <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>
  14699. * @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>
  14700. * @author Nicola Asuni
  14701. * @since 3.1.000 (2008-06-09)
  14702. * @public
  14703. */
  14704. public function write1DBarcode($code, $type, $x='', $y='', $w='', $h='', $xres='', $style=array(), $align='') {
  14705. if (TCPDF_STATIC::empty_string(trim($code))) {
  14706. return;
  14707. }
  14708. require_once(dirname(__FILE__).'/tcpdf_barcodes_1d.php');
  14709. // save current graphic settings
  14710. $gvars = $this->getGraphicVars();
  14711. // create new barcode object
  14712. $barcodeobj = new TCPDFBarcode($code, $type);
  14713. $arrcode = $barcodeobj->getBarcodeArray();
  14714. if (($arrcode === false) OR empty($arrcode) OR ($arrcode['maxw'] <= 0)) {
  14715. $this->Error('Error in 1D barcode string');
  14716. }
  14717. if ($arrcode['maxh'] <= 0) {
  14718. $arrcode['maxh'] = 1;
  14719. }
  14720. // set default values
  14721. if (!isset($style['position'])) {
  14722. $style['position'] = '';
  14723. } elseif ($style['position'] == 'S') {
  14724. // keep this for backward compatibility
  14725. $style['position'] = '';
  14726. $style['stretch'] = true;
  14727. }
  14728. if (!isset($style['fitwidth'])) {
  14729. if (!isset($style['stretch'])) {
  14730. $style['fitwidth'] = true;
  14731. } else {
  14732. $style['fitwidth'] = false;
  14733. }
  14734. }
  14735. if ($style['fitwidth']) {
  14736. // disable stretch
  14737. $style['stretch'] = false;
  14738. }
  14739. if (!isset($style['stretch'])) {
  14740. if (($w === '') OR ($w <= 0)) {
  14741. $style['stretch'] = false;
  14742. } else {
  14743. $style['stretch'] = true;
  14744. }
  14745. }
  14746. if (!isset($style['fgcolor'])) {
  14747. $style['fgcolor'] = array(0,0,0); // default black
  14748. }
  14749. if (!isset($style['bgcolor'])) {
  14750. $style['bgcolor'] = false; // default transparent
  14751. }
  14752. if (!isset($style['border'])) {
  14753. $style['border'] = false;
  14754. }
  14755. $fontsize = 0;
  14756. if (!isset($style['text'])) {
  14757. $style['text'] = false;
  14758. }
  14759. if ($style['text'] AND isset($style['font'])) {
  14760. if (isset($style['fontsize'])) {
  14761. $fontsize = $style['fontsize'];
  14762. }
  14763. $this->SetFont($style['font'], '', $fontsize);
  14764. }
  14765. if (!isset($style['stretchtext'])) {
  14766. $style['stretchtext'] = 4;
  14767. }
  14768. if ($x === '') {
  14769. $x = $this->x;
  14770. }
  14771. if ($y === '') {
  14772. $y = $this->y;
  14773. }
  14774. // check page for no-write regions and adapt page margins if necessary
  14775. list($x, $y) = $this->checkPageRegions($h, $x, $y);
  14776. if (($w === '') OR ($w <= 0)) {
  14777. if ($this->rtl) {
  14778. $w = $x - $this->lMargin;
  14779. } else {
  14780. $w = $this->w - $this->rMargin - $x;
  14781. }
  14782. }
  14783. // padding
  14784. if (!isset($style['padding'])) {
  14785. $padding = 0;
  14786. } elseif ($style['padding'] === 'auto') {
  14787. $padding = 10 * ($w / ($arrcode['maxw'] + 20));
  14788. } else {
  14789. $padding = floatval($style['padding']);
  14790. }
  14791. // horizontal padding
  14792. if (!isset($style['hpadding'])) {
  14793. $hpadding = $padding;
  14794. } elseif ($style['hpadding'] === 'auto') {
  14795. $hpadding = 10 * ($w / ($arrcode['maxw'] + 20));
  14796. } else {
  14797. $hpadding = floatval($style['hpadding']);
  14798. }
  14799. // vertical padding
  14800. if (!isset($style['vpadding'])) {
  14801. $vpadding = $padding;
  14802. } elseif ($style['vpadding'] === 'auto') {
  14803. $vpadding = ($hpadding / 2);
  14804. } else {
  14805. $vpadding = floatval($style['vpadding']);
  14806. }
  14807. // calculate xres (single bar width)
  14808. $max_xres = ($w - (2 * $hpadding)) / $arrcode['maxw'];
  14809. if ($style['stretch']) {
  14810. $xres = $max_xres;
  14811. } else {
  14812. if (TCPDF_STATIC::empty_string($xres)) {
  14813. $xres = (0.141 * $this->k); // default bar width = 0.4 mm
  14814. }
  14815. if ($xres > $max_xres) {
  14816. // correct xres to fit on $w
  14817. $xres = $max_xres;
  14818. }
  14819. if ((isset($style['padding']) AND ($style['padding'] === 'auto'))
  14820. OR (isset($style['hpadding']) AND ($style['hpadding'] === 'auto'))) {
  14821. $hpadding = 10 * $xres;
  14822. if (isset($style['vpadding']) AND ($style['vpadding'] === 'auto')) {
  14823. $vpadding = ($hpadding / 2);
  14824. }
  14825. }
  14826. }
  14827. if ($style['fitwidth']) {
  14828. $wold = $w;
  14829. $w = (($arrcode['maxw'] * $xres) + (2 * $hpadding));
  14830. if (isset($style['cellfitalign'])) {
  14831. switch ($style['cellfitalign']) {
  14832. case 'L': {
  14833. if ($this->rtl) {
  14834. $x -= ($wold - $w);
  14835. }
  14836. break;
  14837. }
  14838. case 'R': {
  14839. if (!$this->rtl) {
  14840. $x += ($wold - $w);
  14841. }
  14842. break;
  14843. }
  14844. case 'C': {
  14845. if ($this->rtl) {
  14846. $x -= (($wold - $w) / 2);
  14847. } else {
  14848. $x += (($wold - $w) / 2);
  14849. }
  14850. break;
  14851. }
  14852. default : {
  14853. break;
  14854. }
  14855. }
  14856. }
  14857. }
  14858. $text_height = $this->getCellHeight($fontsize / $this->k);
  14859. // height
  14860. if (($h === '') OR ($h <= 0)) {
  14861. // set default height
  14862. $h = (($arrcode['maxw'] * $xres) / 3) + (2 * $vpadding) + $text_height;
  14863. }
  14864. $barh = $h - $text_height - (2 * $vpadding);
  14865. if ($barh <=0) {
  14866. // try to reduce font or padding to fit barcode on available height
  14867. if ($text_height > $h) {
  14868. $fontsize = (($h * $this->k) / (4 * $this->cell_height_ratio));
  14869. $text_height = $this->getCellHeight($fontsize / $this->k);
  14870. $this->SetFont($style['font'], '', $fontsize);
  14871. }
  14872. if ($vpadding > 0) {
  14873. $vpadding = (($h - $text_height) / 4);
  14874. }
  14875. $barh = $h - $text_height - (2 * $vpadding);
  14876. }
  14877. // fit the barcode on available space
  14878. list($w, $h, $x, $y) = $this->fitBlock($w, $h, $x, $y, false);
  14879. // set alignment
  14880. $this->img_rb_y = $y + $h;
  14881. // set alignment
  14882. if ($this->rtl) {
  14883. if ($style['position'] == 'L') {
  14884. $xpos = $this->lMargin;
  14885. } elseif ($style['position'] == 'C') {
  14886. $xpos = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
  14887. } elseif ($style['position'] == 'R') {
  14888. $xpos = $this->w - $this->rMargin - $w;
  14889. } else {
  14890. $xpos = $x - $w;
  14891. }
  14892. $this->img_rb_x = $xpos;
  14893. } else {
  14894. if ($style['position'] == 'L') {
  14895. $xpos = $this->lMargin;
  14896. } elseif ($style['position'] == 'C') {
  14897. $xpos = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
  14898. } elseif ($style['position'] == 'R') {
  14899. $xpos = $this->w - $this->rMargin - $w;
  14900. } else {
  14901. $xpos = $x;
  14902. }
  14903. $this->img_rb_x = $xpos + $w;
  14904. }
  14905. $xpos_rect = $xpos;
  14906. if (!isset($style['align'])) {
  14907. $style['align'] = 'C';
  14908. }
  14909. switch ($style['align']) {
  14910. case 'L': {
  14911. $xpos = $xpos_rect + $hpadding;
  14912. break;
  14913. }
  14914. case 'R': {
  14915. $xpos = $xpos_rect + ($w - ($arrcode['maxw'] * $xres)) - $hpadding;
  14916. break;
  14917. }
  14918. case 'C':
  14919. default : {
  14920. $xpos = $xpos_rect + (($w - ($arrcode['maxw'] * $xres)) / 2);
  14921. break;
  14922. }
  14923. }
  14924. $xpos_text = $xpos;
  14925. // barcode is always printed in LTR direction
  14926. $tempRTL = $this->rtl;
  14927. $this->rtl = false;
  14928. // print background color
  14929. if ($style['bgcolor']) {
  14930. $this->Rect($xpos_rect, $y, $w, $h, $style['border'] ? 'DF' : 'F', '', $style['bgcolor']);
  14931. } elseif ($style['border']) {
  14932. $this->Rect($xpos_rect, $y, $w, $h, 'D');
  14933. }
  14934. // set foreground color
  14935. $this->SetDrawColorArray($style['fgcolor']);
  14936. $this->SetTextColorArray($style['fgcolor']);
  14937. // print bars
  14938. foreach ($arrcode['bcode'] as $k => $v) {
  14939. $bw = ($v['w'] * $xres);
  14940. if ($v['t']) {
  14941. // draw a vertical bar
  14942. $ypos = $y + $vpadding + ($v['p'] * $barh / $arrcode['maxh']);
  14943. $this->Rect($xpos, $ypos, $bw, ($v['h'] * $barh / $arrcode['maxh']), 'F', array(), $style['fgcolor']);
  14944. }
  14945. $xpos += $bw;
  14946. }
  14947. // print text
  14948. if ($style['text']) {
  14949. if (isset($style['label']) AND !TCPDF_STATIC::empty_string($style['label'])) {
  14950. $label = $style['label'];
  14951. } else {
  14952. $label = $code;
  14953. }
  14954. $txtwidth = ($arrcode['maxw'] * $xres);
  14955. if ($this->GetStringWidth($label) > $txtwidth) {
  14956. $style['stretchtext'] = 2;
  14957. }
  14958. // print text
  14959. $this->x = $xpos_text;
  14960. $this->y = $y + $vpadding + $barh;
  14961. $cellpadding = $this->cell_padding;
  14962. $this->SetCellPadding(0);
  14963. $this->Cell($txtwidth, 0, $label, 0, 0, 'C', false, '', $style['stretchtext'], false, 'T', 'T');
  14964. $this->cell_padding = $cellpadding;
  14965. }
  14966. // restore original direction
  14967. $this->rtl = $tempRTL;
  14968. // restore previous settings
  14969. $this->setGraphicVars($gvars);
  14970. // set pointer to align the next text/objects
  14971. switch($align) {
  14972. case 'T':{
  14973. $this->y = $y;
  14974. $this->x = $this->img_rb_x;
  14975. break;
  14976. }
  14977. case 'M':{
  14978. $this->y = $y + round($h / 2);
  14979. $this->x = $this->img_rb_x;
  14980. break;
  14981. }
  14982. case 'B':{
  14983. $this->y = $this->img_rb_y;
  14984. $this->x = $this->img_rb_x;
  14985. break;
  14986. }
  14987. case 'N':{
  14988. $this->SetY($this->img_rb_y);
  14989. break;
  14990. }
  14991. default:{
  14992. break;
  14993. }
  14994. }
  14995. $this->endlinex = $this->img_rb_x;
  14996. }
  14997. /**
  14998. * Print 2D Barcode.
  14999. * @param $code (string) code to print
  15000. * @param $type (string) type of barcode (see tcpdf_barcodes_2d.php for supported formats).
  15001. * @param $x (int) x position in user units
  15002. * @param $y (int) y position in user units
  15003. * @param $w (int) width in user units
  15004. * @param $h (int) height in user units
  15005. * @param $style (array) array of options:<ul>
  15006. * <li>boolean $style['border'] if true prints a border around the barcode</li>
  15007. * <li>int $style['padding'] padding to leave around the barcode in barcode units (set to 'auto' for automatic padding)</li>
  15008. * <li>int $style['hpadding'] horizontal padding in barcode units (set to 'auto' for automatic padding)</li>
  15009. * <li>int $style['vpadding'] vertical padding in barcode units (set to 'auto' for automatic padding)</li>
  15010. * <li>int $style['module_width'] width of a single module in points</li>
  15011. * <li>int $style['module_height'] height of a single module in points</li>
  15012. * <li>array $style['fgcolor'] color array for bars and text</li>
  15013. * <li>mixed $style['bgcolor'] color array for background or false for transparent</li>
  15014. * <li>string $style['position'] barcode position on the page: L = left margin; C = center; R = right margin; S = stretch</li>
  15015. * @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>
  15016. * @param $distort (boolean) if true distort the barcode to fit width and height, otherwise preserve aspect ratio
  15017. * @author Nicola Asuni
  15018. * @since 4.5.037 (2009-04-07)
  15019. * @public
  15020. */
  15021. public function write2DBarcode($code, $type, $x='', $y='', $w='', $h='', $style=array(), $align='', $distort=false) {
  15022. if (TCPDF_STATIC::empty_string(trim($code))) {
  15023. return;
  15024. }
  15025. require_once(dirname(__FILE__).'/tcpdf_barcodes_2d.php');
  15026. // save current graphic settings
  15027. $gvars = $this->getGraphicVars();
  15028. // create new barcode object
  15029. $barcodeobj = new TCPDF2DBarcode($code, $type);
  15030. $arrcode = $barcodeobj->getBarcodeArray();
  15031. 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)) {
  15032. $this->Error('Error in 2D barcode string');
  15033. }
  15034. // set default values
  15035. if (!isset($style['position'])) {
  15036. $style['position'] = '';
  15037. }
  15038. if (!isset($style['fgcolor'])) {
  15039. $style['fgcolor'] = array(0,0,0); // default black
  15040. }
  15041. if (!isset($style['bgcolor'])) {
  15042. $style['bgcolor'] = false; // default transparent
  15043. }
  15044. if (!isset($style['border'])) {
  15045. $style['border'] = false;
  15046. }
  15047. // padding
  15048. if (!isset($style['padding'])) {
  15049. $style['padding'] = 0;
  15050. } elseif ($style['padding'] === 'auto') {
  15051. $style['padding'] = 4;
  15052. }
  15053. if (!isset($style['hpadding'])) {
  15054. $style['hpadding'] = $style['padding'];
  15055. } elseif ($style['hpadding'] === 'auto') {
  15056. $style['hpadding'] = 4;
  15057. }
  15058. if (!isset($style['vpadding'])) {
  15059. $style['vpadding'] = $style['padding'];
  15060. } elseif ($style['vpadding'] === 'auto') {
  15061. $style['vpadding'] = 4;
  15062. }
  15063. $hpad = (2 * $style['hpadding']);
  15064. $vpad = (2 * $style['vpadding']);
  15065. // cell (module) dimension
  15066. if (!isset($style['module_width'])) {
  15067. $style['module_width'] = 1; // width of a single module in points
  15068. }
  15069. if (!isset($style['module_height'])) {
  15070. $style['module_height'] = 1; // height of a single module in points
  15071. }
  15072. if ($x === '') {
  15073. $x = $this->x;
  15074. }
  15075. if ($y === '') {
  15076. $y = $this->y;
  15077. }
  15078. // check page for no-write regions and adapt page margins if necessary
  15079. list($x, $y) = $this->checkPageRegions($h, $x, $y);
  15080. // number of barcode columns and rows
  15081. $rows = $arrcode['num_rows'];
  15082. $cols = $arrcode['num_cols'];
  15083. if (($rows <= 0) || ($cols <= 0)){
  15084. $this->Error('Error in 2D barcode string');
  15085. }
  15086. // module width and height
  15087. $mw = $style['module_width'];
  15088. $mh = $style['module_height'];
  15089. if (($mw <= 0) OR ($mh <= 0)) {
  15090. $this->Error('Error in 2D barcode string');
  15091. }
  15092. // get max dimensions
  15093. if ($this->rtl) {
  15094. $maxw = $x - $this->lMargin;
  15095. } else {
  15096. $maxw = $this->w - $this->rMargin - $x;
  15097. }
  15098. $maxh = ($this->h - $this->tMargin - $this->bMargin);
  15099. $ratioHW = ((($rows * $mh) + $hpad) / (($cols * $mw) + $vpad));
  15100. $ratioWH = ((($cols * $mw) + $vpad) / (($rows * $mh) + $hpad));
  15101. if (!$distort) {
  15102. if (($maxw * $ratioHW) > $maxh) {
  15103. $maxw = $maxh * $ratioWH;
  15104. }
  15105. if (($maxh * $ratioWH) > $maxw) {
  15106. $maxh = $maxw * $ratioHW;
  15107. }
  15108. }
  15109. // set maximum dimensions
  15110. if ($w > $maxw) {
  15111. $w = $maxw;
  15112. }
  15113. if ($h > $maxh) {
  15114. $h = $maxh;
  15115. }
  15116. // set dimensions
  15117. if ((($w === '') OR ($w <= 0)) AND (($h === '') OR ($h <= 0))) {
  15118. $w = ($cols + $hpad) * ($mw / $this->k);
  15119. $h = ($rows + $vpad) * ($mh / $this->k);
  15120. } elseif (($w === '') OR ($w <= 0)) {
  15121. $w = $h * $ratioWH;
  15122. } elseif (($h === '') OR ($h <= 0)) {
  15123. $h = $w * $ratioHW;
  15124. }
  15125. // barcode size (excluding padding)
  15126. $bw = ($w * $cols) / ($cols + $hpad);
  15127. $bh = ($h * $rows) / ($rows + $vpad);
  15128. // dimension of single barcode cell unit
  15129. $cw = $bw / $cols;
  15130. $ch = $bh / $rows;
  15131. if (!$distort) {
  15132. if (($cw / $ch) > ($mw / $mh)) {
  15133. // correct horizontal distortion
  15134. $cw = $ch * $mw / $mh;
  15135. $bw = $cw * $cols;
  15136. $style['hpadding'] = ($w - $bw) / (2 * $cw);
  15137. } else {
  15138. // correct vertical distortion
  15139. $ch = $cw * $mh / $mw;
  15140. $bh = $ch * $rows;
  15141. $style['vpadding'] = ($h - $bh) / (2 * $ch);
  15142. }
  15143. }
  15144. // fit the barcode on available space
  15145. list($w, $h, $x, $y) = $this->fitBlock($w, $h, $x, $y, false);
  15146. // set alignment
  15147. $this->img_rb_y = $y + $h;
  15148. // set alignment
  15149. if ($this->rtl) {
  15150. if ($style['position'] == 'L') {
  15151. $xpos = $this->lMargin;
  15152. } elseif ($style['position'] == 'C') {
  15153. $xpos = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
  15154. } elseif ($style['position'] == 'R') {
  15155. $xpos = $this->w - $this->rMargin - $w;
  15156. } else {
  15157. $xpos = $x - $w;
  15158. }
  15159. $this->img_rb_x = $xpos;
  15160. } else {
  15161. if ($style['position'] == 'L') {
  15162. $xpos = $this->lMargin;
  15163. } elseif ($style['position'] == 'C') {
  15164. $xpos = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
  15165. } elseif ($style['position'] == 'R') {
  15166. $xpos = $this->w - $this->rMargin - $w;
  15167. } else {
  15168. $xpos = $x;
  15169. }
  15170. $this->img_rb_x = $xpos + $w;
  15171. }
  15172. $xstart = $xpos + ($style['hpadding'] * $cw);
  15173. $ystart = $y + ($style['vpadding'] * $ch);
  15174. // barcode is always printed in LTR direction
  15175. $tempRTL = $this->rtl;
  15176. $this->rtl = false;
  15177. // print background color
  15178. if ($style['bgcolor']) {
  15179. $this->Rect($xpos, $y, $w, $h, $style['border'] ? 'DF' : 'F', '', $style['bgcolor']);
  15180. } elseif ($style['border']) {
  15181. $this->Rect($xpos, $y, $w, $h, 'D');
  15182. }
  15183. // set foreground color
  15184. $this->SetDrawColorArray($style['fgcolor']);
  15185. // print barcode cells
  15186. // for each row
  15187. for ($r = 0; $r < $rows; ++$r) {
  15188. $xr = $xstart;
  15189. // for each column
  15190. for ($c = 0; $c < $cols; ++$c) {
  15191. if ($arrcode['bcode'][$r][$c] == 1) {
  15192. // draw a single barcode cell
  15193. $this->Rect($xr, $ystart, $cw, $ch, 'F', array(), $style['fgcolor']);
  15194. }
  15195. $xr += $cw;
  15196. }
  15197. $ystart += $ch;
  15198. }
  15199. // restore original direction
  15200. $this->rtl = $tempRTL;
  15201. // restore previous settings
  15202. $this->setGraphicVars($gvars);
  15203. // set pointer to align the next text/objects
  15204. switch($align) {
  15205. case 'T':{
  15206. $this->y = $y;
  15207. $this->x = $this->img_rb_x;
  15208. break;
  15209. }
  15210. case 'M':{
  15211. $this->y = $y + round($h/2);
  15212. $this->x = $this->img_rb_x;
  15213. break;
  15214. }
  15215. case 'B':{
  15216. $this->y = $this->img_rb_y;
  15217. $this->x = $this->img_rb_x;
  15218. break;
  15219. }
  15220. case 'N':{
  15221. $this->SetY($this->img_rb_y);
  15222. break;
  15223. }
  15224. default:{
  15225. break;
  15226. }
  15227. }
  15228. $this->endlinex = $this->img_rb_x;
  15229. }
  15230. /**
  15231. * Returns an array containing current margins:
  15232. * <ul>
  15233. <li>$ret['left'] = left margin</li>
  15234. <li>$ret['right'] = right margin</li>
  15235. <li>$ret['top'] = top margin</li>
  15236. <li>$ret['bottom'] = bottom margin</li>
  15237. <li>$ret['header'] = header margin</li>
  15238. <li>$ret['footer'] = footer margin</li>
  15239. <li>$ret['cell'] = cell padding array</li>
  15240. <li>$ret['padding_left'] = cell left padding</li>
  15241. <li>$ret['padding_top'] = cell top padding</li>
  15242. <li>$ret['padding_right'] = cell right padding</li>
  15243. <li>$ret['padding_bottom'] = cell bottom padding</li>
  15244. * </ul>
  15245. * @return array containing all margins measures
  15246. * @public
  15247. * @since 3.2.000 (2008-06-23)
  15248. */
  15249. public function getMargins() {
  15250. $ret = array(
  15251. 'left' => $this->lMargin,
  15252. 'right' => $this->rMargin,
  15253. 'top' => $this->tMargin,
  15254. 'bottom' => $this->bMargin,
  15255. 'header' => $this->header_margin,
  15256. 'footer' => $this->footer_margin,
  15257. 'cell' => $this->cell_padding,
  15258. 'padding_left' => $this->cell_padding['L'],
  15259. 'padding_top' => $this->cell_padding['T'],
  15260. 'padding_right' => $this->cell_padding['R'],
  15261. 'padding_bottom' => $this->cell_padding['B']
  15262. );
  15263. return $ret;
  15264. }
  15265. /**
  15266. * Returns an array containing original margins:
  15267. * <ul>
  15268. <li>$ret['left'] = left margin</li>
  15269. <li>$ret['right'] = right margin</li>
  15270. * </ul>
  15271. * @return array containing all margins measures
  15272. * @public
  15273. * @since 4.0.012 (2008-07-24)
  15274. */
  15275. public function getOriginalMargins() {
  15276. $ret = array(
  15277. 'left' => $this->original_lMargin,
  15278. 'right' => $this->original_rMargin
  15279. );
  15280. return $ret;
  15281. }
  15282. /**
  15283. * Returns the current font size.
  15284. * @return current font size
  15285. * @public
  15286. * @since 3.2.000 (2008-06-23)
  15287. */
  15288. public function getFontSize() {
  15289. return $this->FontSize;
  15290. }
  15291. /**
  15292. * Returns the current font size in points unit.
  15293. * @return current font size in points unit
  15294. * @public
  15295. * @since 3.2.000 (2008-06-23)
  15296. */
  15297. public function getFontSizePt() {
  15298. return $this->FontSizePt;
  15299. }
  15300. /**
  15301. * Returns the current font family name.
  15302. * @return string current font family name
  15303. * @public
  15304. * @since 4.3.008 (2008-12-05)
  15305. */
  15306. public function getFontFamily() {
  15307. return $this->FontFamily;
  15308. }
  15309. /**
  15310. * Returns the current font style.
  15311. * @return string current font style
  15312. * @public
  15313. * @since 4.3.008 (2008-12-05)
  15314. */
  15315. public function getFontStyle() {
  15316. return $this->FontStyle;
  15317. }
  15318. /**
  15319. * Cleanup HTML code (requires HTML Tidy library).
  15320. * @param $html (string) htmlcode to fix
  15321. * @param $default_css (string) CSS commands to add
  15322. * @param $tagvs (array) parameters for setHtmlVSpace method
  15323. * @param $tidy_options (array) options for tidy_parse_string function
  15324. * @return string XHTML code cleaned up
  15325. * @author Nicola Asuni
  15326. * @public
  15327. * @since 5.9.017 (2010-11-16)
  15328. * @see setHtmlVSpace()
  15329. */
  15330. public function fixHTMLCode($html, $default_css='', $tagvs='', $tidy_options='') {
  15331. return TCPDF_STATIC::fixHTMLCode($html, $default_css, $tagvs, $tidy_options, $this->tagvspaces);
  15332. }
  15333. /**
  15334. * Returns the border width from CSS property
  15335. * @param $width (string) border width
  15336. * @return int with in user units
  15337. * @protected
  15338. * @since 5.7.000 (2010-08-02)
  15339. */
  15340. protected function getCSSBorderWidth($width) {
  15341. if ($width == 'thin') {
  15342. $width = (2 / $this->k);
  15343. } elseif ($width == 'medium') {
  15344. $width = (4 / $this->k);
  15345. } elseif ($width == 'thick') {
  15346. $width = (6 / $this->k);
  15347. } else {
  15348. $width = $this->getHTMLUnitToUnits($width, 1, 'px', false);
  15349. }
  15350. return $width;
  15351. }
  15352. /**
  15353. * Returns the border dash style from CSS property
  15354. * @param $style (string) border style to convert
  15355. * @return int sash style (return -1 in case of none or hidden border)
  15356. * @protected
  15357. * @since 5.7.000 (2010-08-02)
  15358. */
  15359. protected function getCSSBorderDashStyle($style) {
  15360. switch (strtolower($style)) {
  15361. case 'none':
  15362. case 'hidden': {
  15363. $dash = -1;
  15364. break;
  15365. }
  15366. case 'dotted': {
  15367. $dash = 1;
  15368. break;
  15369. }
  15370. case 'dashed': {
  15371. $dash = 3;
  15372. break;
  15373. }
  15374. case 'double':
  15375. case 'groove':
  15376. case 'ridge':
  15377. case 'inset':
  15378. case 'outset':
  15379. case 'solid':
  15380. default: {
  15381. $dash = 0;
  15382. break;
  15383. }
  15384. }
  15385. return $dash;
  15386. }
  15387. /**
  15388. * Returns the border style array from CSS border properties
  15389. * @param $cssborder (string) border properties
  15390. * @return array containing border properties
  15391. * @protected
  15392. * @since 5.7.000 (2010-08-02)
  15393. */
  15394. protected function getCSSBorderStyle($cssborder) {
  15395. $bprop = preg_split('/[\s]+/', trim($cssborder));
  15396. $border = array(); // value to be returned
  15397. switch (count($bprop)) {
  15398. case 3: {
  15399. $width = $bprop[0];
  15400. $style = $bprop[1];
  15401. $color = $bprop[2];
  15402. break;
  15403. }
  15404. case 2: {
  15405. $width = 'medium';
  15406. $style = $bprop[0];
  15407. $color = $bprop[1];
  15408. break;
  15409. }
  15410. case 1: {
  15411. $width = 'medium';
  15412. $style = $bprop[0];
  15413. $color = 'black';
  15414. break;
  15415. }
  15416. default: {
  15417. $width = 'medium';
  15418. $style = 'solid';
  15419. $color = 'black';
  15420. break;
  15421. }
  15422. }
  15423. if ($style == 'none') {
  15424. return array();
  15425. }
  15426. $border['cap'] = 'square';
  15427. $border['join'] = 'miter';
  15428. $border['dash'] = $this->getCSSBorderDashStyle($style);
  15429. if ($border['dash'] < 0) {
  15430. return array();
  15431. }
  15432. $border['width'] = $this->getCSSBorderWidth($width);
  15433. $border['color'] = TCPDF_COLORS::convertHTMLColorToDec($color, $this->spot_colors);
  15434. return $border;
  15435. }
  15436. /**
  15437. * Get the internal Cell padding from CSS attribute.
  15438. * @param $csspadding (string) padding properties
  15439. * @param $width (float) width of the containing element
  15440. * @return array of cell paddings
  15441. * @public
  15442. * @since 5.9.000 (2010-10-04)
  15443. */
  15444. public function getCSSPadding($csspadding, $width=0) {
  15445. $padding = preg_split('/[\s]+/', trim($csspadding));
  15446. $cell_padding = array(); // value to be returned
  15447. switch (count($padding)) {
  15448. case 4: {
  15449. $cell_padding['T'] = $padding[0];
  15450. $cell_padding['R'] = $padding[1];
  15451. $cell_padding['B'] = $padding[2];
  15452. $cell_padding['L'] = $padding[3];
  15453. break;
  15454. }
  15455. case 3: {
  15456. $cell_padding['T'] = $padding[0];
  15457. $cell_padding['R'] = $padding[1];
  15458. $cell_padding['B'] = $padding[2];
  15459. $cell_padding['L'] = $padding[1];
  15460. break;
  15461. }
  15462. case 2: {
  15463. $cell_padding['T'] = $padding[0];
  15464. $cell_padding['R'] = $padding[1];
  15465. $cell_padding['B'] = $padding[0];
  15466. $cell_padding['L'] = $padding[1];
  15467. break;
  15468. }
  15469. case 1: {
  15470. $cell_padding['T'] = $padding[0];
  15471. $cell_padding['R'] = $padding[0];
  15472. $cell_padding['B'] = $padding[0];
  15473. $cell_padding['L'] = $padding[0];
  15474. break;
  15475. }
  15476. default: {
  15477. return $this->cell_padding;
  15478. }
  15479. }
  15480. if ($width == 0) {
  15481. $width = $this->w - $this->lMargin - $this->rMargin;
  15482. }
  15483. $cell_padding['T'] = $this->getHTMLUnitToUnits($cell_padding['T'], $width, 'px', false);
  15484. $cell_padding['R'] = $this->getHTMLUnitToUnits($cell_padding['R'], $width, 'px', false);
  15485. $cell_padding['B'] = $this->getHTMLUnitToUnits($cell_padding['B'], $width, 'px', false);
  15486. $cell_padding['L'] = $this->getHTMLUnitToUnits($cell_padding['L'], $width, 'px', false);
  15487. return $cell_padding;
  15488. }
  15489. /**
  15490. * Get the internal Cell margin from CSS attribute.
  15491. * @param $cssmargin (string) margin properties
  15492. * @param $width (float) width of the containing element
  15493. * @return array of cell margins
  15494. * @public
  15495. * @since 5.9.000 (2010-10-04)
  15496. */
  15497. public function getCSSMargin($cssmargin, $width=0) {
  15498. $margin = preg_split('/[\s]+/', trim($cssmargin));
  15499. $cell_margin = array(); // value to be returned
  15500. switch (count($margin)) {
  15501. case 4: {
  15502. $cell_margin['T'] = $margin[0];
  15503. $cell_margin['R'] = $margin[1];
  15504. $cell_margin['B'] = $margin[2];
  15505. $cell_margin['L'] = $margin[3];
  15506. break;
  15507. }
  15508. case 3: {
  15509. $cell_margin['T'] = $margin[0];
  15510. $cell_margin['R'] = $margin[1];
  15511. $cell_margin['B'] = $margin[2];
  15512. $cell_margin['L'] = $margin[1];
  15513. break;
  15514. }
  15515. case 2: {
  15516. $cell_margin['T'] = $margin[0];
  15517. $cell_margin['R'] = $margin[1];
  15518. $cell_margin['B'] = $margin[0];
  15519. $cell_margin['L'] = $margin[1];
  15520. break;
  15521. }
  15522. case 1: {
  15523. $cell_margin['T'] = $margin[0];
  15524. $cell_margin['R'] = $margin[0];
  15525. $cell_margin['B'] = $margin[0];
  15526. $cell_margin['L'] = $margin[0];
  15527. break;
  15528. }
  15529. default: {
  15530. return $this->cell_margin;
  15531. }
  15532. }
  15533. if ($width == 0) {
  15534. $width = $this->w - $this->lMargin - $this->rMargin;
  15535. }
  15536. $cell_margin['T'] = $this->getHTMLUnitToUnits(str_replace('auto', '0', $cell_margin['T']), $width, 'px', false);
  15537. $cell_margin['R'] = $this->getHTMLUnitToUnits(str_replace('auto', '0', $cell_margin['R']), $width, 'px', false);
  15538. $cell_margin['B'] = $this->getHTMLUnitToUnits(str_replace('auto', '0', $cell_margin['B']), $width, 'px', false);
  15539. $cell_margin['L'] = $this->getHTMLUnitToUnits(str_replace('auto', '0', $cell_margin['L']), $width, 'px', false);
  15540. return $cell_margin;
  15541. }
  15542. /**
  15543. * Get the border-spacing from CSS attribute.
  15544. * @param $cssbspace (string) border-spacing CSS properties
  15545. * @param $width (float) width of the containing element
  15546. * @return array of border spacings
  15547. * @public
  15548. * @since 5.9.010 (2010-10-27)
  15549. */
  15550. public function getCSSBorderMargin($cssbspace, $width=0) {
  15551. $space = preg_split('/[\s]+/', trim($cssbspace));
  15552. $border_spacing = array(); // value to be returned
  15553. switch (count($space)) {
  15554. case 2: {
  15555. $border_spacing['H'] = $space[0];
  15556. $border_spacing['V'] = $space[1];
  15557. break;
  15558. }
  15559. case 1: {
  15560. $border_spacing['H'] = $space[0];
  15561. $border_spacing['V'] = $space[0];
  15562. break;
  15563. }
  15564. default: {
  15565. return array('H' => 0, 'V' => 0);
  15566. }
  15567. }
  15568. if ($width == 0) {
  15569. $width = $this->w - $this->lMargin - $this->rMargin;
  15570. }
  15571. $border_spacing['H'] = $this->getHTMLUnitToUnits($border_spacing['H'], $width, 'px', false);
  15572. $border_spacing['V'] = $this->getHTMLUnitToUnits($border_spacing['V'], $width, 'px', false);
  15573. return $border_spacing;
  15574. }
  15575. /**
  15576. * Returns the letter-spacing value from CSS value
  15577. * @param $spacing (string) letter-spacing value
  15578. * @param $parent (float) font spacing (tracking) value of the parent element
  15579. * @return float quantity to increases or decreases the space between characters in a text.
  15580. * @protected
  15581. * @since 5.9.000 (2010-10-02)
  15582. */
  15583. protected function getCSSFontSpacing($spacing, $parent=0) {
  15584. $val = 0; // value to be returned
  15585. $spacing = trim($spacing);
  15586. switch ($spacing) {
  15587. case 'normal': {
  15588. $val = 0;
  15589. break;
  15590. }
  15591. case 'inherit': {
  15592. if ($parent == 'normal') {
  15593. $val = 0;
  15594. } else {
  15595. $val = $parent;
  15596. }
  15597. break;
  15598. }
  15599. default: {
  15600. $val = $this->getHTMLUnitToUnits($spacing, 0, 'px', false);
  15601. }
  15602. }
  15603. return $val;
  15604. }
  15605. /**
  15606. * Returns the percentage of font stretching from CSS value
  15607. * @param $stretch (string) stretch mode
  15608. * @param $parent (float) stretch value of the parent element
  15609. * @return float font stretching percentage
  15610. * @protected
  15611. * @since 5.9.000 (2010-10-02)
  15612. */
  15613. protected function getCSSFontStretching($stretch, $parent=100) {
  15614. $val = 100; // value to be returned
  15615. $stretch = trim($stretch);
  15616. switch ($stretch) {
  15617. case 'ultra-condensed': {
  15618. $val = 40;
  15619. break;
  15620. }
  15621. case 'extra-condensed': {
  15622. $val = 55;
  15623. break;
  15624. }
  15625. case 'condensed': {
  15626. $val = 70;
  15627. break;
  15628. }
  15629. case 'semi-condensed': {
  15630. $val = 85;
  15631. break;
  15632. }
  15633. case 'normal': {
  15634. $val = 100;
  15635. break;
  15636. }
  15637. case 'semi-expanded': {
  15638. $val = 115;
  15639. break;
  15640. }
  15641. case 'expanded': {
  15642. $val = 130;
  15643. break;
  15644. }
  15645. case 'extra-expanded': {
  15646. $val = 145;
  15647. break;
  15648. }
  15649. case 'ultra-expanded': {
  15650. $val = 160;
  15651. break;
  15652. }
  15653. case 'wider': {
  15654. $val = ($parent + 10);
  15655. break;
  15656. }
  15657. case 'narrower': {
  15658. $val = ($parent - 10);
  15659. break;
  15660. }
  15661. case 'inherit': {
  15662. if ($parent == 'normal') {
  15663. $val = 100;
  15664. } else {
  15665. $val = $parent;
  15666. }
  15667. break;
  15668. }
  15669. default: {
  15670. $val = $this->getHTMLUnitToUnits($stretch, 100, '%', false);
  15671. }
  15672. }
  15673. return $val;
  15674. }
  15675. /**
  15676. * Convert HTML string containing font size value to points
  15677. * @param $val (string) String containing font size value and unit.
  15678. * @param $refsize (float) Reference font size in points.
  15679. * @param $parent_size (float) Parent font size in points.
  15680. * @param $defaultunit (string) Default unit (can be one of the following: %, em, ex, px, in, mm, pc, pt).
  15681. * @return float value in points
  15682. * @public
  15683. */
  15684. public function getHTMLFontUnits($val, $refsize=12, $parent_size=12, $defaultunit='pt') {
  15685. $refsize = TCPDF_FONTS::getFontRefSize($refsize);
  15686. $parent_size = TCPDF_FONTS::getFontRefSize($parent_size, $refsize);
  15687. switch ($val) {
  15688. case 'xx-small': {
  15689. $size = ($refsize - 4);
  15690. break;
  15691. }
  15692. case 'x-small': {
  15693. $size = ($refsize - 3);
  15694. break;
  15695. }
  15696. case 'small': {
  15697. $size = ($refsize - 2);
  15698. break;
  15699. }
  15700. case 'medium': {
  15701. $size = $refsize;
  15702. break;
  15703. }
  15704. case 'large': {
  15705. $size = ($refsize + 2);
  15706. break;
  15707. }
  15708. case 'x-large': {
  15709. $size = ($refsize + 4);
  15710. break;
  15711. }
  15712. case 'xx-large': {
  15713. $size = ($refsize + 6);
  15714. break;
  15715. }
  15716. case 'smaller': {
  15717. $size = ($parent_size - 3);
  15718. break;
  15719. }
  15720. case 'larger': {
  15721. $size = ($parent_size + 3);
  15722. break;
  15723. }
  15724. default: {
  15725. $size = $this->getHTMLUnitToUnits($val, $parent_size, $defaultunit, true);
  15726. }
  15727. }
  15728. return $size;
  15729. }
  15730. /**
  15731. * Returns the HTML DOM array.
  15732. * @param $html (string) html code
  15733. * @return array
  15734. * @protected
  15735. * @since 3.2.000 (2008-06-20)
  15736. */
  15737. protected function getHtmlDomArray($html) {
  15738. // array of CSS styles ( selector => properties).
  15739. $css = array();
  15740. // get CSS array defined at previous call
  15741. $matches = array();
  15742. if (preg_match_all('/<cssarray>([^\<]*)<\/cssarray>/isU', $html, $matches) > 0) {
  15743. if (isset($matches[1][0])) {
  15744. $css = array_merge($css, json_decode($this->unhtmlentities($matches[1][0]), true));
  15745. }
  15746. $html = preg_replace('/<cssarray>(.*?)<\/cssarray>/isU', '', $html);
  15747. }
  15748. // extract external CSS files
  15749. $matches = array();
  15750. if (preg_match_all('/<link([^\>]*)>/isU', $html, $matches) > 0) {
  15751. foreach ($matches[1] as $key => $link) {
  15752. $type = array();
  15753. if (preg_match('/type[\s]*=[\s]*"text\/css"/', $link, $type)) {
  15754. $type = array();
  15755. preg_match('/media[\s]*=[\s]*"([^"]*)"/', $link, $type);
  15756. // get 'all' and 'print' media, other media types are discarded
  15757. // (all, braille, embossed, handheld, print, projection, screen, speech, tty, tv)
  15758. if (empty($type) OR (isset($type[1]) AND (($type[1] == 'all') OR ($type[1] == 'print')))) {
  15759. $type = array();
  15760. if (preg_match('/href[\s]*=[\s]*"([^"]*)"/', $link, $type) > 0) {
  15761. // read CSS data file
  15762. $cssdata = $this->getCachedFileContents(trim($type[1]));
  15763. if (($cssdata !== FALSE) AND (strlen($cssdata) > 0)) {
  15764. $css = array_merge($css, TCPDF_STATIC::extractCSSproperties($cssdata));
  15765. }
  15766. }
  15767. }
  15768. }
  15769. }
  15770. }
  15771. // extract style tags
  15772. $matches = array();
  15773. if (preg_match_all('/<style([^\>]*)>([^\<]*)<\/style>/isU', $html, $matches) > 0) {
  15774. foreach ($matches[1] as $key => $media) {
  15775. $type = array();
  15776. preg_match('/media[\s]*=[\s]*"([^"]*)"/', $media, $type);
  15777. // get 'all' and 'print' media, other media types are discarded
  15778. // (all, braille, embossed, handheld, print, projection, screen, speech, tty, tv)
  15779. if (empty($type) OR (isset($type[1]) AND (($type[1] == 'all') OR ($type[1] == 'print')))) {
  15780. $cssdata = $matches[2][$key];
  15781. $css = array_merge($css, TCPDF_STATIC::extractCSSproperties($cssdata));
  15782. }
  15783. }
  15784. }
  15785. // create a special tag to contain the CSS array (used for table content)
  15786. $csstagarray = '<cssarray>'.htmlentities(json_encode($css)).'</cssarray>';
  15787. // remove head and style blocks
  15788. $html = preg_replace('/<head([^\>]*)>(.*)?<\/head>/siU', '', $html);
  15789. $html = preg_replace('/<style([^\>]*)>([^\<]*)<\/style>/isU', '', $html);
  15790. // define block tags
  15791. $blocktags = array('blockquote','br','dd','dl','div','dt','h1','h2','h3','h4','h5','h6','hr','li','ol','p','pre','ul','tcpdf','table','tr','td');
  15792. // define self-closing tags
  15793. $selfclosingtags = array('area','base','basefont','br','hr','input','img','link','meta');
  15794. // remove all unsupported tags (the line below lists all supported tags)
  15795. $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>');
  15796. //replace some blank characters
  15797. $html = preg_replace('/<pre/', '<xre', $html); // preserve pre tag
  15798. $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);
  15799. $html = preg_replace('@(\r\n|\r)@', "\n", $html);
  15800. $repTable = array("\t" => ' ', "\0" => ' ', "\x0B" => ' ', "\\" => "\\\\");
  15801. $html = strtr($html, $repTable);
  15802. $offset = 0;
  15803. while (($offset < strlen($html)) AND ($pos = strpos($html, '</pre>', $offset)) !== false) {
  15804. $html_a = substr($html, 0, $offset);
  15805. $html_b = substr($html, $offset, ($pos - $offset + 6));
  15806. while (preg_match("'<xre([^\>]*)>(.*?)\n(.*?)</pre>'si", $html_b)) {
  15807. // preserve newlines on <pre> tag
  15808. $html_b = preg_replace("'<xre([^\>]*)>(.*?)\n(.*?)</pre>'si", "<xre\\1>\\2<br />\\3</pre>", $html_b);
  15809. }
  15810. while (preg_match("'<xre([^\>]*)>(.*?)".$this->re_space['p']."(.*?)</pre>'".$this->re_space['m'], $html_b)) {
  15811. // preserve spaces on <pre> tag
  15812. $html_b = preg_replace("'<xre([^\>]*)>(.*?)".$this->re_space['p']."(.*?)</pre>'".$this->re_space['m'], "<xre\\1>\\2&nbsp;\\3</pre>", $html_b);
  15813. }
  15814. $html = $html_a.$html_b.substr($html, $pos + 6);
  15815. $offset = strlen($html_a.$html_b);
  15816. }
  15817. $offset = 0;
  15818. while (($offset < strlen($html)) AND ($pos = strpos($html, '</textarea>', $offset)) !== false) {
  15819. $html_a = substr($html, 0, $offset);
  15820. $html_b = substr($html, $offset, ($pos - $offset + 11));
  15821. while (preg_match("'<textarea([^\>]*)>(.*?)\n(.*?)</textarea>'si", $html_b)) {
  15822. // preserve newlines on <textarea> tag
  15823. $html_b = preg_replace("'<textarea([^\>]*)>(.*?)\n(.*?)</textarea>'si", "<textarea\\1>\\2<TBR>\\3</textarea>", $html_b);
  15824. $html_b = preg_replace("'<textarea([^\>]*)>(.*?)[\"](.*?)</textarea>'si", "<textarea\\1>\\2''\\3</textarea>", $html_b);
  15825. }
  15826. $html = $html_a.$html_b.substr($html, $pos + 11);
  15827. $offset = strlen($html_a.$html_b);
  15828. }
  15829. $html = preg_replace('/([\s]*)<option/si', '<option', $html);
  15830. $html = preg_replace('/<\/option>([\s]*)/si', '</option>', $html);
  15831. $offset = 0;
  15832. while (($offset < strlen($html)) AND ($pos = strpos($html, '</option>', $offset)) !== false) {
  15833. $html_a = substr($html, 0, $offset);
  15834. $html_b = substr($html, $offset, ($pos - $offset + 9));
  15835. while (preg_match("'<option([^\>]*)>(.*?)</option>'si", $html_b)) {
  15836. $html_b = preg_replace("'<option([\s]+)value=\"([^\"]*)\"([^\>]*)>(.*?)</option>'si", "\\2#!TaB!#\\4#!NwL!#", $html_b);
  15837. $html_b = preg_replace("'<option([^\>]*)>(.*?)</option>'si", "\\2#!NwL!#", $html_b);
  15838. }
  15839. $html = $html_a.$html_b.substr($html, $pos + 9);
  15840. $offset = strlen($html_a.$html_b);
  15841. }
  15842. if (preg_match("'</select'si", $html)) {
  15843. $html = preg_replace("'<select([^\>]*)>'si", "<select\\1 opt=\"", $html);
  15844. $html = preg_replace("'#!NwL!#</select>'si", "\" />", $html);
  15845. }
  15846. $html = str_replace("\n", ' ', $html);
  15847. // restore textarea newlines
  15848. $html = str_replace('<TBR>', "\n", $html);
  15849. // remove extra spaces from code
  15850. $html = preg_replace('/[\s]+<\/(table|tr|ul|ol|dl)>/', '</\\1>', $html);
  15851. $html = preg_replace('/'.$this->re_space['p'].'+<\/(td|th|li|dt|dd)>/'.$this->re_space['m'], '</\\1>', $html);
  15852. $html = preg_replace('/[\s]+<(tr|td|th|li|dt|dd)/', '<\\1', $html);
  15853. $html = preg_replace('/'.$this->re_space['p'].'+<(ul|ol|dl|br)/'.$this->re_space['m'], '<\\1', $html);
  15854. $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);
  15855. $html = preg_replace('/<\/(td|th)>/', '<marker style="font-size:0"/></\\1>', $html);
  15856. $html = preg_replace('/<\/table>([\s]*)<marker style="font-size:0"\/>/', '</table>', $html);
  15857. $html = preg_replace('/'.$this->re_space['p'].'+<img/'.$this->re_space['m'], chr(32).'<img', $html);
  15858. $html = preg_replace('/<img([^\>]*)>[\s]+([^\<])/xi', '<img\\1>&nbsp;\\2', $html);
  15859. $html = preg_replace('/<img([^\>]*)>/xi', '<img\\1><span><marker style="font-size:0"/></span>', $html);
  15860. $html = preg_replace('/<xre/', '<pre', $html); // restore pre tag
  15861. $html = preg_replace('/<textarea([^\>]*)>([^\<]*)<\/textarea>/xi', '<textarea\\1 value="\\2" />', $html);
  15862. $html = preg_replace('/<li([^\>]*)><\/li>/', '<li\\1>&nbsp;</li>', $html);
  15863. $html = preg_replace('/<li([^\>]*)>'.$this->re_space['p'].'*<img/'.$this->re_space['m'], '<li\\1><font size="1">&nbsp;</font><img', $html);
  15864. $html = preg_replace('/<([^\>\/]*)>[\s]/', '<\\1>&nbsp;', $html); // preserve some spaces
  15865. $html = preg_replace('/[\s]<\/([^\>]*)>/', '&nbsp;</\\1>', $html); // preserve some spaces
  15866. $html = preg_replace('/<su([bp])/', '<zws/><su\\1', $html); // fix sub/sup alignment
  15867. $html = preg_replace('/<\/su([bp])>/', '</su\\1><zws/>', $html); // fix sub/sup alignment
  15868. $html = preg_replace('/'.$this->re_space['p'].'+/'.$this->re_space['m'], chr(32), $html); // replace multiple spaces with a single space
  15869. // trim string
  15870. $html = $this->stringTrim($html);
  15871. // fix br tag after li
  15872. $html = preg_replace('/<li><br([^\>]*)>/', '<li> <br\\1>', $html);
  15873. // fix first image tag alignment
  15874. $html = preg_replace('/^<img/', '<span style="font-size:0"><br /></span> <img', $html, 1);
  15875. // pattern for generic tag
  15876. $tagpattern = '/(<[^>]+>)/';
  15877. // explodes the string
  15878. $a = preg_split($tagpattern, $html, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  15879. // count elements
  15880. $maxel = count($a);
  15881. $elkey = 0;
  15882. $key = 0;
  15883. // create an array of elements
  15884. $dom = array();
  15885. $dom[$key] = array();
  15886. // set inheritable properties fot the first void element
  15887. // 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
  15888. $dom[$key]['tag'] = false;
  15889. $dom[$key]['block'] = false;
  15890. $dom[$key]['value'] = '';
  15891. $dom[$key]['parent'] = 0;
  15892. $dom[$key]['hide'] = false;
  15893. $dom[$key]['fontname'] = $this->FontFamily;
  15894. $dom[$key]['fontstyle'] = $this->FontStyle;
  15895. $dom[$key]['fontsize'] = $this->FontSizePt;
  15896. $dom[$key]['font-stretch'] = $this->font_stretching;
  15897. $dom[$key]['letter-spacing'] = $this->font_spacing;
  15898. $dom[$key]['stroke'] = $this->textstrokewidth;
  15899. $dom[$key]['fill'] = (($this->textrendermode % 2) == 0);
  15900. $dom[$key]['clip'] = ($this->textrendermode > 3);
  15901. $dom[$key]['line-height'] = $this->cell_height_ratio;
  15902. $dom[$key]['bgcolor'] = false;
  15903. $dom[$key]['fgcolor'] = $this->fgcolor; // color
  15904. $dom[$key]['strokecolor'] = $this->strokecolor;
  15905. $dom[$key]['align'] = '';
  15906. $dom[$key]['listtype'] = '';
  15907. $dom[$key]['text-indent'] = 0;
  15908. $dom[$key]['text-transform'] = '';
  15909. $dom[$key]['border'] = array();
  15910. $dom[$key]['dir'] = $this->rtl?'rtl':'ltr';
  15911. $thead = false; // true when we are inside the THEAD tag
  15912. ++$key;
  15913. $level = array();
  15914. array_push($level, 0); // root
  15915. while ($elkey < $maxel) {
  15916. $dom[$key] = array();
  15917. $element = $a[$elkey];
  15918. $dom[$key]['elkey'] = $elkey;
  15919. if (preg_match($tagpattern, $element)) {
  15920. // html tag
  15921. $element = substr($element, 1, -1);
  15922. // get tag name
  15923. preg_match('/[\/]?([a-zA-Z0-9]*)/', $element, $tag);
  15924. $tagname = strtolower($tag[1]);
  15925. // check if we are inside a table header
  15926. if ($tagname == 'thead') {
  15927. if ($element[0] == '/') {
  15928. $thead = false;
  15929. } else {
  15930. $thead = true;
  15931. }
  15932. ++$elkey;
  15933. continue;
  15934. }
  15935. $dom[$key]['tag'] = true;
  15936. $dom[$key]['value'] = $tagname;
  15937. if (in_array($dom[$key]['value'], $blocktags)) {
  15938. $dom[$key]['block'] = true;
  15939. } else {
  15940. $dom[$key]['block'] = false;
  15941. }
  15942. if ($element[0] == '/') {
  15943. // *** closing html tag
  15944. $dom[$key]['opening'] = false;
  15945. $dom[$key]['parent'] = end($level);
  15946. array_pop($level);
  15947. $dom[$key]['hide'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['hide'];
  15948. $dom[$key]['fontname'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fontname'];
  15949. $dom[$key]['fontstyle'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fontstyle'];
  15950. $dom[$key]['fontsize'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fontsize'];
  15951. $dom[$key]['font-stretch'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['font-stretch'];
  15952. $dom[$key]['letter-spacing'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['letter-spacing'];
  15953. $dom[$key]['stroke'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['stroke'];
  15954. $dom[$key]['fill'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fill'];
  15955. $dom[$key]['clip'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['clip'];
  15956. $dom[$key]['line-height'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['line-height'];
  15957. $dom[$key]['bgcolor'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['bgcolor'];
  15958. $dom[$key]['fgcolor'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fgcolor'];
  15959. $dom[$key]['strokecolor'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['strokecolor'];
  15960. $dom[$key]['align'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['align'];
  15961. $dom[$key]['text-transform'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['text-transform'];
  15962. $dom[$key]['dir'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['dir'];
  15963. if (isset($dom[($dom[($dom[$key]['parent'])]['parent'])]['listtype'])) {
  15964. $dom[$key]['listtype'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['listtype'];
  15965. }
  15966. // set the number of columns in table tag
  15967. if (($dom[$key]['value'] == 'tr') AND (!isset($dom[($dom[($dom[$key]['parent'])]['parent'])]['cols']))) {
  15968. $dom[($dom[($dom[$key]['parent'])]['parent'])]['cols'] = $dom[($dom[$key]['parent'])]['cols'];
  15969. }
  15970. if (($dom[$key]['value'] == 'td') OR ($dom[$key]['value'] == 'th')) {
  15971. $dom[($dom[$key]['parent'])]['content'] = $csstagarray;
  15972. for ($i = ($dom[$key]['parent'] + 1); $i < $key; ++$i) {
  15973. $dom[($dom[$key]['parent'])]['content'] .= stripslashes($a[$dom[$i]['elkey']]);
  15974. }
  15975. $key = $i;
  15976. // mark nested tables
  15977. $dom[($dom[$key]['parent'])]['content'] = str_replace('<table', '<table nested="true"', $dom[($dom[$key]['parent'])]['content']);
  15978. // remove thead sections from nested tables
  15979. $dom[($dom[$key]['parent'])]['content'] = str_replace('<thead>', '', $dom[($dom[$key]['parent'])]['content']);
  15980. $dom[($dom[$key]['parent'])]['content'] = str_replace('</thead>', '', $dom[($dom[$key]['parent'])]['content']);
  15981. }
  15982. // store header rows on a new table
  15983. if (
  15984. ($dom[$key]['value'] === 'tr')
  15985. && !empty($dom[($dom[$key]['parent'])]['thead'])
  15986. && ($dom[($dom[$key]['parent'])]['thead'] === true)
  15987. ) {
  15988. if (TCPDF_STATIC::empty_string($dom[($dom[($dom[$key]['parent'])]['parent'])]['thead'])) {
  15989. $dom[($dom[($dom[$key]['parent'])]['parent'])]['thead'] = $csstagarray.$a[$dom[($dom[($dom[$key]['parent'])]['parent'])]['elkey']];
  15990. }
  15991. for ($i = $dom[$key]['parent']; $i <= $key; ++$i) {
  15992. $dom[($dom[($dom[$key]['parent'])]['parent'])]['thead'] .= $a[$dom[$i]['elkey']];
  15993. }
  15994. if (!isset($dom[($dom[$key]['parent'])]['attribute'])) {
  15995. $dom[($dom[$key]['parent'])]['attribute'] = array();
  15996. }
  15997. // header elements must be always contained in a single page
  15998. $dom[($dom[$key]['parent'])]['attribute']['nobr'] = 'true';
  15999. }
  16000. if (($dom[$key]['value'] == 'table') AND (!TCPDF_STATIC::empty_string($dom[($dom[$key]['parent'])]['thead']))) {
  16001. // remove the nobr attributes from the table header
  16002. $dom[($dom[$key]['parent'])]['thead'] = str_replace(' nobr="true"', '', $dom[($dom[$key]['parent'])]['thead']);
  16003. $dom[($dom[$key]['parent'])]['thead'] .= '</tablehead>';
  16004. }
  16005. } else {
  16006. // *** opening or self-closing html tag
  16007. $dom[$key]['opening'] = true;
  16008. $dom[$key]['parent'] = end($level);
  16009. if ((substr($element, -1, 1) == '/') OR (in_array($dom[$key]['value'], $selfclosingtags))) {
  16010. // self-closing tag
  16011. $dom[$key]['self'] = true;
  16012. } else {
  16013. // opening tag
  16014. array_push($level, $key);
  16015. $dom[$key]['self'] = false;
  16016. }
  16017. // copy some values from parent
  16018. $parentkey = 0;
  16019. if ($key > 0) {
  16020. $parentkey = $dom[$key]['parent'];
  16021. $dom[$key]['hide'] = $dom[$parentkey]['hide'];
  16022. $dom[$key]['fontname'] = $dom[$parentkey]['fontname'];
  16023. $dom[$key]['fontstyle'] = $dom[$parentkey]['fontstyle'];
  16024. $dom[$key]['fontsize'] = $dom[$parentkey]['fontsize'];
  16025. $dom[$key]['font-stretch'] = $dom[$parentkey]['font-stretch'];
  16026. $dom[$key]['letter-spacing'] = $dom[$parentkey]['letter-spacing'];
  16027. $dom[$key]['stroke'] = $dom[$parentkey]['stroke'];
  16028. $dom[$key]['fill'] = $dom[$parentkey]['fill'];
  16029. $dom[$key]['clip'] = $dom[$parentkey]['clip'];
  16030. $dom[$key]['line-height'] = $dom[$parentkey]['line-height'];
  16031. $dom[$key]['bgcolor'] = $dom[$parentkey]['bgcolor'];
  16032. $dom[$key]['fgcolor'] = $dom[$parentkey]['fgcolor'];
  16033. $dom[$key]['strokecolor'] = $dom[$parentkey]['strokecolor'];
  16034. $dom[$key]['align'] = $dom[$parentkey]['align'];
  16035. $dom[$key]['listtype'] = $dom[$parentkey]['listtype'];
  16036. $dom[$key]['text-indent'] = $dom[$parentkey]['text-indent'];
  16037. $dom[$key]['text-transform'] = $dom[$parentkey]['text-transform'];
  16038. $dom[$key]['border'] = array();
  16039. $dom[$key]['dir'] = $dom[$parentkey]['dir'];
  16040. }
  16041. // get attributes
  16042. preg_match_all('/([^=\s]*)[\s]*=[\s]*"([^"]*)"/', $element, $attr_array, PREG_PATTERN_ORDER);
  16043. $dom[$key]['attribute'] = array(); // reset attribute array
  16044. foreach($attr_array[1] as $id => $name) {
  16045. $dom[$key]['attribute'][strtolower($name)] = $attr_array[2][$id];
  16046. }
  16047. if (!empty($css)) {
  16048. // merge CSS style to current style
  16049. list($dom[$key]['csssel'], $dom[$key]['cssdata']) = TCPDF_STATIC::getCSSdataArray($dom, $key, $css);
  16050. $dom[$key]['attribute']['style'] = TCPDF_STATIC::getTagStyleFromCSSarray($dom[$key]['cssdata']);
  16051. }
  16052. // split style attributes
  16053. if (isset($dom[$key]['attribute']['style']) AND !empty($dom[$key]['attribute']['style'])) {
  16054. // get style attributes
  16055. preg_match_all('/([^;:\s]*):([^;]*)/', $dom[$key]['attribute']['style'], $style_array, PREG_PATTERN_ORDER);
  16056. $dom[$key]['style'] = array(); // reset style attribute array
  16057. foreach($style_array[1] as $id => $name) {
  16058. // in case of duplicate attribute the last replace the previous
  16059. $dom[$key]['style'][strtolower($name)] = trim($style_array[2][$id]);
  16060. }
  16061. // --- get some style attributes ---
  16062. // text direction
  16063. if (isset($dom[$key]['style']['direction'])) {
  16064. $dom[$key]['dir'] = $dom[$key]['style']['direction'];
  16065. }
  16066. // display
  16067. if (isset($dom[$key]['style']['display'])) {
  16068. $dom[$key]['hide'] = (trim(strtolower($dom[$key]['style']['display'])) == 'none');
  16069. }
  16070. // font family
  16071. if (isset($dom[$key]['style']['font-family'])) {
  16072. $dom[$key]['fontname'] = $this->getFontFamilyName($dom[$key]['style']['font-family']);
  16073. }
  16074. // list-style-type
  16075. if (isset($dom[$key]['style']['list-style-type'])) {
  16076. $dom[$key]['listtype'] = trim(strtolower($dom[$key]['style']['list-style-type']));
  16077. if ($dom[$key]['listtype'] == 'inherit') {
  16078. $dom[$key]['listtype'] = $dom[$parentkey]['listtype'];
  16079. }
  16080. }
  16081. // text-indent
  16082. if (isset($dom[$key]['style']['text-indent'])) {
  16083. $dom[$key]['text-indent'] = $this->getHTMLUnitToUnits($dom[$key]['style']['text-indent']);
  16084. if ($dom[$key]['text-indent'] == 'inherit') {
  16085. $dom[$key]['text-indent'] = $dom[$parentkey]['text-indent'];
  16086. }
  16087. }
  16088. // text-transform
  16089. if (isset($dom[$key]['style']['text-transform'])) {
  16090. $dom[$key]['text-transform'] = $dom[$key]['style']['text-transform'];
  16091. }
  16092. // font size
  16093. if (isset($dom[$key]['style']['font-size'])) {
  16094. $fsize = trim($dom[$key]['style']['font-size']);
  16095. $dom[$key]['fontsize'] = $this->getHTMLFontUnits($fsize, $dom[0]['fontsize'], $dom[$parentkey]['fontsize'], 'pt');
  16096. }
  16097. // font-stretch
  16098. if (isset($dom[$key]['style']['font-stretch'])) {
  16099. $dom[$key]['font-stretch'] = $this->getCSSFontStretching($dom[$key]['style']['font-stretch'], $dom[$parentkey]['font-stretch']);
  16100. }
  16101. // letter-spacing
  16102. if (isset($dom[$key]['style']['letter-spacing'])) {
  16103. $dom[$key]['letter-spacing'] = $this->getCSSFontSpacing($dom[$key]['style']['letter-spacing'], $dom[$parentkey]['letter-spacing']);
  16104. }
  16105. // line-height (internally is the cell height ratio)
  16106. if (isset($dom[$key]['style']['line-height'])) {
  16107. $lineheight = trim($dom[$key]['style']['line-height']);
  16108. switch ($lineheight) {
  16109. // A normal line height. This is default
  16110. case 'normal': {
  16111. $dom[$key]['line-height'] = $dom[0]['line-height'];
  16112. break;
  16113. }
  16114. case 'inherit': {
  16115. $dom[$key]['line-height'] = $dom[$parentkey]['line-height'];
  16116. }
  16117. default: {
  16118. if (is_numeric($lineheight)) {
  16119. // convert to percentage of font height
  16120. $lineheight = ($lineheight * 100).'%';
  16121. }
  16122. $dom[$key]['line-height'] = $this->getHTMLUnitToUnits($lineheight, 1, '%', true);
  16123. if (substr($lineheight, -1) !== '%') {
  16124. if ($dom[$key]['fontsize'] <= 0) {
  16125. $dom[$key]['line-height'] = 1;
  16126. } else {
  16127. $dom[$key]['line-height'] = (($dom[$key]['line-height'] - $this->cell_padding['T'] - $this->cell_padding['B']) / $dom[$key]['fontsize']);
  16128. }
  16129. }
  16130. }
  16131. }
  16132. }
  16133. // font style
  16134. if (isset($dom[$key]['style']['font-weight'])) {
  16135. if (strtolower($dom[$key]['style']['font-weight'][0]) == 'n') {
  16136. if (strpos($dom[$key]['fontstyle'], 'B') !== false) {
  16137. $dom[$key]['fontstyle'] = str_replace('B', '', $dom[$key]['fontstyle']);
  16138. }
  16139. } elseif (strtolower($dom[$key]['style']['font-weight'][0]) == 'b') {
  16140. $dom[$key]['fontstyle'] .= 'B';
  16141. }
  16142. }
  16143. if (isset($dom[$key]['style']['font-style']) AND (strtolower($dom[$key]['style']['font-style'][0]) == 'i')) {
  16144. $dom[$key]['fontstyle'] .= 'I';
  16145. }
  16146. // font color
  16147. if (isset($dom[$key]['style']['color']) AND (!TCPDF_STATIC::empty_string($dom[$key]['style']['color']))) {
  16148. $dom[$key]['fgcolor'] = TCPDF_COLORS::convertHTMLColorToDec($dom[$key]['style']['color'], $this->spot_colors);
  16149. } elseif ($dom[$key]['value'] == 'a') {
  16150. $dom[$key]['fgcolor'] = $this->htmlLinkColorArray;
  16151. }
  16152. // background color
  16153. if (isset($dom[$key]['style']['background-color']) AND (!TCPDF_STATIC::empty_string($dom[$key]['style']['background-color']))) {
  16154. $dom[$key]['bgcolor'] = TCPDF_COLORS::convertHTMLColorToDec($dom[$key]['style']['background-color'], $this->spot_colors);
  16155. }
  16156. // text-decoration
  16157. if (isset($dom[$key]['style']['text-decoration'])) {
  16158. $decors = explode(' ', strtolower($dom[$key]['style']['text-decoration']));
  16159. foreach ($decors as $dec) {
  16160. $dec = trim($dec);
  16161. if (!TCPDF_STATIC::empty_string($dec)) {
  16162. if ($dec[0] == 'u') {
  16163. // underline
  16164. $dom[$key]['fontstyle'] .= 'U';
  16165. } elseif ($dec[0] == 'l') {
  16166. // line-through
  16167. $dom[$key]['fontstyle'] .= 'D';
  16168. } elseif ($dec[0] == 'o') {
  16169. // overline
  16170. $dom[$key]['fontstyle'] .= 'O';
  16171. }
  16172. }
  16173. }
  16174. } elseif ($dom[$key]['value'] == 'a') {
  16175. $dom[$key]['fontstyle'] = $this->htmlLinkFontStyle;
  16176. }
  16177. // check for width attribute
  16178. if (isset($dom[$key]['style']['width'])) {
  16179. $dom[$key]['width'] = $dom[$key]['style']['width'];
  16180. }
  16181. // check for height attribute
  16182. if (isset($dom[$key]['style']['height'])) {
  16183. $dom[$key]['height'] = $dom[$key]['style']['height'];
  16184. }
  16185. // check for text alignment
  16186. if (isset($dom[$key]['style']['text-align'])) {
  16187. $dom[$key]['align'] = strtoupper($dom[$key]['style']['text-align'][0]);
  16188. }
  16189. // check for CSS border properties
  16190. if (isset($dom[$key]['style']['border'])) {
  16191. $borderstyle = $this->getCSSBorderStyle($dom[$key]['style']['border']);
  16192. if (!empty($borderstyle)) {
  16193. $dom[$key]['border']['LTRB'] = $borderstyle;
  16194. }
  16195. }
  16196. if (isset($dom[$key]['style']['border-color'])) {
  16197. $brd_colors = preg_split('/[\s]+/', trim($dom[$key]['style']['border-color']));
  16198. if (isset($brd_colors[3])) {
  16199. $dom[$key]['border']['L']['color'] = TCPDF_COLORS::convertHTMLColorToDec($brd_colors[3], $this->spot_colors);
  16200. }
  16201. if (isset($brd_colors[1])) {
  16202. $dom[$key]['border']['R']['color'] = TCPDF_COLORS::convertHTMLColorToDec($brd_colors[1], $this->spot_colors);
  16203. }
  16204. if (isset($brd_colors[0])) {
  16205. $dom[$key]['border']['T']['color'] = TCPDF_COLORS::convertHTMLColorToDec($brd_colors[0], $this->spot_colors);
  16206. }
  16207. if (isset($brd_colors[2])) {
  16208. $dom[$key]['border']['B']['color'] = TCPDF_COLORS::convertHTMLColorToDec($brd_colors[2], $this->spot_colors);
  16209. }
  16210. }
  16211. if (isset($dom[$key]['style']['border-width'])) {
  16212. $brd_widths = preg_split('/[\s]+/', trim($dom[$key]['style']['border-width']));
  16213. if (isset($brd_widths[3])) {
  16214. $dom[$key]['border']['L']['width'] = $this->getCSSBorderWidth($brd_widths[3]);
  16215. }
  16216. if (isset($brd_widths[1])) {
  16217. $dom[$key]['border']['R']['width'] = $this->getCSSBorderWidth($brd_widths[1]);
  16218. }
  16219. if (isset($brd_widths[0])) {
  16220. $dom[$key]['border']['T']['width'] = $this->getCSSBorderWidth($brd_widths[0]);
  16221. }
  16222. if (isset($brd_widths[2])) {
  16223. $dom[$key]['border']['B']['width'] = $this->getCSSBorderWidth($brd_widths[2]);
  16224. }
  16225. }
  16226. if (isset($dom[$key]['style']['border-style'])) {
  16227. $brd_styles = preg_split('/[\s]+/', trim($dom[$key]['style']['border-style']));
  16228. if (isset($brd_styles[3]) AND ($brd_styles[3]!='none')) {
  16229. $dom[$key]['border']['L']['cap'] = 'square';
  16230. $dom[$key]['border']['L']['join'] = 'miter';
  16231. $dom[$key]['border']['L']['dash'] = $this->getCSSBorderDashStyle($brd_styles[3]);
  16232. if ($dom[$key]['border']['L']['dash'] < 0) {
  16233. $dom[$key]['border']['L'] = array();
  16234. }
  16235. }
  16236. if (isset($brd_styles[1])) {
  16237. $dom[$key]['border']['R']['cap'] = 'square';
  16238. $dom[$key]['border']['R']['join'] = 'miter';
  16239. $dom[$key]['border']['R']['dash'] = $this->getCSSBorderDashStyle($brd_styles[1]);
  16240. if ($dom[$key]['border']['R']['dash'] < 0) {
  16241. $dom[$key]['border']['R'] = array();
  16242. }
  16243. }
  16244. if (isset($brd_styles[0])) {
  16245. $dom[$key]['border']['T']['cap'] = 'square';
  16246. $dom[$key]['border']['T']['join'] = 'miter';
  16247. $dom[$key]['border']['T']['dash'] = $this->getCSSBorderDashStyle($brd_styles[0]);
  16248. if ($dom[$key]['border']['T']['dash'] < 0) {
  16249. $dom[$key]['border']['T'] = array();
  16250. }
  16251. }
  16252. if (isset($brd_styles[2])) {
  16253. $dom[$key]['border']['B']['cap'] = 'square';
  16254. $dom[$key]['border']['B']['join'] = 'miter';
  16255. $dom[$key]['border']['B']['dash'] = $this->getCSSBorderDashStyle($brd_styles[2]);
  16256. if ($dom[$key]['border']['B']['dash'] < 0) {
  16257. $dom[$key]['border']['B'] = array();
  16258. }
  16259. }
  16260. }
  16261. $cellside = array('L' => 'left', 'R' => 'right', 'T' => 'top', 'B' => 'bottom');
  16262. foreach ($cellside as $bsk => $bsv) {
  16263. if (isset($dom[$key]['style']['border-'.$bsv])) {
  16264. $borderstyle = $this->getCSSBorderStyle($dom[$key]['style']['border-'.$bsv]);
  16265. if (!empty($borderstyle)) {
  16266. $dom[$key]['border'][$bsk] = $borderstyle;
  16267. }
  16268. }
  16269. if (isset($dom[$key]['style']['border-'.$bsv.'-color'])) {
  16270. $dom[$key]['border'][$bsk]['color'] = TCPDF_COLORS::convertHTMLColorToDec($dom[$key]['style']['border-'.$bsv.'-color'], $this->spot_colors);
  16271. }
  16272. if (isset($dom[$key]['style']['border-'.$bsv.'-width'])) {
  16273. $dom[$key]['border'][$bsk]['width'] = $this->getCSSBorderWidth($dom[$key]['style']['border-'.$bsv.'-width']);
  16274. }
  16275. if (isset($dom[$key]['style']['border-'.$bsv.'-style'])) {
  16276. $dom[$key]['border'][$bsk]['dash'] = $this->getCSSBorderDashStyle($dom[$key]['style']['border-'.$bsv.'-style']);
  16277. if ($dom[$key]['border'][$bsk]['dash'] < 0) {
  16278. $dom[$key]['border'][$bsk] = array();
  16279. }
  16280. }
  16281. }
  16282. // check for CSS padding properties
  16283. if (isset($dom[$key]['style']['padding'])) {
  16284. $dom[$key]['padding'] = $this->getCSSPadding($dom[$key]['style']['padding']);
  16285. } else {
  16286. $dom[$key]['padding'] = $this->cell_padding;
  16287. }
  16288. foreach ($cellside as $psk => $psv) {
  16289. if (isset($dom[$key]['style']['padding-'.$psv])) {
  16290. $dom[$key]['padding'][$psk] = $this->getHTMLUnitToUnits($dom[$key]['style']['padding-'.$psv], 0, 'px', false);
  16291. }
  16292. }
  16293. // check for CSS margin properties
  16294. if (isset($dom[$key]['style']['margin'])) {
  16295. $dom[$key]['margin'] = $this->getCSSMargin($dom[$key]['style']['margin']);
  16296. } else {
  16297. $dom[$key]['margin'] = $this->cell_margin;
  16298. }
  16299. foreach ($cellside as $psk => $psv) {
  16300. if (isset($dom[$key]['style']['margin-'.$psv])) {
  16301. $dom[$key]['margin'][$psk] = $this->getHTMLUnitToUnits(str_replace('auto', '0', $dom[$key]['style']['margin-'.$psv]), 0, 'px', false);
  16302. }
  16303. }
  16304. // check for CSS border-spacing properties
  16305. if (isset($dom[$key]['style']['border-spacing'])) {
  16306. $dom[$key]['border-spacing'] = $this->getCSSBorderMargin($dom[$key]['style']['border-spacing']);
  16307. }
  16308. // page-break-inside
  16309. if (isset($dom[$key]['style']['page-break-inside']) AND ($dom[$key]['style']['page-break-inside'] == 'avoid')) {
  16310. $dom[$key]['attribute']['nobr'] = 'true';
  16311. }
  16312. // page-break-before
  16313. if (isset($dom[$key]['style']['page-break-before'])) {
  16314. if ($dom[$key]['style']['page-break-before'] == 'always') {
  16315. $dom[$key]['attribute']['pagebreak'] = 'true';
  16316. } elseif ($dom[$key]['style']['page-break-before'] == 'left') {
  16317. $dom[$key]['attribute']['pagebreak'] = 'left';
  16318. } elseif ($dom[$key]['style']['page-break-before'] == 'right') {
  16319. $dom[$key]['attribute']['pagebreak'] = 'right';
  16320. }
  16321. }
  16322. // page-break-after
  16323. if (isset($dom[$key]['style']['page-break-after'])) {
  16324. if ($dom[$key]['style']['page-break-after'] == 'always') {
  16325. $dom[$key]['attribute']['pagebreakafter'] = 'true';
  16326. } elseif ($dom[$key]['style']['page-break-after'] == 'left') {
  16327. $dom[$key]['attribute']['pagebreakafter'] = 'left';
  16328. } elseif ($dom[$key]['style']['page-break-after'] == 'right') {
  16329. $dom[$key]['attribute']['pagebreakafter'] = 'right';
  16330. }
  16331. }
  16332. }
  16333. if (isset($dom[$key]['attribute']['display'])) {
  16334. $dom[$key]['hide'] = (trim(strtolower($dom[$key]['attribute']['display'])) == 'none');
  16335. }
  16336. if (isset($dom[$key]['attribute']['border']) AND ($dom[$key]['attribute']['border'] != 0)) {
  16337. $borderstyle = $this->getCSSBorderStyle($dom[$key]['attribute']['border'].' solid black');
  16338. if (!empty($borderstyle)) {
  16339. $dom[$key]['border']['LTRB'] = $borderstyle;
  16340. }
  16341. }
  16342. // check for font tag
  16343. if ($dom[$key]['value'] == 'font') {
  16344. // font family
  16345. if (isset($dom[$key]['attribute']['face'])) {
  16346. $dom[$key]['fontname'] = $this->getFontFamilyName($dom[$key]['attribute']['face']);
  16347. }
  16348. // font size
  16349. if (isset($dom[$key]['attribute']['size'])) {
  16350. if ($key > 0) {
  16351. if ($dom[$key]['attribute']['size'][0] == '+') {
  16352. $dom[$key]['fontsize'] = $dom[($dom[$key]['parent'])]['fontsize'] + intval(substr($dom[$key]['attribute']['size'], 1));
  16353. } elseif ($dom[$key]['attribute']['size'][0] == '-') {
  16354. $dom[$key]['fontsize'] = $dom[($dom[$key]['parent'])]['fontsize'] - intval(substr($dom[$key]['attribute']['size'], 1));
  16355. } else {
  16356. $dom[$key]['fontsize'] = intval($dom[$key]['attribute']['size']);
  16357. }
  16358. } else {
  16359. $dom[$key]['fontsize'] = intval($dom[$key]['attribute']['size']);
  16360. }
  16361. }
  16362. }
  16363. // force natural alignment for lists
  16364. if ((($dom[$key]['value'] == 'ul') OR ($dom[$key]['value'] == 'ol') OR ($dom[$key]['value'] == 'dl'))
  16365. AND (!isset($dom[$key]['align']) OR TCPDF_STATIC::empty_string($dom[$key]['align']) OR ($dom[$key]['align'] != 'J'))) {
  16366. if ($this->rtl) {
  16367. $dom[$key]['align'] = 'R';
  16368. } else {
  16369. $dom[$key]['align'] = 'L';
  16370. }
  16371. }
  16372. if (($dom[$key]['value'] == 'small') OR ($dom[$key]['value'] == 'sup') OR ($dom[$key]['value'] == 'sub')) {
  16373. if (!isset($dom[$key]['attribute']['size']) AND !isset($dom[$key]['style']['font-size'])) {
  16374. $dom[$key]['fontsize'] = $dom[$key]['fontsize'] * K_SMALL_RATIO;
  16375. }
  16376. }
  16377. if (($dom[$key]['value'] == 'strong') OR ($dom[$key]['value'] == 'b')) {
  16378. $dom[$key]['fontstyle'] .= 'B';
  16379. }
  16380. if (($dom[$key]['value'] == 'em') OR ($dom[$key]['value'] == 'i')) {
  16381. $dom[$key]['fontstyle'] .= 'I';
  16382. }
  16383. if ($dom[$key]['value'] == 'u') {
  16384. $dom[$key]['fontstyle'] .= 'U';
  16385. }
  16386. if (($dom[$key]['value'] == 'del') OR ($dom[$key]['value'] == 's') OR ($dom[$key]['value'] == 'strike')) {
  16387. $dom[$key]['fontstyle'] .= 'D';
  16388. }
  16389. if (!isset($dom[$key]['style']['text-decoration']) AND ($dom[$key]['value'] == 'a')) {
  16390. $dom[$key]['fontstyle'] = $this->htmlLinkFontStyle;
  16391. }
  16392. if (($dom[$key]['value'] == 'pre') OR ($dom[$key]['value'] == 'tt')) {
  16393. $dom[$key]['fontname'] = $this->default_monospaced_font;
  16394. }
  16395. 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)) {
  16396. // headings h1, h2, h3, h4, h5, h6
  16397. if (!isset($dom[$key]['attribute']['size']) AND !isset($dom[$key]['style']['font-size'])) {
  16398. $headsize = (4 - intval($dom[$key]['value'][1])) * 2;
  16399. $dom[$key]['fontsize'] = $dom[0]['fontsize'] + $headsize;
  16400. }
  16401. if (!isset($dom[$key]['style']['font-weight'])) {
  16402. $dom[$key]['fontstyle'] .= 'B';
  16403. }
  16404. }
  16405. if (($dom[$key]['value'] == 'table')) {
  16406. $dom[$key]['rows'] = 0; // number of rows
  16407. $dom[$key]['trids'] = array(); // IDs of TR elements
  16408. $dom[$key]['thead'] = ''; // table header rows
  16409. }
  16410. if (($dom[$key]['value'] == 'tr')) {
  16411. $dom[$key]['cols'] = 0;
  16412. if ($thead) {
  16413. $dom[$key]['thead'] = true;
  16414. // rows on thead block are printed as a separate table
  16415. } else {
  16416. $dom[$key]['thead'] = false;
  16417. $parent = $dom[$key]['parent'];
  16418. if (!isset($dom[$parent]['rows'])) {
  16419. $dom[$parent]['rows'] = 0;
  16420. }
  16421. // store the number of rows on table element
  16422. ++$dom[$parent]['rows'];
  16423. if (!isset($dom[$parent]['trids'])) {
  16424. $dom[$parent]['trids'] = array();
  16425. }
  16426. // store the TR elements IDs on table element
  16427. array_push($dom[$parent]['trids'], $key);
  16428. }
  16429. }
  16430. if (($dom[$key]['value'] == 'th') OR ($dom[$key]['value'] == 'td')) {
  16431. if (isset($dom[$key]['attribute']['colspan'])) {
  16432. $colspan = intval($dom[$key]['attribute']['colspan']);
  16433. } else {
  16434. $colspan = 1;
  16435. }
  16436. $dom[$key]['attribute']['colspan'] = $colspan;
  16437. $dom[($dom[$key]['parent'])]['cols'] += $colspan;
  16438. }
  16439. // text direction
  16440. if (isset($dom[$key]['attribute']['dir'])) {
  16441. $dom[$key]['dir'] = $dom[$key]['attribute']['dir'];
  16442. }
  16443. // set foreground color attribute
  16444. if (isset($dom[$key]['attribute']['color']) AND (!TCPDF_STATIC::empty_string($dom[$key]['attribute']['color']))) {
  16445. $dom[$key]['fgcolor'] = TCPDF_COLORS::convertHTMLColorToDec($dom[$key]['attribute']['color'], $this->spot_colors);
  16446. } elseif (!isset($dom[$key]['style']['color']) AND ($dom[$key]['value'] == 'a')) {
  16447. $dom[$key]['fgcolor'] = $this->htmlLinkColorArray;
  16448. }
  16449. // set background color attribute
  16450. if (isset($dom[$key]['attribute']['bgcolor']) AND (!TCPDF_STATIC::empty_string($dom[$key]['attribute']['bgcolor']))) {
  16451. $dom[$key]['bgcolor'] = TCPDF_COLORS::convertHTMLColorToDec($dom[$key]['attribute']['bgcolor'], $this->spot_colors);
  16452. }
  16453. // set stroke color attribute
  16454. if (isset($dom[$key]['attribute']['strokecolor']) AND (!TCPDF_STATIC::empty_string($dom[$key]['attribute']['strokecolor']))) {
  16455. $dom[$key]['strokecolor'] = TCPDF_COLORS::convertHTMLColorToDec($dom[$key]['attribute']['strokecolor'], $this->spot_colors);
  16456. }
  16457. // check for width attribute
  16458. if (isset($dom[$key]['attribute']['width'])) {
  16459. $dom[$key]['width'] = $dom[$key]['attribute']['width'];
  16460. }
  16461. // check for height attribute
  16462. if (isset($dom[$key]['attribute']['height'])) {
  16463. $dom[$key]['height'] = $dom[$key]['attribute']['height'];
  16464. }
  16465. // check for text alignment
  16466. if (isset($dom[$key]['attribute']['align']) AND (!TCPDF_STATIC::empty_string($dom[$key]['attribute']['align'])) AND ($dom[$key]['value'] !== 'img')) {
  16467. $dom[$key]['align'] = strtoupper($dom[$key]['attribute']['align'][0]);
  16468. }
  16469. // check for text rendering mode (the following attributes do not exist in HTML)
  16470. if (isset($dom[$key]['attribute']['stroke'])) {
  16471. // font stroke width
  16472. $dom[$key]['stroke'] = $this->getHTMLUnitToUnits($dom[$key]['attribute']['stroke'], $dom[$key]['fontsize'], 'pt', true);
  16473. }
  16474. if (isset($dom[$key]['attribute']['fill'])) {
  16475. // font fill
  16476. if ($dom[$key]['attribute']['fill'] == 'true') {
  16477. $dom[$key]['fill'] = true;
  16478. } else {
  16479. $dom[$key]['fill'] = false;
  16480. }
  16481. }
  16482. if (isset($dom[$key]['attribute']['clip'])) {
  16483. // clipping mode
  16484. if ($dom[$key]['attribute']['clip'] == 'true') {
  16485. $dom[$key]['clip'] = true;
  16486. } else {
  16487. $dom[$key]['clip'] = false;
  16488. }
  16489. }
  16490. } // end opening tag
  16491. } else {
  16492. // text
  16493. $dom[$key]['tag'] = false;
  16494. $dom[$key]['block'] = false;
  16495. $dom[$key]['parent'] = end($level);
  16496. $dom[$key]['dir'] = $dom[$dom[$key]['parent']]['dir'];
  16497. if (!empty($dom[$dom[$key]['parent']]['text-transform'])) {
  16498. // text-transform for unicode requires mb_convert_case (Multibyte String Functions)
  16499. if (function_exists('mb_convert_case')) {
  16500. $ttm = array('capitalize' => MB_CASE_TITLE, 'uppercase' => MB_CASE_UPPER, 'lowercase' => MB_CASE_LOWER);
  16501. if (isset($ttm[$dom[$dom[$key]['parent']]['text-transform']])) {
  16502. $element = mb_convert_case($element, $ttm[$dom[$dom[$key]['parent']]['text-transform']], $this->encoding);
  16503. }
  16504. } elseif (!$this->isunicode) {
  16505. switch ($dom[$dom[$key]['parent']]['text-transform']) {
  16506. case 'capitalize': {
  16507. $element = ucwords(strtolower($element));
  16508. break;
  16509. }
  16510. case 'uppercase': {
  16511. $element = strtoupper($element);
  16512. break;
  16513. }
  16514. case 'lowercase': {
  16515. $element = strtolower($element);
  16516. break;
  16517. }
  16518. }
  16519. }
  16520. }
  16521. $dom[$key]['value'] = stripslashes($this->unhtmlentities($element));
  16522. }
  16523. ++$elkey;
  16524. ++$key;
  16525. }
  16526. return $dom;
  16527. }
  16528. /**
  16529. * Returns the string used to find spaces
  16530. * @return string
  16531. * @protected
  16532. * @author Nicola Asuni
  16533. * @since 4.8.024 (2010-01-15)
  16534. */
  16535. protected function getSpaceString() {
  16536. $spacestr = chr(32);
  16537. if ($this->isUnicodeFont()) {
  16538. $spacestr = chr(0).chr(32);
  16539. }
  16540. return $spacestr;
  16541. }
  16542. /**
  16543. * Return an hash code used to ensure that the serialized data has been generated by this TCPDF instance.
  16544. * @param $data (string) serialized data
  16545. * @return string
  16546. * @public static
  16547. */
  16548. protected function getHashForTCPDFtagParams($data) {
  16549. return md5(strlen($data).$this->file_id.$data);
  16550. }
  16551. /**
  16552. * Serialize an array of parameters to be used with TCPDF tag in HTML code.
  16553. * @param $data (array) parameters array
  16554. * @return string containing serialized data
  16555. * @public static
  16556. */
  16557. public function serializeTCPDFtagParameters($data) {
  16558. $encoded = urlencode(json_encode($data));
  16559. return $this->getHashForTCPDFtagParams($encoded).$encoded;
  16560. }
  16561. /**
  16562. * Unserialize parameters to be used with TCPDF tag in HTML code.
  16563. * @param $data (string) serialized data
  16564. * @return array containing unserialized data
  16565. * @protected static
  16566. */
  16567. protected function unserializeTCPDFtagParameters($data) {
  16568. $hash = substr($data, 0, 32);
  16569. $encoded = substr($data, 32);
  16570. if ($hash != $this->getHashForTCPDFtagParams($encoded)) {
  16571. $this->Error('Invalid parameters');
  16572. }
  16573. return json_decode(urldecode($encoded), true);
  16574. }
  16575. /**
  16576. * Prints a cell (rectangular area) with optional borders, background color and html text string.
  16577. * 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 />
  16578. * If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting.
  16579. * IMPORTANT: The HTML must be well formatted - try to clean-up it using an application like HTML-Tidy before submitting.
  16580. * 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
  16581. * NOTE: all the HTML attributes must be enclosed in double-quote.
  16582. * @param $w (float) Cell width. If 0, the cell extends up to the right margin.
  16583. * @param $h (float) Cell minimum height. The cell extends automatically if needed.
  16584. * @param $x (float) upper-left corner X coordinate
  16585. * @param $y (float) upper-left corner Y coordinate
  16586. * @param $html (string) html text to print. Default value: empty string.
  16587. * @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)))
  16588. * @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>
  16589. Putting 1 is equivalent to putting 0 and calling Ln() just after. Default value: 0.
  16590. * @param $fill (boolean) Indicates if the cell background must be painted (true) or transparent (false).
  16591. * @param $reseth (boolean) if true reset the last cell height (default true).
  16592. * @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>
  16593. * @param $autopadding (boolean) if true, uses internal padding and automatically adjust it to account for line width.
  16594. * @see Multicell(), writeHTML()
  16595. * @public
  16596. */
  16597. public function writeHTMLCell($w, $h, $x, $y, $html='', $border=0, $ln=0, $fill=false, $reseth=true, $align='', $autopadding=true) {
  16598. return $this->MultiCell($w, $h, $html, $border, $align, $fill, $ln, $x, $y, $reseth, 0, true, $autopadding, 0, 'T', false);
  16599. }
  16600. /**
  16601. * Allows to preserve some HTML formatting (limited support).<br />
  16602. * IMPORTANT: The HTML must be well formatted - try to clean-up it using an application like HTML-Tidy before submitting.
  16603. * 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
  16604. * NOTE: all the HTML attributes must be enclosed in double-quote.
  16605. * @param $html (string) text to display
  16606. * @param $ln (boolean) if true add a new line after text (default = true)
  16607. * @param $fill (boolean) Indicates if the background must be painted (true) or transparent (false).
  16608. * @param $reseth (boolean) if true reset the last cell height (default false).
  16609. * @param $cell (boolean) if true add the current left (or right for RTL) padding to each Write (default false).
  16610. * @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>
  16611. * @public
  16612. */
  16613. public function writeHTML($html, $ln=true, $fill=false, $reseth=false, $cell=false, $align='') {
  16614. $gvars = $this->getGraphicVars();
  16615. // store current values
  16616. $prev_cell_margin = $this->cell_margin;
  16617. $prev_cell_padding = $this->cell_padding;
  16618. $prevPage = $this->page;
  16619. $prevlMargin = $this->lMargin;
  16620. $prevrMargin = $this->rMargin;
  16621. $curfontname = $this->FontFamily;
  16622. $curfontstyle = $this->FontStyle;
  16623. $curfontsize = $this->FontSizePt;
  16624. $curfontascent = $this->getFontAscent($curfontname, $curfontstyle, $curfontsize);
  16625. $curfontdescent = $this->getFontDescent($curfontname, $curfontstyle, $curfontsize);
  16626. $curfontstretcing = $this->font_stretching;
  16627. $curfonttracking = $this->font_spacing;
  16628. $this->newline = true;
  16629. $newline = true;
  16630. $startlinepage = $this->page;
  16631. $minstartliney = $this->y;
  16632. $maxbottomliney = 0;
  16633. $startlinex = $this->x;
  16634. $startliney = $this->y;
  16635. $yshift = 0;
  16636. $loop = 0;
  16637. $curpos = 0;
  16638. $this_method_vars = array();
  16639. $undo = false;
  16640. $fontaligned = false;
  16641. $reverse_dir = false; // true when the text direction is reversed
  16642. $this->premode = false;
  16643. if ($this->inxobj) {
  16644. // we are inside an XObject template
  16645. $pask = count($this->xobjects[$this->xobjid]['annotations']);
  16646. } elseif (isset($this->PageAnnots[$this->page])) {
  16647. $pask = count($this->PageAnnots[$this->page]);
  16648. } else {
  16649. $pask = 0;
  16650. }
  16651. if ($this->inxobj) {
  16652. // we are inside an XObject template
  16653. $startlinepos = strlen($this->xobjects[$this->xobjid]['outdata']);
  16654. } elseif (!$this->InFooter) {
  16655. if (isset($this->footerlen[$this->page])) {
  16656. $this->footerpos[$this->page] = $this->pagelen[$this->page] - $this->footerlen[$this->page];
  16657. } else {
  16658. $this->footerpos[$this->page] = $this->pagelen[$this->page];
  16659. }
  16660. $startlinepos = $this->footerpos[$this->page];
  16661. } else {
  16662. // we are inside the footer
  16663. $startlinepos = $this->pagelen[$this->page];
  16664. }
  16665. $lalign = $align;
  16666. $plalign = $align;
  16667. if ($this->rtl) {
  16668. $w = $this->x - $this->lMargin;
  16669. } else {
  16670. $w = $this->w - $this->rMargin - $this->x;
  16671. }
  16672. $w -= ($this->cell_padding['L'] + $this->cell_padding['R']);
  16673. if ($cell) {
  16674. if ($this->rtl) {
  16675. $this->x -= $this->cell_padding['R'];
  16676. $this->lMargin += $this->cell_padding['L'];
  16677. } else {
  16678. $this->x += $this->cell_padding['L'];
  16679. $this->rMargin += $this->cell_padding['R'];
  16680. }
  16681. }
  16682. if ($this->customlistindent >= 0) {
  16683. $this->listindent = $this->customlistindent;
  16684. } else {
  16685. $this->listindent = $this->GetStringWidth('000000');
  16686. }
  16687. $this->listindentlevel = 0;
  16688. // save previous states
  16689. $prev_cell_height_ratio = $this->cell_height_ratio;
  16690. $prev_listnum = $this->listnum;
  16691. $prev_listordered = $this->listordered;
  16692. $prev_listcount = $this->listcount;
  16693. $prev_lispacer = $this->lispacer;
  16694. $this->listnum = 0;
  16695. $this->listordered = array();
  16696. $this->listcount = array();
  16697. $this->lispacer = '';
  16698. if ((TCPDF_STATIC::empty_string($this->lasth)) OR ($reseth)) {
  16699. // reset row height
  16700. $this->resetLastH();
  16701. }
  16702. $dom = $this->getHtmlDomArray($html);
  16703. $maxel = count($dom);
  16704. $key = 0;
  16705. while ($key < $maxel) {
  16706. if ($dom[$key]['tag'] AND $dom[$key]['opening'] AND $dom[$key]['hide']) {
  16707. // store the node key
  16708. $hidden_node_key = $key;
  16709. if ($dom[$key]['self']) {
  16710. // skip just this self-closing tag
  16711. ++$key;
  16712. } else {
  16713. // skip this and all children tags
  16714. while (($key < $maxel) AND (!$dom[$key]['tag'] OR $dom[$key]['opening'] OR ($dom[$key]['parent'] != $hidden_node_key))) {
  16715. // skip hidden objects
  16716. ++$key;
  16717. }
  16718. ++$key;
  16719. }
  16720. }
  16721. if ($dom[$key]['tag'] AND isset($dom[$key]['attribute']['pagebreak'])) {
  16722. // check for pagebreak
  16723. if (($dom[$key]['attribute']['pagebreak'] == 'true') OR ($dom[$key]['attribute']['pagebreak'] == 'left') OR ($dom[$key]['attribute']['pagebreak'] == 'right')) {
  16724. // add a page (or trig AcceptPageBreak() for multicolumn mode)
  16725. $this->checkPageBreak($this->PageBreakTrigger + 1);
  16726. $this->htmlvspace = ($this->PageBreakTrigger + 1);
  16727. }
  16728. if ((($dom[$key]['attribute']['pagebreak'] == 'left') AND (((!$this->rtl) AND (($this->page % 2) == 0)) OR (($this->rtl) AND (($this->page % 2) != 0))))
  16729. OR (($dom[$key]['attribute']['pagebreak'] == 'right') AND (((!$this->rtl) AND (($this->page % 2) != 0)) OR (($this->rtl) AND (($this->page % 2) == 0))))) {
  16730. // add a page (or trig AcceptPageBreak() for multicolumn mode)
  16731. $this->checkPageBreak($this->PageBreakTrigger + 1);
  16732. $this->htmlvspace = ($this->PageBreakTrigger + 1);
  16733. }
  16734. }
  16735. if ($dom[$key]['tag'] AND $dom[$key]['opening'] AND isset($dom[$key]['attribute']['nobr']) AND ($dom[$key]['attribute']['nobr'] == 'true')) {
  16736. if (isset($dom[($dom[$key]['parent'])]['attribute']['nobr']) AND ($dom[($dom[$key]['parent'])]['attribute']['nobr'] == 'true')) {
  16737. $dom[$key]['attribute']['nobr'] = false;
  16738. } else {
  16739. // store current object
  16740. $this->startTransaction();
  16741. // save this method vars
  16742. $this_method_vars['html'] = $html;
  16743. $this_method_vars['ln'] = $ln;
  16744. $this_method_vars['fill'] = $fill;
  16745. $this_method_vars['reseth'] = $reseth;
  16746. $this_method_vars['cell'] = $cell;
  16747. $this_method_vars['align'] = $align;
  16748. $this_method_vars['gvars'] = $gvars;
  16749. $this_method_vars['prevPage'] = $prevPage;
  16750. $this_method_vars['prev_cell_margin'] = $prev_cell_margin;
  16751. $this_method_vars['prev_cell_padding'] = $prev_cell_padding;
  16752. $this_method_vars['prevlMargin'] = $prevlMargin;
  16753. $this_method_vars['prevrMargin'] = $prevrMargin;
  16754. $this_method_vars['curfontname'] = $curfontname;
  16755. $this_method_vars['curfontstyle'] = $curfontstyle;
  16756. $this_method_vars['curfontsize'] = $curfontsize;
  16757. $this_method_vars['curfontascent'] = $curfontascent;
  16758. $this_method_vars['curfontdescent'] = $curfontdescent;
  16759. $this_method_vars['curfontstretcing'] = $curfontstretcing;
  16760. $this_method_vars['curfonttracking'] = $curfonttracking;
  16761. $this_method_vars['minstartliney'] = $minstartliney;
  16762. $this_method_vars['maxbottomliney'] = $maxbottomliney;
  16763. $this_method_vars['yshift'] = $yshift;
  16764. $this_method_vars['startlinepage'] = $startlinepage;
  16765. $this_method_vars['startlinepos'] = $startlinepos;
  16766. $this_method_vars['startlinex'] = $startlinex;
  16767. $this_method_vars['startliney'] = $startliney;
  16768. $this_method_vars['newline'] = $newline;
  16769. $this_method_vars['loop'] = $loop;
  16770. $this_method_vars['curpos'] = $curpos;
  16771. $this_method_vars['pask'] = $pask;
  16772. $this_method_vars['lalign'] = $lalign;
  16773. $this_method_vars['plalign'] = $plalign;
  16774. $this_method_vars['w'] = $w;
  16775. $this_method_vars['prev_cell_height_ratio'] = $prev_cell_height_ratio;
  16776. $this_method_vars['prev_listnum'] = $prev_listnum;
  16777. $this_method_vars['prev_listordered'] = $prev_listordered;
  16778. $this_method_vars['prev_listcount'] = $prev_listcount;
  16779. $this_method_vars['prev_lispacer'] = $prev_lispacer;
  16780. $this_method_vars['fontaligned'] = $fontaligned;
  16781. $this_method_vars['key'] = $key;
  16782. $this_method_vars['dom'] = $dom;
  16783. }
  16784. }
  16785. // print THEAD block
  16786. if (($dom[$key]['value'] == 'tr') AND isset($dom[$key]['thead']) AND $dom[$key]['thead']) {
  16787. if (isset($dom[$key]['parent']) AND isset($dom[$dom[$key]['parent']]['thead']) AND !TCPDF_STATIC::empty_string($dom[$dom[$key]['parent']]['thead'])) {
  16788. $this->inthead = true;
  16789. // print table header (thead)
  16790. $this->writeHTML($this->thead, false, false, false, false, '');
  16791. // check if we are on a new page or on a new column
  16792. if (($this->y < $this->start_transaction_y) OR ($this->checkPageBreak($this->lasth, '', false))) {
  16793. // we are on a new page or on a new column and the total object height is less than the available vertical space.
  16794. // restore previous object
  16795. $this->rollbackTransaction(true);
  16796. // restore previous values
  16797. foreach ($this_method_vars as $vkey => $vval) {
  16798. $$vkey = $vval;
  16799. }
  16800. // disable table header
  16801. $tmp_thead = $this->thead;
  16802. $this->thead = '';
  16803. // add a page (or trig AcceptPageBreak() for multicolumn mode)
  16804. $pre_y = $this->y;
  16805. if ((!$this->checkPageBreak($this->PageBreakTrigger + 1)) AND ($this->y < $pre_y)) {
  16806. // fix for multicolumn mode
  16807. $startliney = $this->y;
  16808. }
  16809. $this->start_transaction_page = $this->page;
  16810. $this->start_transaction_y = $this->y;
  16811. // restore table header
  16812. $this->thead = $tmp_thead;
  16813. // fix table border properties
  16814. if (isset($dom[$dom[$key]['parent']]['attribute']['cellspacing'])) {
  16815. $tmp_cellspacing = $this->getHTMLUnitToUnits($dom[$dom[$key]['parent']]['attribute']['cellspacing'], 1, 'px');
  16816. } elseif (isset($dom[$dom[$key]['parent']]['border-spacing'])) {
  16817. $tmp_cellspacing = $dom[$dom[$key]['parent']]['border-spacing']['V'];
  16818. } else {
  16819. $tmp_cellspacing = 0;
  16820. }
  16821. $dom[$dom[$key]['parent']]['borderposition']['page'] = $this->page;
  16822. $dom[$dom[$key]['parent']]['borderposition']['column'] = $this->current_column;
  16823. $dom[$dom[$key]['parent']]['borderposition']['y'] = $this->y + $tmp_cellspacing;
  16824. $xoffset = ($this->x - $dom[$dom[$key]['parent']]['borderposition']['x']);
  16825. $dom[$dom[$key]['parent']]['borderposition']['x'] += $xoffset;
  16826. $dom[$dom[$key]['parent']]['borderposition']['xmax'] += $xoffset;
  16827. // print table header (thead)
  16828. $this->writeHTML($this->thead, false, false, false, false, '');
  16829. }
  16830. }
  16831. // move $key index forward to skip THEAD block
  16832. while ( ($key < $maxel) AND (!(
  16833. ($dom[$key]['tag'] AND $dom[$key]['opening'] AND ($dom[$key]['value'] == 'tr') AND (!isset($dom[$key]['thead']) OR !$dom[$key]['thead']))
  16834. OR ($dom[$key]['tag'] AND (!$dom[$key]['opening']) AND ($dom[$key]['value'] == 'table'))) )) {
  16835. ++$key;
  16836. }
  16837. }
  16838. if ($dom[$key]['tag'] OR ($key == 0)) {
  16839. if ((($dom[$key]['value'] == 'table') OR ($dom[$key]['value'] == 'tr')) AND (isset($dom[$key]['align']))) {
  16840. $dom[$key]['align'] = ($this->rtl) ? 'R' : 'L';
  16841. }
  16842. // vertically align image in line
  16843. if ((!$this->newline) AND ($dom[$key]['value'] == 'img') AND (isset($dom[$key]['height'])) AND ($dom[$key]['height'] > 0)) {
  16844. // get image height
  16845. $imgh = $this->getHTMLUnitToUnits($dom[$key]['height'], ($dom[$key]['fontsize'] / $this->k), 'px');
  16846. $autolinebreak = false;
  16847. if (!empty($dom[$key]['width'])) {
  16848. $imgw = $this->getHTMLUnitToUnits($dom[$key]['width'], ($dom[$key]['fontsize'] / $this->k), 'px', false);
  16849. if (($imgw <= ($this->w - $this->lMargin - $this->rMargin - $this->cell_padding['L'] - $this->cell_padding['R']))
  16850. AND ((($this->rtl) AND (($this->x - $imgw) < ($this->lMargin + $this->cell_padding['L'])))
  16851. OR ((!$this->rtl) AND (($this->x + $imgw) > ($this->w - $this->rMargin - $this->cell_padding['R']))))) {
  16852. // add automatic line break
  16853. $autolinebreak = true;
  16854. $this->Ln('', $cell);
  16855. if ((!$dom[($key-1)]['tag']) AND ($dom[($key-1)]['value'] == ' ')) {
  16856. // go back to evaluate this line break
  16857. --$key;
  16858. }
  16859. }
  16860. }
  16861. if (!$autolinebreak) {
  16862. if ($this->inPageBody()) {
  16863. $pre_y = $this->y;
  16864. // check for page break
  16865. if ((!$this->checkPageBreak($imgh)) AND ($this->y < $pre_y)) {
  16866. // fix for multicolumn mode
  16867. $startliney = $this->y;
  16868. }
  16869. }
  16870. if ($this->page > $startlinepage) {
  16871. // fix line splitted over two pages
  16872. if (isset($this->footerlen[$startlinepage])) {
  16873. $curpos = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
  16874. }
  16875. // line to be moved one page forward
  16876. $pagebuff = $this->getPageBuffer($startlinepage);
  16877. $linebeg = substr($pagebuff, $startlinepos, ($curpos - $startlinepos));
  16878. $tstart = substr($pagebuff, 0, $startlinepos);
  16879. $tend = substr($this->getPageBuffer($startlinepage), $curpos);
  16880. // remove line from previous page
  16881. $this->setPageBuffer($startlinepage, $tstart.''.$tend);
  16882. $pagebuff = $this->getPageBuffer($this->page);
  16883. $tstart = substr($pagebuff, 0, $this->cntmrk[$this->page]);
  16884. $tend = substr($pagebuff, $this->cntmrk[$this->page]);
  16885. // add line start to current page
  16886. $yshift = ($minstartliney - $this->y);
  16887. if ($fontaligned) {
  16888. $yshift += ($curfontsize / $this->k);
  16889. }
  16890. $try = sprintf('1 0 0 1 0 %F cm', ($yshift * $this->k));
  16891. $this->setPageBuffer($this->page, $tstart."\nq\n".$try."\n".$linebeg."\nQ\n".$tend);
  16892. // shift the annotations and links
  16893. if (isset($this->PageAnnots[$this->page])) {
  16894. $next_pask = count($this->PageAnnots[$this->page]);
  16895. } else {
  16896. $next_pask = 0;
  16897. }
  16898. if (isset($this->PageAnnots[$startlinepage])) {
  16899. foreach ($this->PageAnnots[$startlinepage] as $pak => $pac) {
  16900. if ($pak >= $pask) {
  16901. $this->PageAnnots[$this->page][] = $pac;
  16902. unset($this->PageAnnots[$startlinepage][$pak]);
  16903. $npak = count($this->PageAnnots[$this->page]) - 1;
  16904. $this->PageAnnots[$this->page][$npak]['y'] -= $yshift;
  16905. }
  16906. }
  16907. }
  16908. $pask = $next_pask;
  16909. $startlinepos = $this->cntmrk[$this->page];
  16910. $startlinepage = $this->page;
  16911. $startliney = $this->y;
  16912. $this->newline = false;
  16913. }
  16914. $this->y += ($this->getCellHeight($curfontsize / $this->k) - ($curfontdescent * $this->cell_height_ratio) - $imgh);
  16915. $minstartliney = min($this->y, $minstartliney);
  16916. $maxbottomliney = ($startliney + $this->getCellHeight($curfontsize / $this->k));
  16917. }
  16918. } elseif (isset($dom[$key]['fontname']) OR isset($dom[$key]['fontstyle']) OR isset($dom[$key]['fontsize']) OR isset($dom[$key]['line-height'])) {
  16919. // account for different font size
  16920. $pfontname = $curfontname;
  16921. $pfontstyle = $curfontstyle;
  16922. $pfontsize = $curfontsize;
  16923. $fontname = (isset($dom[$key]['fontname']) ? $dom[$key]['fontname'] : $curfontname);
  16924. $fontstyle = (isset($dom[$key]['fontstyle']) ? $dom[$key]['fontstyle'] : $curfontstyle);
  16925. $fontsize = (isset($dom[$key]['fontsize']) ? $dom[$key]['fontsize'] : $curfontsize);
  16926. $fontascent = $this->getFontAscent($fontname, $fontstyle, $fontsize);
  16927. $fontdescent = $this->getFontDescent($fontname, $fontstyle, $fontsize);
  16928. if (($fontname != $curfontname) OR ($fontstyle != $curfontstyle) OR ($fontsize != $curfontsize)
  16929. OR ($this->cell_height_ratio != $dom[$key]['line-height'])
  16930. OR ($dom[$key]['tag'] AND $dom[$key]['opening'] AND ($dom[$key]['value'] == 'li')) ) {
  16931. if (($key < ($maxel - 1)) AND (
  16932. ($dom[$key]['tag'] AND $dom[$key]['opening'] AND ($dom[$key]['value'] == 'li'))
  16933. OR ($this->cell_height_ratio != $dom[$key]['line-height'])
  16934. OR (!$this->newline AND is_numeric($fontsize) AND is_numeric($curfontsize)
  16935. AND ($fontsize >= 0) AND ($curfontsize >= 0)
  16936. AND (($fontsize != $curfontsize) OR ($fontstyle != $curfontstyle) OR ($fontname != $curfontname)))
  16937. )) {
  16938. if ($this->page > $startlinepage) {
  16939. // fix lines splitted over two pages
  16940. if (isset($this->footerlen[$startlinepage])) {
  16941. $curpos = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
  16942. }
  16943. // line to be moved one page forward
  16944. $pagebuff = $this->getPageBuffer($startlinepage);
  16945. $linebeg = substr($pagebuff, $startlinepos, ($curpos - $startlinepos));
  16946. $tstart = substr($pagebuff, 0, $startlinepos);
  16947. $tend = substr($this->getPageBuffer($startlinepage), $curpos);
  16948. // remove line start from previous page
  16949. $this->setPageBuffer($startlinepage, $tstart.''.$tend);
  16950. $pagebuff = $this->getPageBuffer($this->page);
  16951. $tstart = substr($pagebuff, 0, $this->cntmrk[$this->page]);
  16952. $tend = substr($pagebuff, $this->cntmrk[$this->page]);
  16953. // add line start to current page
  16954. $yshift = ($minstartliney - $this->y);
  16955. $try = sprintf('1 0 0 1 0 %F cm', ($yshift * $this->k));
  16956. $this->setPageBuffer($this->page, $tstart."\nq\n".$try."\n".$linebeg."\nQ\n".$tend);
  16957. // shift the annotations and links
  16958. if (isset($this->PageAnnots[$this->page])) {
  16959. $next_pask = count($this->PageAnnots[$this->page]);
  16960. } else {
  16961. $next_pask = 0;
  16962. }
  16963. if (isset($this->PageAnnots[$startlinepage])) {
  16964. foreach ($this->PageAnnots[$startlinepage] as $pak => $pac) {
  16965. if ($pak >= $pask) {
  16966. $this->PageAnnots[$this->page][] = $pac;
  16967. unset($this->PageAnnots[$startlinepage][$pak]);
  16968. $npak = count($this->PageAnnots[$this->page]) - 1;
  16969. $this->PageAnnots[$this->page][$npak]['y'] -= $yshift;
  16970. }
  16971. }
  16972. }
  16973. $pask = $next_pask;
  16974. $startlinepos = $this->cntmrk[$this->page];
  16975. $startlinepage = $this->page;
  16976. $startliney = $this->y;
  16977. }
  16978. if (!isset($dom[$key]['line-height'])) {
  16979. $dom[$key]['line-height'] = $this->cell_height_ratio;
  16980. }
  16981. if (!$dom[$key]['block']) {
  16982. 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']))) {
  16983. $this->y += (((($curfontsize * $this->cell_height_ratio) - ($fontsize * $dom[$key]['line-height'])) / $this->k) + $curfontascent - $fontascent - $curfontdescent + $fontdescent) / 2;
  16984. }
  16985. if (($dom[$key]['value'] != 'sup') AND ($dom[$key]['value'] != 'sub')) {
  16986. $current_line_align_data = array($key, $minstartliney, $maxbottomliney);
  16987. 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)))) {
  16988. $minstartliney = min($this->y, $line_align_data[1]);
  16989. $maxbottomliney = max(($this->y + $this->getCellHeight($fontsize / $this->k)), $line_align_data[2]);
  16990. } else {
  16991. $minstartliney = min($this->y, $minstartliney);
  16992. $maxbottomliney = max(($this->y + $this->getCellHeight($fontsize / $this->k)), $maxbottomliney);
  16993. }
  16994. $line_align_data = $current_line_align_data;
  16995. }
  16996. }
  16997. $this->cell_height_ratio = $dom[$key]['line-height'];
  16998. $fontaligned = true;
  16999. }
  17000. $this->SetFont($fontname, $fontstyle, $fontsize);
  17001. // reset row height
  17002. $this->resetLastH();
  17003. $curfontname = $fontname;
  17004. $curfontstyle = $fontstyle;
  17005. $curfontsize = $fontsize;
  17006. $curfontascent = $fontascent;
  17007. $curfontdescent = $fontdescent;
  17008. }
  17009. }
  17010. // set text rendering mode
  17011. $textstroke = isset($dom[$key]['stroke']) ? $dom[$key]['stroke'] : $this->textstrokewidth;
  17012. $textfill = isset($dom[$key]['fill']) ? $dom[$key]['fill'] : (($this->textrendermode % 2) == 0);
  17013. $textclip = isset($dom[$key]['clip']) ? $dom[$key]['clip'] : ($this->textrendermode > 3);
  17014. $this->setTextRenderingMode($textstroke, $textfill, $textclip);
  17015. if (isset($dom[$key]['font-stretch']) AND ($dom[$key]['font-stretch'] !== false)) {
  17016. $this->setFontStretching($dom[$key]['font-stretch']);
  17017. }
  17018. if (isset($dom[$key]['letter-spacing']) AND ($dom[$key]['letter-spacing'] !== false)) {
  17019. $this->setFontSpacing($dom[$key]['letter-spacing']);
  17020. }
  17021. if (($plalign == 'J') AND $dom[$key]['block']) {
  17022. $plalign = '';
  17023. }
  17024. // get current position on page buffer
  17025. $curpos = $this->pagelen[$startlinepage];
  17026. if (isset($dom[$key]['bgcolor']) AND ($dom[$key]['bgcolor'] !== false)) {
  17027. $this->SetFillColorArray($dom[$key]['bgcolor']);
  17028. $wfill = true;
  17029. } else {
  17030. $wfill = $fill | false;
  17031. }
  17032. if (isset($dom[$key]['fgcolor']) AND ($dom[$key]['fgcolor'] !== false)) {
  17033. $this->SetTextColorArray($dom[$key]['fgcolor']);
  17034. }
  17035. if (isset($dom[$key]['strokecolor']) AND ($dom[$key]['strokecolor'] !== false)) {
  17036. $this->SetDrawColorArray($dom[$key]['strokecolor']);
  17037. }
  17038. if (isset($dom[$key]['align'])) {
  17039. $lalign = $dom[$key]['align'];
  17040. }
  17041. if (TCPDF_STATIC::empty_string($lalign)) {
  17042. $lalign = $align;
  17043. }
  17044. }
  17045. // align lines
  17046. if ($this->newline AND (strlen($dom[$key]['value']) > 0) AND ($dom[$key]['value'] != 'td') AND ($dom[$key]['value'] != 'th')) {
  17047. $newline = true;
  17048. $fontaligned = false;
  17049. // we are at the beginning of a new line
  17050. if (isset($startlinex)) {
  17051. $yshift = ($minstartliney - $startliney);
  17052. if (($yshift > 0) OR ($this->page > $startlinepage)) {
  17053. $yshift = 0;
  17054. }
  17055. $t_x = 0;
  17056. // the last line must be shifted to be aligned as requested
  17057. $linew = abs($this->endlinex - $startlinex);
  17058. if ($this->inxobj) {
  17059. // we are inside an XObject template
  17060. $pstart = substr($this->xobjects[$this->xobjid]['outdata'], 0, $startlinepos);
  17061. if (isset($opentagpos)) {
  17062. $midpos = $opentagpos;
  17063. } else {
  17064. $midpos = 0;
  17065. }
  17066. if ($midpos > 0) {
  17067. $pmid = substr($this->xobjects[$this->xobjid]['outdata'], $startlinepos, ($midpos - $startlinepos));
  17068. $pend = substr($this->xobjects[$this->xobjid]['outdata'], $midpos);
  17069. } else {
  17070. $pmid = substr($this->xobjects[$this->xobjid]['outdata'], $startlinepos);
  17071. $pend = '';
  17072. }
  17073. } else {
  17074. $pstart = substr($this->getPageBuffer($startlinepage), 0, $startlinepos);
  17075. if (isset($opentagpos) AND isset($this->footerlen[$startlinepage]) AND (!$this->InFooter)) {
  17076. $this->footerpos[$startlinepage] = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
  17077. $midpos = min($opentagpos, $this->footerpos[$startlinepage]);
  17078. } elseif (isset($opentagpos)) {
  17079. $midpos = $opentagpos;
  17080. } elseif (isset($this->footerlen[$startlinepage]) AND (!$this->InFooter)) {
  17081. $this->footerpos[$startlinepage] = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
  17082. $midpos = $this->footerpos[$startlinepage];
  17083. } else {
  17084. $midpos = 0;
  17085. }
  17086. if ($midpos > 0) {
  17087. $pmid = substr($this->getPageBuffer($startlinepage), $startlinepos, ($midpos - $startlinepos));
  17088. $pend = substr($this->getPageBuffer($startlinepage), $midpos);
  17089. } else {
  17090. $pmid = substr($this->getPageBuffer($startlinepage), $startlinepos);
  17091. $pend = '';
  17092. }
  17093. }
  17094. if ((isset($plalign) AND ((($plalign == 'C') OR ($plalign == 'J') OR (($plalign == 'R') AND (!$this->rtl)) OR (($plalign == 'L') AND ($this->rtl)))))) {
  17095. // calculate shifting amount
  17096. $tw = $w;
  17097. if (($plalign == 'J') AND $this->isRTLTextDir() AND ($this->num_columns > 1)) {
  17098. $tw += $this->cell_padding['R'];
  17099. }
  17100. if ($this->lMargin != $prevlMargin) {
  17101. $tw += ($prevlMargin - $this->lMargin);
  17102. }
  17103. if ($this->rMargin != $prevrMargin) {
  17104. $tw += ($prevrMargin - $this->rMargin);
  17105. }
  17106. $one_space_width = $this->GetStringWidth(chr(32));
  17107. $no = 0; // number of spaces on a line contained on a single block
  17108. if ($this->isRTLTextDir()) { // RTL
  17109. // remove left space if exist
  17110. $pos1 = TCPDF_STATIC::revstrpos($pmid, '[(');
  17111. if ($pos1 > 0) {
  17112. $pos1 = intval($pos1);
  17113. if ($this->isUnicodeFont()) {
  17114. $pos2 = intval(TCPDF_STATIC::revstrpos($pmid, '[('.chr(0).chr(32)));
  17115. $spacelen = 2;
  17116. } else {
  17117. $pos2 = intval(TCPDF_STATIC::revstrpos($pmid, '[('.chr(32)));
  17118. $spacelen = 1;
  17119. }
  17120. if ($pos1 == $pos2) {
  17121. $pmid = substr($pmid, 0, ($pos1 + 2)).substr($pmid, ($pos1 + 2 + $spacelen));
  17122. if (substr($pmid, $pos1, 4) == '[()]') {
  17123. $linew -= $one_space_width;
  17124. } elseif ($pos1 == strpos($pmid, '[(')) {
  17125. $no = 1;
  17126. }
  17127. }
  17128. }
  17129. } else { // LTR
  17130. // remove right space if exist
  17131. $pos1 = TCPDF_STATIC::revstrpos($pmid, ')]');
  17132. if ($pos1 > 0) {
  17133. $pos1 = intval($pos1);
  17134. if ($this->isUnicodeFont()) {
  17135. $pos2 = intval(TCPDF_STATIC::revstrpos($pmid, chr(0).chr(32).')]')) + 2;
  17136. $spacelen = 2;
  17137. } else {
  17138. $pos2 = intval(TCPDF_STATIC::revstrpos($pmid, chr(32).')]')) + 1;
  17139. $spacelen = 1;
  17140. }
  17141. if ($pos1 == $pos2) {
  17142. $pmid = substr($pmid, 0, ($pos1 - $spacelen)).substr($pmid, $pos1);
  17143. $linew -= $one_space_width;
  17144. }
  17145. }
  17146. }
  17147. $mdiff = ($tw - $linew);
  17148. if ($plalign == 'C') {
  17149. if ($this->rtl) {
  17150. $t_x = -($mdiff / 2);
  17151. } else {
  17152. $t_x = ($mdiff / 2);
  17153. }
  17154. } elseif ($plalign == 'R') {
  17155. // right alignment on LTR document
  17156. $t_x = $mdiff;
  17157. } elseif ($plalign == 'L') {
  17158. // left alignment on RTL document
  17159. $t_x = -$mdiff;
  17160. } elseif (($plalign == 'J') AND ($plalign == $lalign)) {
  17161. // Justification
  17162. if ($this->isRTLTextDir()) {
  17163. // align text on the left
  17164. $t_x = -$mdiff;
  17165. }
  17166. $ns = 0; // number of spaces
  17167. $pmidtemp = $pmid;
  17168. // escape special characters
  17169. $pmidtemp = preg_replace('/[\\\][\(]/x', '\\#!#OP#!#', $pmidtemp);
  17170. $pmidtemp = preg_replace('/[\\\][\)]/x', '\\#!#CP#!#', $pmidtemp);
  17171. // search spaces
  17172. if (preg_match_all('/\[\(([^\)]*)\)\]/x', $pmidtemp, $lnstring, PREG_PATTERN_ORDER)) {
  17173. $spacestr = $this->getSpaceString();
  17174. $maxkk = count($lnstring[1]) - 1;
  17175. for ($kk=0; $kk <= $maxkk; ++$kk) {
  17176. // restore special characters
  17177. $lnstring[1][$kk] = str_replace('#!#OP#!#', '(', $lnstring[1][$kk]);
  17178. $lnstring[1][$kk] = str_replace('#!#CP#!#', ')', $lnstring[1][$kk]);
  17179. // store number of spaces on the strings
  17180. $lnstring[2][$kk] = substr_count($lnstring[1][$kk], $spacestr);
  17181. // count total spaces on line
  17182. $ns += $lnstring[2][$kk];
  17183. $lnstring[3][$kk] = $ns;
  17184. }
  17185. if ($ns == 0) {
  17186. $ns = 1;
  17187. }
  17188. // calculate additional space to add to each existing space
  17189. $spacewidth = ($mdiff / ($ns - $no)) * $this->k;
  17190. if ($this->FontSize <= 0) {
  17191. $this->FontSize = 1;
  17192. }
  17193. $spacewidthu = -1000 * ($mdiff + (($ns + $no) * $one_space_width)) / $ns / $this->FontSize;
  17194. if ($this->font_spacing != 0) {
  17195. // fixed spacing mode
  17196. $osw = -1000 * $this->font_spacing / $this->FontSize;
  17197. $spacewidthu += $osw;
  17198. }
  17199. $nsmax = $ns;
  17200. $ns = 0;
  17201. reset($lnstring);
  17202. $offset = 0;
  17203. $strcount = 0;
  17204. $prev_epsposbeg = 0;
  17205. $textpos = 0;
  17206. if ($this->isRTLTextDir()) {
  17207. $textpos = $this->wPt;
  17208. }
  17209. while (preg_match('/([0-9\.\+\-]*)[\s](Td|cm|m|l|c|re)[\s]/x', $pmid, $strpiece, PREG_OFFSET_CAPTURE, $offset) == 1) {
  17210. // check if we are inside a string section '[( ... )]'
  17211. $stroffset = strpos($pmid, '[(', $offset);
  17212. if (($stroffset !== false) AND ($stroffset <= $strpiece[2][1])) {
  17213. // set offset to the end of string section
  17214. $offset = strpos($pmid, ')]', $stroffset);
  17215. while (($offset !== false) AND ($pmid[($offset - 1)] == '\\')) {
  17216. $offset = strpos($pmid, ')]', ($offset + 1));
  17217. }
  17218. if ($offset === false) {
  17219. $this->Error('HTML Justification: malformed PDF code.');
  17220. }
  17221. continue;
  17222. }
  17223. if ($this->isRTLTextDir()) {
  17224. $spacew = ($spacewidth * ($nsmax - $ns));
  17225. } else {
  17226. $spacew = ($spacewidth * $ns);
  17227. }
  17228. $offset = $strpiece[2][1] + strlen($strpiece[2][0]);
  17229. $epsposend = strpos($pmid, $this->epsmarker.'Q', $offset);
  17230. if ($epsposend !== null) {
  17231. $epsposend += strlen($this->epsmarker.'Q');
  17232. $epsposbeg = strpos($pmid, 'q'.$this->epsmarker, $offset);
  17233. if ($epsposbeg === null) {
  17234. $epsposbeg = strpos($pmid, 'q'.$this->epsmarker, ($prev_epsposbeg - 6));
  17235. $prev_epsposbeg = $epsposbeg;
  17236. }
  17237. if (($epsposbeg > 0) AND ($epsposend > 0) AND ($offset > $epsposbeg) AND ($offset < $epsposend)) {
  17238. // shift EPS images
  17239. $trx = sprintf('1 0 0 1 %F 0 cm', $spacew);
  17240. $pmid_b = substr($pmid, 0, $epsposbeg);
  17241. $pmid_m = substr($pmid, $epsposbeg, ($epsposend - $epsposbeg));
  17242. $pmid_e = substr($pmid, $epsposend);
  17243. $pmid = $pmid_b."\nq\n".$trx."\n".$pmid_m."\nQ\n".$pmid_e;
  17244. $offset = $epsposend;
  17245. continue;
  17246. }
  17247. }
  17248. $currentxpos = 0;
  17249. // shift blocks of code
  17250. switch ($strpiece[2][0]) {
  17251. case 'Td':
  17252. case 'cm':
  17253. case 'm':
  17254. case 'l': {
  17255. // get current X position
  17256. preg_match('/([0-9\.\+\-]*)[\s]('.$strpiece[1][0].')[\s]('.$strpiece[2][0].')([\s]*)/x', $pmid, $xmatches);
  17257. if (!isset($xmatches[1])) {
  17258. break;
  17259. }
  17260. $currentxpos = $xmatches[1];
  17261. $textpos = $currentxpos;
  17262. if (($strcount <= $maxkk) AND ($strpiece[2][0] == 'Td')) {
  17263. $ns = $lnstring[3][$strcount];
  17264. if ($this->isRTLTextDir()) {
  17265. $spacew = ($spacewidth * ($nsmax - $ns));
  17266. }
  17267. ++$strcount;
  17268. }
  17269. // justify block
  17270. if (preg_match('/([0-9\.\+\-]*)[\s]('.$strpiece[1][0].')[\s]('.$strpiece[2][0].')([\s]*)/x', $pmid, $pmatch) == 1) {
  17271. $newpmid = sprintf('%F',(floatval($pmatch[1]) + $spacew)).' '.$pmatch[2].' x*#!#*x'.$pmatch[3].$pmatch[4];
  17272. $pmid = str_replace($pmatch[0], $newpmid, $pmid);
  17273. unset($pmatch, $newpmid);
  17274. }
  17275. break;
  17276. }
  17277. case 're': {
  17278. // justify block
  17279. if (!TCPDF_STATIC::empty_string($this->lispacer)) {
  17280. $this->lispacer = '';
  17281. break;
  17282. }
  17283. preg_match('/([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]('.$strpiece[1][0].')[\s](re)([\s]*)/x', $pmid, $xmatches);
  17284. if (!isset($xmatches[1])) {
  17285. break;
  17286. }
  17287. $currentxpos = $xmatches[1];
  17288. $x_diff = 0;
  17289. $w_diff = 0;
  17290. if ($this->isRTLTextDir()) { // RTL
  17291. if ($currentxpos < $textpos) {
  17292. $x_diff = ($spacewidth * ($nsmax - $lnstring[3][$strcount]));
  17293. $w_diff = ($spacewidth * $lnstring[2][$strcount]);
  17294. } else {
  17295. if ($strcount > 0) {
  17296. $x_diff = ($spacewidth * ($nsmax - $lnstring[3][($strcount - 1)]));
  17297. $w_diff = ($spacewidth * $lnstring[2][($strcount - 1)]);
  17298. }
  17299. }
  17300. } else { // LTR
  17301. if ($currentxpos > $textpos) {
  17302. if ($strcount > 0) {
  17303. $x_diff = ($spacewidth * $lnstring[3][($strcount - 1)]);
  17304. }
  17305. $w_diff = ($spacewidth * $lnstring[2][$strcount]);
  17306. } else {
  17307. if ($strcount > 1) {
  17308. $x_diff = ($spacewidth * $lnstring[3][($strcount - 2)]);
  17309. }
  17310. if ($strcount > 0) {
  17311. $w_diff = ($spacewidth * $lnstring[2][($strcount - 1)]);
  17312. }
  17313. }
  17314. }
  17315. if (preg_match('/('.$xmatches[1].')[\s]('.$xmatches[2].')[\s]('.$xmatches[3].')[\s]('.$strpiece[1][0].')[\s](re)([\s]*)/x', $pmid, $pmatch) == 1) {
  17316. $newx = sprintf('%F',(floatval($pmatch[1]) + $x_diff));
  17317. $neww = sprintf('%F',(floatval($pmatch[3]) + $w_diff));
  17318. $newpmid = $newx.' '.$pmatch[2].' '.$neww.' '.$pmatch[4].' x*#!#*x'.$pmatch[5].$pmatch[6];
  17319. $pmid = str_replace($pmatch[0], $newpmid, $pmid);
  17320. unset($pmatch, $newpmid, $newx, $neww);
  17321. }
  17322. break;
  17323. }
  17324. case 'c': {
  17325. // get current X position
  17326. 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);
  17327. if (!isset($xmatches[1])) {
  17328. break;
  17329. }
  17330. $currentxpos = $xmatches[1];
  17331. // justify block
  17332. 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) {
  17333. $newx1 = sprintf('%F',(floatval($pmatch[1]) + $spacew));
  17334. $newx2 = sprintf('%F',(floatval($pmatch[3]) + $spacew));
  17335. $newx3 = sprintf('%F',(floatval($pmatch[5]) + $spacew));
  17336. $newpmid = $newx1.' '.$pmatch[2].' '.$newx2.' '.$pmatch[4].' '.$newx3.' '.$pmatch[6].' x*#!#*x'.$pmatch[7].$pmatch[8];
  17337. $pmid = str_replace($pmatch[0], $newpmid, $pmid);
  17338. unset($pmatch, $newpmid, $newx1, $newx2, $newx3);
  17339. }
  17340. break;
  17341. }
  17342. }
  17343. // shift the annotations and links
  17344. $cxpos = ($currentxpos / $this->k);
  17345. $lmpos = ($this->lMargin + $this->cell_padding['L'] + $this->feps);
  17346. if ($this->inxobj) {
  17347. // we are inside an XObject template
  17348. foreach ($this->xobjects[$this->xobjid]['annotations'] as $pak => $pac) {
  17349. if (($pac['y'] >= $minstartliney) AND (($pac['x'] * $this->k) >= ($currentxpos - $this->feps)) AND (($pac['x'] * $this->k) <= ($currentxpos + $this->feps))) {
  17350. if ($cxpos > $lmpos) {
  17351. $this->xobjects[$this->xobjid]['annotations'][$pak]['x'] += ($spacew / $this->k);
  17352. $this->xobjects[$this->xobjid]['annotations'][$pak]['w'] += (($spacewidth * $pac['numspaces']) / $this->k);
  17353. } else {
  17354. $this->xobjects[$this->xobjid]['annotations'][$pak]['w'] += (($spacewidth * $pac['numspaces']) / $this->k);
  17355. }
  17356. break;
  17357. }
  17358. }
  17359. } elseif (isset($this->PageAnnots[$this->page])) {
  17360. foreach ($this->PageAnnots[$this->page] as $pak => $pac) {
  17361. if (($pac['y'] >= $minstartliney) AND (($pac['x'] * $this->k) >= ($currentxpos - $this->feps)) AND (($pac['x'] * $this->k) <= ($currentxpos + $this->feps))) {
  17362. if ($cxpos > $lmpos) {
  17363. $this->PageAnnots[$this->page][$pak]['x'] += ($spacew / $this->k);
  17364. $this->PageAnnots[$this->page][$pak]['w'] += (($spacewidth * $pac['numspaces']) / $this->k);
  17365. } else {
  17366. $this->PageAnnots[$this->page][$pak]['w'] += (($spacewidth * $pac['numspaces']) / $this->k);
  17367. }
  17368. break;
  17369. }
  17370. }
  17371. }
  17372. } // end of while
  17373. // remove markers
  17374. $pmid = str_replace('x*#!#*x', '', $pmid);
  17375. if ($this->isUnicodeFont()) {
  17376. // multibyte characters
  17377. $spacew = $spacewidthu;
  17378. if ($this->font_stretching != 100) {
  17379. // word spacing is affected by stretching
  17380. $spacew /= ($this->font_stretching / 100);
  17381. }
  17382. // escape special characters
  17383. $pos = 0;
  17384. $pmid = preg_replace('/[\\\][\(]/x', '\\#!#OP#!#', $pmid);
  17385. $pmid = preg_replace('/[\\\][\)]/x', '\\#!#CP#!#', $pmid);
  17386. if (preg_match_all('/\[\(([^\)]*)\)\]/x', $pmid, $pamatch) > 0) {
  17387. foreach($pamatch[0] as $pk => $pmatch) {
  17388. $replace = $pamatch[1][$pk];
  17389. $replace = str_replace('#!#OP#!#', '(', $replace);
  17390. $replace = str_replace('#!#CP#!#', ')', $replace);
  17391. $newpmid = '[('.str_replace(chr(0).chr(32), ') '.sprintf('%F', $spacew).' (', $replace).')]';
  17392. $pos = strpos($pmid, $pmatch, $pos);
  17393. if ($pos !== FALSE) {
  17394. $pmid = substr_replace($pmid, $newpmid, $pos, strlen($pmatch));
  17395. }
  17396. ++$pos;
  17397. }
  17398. unset($pamatch);
  17399. }
  17400. if ($this->inxobj) {
  17401. // we are inside an XObject template
  17402. $this->xobjects[$this->xobjid]['outdata'] = $pstart."\n".$pmid."\n".$pend;
  17403. } else {
  17404. $this->setPageBuffer($startlinepage, $pstart."\n".$pmid."\n".$pend);
  17405. }
  17406. $endlinepos = strlen($pstart."\n".$pmid."\n");
  17407. } else {
  17408. // non-unicode (single-byte characters)
  17409. if ($this->font_stretching != 100) {
  17410. // word spacing (Tw) is affected by stretching
  17411. $spacewidth /= ($this->font_stretching / 100);
  17412. }
  17413. $rs = sprintf('%F Tw', $spacewidth);
  17414. $pmid = preg_replace("/\[\(/x", $rs.' [(', $pmid);
  17415. if ($this->inxobj) {
  17416. // we are inside an XObject template
  17417. $this->xobjects[$this->xobjid]['outdata'] = $pstart."\n".$pmid."\nBT 0 Tw ET\n".$pend;
  17418. } else {
  17419. $this->setPageBuffer($startlinepage, $pstart."\n".$pmid."\nBT 0 Tw ET\n".$pend);
  17420. }
  17421. $endlinepos = strlen($pstart."\n".$pmid."\nBT 0 Tw ET\n");
  17422. }
  17423. }
  17424. } // end of J
  17425. } // end if $startlinex
  17426. if (($t_x != 0) OR ($yshift < 0)) {
  17427. // shift the line
  17428. $trx = sprintf('1 0 0 1 %F %F cm', ($t_x * $this->k), ($yshift * $this->k));
  17429. $pstart .= "\nq\n".$trx."\n".$pmid."\nQ\n";
  17430. $endlinepos = strlen($pstart);
  17431. if ($this->inxobj) {
  17432. // we are inside an XObject template
  17433. $this->xobjects[$this->xobjid]['outdata'] = $pstart.$pend;
  17434. foreach ($this->xobjects[$this->xobjid]['annotations'] as $pak => $pac) {
  17435. if ($pak >= $pask) {
  17436. $this->xobjects[$this->xobjid]['annotations'][$pak]['x'] += $t_x;
  17437. $this->xobjects[$this->xobjid]['annotations'][$pak]['y'] -= $yshift;
  17438. }
  17439. }
  17440. } else {
  17441. $this->setPageBuffer($startlinepage, $pstart.$pend);
  17442. // shift the annotations and links
  17443. if (isset($this->PageAnnots[$this->page])) {
  17444. foreach ($this->PageAnnots[$this->page] as $pak => $pac) {
  17445. if ($pak >= $pask) {
  17446. $this->PageAnnots[$this->page][$pak]['x'] += $t_x;
  17447. $this->PageAnnots[$this->page][$pak]['y'] -= $yshift;
  17448. }
  17449. }
  17450. }
  17451. }
  17452. $this->y -= $yshift;
  17453. }
  17454. }
  17455. $pbrk = $this->checkPageBreak($this->lasth);
  17456. $this->newline = false;
  17457. $startlinex = $this->x;
  17458. $startliney = $this->y;
  17459. if ($dom[$dom[$key]['parent']]['value'] == 'sup') {
  17460. $startliney -= ((0.3 * $this->FontSizePt) / $this->k);
  17461. } elseif ($dom[$dom[$key]['parent']]['value'] == 'sub') {
  17462. $startliney -= (($this->FontSizePt / 0.7) / $this->k);
  17463. } else {
  17464. $minstartliney = $startliney;
  17465. $maxbottomliney = ($this->y + $this->getCellHeight($fontsize / $this->k));
  17466. }
  17467. $startlinepage = $this->page;
  17468. if (isset($endlinepos) AND (!$pbrk)) {
  17469. $startlinepos = $endlinepos;
  17470. } else {
  17471. if ($this->inxobj) {
  17472. // we are inside an XObject template
  17473. $startlinepos = strlen($this->xobjects[$this->xobjid]['outdata']);
  17474. } elseif (!$this->InFooter) {
  17475. if (isset($this->footerlen[$this->page])) {
  17476. $this->footerpos[$this->page] = $this->pagelen[$this->page] - $this->footerlen[$this->page];
  17477. } else {
  17478. $this->footerpos[$this->page] = $this->pagelen[$this->page];
  17479. }
  17480. $startlinepos = $this->footerpos[$this->page];
  17481. } else {
  17482. $startlinepos = $this->pagelen[$this->page];
  17483. }
  17484. }
  17485. unset($endlinepos);
  17486. $plalign = $lalign;
  17487. if (isset($this->PageAnnots[$this->page])) {
  17488. $pask = count($this->PageAnnots[$this->page]);
  17489. } else {
  17490. $pask = 0;
  17491. }
  17492. if (!($dom[$key]['tag'] AND !$dom[$key]['opening'] AND ($dom[$key]['value'] == 'table')
  17493. AND (isset($this->emptypagemrk[$this->page]))
  17494. AND ($this->emptypagemrk[$this->page] == $this->pagelen[$this->page]))) {
  17495. $this->SetFont($fontname, $fontstyle, $fontsize);
  17496. if ($wfill) {
  17497. $this->SetFillColorArray($this->bgcolor);
  17498. }
  17499. }
  17500. } // end newline
  17501. if (isset($opentagpos)) {
  17502. unset($opentagpos);
  17503. }
  17504. if ($dom[$key]['tag']) {
  17505. if ($dom[$key]['opening']) {
  17506. // get text indentation (if any)
  17507. if (isset($dom[$key]['text-indent']) AND $dom[$key]['block']) {
  17508. $this->textindent = $dom[$key]['text-indent'];
  17509. $this->newline = true;
  17510. }
  17511. // table
  17512. if (($dom[$key]['value'] == 'table') AND isset($dom[$key]['cols']) AND ($dom[$key]['cols'] > 0)) {
  17513. // available page width
  17514. if ($this->rtl) {
  17515. $wtmp = $this->x - $this->lMargin;
  17516. } else {
  17517. $wtmp = $this->w - $this->rMargin - $this->x;
  17518. }
  17519. // get cell spacing
  17520. if (isset($dom[$key]['attribute']['cellspacing'])) {
  17521. $clsp = $this->getHTMLUnitToUnits($dom[$key]['attribute']['cellspacing'], 1, 'px');
  17522. $cellspacing = array('H' => $clsp, 'V' => $clsp);
  17523. } elseif (isset($dom[$key]['border-spacing'])) {
  17524. $cellspacing = $dom[$key]['border-spacing'];
  17525. } else {
  17526. $cellspacing = array('H' => 0, 'V' => 0);
  17527. }
  17528. // table width
  17529. if (isset($dom[$key]['width'])) {
  17530. $table_width = $this->getHTMLUnitToUnits($dom[$key]['width'], $wtmp, 'px');
  17531. } else {
  17532. $table_width = $wtmp;
  17533. }
  17534. $table_width -= (2 * $cellspacing['H']);
  17535. if (!$this->inthead) {
  17536. $this->y += $cellspacing['V'];
  17537. }
  17538. if ($this->rtl) {
  17539. $cellspacingx = -$cellspacing['H'];
  17540. } else {
  17541. $cellspacingx = $cellspacing['H'];
  17542. }
  17543. // total table width without cellspaces
  17544. $table_columns_width = ($table_width - ($cellspacing['H'] * ($dom[$key]['cols'] - 1)));
  17545. // minimum column width
  17546. $table_min_column_width = ($table_columns_width / $dom[$key]['cols']);
  17547. // array of custom column widths
  17548. $table_colwidths = array_fill(0, $dom[$key]['cols'], $table_min_column_width);
  17549. }
  17550. // table row
  17551. if ($dom[$key]['value'] == 'tr') {
  17552. // reset column counter
  17553. $colid = 0;
  17554. }
  17555. // table cell
  17556. if (($dom[$key]['value'] == 'td') OR ($dom[$key]['value'] == 'th')) {
  17557. $trid = $dom[$key]['parent'];
  17558. $table_el = $dom[$trid]['parent'];
  17559. if (!isset($dom[$table_el]['cols'])) {
  17560. $dom[$table_el]['cols'] = $dom[$trid]['cols'];
  17561. }
  17562. // store border info
  17563. $tdborder = 0;
  17564. if (isset($dom[$key]['border']) AND !empty($dom[$key]['border'])) {
  17565. $tdborder = $dom[$key]['border'];
  17566. }
  17567. $colspan = intval($dom[$key]['attribute']['colspan']);
  17568. if ($colspan <= 0) {
  17569. $colspan = 1;
  17570. }
  17571. $old_cell_padding = $this->cell_padding;
  17572. if (isset($dom[($dom[$trid]['parent'])]['attribute']['cellpadding'])) {
  17573. $crclpd = $this->getHTMLUnitToUnits($dom[($dom[$trid]['parent'])]['attribute']['cellpadding'], 1, 'px');
  17574. $current_cell_padding = array('L' => $crclpd, 'T' => $crclpd, 'R' => $crclpd, 'B' => $crclpd);
  17575. } elseif (isset($dom[($dom[$trid]['parent'])]['padding'])) {
  17576. $current_cell_padding = $dom[($dom[$trid]['parent'])]['padding'];
  17577. } else {
  17578. $current_cell_padding = array('L' => 0, 'T' => 0, 'R' => 0, 'B' => 0);
  17579. }
  17580. $this->cell_padding = $current_cell_padding;
  17581. if (isset($dom[$key]['height'])) {
  17582. // minimum cell height
  17583. $cellh = $this->getHTMLUnitToUnits($dom[$key]['height'], 0, 'px');
  17584. } else {
  17585. $cellh = 0;
  17586. }
  17587. if (isset($dom[$key]['content'])) {
  17588. $cell_content = $dom[$key]['content'];
  17589. } else {
  17590. $cell_content = '&nbsp;';
  17591. }
  17592. $tagtype = $dom[$key]['value'];
  17593. $parentid = $key;
  17594. while (($key < $maxel) AND (!(($dom[$key]['tag']) AND (!$dom[$key]['opening']) AND ($dom[$key]['value'] == $tagtype) AND ($dom[$key]['parent'] == $parentid)))) {
  17595. // move $key index forward
  17596. ++$key;
  17597. }
  17598. if (!isset($dom[$trid]['startpage'])) {
  17599. $dom[$trid]['startpage'] = $this->page;
  17600. } else {
  17601. $this->setPage($dom[$trid]['startpage']);
  17602. }
  17603. if (!isset($dom[$trid]['startcolumn'])) {
  17604. $dom[$trid]['startcolumn'] = $this->current_column;
  17605. } elseif ($this->current_column != $dom[$trid]['startcolumn']) {
  17606. $tmpx = $this->x;
  17607. $this->selectColumn($dom[$trid]['startcolumn']);
  17608. $this->x = $tmpx;
  17609. }
  17610. if (!isset($dom[$trid]['starty'])) {
  17611. $dom[$trid]['starty'] = $this->y;
  17612. } else {
  17613. $this->y = $dom[$trid]['starty'];
  17614. }
  17615. if (!isset($dom[$trid]['startx'])) {
  17616. $dom[$trid]['startx'] = $this->x;
  17617. $this->x += $cellspacingx;
  17618. } else {
  17619. $this->x += ($cellspacingx / 2);
  17620. }
  17621. if (isset($dom[$parentid]['attribute']['rowspan'])) {
  17622. $rowspan = intval($dom[$parentid]['attribute']['rowspan']);
  17623. } else {
  17624. $rowspan = 1;
  17625. }
  17626. // skip row-spanned cells started on the previous rows
  17627. if (isset($dom[$table_el]['rowspans'])) {
  17628. $rsk = 0;
  17629. $rskmax = count($dom[$table_el]['rowspans']);
  17630. while ($rsk < $rskmax) {
  17631. $trwsp = $dom[$table_el]['rowspans'][$rsk];
  17632. $rsstartx = $trwsp['startx'];
  17633. $rsendx = $trwsp['endx'];
  17634. // account for margin changes
  17635. if ($trwsp['startpage'] < $this->page) {
  17636. if (($this->rtl) AND ($this->pagedim[$this->page]['orm'] != $this->pagedim[$trwsp['startpage']]['orm'])) {
  17637. $dl = ($this->pagedim[$this->page]['orm'] - $this->pagedim[$trwsp['startpage']]['orm']);
  17638. $rsstartx -= $dl;
  17639. $rsendx -= $dl;
  17640. } elseif ((!$this->rtl) AND ($this->pagedim[$this->page]['olm'] != $this->pagedim[$trwsp['startpage']]['olm'])) {
  17641. $dl = ($this->pagedim[$this->page]['olm'] - $this->pagedim[$trwsp['startpage']]['olm']);
  17642. $rsstartx += $dl;
  17643. $rsendx += $dl;
  17644. }
  17645. }
  17646. if (($trwsp['rowspan'] > 0)
  17647. AND ($rsstartx > ($this->x - $cellspacing['H'] - $current_cell_padding['L'] - $this->feps))
  17648. AND ($rsstartx < ($this->x + $cellspacing['H'] + $current_cell_padding['R'] + $this->feps))
  17649. AND (($trwsp['starty'] < ($this->y - $this->feps)) OR ($trwsp['startpage'] < $this->page) OR ($trwsp['startcolumn'] < $this->current_column))) {
  17650. // set the starting X position of the current cell
  17651. $this->x = $rsendx + $cellspacingx;
  17652. // increment column indicator
  17653. $colid += $trwsp['colspan'];
  17654. if (($trwsp['rowspan'] == 1)
  17655. AND (isset($dom[$trid]['endy']))
  17656. AND (isset($dom[$trid]['endpage']))
  17657. AND (isset($dom[$trid]['endcolumn']))
  17658. AND ($trwsp['endpage'] == $dom[$trid]['endpage'])
  17659. AND ($trwsp['endcolumn'] == $dom[$trid]['endcolumn'])) {
  17660. // set ending Y position for row
  17661. $dom[$table_el]['rowspans'][$rsk]['endy'] = max($dom[$trid]['endy'], $trwsp['endy']);
  17662. $dom[$trid]['endy'] = $dom[$table_el]['rowspans'][$rsk]['endy'];
  17663. }
  17664. $rsk = 0;
  17665. } else {
  17666. ++$rsk;
  17667. }
  17668. }
  17669. }
  17670. if (isset($dom[$parentid]['width'])) {
  17671. // user specified width
  17672. $cellw = $this->getHTMLUnitToUnits($dom[$parentid]['width'], $table_columns_width, 'px');
  17673. $tmpcw = ($cellw / $colspan);
  17674. for ($i = 0; $i < $colspan; ++$i) {
  17675. $table_colwidths[($colid + $i)] = $tmpcw;
  17676. }
  17677. } else {
  17678. // inherit column width
  17679. $cellw = 0;
  17680. for ($i = 0; $i < $colspan; ++$i) {
  17681. $cellw += (isset($table_colwidths[($colid + $i)]) ? $table_colwidths[($colid + $i)] : 0);
  17682. }
  17683. }
  17684. $cellw += (($colspan - 1) * $cellspacing['H']);
  17685. // increment column indicator
  17686. $colid += $colspan;
  17687. // add rowspan information to table element
  17688. if ($rowspan > 1) {
  17689. $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));
  17690. }
  17691. $cellid = array_push($dom[$trid]['cellpos'], array('startx' => $this->x));
  17692. if ($rowspan > 1) {
  17693. $dom[$trid]['cellpos'][($cellid - 1)]['rowspanid'] = ($trsid - 1);
  17694. }
  17695. // push background colors
  17696. if (isset($dom[$parentid]['bgcolor']) AND ($dom[$parentid]['bgcolor'] !== false)) {
  17697. $dom[$trid]['cellpos'][($cellid - 1)]['bgcolor'] = $dom[$parentid]['bgcolor'];
  17698. }
  17699. // store border info
  17700. if (isset($tdborder) AND !empty($tdborder)) {
  17701. $dom[$trid]['cellpos'][($cellid - 1)]['border'] = $tdborder;
  17702. }
  17703. $prevLastH = $this->lasth;
  17704. // store some info for multicolumn mode
  17705. if ($this->rtl) {
  17706. $this->colxshift['x'] = $this->w - $this->x - $this->rMargin;
  17707. } else {
  17708. $this->colxshift['x'] = $this->x - $this->lMargin;
  17709. }
  17710. $this->colxshift['s'] = $cellspacing;
  17711. $this->colxshift['p'] = $current_cell_padding;
  17712. // ****** write the cell content ******
  17713. $this->MultiCell($cellw, $cellh, $cell_content, false, $lalign, false, 2, '', '', true, 0, true, true, 0, 'T', false);
  17714. // restore some values
  17715. $this->colxshift = array('x' => 0, 's' => array('H' => 0, 'V' => 0), 'p' => array('L' => 0, 'T' => 0, 'R' => 0, 'B' => 0));
  17716. $this->lasth = $prevLastH;
  17717. $this->cell_padding = $old_cell_padding;
  17718. $dom[$trid]['cellpos'][($cellid - 1)]['endx'] = $this->x;
  17719. // update the end of row position
  17720. if ($rowspan <= 1) {
  17721. if (isset($dom[$trid]['endy'])) {
  17722. if (($this->page == $dom[$trid]['endpage']) AND ($this->current_column == $dom[$trid]['endcolumn'])) {
  17723. $dom[$trid]['endy'] = max($this->y, $dom[$trid]['endy']);
  17724. } elseif (($this->page > $dom[$trid]['endpage']) OR ($this->current_column > $dom[$trid]['endcolumn'])) {
  17725. $dom[$trid]['endy'] = $this->y;
  17726. }
  17727. } else {
  17728. $dom[$trid]['endy'] = $this->y;
  17729. }
  17730. if (isset($dom[$trid]['endpage'])) {
  17731. $dom[$trid]['endpage'] = max($this->page, $dom[$trid]['endpage']);
  17732. } else {
  17733. $dom[$trid]['endpage'] = $this->page;
  17734. }
  17735. if (isset($dom[$trid]['endcolumn'])) {
  17736. $dom[$trid]['endcolumn'] = max($this->current_column, $dom[$trid]['endcolumn']);
  17737. } else {
  17738. $dom[$trid]['endcolumn'] = $this->current_column;
  17739. }
  17740. } else {
  17741. // account for row-spanned cells
  17742. $dom[$table_el]['rowspans'][($trsid - 1)]['endx'] = $this->x;
  17743. $dom[$table_el]['rowspans'][($trsid - 1)]['endy'] = $this->y;
  17744. $dom[$table_el]['rowspans'][($trsid - 1)]['endpage'] = $this->page;
  17745. $dom[$table_el]['rowspans'][($trsid - 1)]['endcolumn'] = $this->current_column;
  17746. }
  17747. if (isset($dom[$table_el]['rowspans'])) {
  17748. // update endy and endpage on rowspanned cells
  17749. foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
  17750. if ($trwsp['rowspan'] > 0) {
  17751. if (isset($dom[$trid]['endpage'])) {
  17752. if (($trwsp['endpage'] == $dom[$trid]['endpage']) AND ($trwsp['endcolumn'] == $dom[$trid]['endcolumn'])) {
  17753. $dom[$table_el]['rowspans'][$k]['endy'] = max($dom[$trid]['endy'], $trwsp['endy']);
  17754. } elseif (($trwsp['endpage'] < $dom[$trid]['endpage']) OR ($trwsp['endcolumn'] < $dom[$trid]['endcolumn'])) {
  17755. $dom[$table_el]['rowspans'][$k]['endy'] = $dom[$trid]['endy'];
  17756. $dom[$table_el]['rowspans'][$k]['endpage'] = $dom[$trid]['endpage'];
  17757. $dom[$table_el]['rowspans'][$k]['endcolumn'] = $dom[$trid]['endcolumn'];
  17758. } else {
  17759. $dom[$trid]['endy'] = $this->pagedim[$dom[$trid]['endpage']]['hk'] - $this->pagedim[$dom[$trid]['endpage']]['bm'];
  17760. }
  17761. }
  17762. }
  17763. }
  17764. }
  17765. $this->x += ($cellspacingx / 2);
  17766. } else {
  17767. // opening tag (or self-closing tag)
  17768. if (!isset($opentagpos)) {
  17769. if ($this->inxobj) {
  17770. // we are inside an XObject template
  17771. $opentagpos = strlen($this->xobjects[$this->xobjid]['outdata']);
  17772. } elseif (!$this->InFooter) {
  17773. if (isset($this->footerlen[$this->page])) {
  17774. $this->footerpos[$this->page] = $this->pagelen[$this->page] - $this->footerlen[$this->page];
  17775. } else {
  17776. $this->footerpos[$this->page] = $this->pagelen[$this->page];
  17777. }
  17778. $opentagpos = $this->footerpos[$this->page];
  17779. }
  17780. }
  17781. $dom = $this->openHTMLTagHandler($dom, $key, $cell);
  17782. }
  17783. } else { // closing tag
  17784. $prev_numpages = $this->numpages;
  17785. $old_bordermrk = $this->bordermrk[$this->page];
  17786. $dom = $this->closeHTMLTagHandler($dom, $key, $cell, $maxbottomliney);
  17787. if ($this->bordermrk[$this->page] > $old_bordermrk) {
  17788. $startlinepos += ($this->bordermrk[$this->page] - $old_bordermrk);
  17789. }
  17790. if ($prev_numpages > $this->numpages) {
  17791. $startlinepage = $this->page;
  17792. }
  17793. }
  17794. } elseif (strlen($dom[$key]['value']) > 0) {
  17795. // print list-item
  17796. if (!TCPDF_STATIC::empty_string($this->lispacer) AND ($this->lispacer != '^')) {
  17797. $this->SetFont($pfontname, $pfontstyle, $pfontsize);
  17798. $this->resetLastH();
  17799. $minstartliney = $this->y;
  17800. $maxbottomliney = ($startliney + $this->getCellHeight($this->FontSize));
  17801. if (is_numeric($pfontsize) AND ($pfontsize > 0)) {
  17802. $this->putHtmlListBullet($this->listnum, $this->lispacer, $pfontsize);
  17803. }
  17804. $this->SetFont($curfontname, $curfontstyle, $curfontsize);
  17805. $this->resetLastH();
  17806. if (is_numeric($pfontsize) AND ($pfontsize > 0) AND is_numeric($curfontsize) AND ($curfontsize > 0) AND ($pfontsize != $curfontsize)) {
  17807. $pfontascent = $this->getFontAscent($pfontname, $pfontstyle, $pfontsize);
  17808. $pfontdescent = $this->getFontDescent($pfontname, $pfontstyle, $pfontsize);
  17809. $this->y += ($this->getCellHeight(($pfontsize - $curfontsize) / $this->k) + $pfontascent - $curfontascent - $pfontdescent + $curfontdescent) / 2;
  17810. $minstartliney = min($this->y, $minstartliney);
  17811. $maxbottomliney = max(($this->y + $this->getCellHeight($pfontsize / $this->k)), $maxbottomliney);
  17812. }
  17813. }
  17814. // text
  17815. $this->htmlvspace = 0;
  17816. $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']);
  17817. if ((!$this->premode) AND $this->isRTLTextDir() AND !$isRTLString) {
  17818. // reverse spaces order
  17819. $lsp = ''; // left spaces
  17820. $rsp = ''; // right spaces
  17821. if (preg_match('/^('.$this->re_space['p'].'+)/'.$this->re_space['m'], $dom[$key]['value'], $matches)) {
  17822. $lsp = $matches[1];
  17823. }
  17824. if (preg_match('/('.$this->re_space['p'].'+)$/'.$this->re_space['m'], $dom[$key]['value'], $matches)) {
  17825. $rsp = $matches[1];
  17826. }
  17827. $dom[$key]['value'] = $rsp.$this->stringTrim($dom[$key]['value']).$lsp;
  17828. }
  17829. if ($newline) {
  17830. if (!$this->premode) {
  17831. $prelen = strlen($dom[$key]['value']);
  17832. if ($this->isRTLTextDir() AND !$isRTLString) {
  17833. // right trim except non-breaking space
  17834. $dom[$key]['value'] = $this->stringRightTrim($dom[$key]['value']);
  17835. } else {
  17836. // left trim except non-breaking space
  17837. $dom[$key]['value'] = $this->stringLeftTrim($dom[$key]['value']);
  17838. }
  17839. $postlen = strlen($dom[$key]['value']);
  17840. if (($postlen == 0) AND ($prelen > 0)) {
  17841. $dom[$key]['trimmed_space'] = true;
  17842. }
  17843. }
  17844. $newline = false;
  17845. $firstblock = true;
  17846. } else {
  17847. $firstblock = false;
  17848. // replace empty multiple spaces string with a single space
  17849. $dom[$key]['value'] = preg_replace('/^'.$this->re_space['p'].'+$/'.$this->re_space['m'], chr(32), $dom[$key]['value']);
  17850. }
  17851. $strrest = '';
  17852. if ($this->rtl) {
  17853. $this->x -= $this->textindent;
  17854. } else {
  17855. $this->x += $this->textindent;
  17856. }
  17857. if (!isset($dom[$key]['trimmed_space']) OR !$dom[$key]['trimmed_space']) {
  17858. $strlinelen = $this->GetStringWidth($dom[$key]['value']);
  17859. if (!empty($this->HREF) AND (isset($this->HREF['url']))) {
  17860. // HTML <a> Link
  17861. $hrefcolor = '';
  17862. if (isset($dom[($dom[$key]['parent'])]['fgcolor']) AND ($dom[($dom[$key]['parent'])]['fgcolor'] !== false)) {
  17863. $hrefcolor = $dom[($dom[$key]['parent'])]['fgcolor'];
  17864. }
  17865. $hrefstyle = -1;
  17866. if (isset($dom[($dom[$key]['parent'])]['fontstyle']) AND ($dom[($dom[$key]['parent'])]['fontstyle'] !== false)) {
  17867. $hrefstyle = $dom[($dom[$key]['parent'])]['fontstyle'];
  17868. }
  17869. $strrest = $this->addHtmlLink($this->HREF['url'], $dom[$key]['value'], $wfill, true, $hrefcolor, $hrefstyle, true);
  17870. } else {
  17871. $wadj = 0; // space to leave for block continuity
  17872. if ($this->rtl) {
  17873. $cwa = ($this->x - $this->lMargin);
  17874. } else {
  17875. $cwa = ($this->w - $this->rMargin - $this->x);
  17876. }
  17877. if (($strlinelen < $cwa) AND (isset($dom[($key + 1)])) AND ($dom[($key + 1)]['tag']) AND (!$dom[($key + 1)]['block'])) {
  17878. // check the next text blocks for continuity
  17879. $nkey = ($key + 1);
  17880. $write_block = true;
  17881. $same_textdir = true;
  17882. $tmp_fontname = $this->FontFamily;
  17883. $tmp_fontstyle = $this->FontStyle;
  17884. $tmp_fontsize = $this->FontSizePt;
  17885. while ($write_block AND isset($dom[$nkey])) {
  17886. if ($dom[$nkey]['tag']) {
  17887. if ($dom[$nkey]['block']) {
  17888. // end of block
  17889. $write_block = false;
  17890. }
  17891. $tmp_fontname = isset($dom[$nkey]['fontname']) ? $dom[$nkey]['fontname'] : $this->FontFamily;
  17892. $tmp_fontstyle = isset($dom[$nkey]['fontstyle']) ? $dom[$nkey]['fontstyle'] : $this->FontStyle;
  17893. $tmp_fontsize = isset($dom[$nkey]['fontsize']) ? $dom[$nkey]['fontsize'] : $this->FontSizePt;
  17894. $same_textdir = ($dom[$nkey]['dir'] == $dom[$key]['dir']);
  17895. } else {
  17896. $nextstr = TCPDF_STATIC::pregSplit('/'.$this->re_space['p'].'+/', $this->re_space['m'], $dom[$nkey]['value']);
  17897. if (isset($nextstr[0]) AND $same_textdir) {
  17898. $wadj += $this->GetStringWidth($nextstr[0], $tmp_fontname, $tmp_fontstyle, $tmp_fontsize);
  17899. if (isset($nextstr[1])) {
  17900. $write_block = false;
  17901. }
  17902. }
  17903. }
  17904. ++$nkey;
  17905. }
  17906. }
  17907. if (($wadj > 0) AND (($strlinelen + $wadj) >= $cwa)) {
  17908. $wadj = 0;
  17909. $nextstr = TCPDF_STATIC::pregSplit('/'.$this->re_space['p'].'/', $this->re_space['m'], $dom[$key]['value']);
  17910. $numblks = count($nextstr);
  17911. if ($numblks > 1) {
  17912. // try to split on blank spaces
  17913. $wadj = ($cwa - $strlinelen + $this->GetStringWidth($nextstr[($numblks - 1)]));
  17914. } else {
  17915. // set the entire block on new line
  17916. $wadj = $this->GetStringWidth($nextstr[0]);
  17917. }
  17918. }
  17919. // check for reversed text direction
  17920. if (($wadj > 0) AND (($this->rtl AND ($this->tmprtl === 'L')) OR (!$this->rtl AND ($this->tmprtl === 'R')))) {
  17921. // LTR text on RTL direction or RTL text on LTR direction
  17922. $reverse_dir = true;
  17923. $this->rtl = !$this->rtl;
  17924. $revshift = ($strlinelen + $wadj + 0.000001); // add little quantity for rounding problems
  17925. if ($this->rtl) {
  17926. $this->x += $revshift;
  17927. } else {
  17928. $this->x -= $revshift;
  17929. }
  17930. $xws = $this->x;
  17931. }
  17932. // ****** write only until the end of the line and get the rest ******
  17933. $strrest = $this->Write($this->lasth, $dom[$key]['value'], '', $wfill, '', false, 0, true, $firstblock, 0, $wadj);
  17934. // restore default direction
  17935. if ($reverse_dir AND ($wadj == 0)) {
  17936. $this->x = $xws;
  17937. $this->rtl = !$this->rtl;
  17938. $reverse_dir = false;
  17939. }
  17940. }
  17941. }
  17942. $this->textindent = 0;
  17943. if (strlen($strrest) > 0) {
  17944. // store the remaining string on the previous $key position
  17945. $this->newline = true;
  17946. if ($strrest == $dom[$key]['value']) {
  17947. // used to avoid infinite loop
  17948. ++$loop;
  17949. } else {
  17950. $loop = 0;
  17951. }
  17952. $dom[$key]['value'] = $strrest;
  17953. if ($cell) {
  17954. if ($this->rtl) {
  17955. $this->x -= $this->cell_padding['R'];
  17956. } else {
  17957. $this->x += $this->cell_padding['L'];
  17958. }
  17959. }
  17960. if ($loop < 3) {
  17961. --$key;
  17962. }
  17963. } else {
  17964. $loop = 0;
  17965. // add the positive font spacing of the last character (if any)
  17966. if ($this->font_spacing > 0) {
  17967. if ($this->rtl) {
  17968. $this->x -= $this->font_spacing;
  17969. } else {
  17970. $this->x += $this->font_spacing;
  17971. }
  17972. }
  17973. }
  17974. }
  17975. ++$key;
  17976. 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')) {
  17977. // check if we are on a new page or on a new column
  17978. if ((!$undo) AND (($this->y < $this->start_transaction_y) OR (($dom[$key]['value'] == 'tr') AND ($dom[($dom[$key]['parent'])]['endy'] < $this->start_transaction_y)))) {
  17979. // we are on a new page or on a new column and the total object height is less than the available vertical space.
  17980. // restore previous object
  17981. $this->rollbackTransaction(true);
  17982. // restore previous values
  17983. foreach ($this_method_vars as $vkey => $vval) {
  17984. $$vkey = $vval;
  17985. }
  17986. if (!empty($dom[$key]['thead'])) {
  17987. $this->inthead = true;
  17988. }
  17989. // add a page (or trig AcceptPageBreak() for multicolumn mode)
  17990. $pre_y = $this->y;
  17991. if ((!$this->checkPageBreak($this->PageBreakTrigger + 1)) AND ($this->y < $pre_y)) {
  17992. $startliney = $this->y;
  17993. }
  17994. $undo = true; // avoid infinite loop
  17995. } else {
  17996. $undo = false;
  17997. }
  17998. }
  17999. } // end for each $key
  18000. // align the last line
  18001. if (isset($startlinex)) {
  18002. $yshift = ($minstartliney - $startliney);
  18003. if (($yshift > 0) OR ($this->page > $startlinepage)) {
  18004. $yshift = 0;
  18005. }
  18006. $t_x = 0;
  18007. // the last line must be shifted to be aligned as requested
  18008. $linew = abs($this->endlinex - $startlinex);
  18009. if ($this->inxobj) {
  18010. // we are inside an XObject template
  18011. $pstart = substr($this->xobjects[$this->xobjid]['outdata'], 0, $startlinepos);
  18012. if (isset($opentagpos)) {
  18013. $midpos = $opentagpos;
  18014. } else {
  18015. $midpos = 0;
  18016. }
  18017. if ($midpos > 0) {
  18018. $pmid = substr($this->xobjects[$this->xobjid]['outdata'], $startlinepos, ($midpos - $startlinepos));
  18019. $pend = substr($this->xobjects[$this->xobjid]['outdata'], $midpos);
  18020. } else {
  18021. $pmid = substr($this->xobjects[$this->xobjid]['outdata'], $startlinepos);
  18022. $pend = '';
  18023. }
  18024. } else {
  18025. $pstart = substr($this->getPageBuffer($startlinepage), 0, $startlinepos);
  18026. if (isset($opentagpos) AND isset($this->footerlen[$startlinepage]) AND (!$this->InFooter)) {
  18027. $this->footerpos[$startlinepage] = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
  18028. $midpos = min($opentagpos, $this->footerpos[$startlinepage]);
  18029. } elseif (isset($opentagpos)) {
  18030. $midpos = $opentagpos;
  18031. } elseif (isset($this->footerlen[$startlinepage]) AND (!$this->InFooter)) {
  18032. $this->footerpos[$startlinepage] = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
  18033. $midpos = $this->footerpos[$startlinepage];
  18034. } else {
  18035. $midpos = 0;
  18036. }
  18037. if ($midpos > 0) {
  18038. $pmid = substr($this->getPageBuffer($startlinepage), $startlinepos, ($midpos - $startlinepos));
  18039. $pend = substr($this->getPageBuffer($startlinepage), $midpos);
  18040. } else {
  18041. $pmid = substr($this->getPageBuffer($startlinepage), $startlinepos);
  18042. $pend = '';
  18043. }
  18044. }
  18045. if ((isset($plalign) AND ((($plalign == 'C') OR (($plalign == 'R') AND (!$this->rtl)) OR (($plalign == 'L') AND ($this->rtl)))))) {
  18046. // calculate shifting amount
  18047. $tw = $w;
  18048. if ($this->lMargin != $prevlMargin) {
  18049. $tw += ($prevlMargin - $this->lMargin);
  18050. }
  18051. if ($this->rMargin != $prevrMargin) {
  18052. $tw += ($prevrMargin - $this->rMargin);
  18053. }
  18054. $one_space_width = $this->GetStringWidth(chr(32));
  18055. $no = 0; // number of spaces on a line contained on a single block
  18056. if ($this->isRTLTextDir()) { // RTL
  18057. // remove left space if exist
  18058. $pos1 = TCPDF_STATIC::revstrpos($pmid, '[(');
  18059. if ($pos1 > 0) {
  18060. $pos1 = intval($pos1);
  18061. if ($this->isUnicodeFont()) {
  18062. $pos2 = intval(TCPDF_STATIC::revstrpos($pmid, '[('.chr(0).chr(32)));
  18063. $spacelen = 2;
  18064. } else {
  18065. $pos2 = intval(TCPDF_STATIC::revstrpos($pmid, '[('.chr(32)));
  18066. $spacelen = 1;
  18067. }
  18068. if ($pos1 == $pos2) {
  18069. $pmid = substr($pmid, 0, ($pos1 + 2)).substr($pmid, ($pos1 + 2 + $spacelen));
  18070. if (substr($pmid, $pos1, 4) == '[()]') {
  18071. $linew -= $one_space_width;
  18072. } elseif ($pos1 == strpos($pmid, '[(')) {
  18073. $no = 1;
  18074. }
  18075. }
  18076. }
  18077. } else { // LTR
  18078. // remove right space if exist
  18079. $pos1 = TCPDF_STATIC::revstrpos($pmid, ')]');
  18080. if ($pos1 > 0) {
  18081. $pos1 = intval($pos1);
  18082. if ($this->isUnicodeFont()) {
  18083. $pos2 = intval(TCPDF_STATIC::revstrpos($pmid, chr(0).chr(32).')]')) + 2;
  18084. $spacelen = 2;
  18085. } else {
  18086. $pos2 = intval(TCPDF_STATIC::revstrpos($pmid, chr(32).')]')) + 1;
  18087. $spacelen = 1;
  18088. }
  18089. if ($pos1 == $pos2) {
  18090. $pmid = substr($pmid, 0, ($pos1 - $spacelen)).substr($pmid, $pos1);
  18091. $linew -= $one_space_width;
  18092. }
  18093. }
  18094. }
  18095. $mdiff = ($tw - $linew);
  18096. if ($plalign == 'C') {
  18097. if ($this->rtl) {
  18098. $t_x = -($mdiff / 2);
  18099. } else {
  18100. $t_x = ($mdiff / 2);
  18101. }
  18102. } elseif ($plalign == 'R') {
  18103. // right alignment on LTR document
  18104. $t_x = $mdiff;
  18105. } elseif ($plalign == 'L') {
  18106. // left alignment on RTL document
  18107. $t_x = -$mdiff;
  18108. }
  18109. } // end if startlinex
  18110. if (($t_x != 0) OR ($yshift < 0)) {
  18111. // shift the line
  18112. $trx = sprintf('1 0 0 1 %F %F cm', ($t_x * $this->k), ($yshift * $this->k));
  18113. $pstart .= "\nq\n".$trx."\n".$pmid."\nQ\n";
  18114. $endlinepos = strlen($pstart);
  18115. if ($this->inxobj) {
  18116. // we are inside an XObject template
  18117. $this->xobjects[$this->xobjid]['outdata'] = $pstart.$pend;
  18118. foreach ($this->xobjects[$this->xobjid]['annotations'] as $pak => $pac) {
  18119. if ($pak >= $pask) {
  18120. $this->xobjects[$this->xobjid]['annotations'][$pak]['x'] += $t_x;
  18121. $this->xobjects[$this->xobjid]['annotations'][$pak]['y'] -= $yshift;
  18122. }
  18123. }
  18124. } else {
  18125. $this->setPageBuffer($startlinepage, $pstart.$pend);
  18126. // shift the annotations and links
  18127. if (isset($this->PageAnnots[$this->page])) {
  18128. foreach ($this->PageAnnots[$this->page] as $pak => $pac) {
  18129. if ($pak >= $pask) {
  18130. $this->PageAnnots[$this->page][$pak]['x'] += $t_x;
  18131. $this->PageAnnots[$this->page][$pak]['y'] -= $yshift;
  18132. }
  18133. }
  18134. }
  18135. }
  18136. $this->y -= $yshift;
  18137. $yshift = 0;
  18138. }
  18139. }
  18140. // restore previous values
  18141. $this->setGraphicVars($gvars);
  18142. if ($this->num_columns > 1) {
  18143. $this->selectColumn();
  18144. } elseif ($this->page > $prevPage) {
  18145. $this->lMargin = $this->pagedim[$this->page]['olm'];
  18146. $this->rMargin = $this->pagedim[$this->page]['orm'];
  18147. }
  18148. // restore previous list state
  18149. $this->cell_height_ratio = $prev_cell_height_ratio;
  18150. $this->listnum = $prev_listnum;
  18151. $this->listordered = $prev_listordered;
  18152. $this->listcount = $prev_listcount;
  18153. $this->lispacer = $prev_lispacer;
  18154. if ($ln AND (!($cell AND ($dom[$key-1]['value'] == 'table')))) {
  18155. $this->Ln($this->lasth);
  18156. if (($this->y < $maxbottomliney) AND ($startlinepage == $this->page)) {
  18157. $this->y = $maxbottomliney;
  18158. }
  18159. }
  18160. unset($dom);
  18161. }
  18162. /**
  18163. * Process opening tags.
  18164. * @param $dom (array) html dom array
  18165. * @param $key (int) current element id
  18166. * @param $cell (boolean) if true add the default left (or right if RTL) padding to each new line (default false).
  18167. * @return $dom array
  18168. * @protected
  18169. */
  18170. protected function openHTMLTagHandler($dom, $key, $cell) {
  18171. $tag = $dom[$key];
  18172. $parent = $dom[($dom[$key]['parent'])];
  18173. $firsttag = ($key == 1);
  18174. // check for text direction attribute
  18175. if (isset($tag['dir'])) {
  18176. $this->setTempRTL($tag['dir']);
  18177. } else {
  18178. $this->tmprtl = false;
  18179. }
  18180. if ($tag['block']) {
  18181. $hbz = 0; // distance from y to line bottom
  18182. $hb = 0; // vertical space between block tags
  18183. // calculate vertical space for block tags
  18184. if (isset($this->tagvspaces[$tag['value']][0]['h']) && !empty($this->tagvspaces[$tag['value']][0]['h']) && ($this->tagvspaces[$tag['value']][0]['h'] >= 0)) {
  18185. $cur_h = $this->tagvspaces[$tag['value']][0]['h'];
  18186. } elseif (isset($tag['fontsize'])) {
  18187. $cur_h = $this->getCellHeight($tag['fontsize'] / $this->k);
  18188. } else {
  18189. $cur_h = $this->getCellHeight($this->FontSize);
  18190. }
  18191. if (isset($this->tagvspaces[$tag['value']][0]['n'])) {
  18192. $on = $this->tagvspaces[$tag['value']][0]['n'];
  18193. } elseif (preg_match('/[h][0-9]/', $tag['value']) > 0) {
  18194. $on = 0.6;
  18195. } else {
  18196. $on = 1;
  18197. }
  18198. if ((!isset($this->tagvspaces[$tag['value']])) AND (in_array($tag['value'], array('div', 'dt', 'dd', 'li', 'br', 'hr')))) {
  18199. $hb = 0;
  18200. } else {
  18201. $hb = ($on * $cur_h);
  18202. }
  18203. if (($this->htmlvspace <= 0) AND ($on > 0)) {
  18204. if (isset($parent['fontsize'])) {
  18205. $hbz = (($parent['fontsize'] / $this->k) * $this->cell_height_ratio);
  18206. } else {
  18207. $hbz = $this->getCellHeight($this->FontSize);
  18208. }
  18209. }
  18210. if (isset($dom[($key - 1)]) AND ($dom[($key - 1)]['value'] == 'table')) {
  18211. // fix vertical space after table
  18212. $hbz = 0;
  18213. }
  18214. // closing vertical space
  18215. $hbc = 0;
  18216. if (isset($this->tagvspaces[$tag['value']][1]['h']) && !empty($this->tagvspaces[$tag['value']][1]['h']) && ($this->tagvspaces[$tag['value']][1]['h'] >= 0)) {
  18217. $pre_h = $this->tagvspaces[$tag['value']][1]['h'];
  18218. } elseif (isset($parent['fontsize'])) {
  18219. $pre_h = $this->getCellHeight($parent['fontsize'] / $this->k);
  18220. } else {
  18221. $pre_h = $this->getCellHeight($this->FontSize);
  18222. }
  18223. if (isset($this->tagvspaces[$tag['value']][1]['n'])) {
  18224. $cn = $this->tagvspaces[$tag['value']][1]['n'];
  18225. } elseif (preg_match('/[h][0-9]/', $tag['value']) > 0) {
  18226. $cn = 0.6;
  18227. } else {
  18228. $cn = 1;
  18229. }
  18230. if (isset($this->tagvspaces[$tag['value']][1])) {
  18231. $hbc = ($cn * $pre_h);
  18232. }
  18233. }
  18234. // Opening tag
  18235. switch($tag['value']) {
  18236. case 'table': {
  18237. $cp = 0;
  18238. $cs = 0;
  18239. $dom[$key]['rowspans'] = array();
  18240. if (!isset($dom[$key]['attribute']['nested']) OR ($dom[$key]['attribute']['nested'] != 'true')) {
  18241. $this->htmlvspace = 0;
  18242. // set table header
  18243. if (!TCPDF_STATIC::empty_string($dom[$key]['thead'])) {
  18244. // set table header
  18245. $this->thead = $dom[$key]['thead'];
  18246. if (!isset($this->theadMargins) OR (empty($this->theadMargins))) {
  18247. $this->theadMargins = array();
  18248. $this->theadMargins['cell_padding'] = $this->cell_padding;
  18249. $this->theadMargins['lmargin'] = $this->lMargin;
  18250. $this->theadMargins['rmargin'] = $this->rMargin;
  18251. $this->theadMargins['page'] = $this->page;
  18252. $this->theadMargins['cell'] = $cell;
  18253. $this->theadMargins['gvars'] = $this->getGraphicVars();
  18254. }
  18255. }
  18256. }
  18257. // store current margins and page
  18258. $dom[$key]['old_cell_padding'] = $this->cell_padding;
  18259. if (isset($tag['attribute']['cellpadding'])) {
  18260. $pad = $this->getHTMLUnitToUnits($tag['attribute']['cellpadding'], 1, 'px');
  18261. $this->SetCellPadding($pad);
  18262. } elseif (isset($tag['padding'])) {
  18263. $this->cell_padding = $tag['padding'];
  18264. }
  18265. if (isset($tag['attribute']['cellspacing'])) {
  18266. $cs = $this->getHTMLUnitToUnits($tag['attribute']['cellspacing'], 1, 'px');
  18267. } elseif (isset($tag['border-spacing'])) {
  18268. $cs = $tag['border-spacing']['V'];
  18269. }
  18270. $prev_y = $this->y;
  18271. if ($this->checkPageBreak(((2 * $cp) + (2 * $cs) + $this->lasth), '', false) OR ($this->y < $prev_y)) {
  18272. $this->inthead = true;
  18273. // add a page (or trig AcceptPageBreak() for multicolumn mode)
  18274. $this->checkPageBreak($this->PageBreakTrigger + 1);
  18275. }
  18276. break;
  18277. }
  18278. case 'tr': {
  18279. // array of columns positions
  18280. $dom[$key]['cellpos'] = array();
  18281. break;
  18282. }
  18283. case 'hr': {
  18284. if ((isset($tag['height'])) AND ($tag['height'] != '')) {
  18285. $hrHeight = $this->getHTMLUnitToUnits($tag['height'], 1, 'px');
  18286. } else {
  18287. $hrHeight = $this->GetLineWidth();
  18288. }
  18289. $this->addHTMLVertSpace($hbz, max($hb, ($hrHeight / 2)), $cell, $firsttag);
  18290. $x = $this->GetX();
  18291. $y = $this->GetY();
  18292. $wtmp = $this->w - $this->lMargin - $this->rMargin;
  18293. if ($cell) {
  18294. $wtmp -= ($this->cell_padding['L'] + $this->cell_padding['R']);
  18295. }
  18296. if ((isset($tag['width'])) AND ($tag['width'] != '')) {
  18297. $hrWidth = $this->getHTMLUnitToUnits($tag['width'], $wtmp, 'px');
  18298. } else {
  18299. $hrWidth = $wtmp;
  18300. }
  18301. $prevlinewidth = $this->GetLineWidth();
  18302. $this->SetLineWidth($hrHeight);
  18303. $lineStyle = array(
  18304. 'color' => $tag['fgcolor'],
  18305. 'cap' => $tag['style']['cap'],
  18306. 'join' => $tag['style']['join'],
  18307. 'dash' => $tag['style']['dash'],
  18308. 'phase' => $tag['style']['phase'],
  18309. );
  18310. $lineStyle = array_filter($lineStyle);
  18311. $this->Line($x, $y, $x + $hrWidth, $y, $lineStyle);
  18312. $this->SetLineWidth($prevlinewidth);
  18313. $this->addHTMLVertSpace(max($hbc, ($hrHeight / 2)), 0, $cell, !isset($dom[($key + 1)]));
  18314. break;
  18315. }
  18316. case 'a': {
  18317. if (array_key_exists('href', $tag['attribute'])) {
  18318. $this->HREF['url'] = $tag['attribute']['href'];
  18319. }
  18320. break;
  18321. }
  18322. case 'img': {
  18323. if (empty($tag['attribute']['src'])) {
  18324. break;
  18325. }
  18326. $imgsrc = $tag['attribute']['src'];
  18327. if ($imgsrc[0] === '@') {
  18328. // data stream
  18329. $imgsrc = '@'.base64_decode(substr($imgsrc, 1));
  18330. $type = '';
  18331. } elseif ( $this->allowLocalFiles && substr($imgsrc, 0, 7) === 'file://') {
  18332. // get image type from a local file path
  18333. $imgsrc = substr($imgsrc, 7);
  18334. $type = TCPDF_IMAGES::getImageFileType($imgsrc);
  18335. } else {
  18336. if (($imgsrc[0] === '/') AND !empty($_SERVER['DOCUMENT_ROOT']) AND ($_SERVER['DOCUMENT_ROOT'] != '/')) {
  18337. // fix image path
  18338. $findroot = strpos($imgsrc, $_SERVER['DOCUMENT_ROOT']);
  18339. if (($findroot === false) OR ($findroot > 1)) {
  18340. if (substr($_SERVER['DOCUMENT_ROOT'], -1) == '/') {
  18341. $imgsrc = substr($_SERVER['DOCUMENT_ROOT'], 0, -1).$imgsrc;
  18342. } else {
  18343. $imgsrc = $_SERVER['DOCUMENT_ROOT'].$imgsrc;
  18344. }
  18345. }
  18346. $imgsrc = urldecode($imgsrc);
  18347. $testscrtype = @parse_url($imgsrc);
  18348. if (empty($testscrtype['query'])) {
  18349. // convert URL to server path
  18350. $imgsrc = str_replace(K_PATH_URL, K_PATH_MAIN, $imgsrc);
  18351. } elseif (preg_match('|^https?://|', $imgsrc) !== 1) {
  18352. // convert URL to server path
  18353. $imgsrc = str_replace(K_PATH_MAIN, K_PATH_URL, $imgsrc);
  18354. }
  18355. }
  18356. // get image type
  18357. $type = TCPDF_IMAGES::getImageFileType($imgsrc);
  18358. }
  18359. if (!isset($tag['width'])) {
  18360. $tag['width'] = 0;
  18361. }
  18362. if (!isset($tag['height'])) {
  18363. $tag['height'] = 0;
  18364. }
  18365. //if (!isset($tag['attribute']['align'])) {
  18366. // the only alignment supported is "bottom"
  18367. // further development is required for other modes.
  18368. $tag['attribute']['align'] = 'bottom';
  18369. //}
  18370. switch($tag['attribute']['align']) {
  18371. case 'top': {
  18372. $align = 'T';
  18373. break;
  18374. }
  18375. case 'middle': {
  18376. $align = 'M';
  18377. break;
  18378. }
  18379. case 'bottom': {
  18380. $align = 'B';
  18381. break;
  18382. }
  18383. default: {
  18384. $align = 'B';
  18385. break;
  18386. }
  18387. }
  18388. $prevy = $this->y;
  18389. $xpos = $this->x;
  18390. $imglink = '';
  18391. if (isset($this->HREF['url']) AND !TCPDF_STATIC::empty_string($this->HREF['url'])) {
  18392. $imglink = $this->HREF['url'];
  18393. if ($imglink[0] == '#') {
  18394. // convert url to internal link
  18395. $lnkdata = explode(',', $imglink);
  18396. if (isset($lnkdata[0])) {
  18397. $page = intval(substr($lnkdata[0], 1));
  18398. if (empty($page) OR ($page <= 0)) {
  18399. $page = $this->page;
  18400. }
  18401. if (isset($lnkdata[1]) AND (strlen($lnkdata[1]) > 0)) {
  18402. $lnky = floatval($lnkdata[1]);
  18403. } else {
  18404. $lnky = 0;
  18405. }
  18406. $imglink = $this->AddLink();
  18407. $this->SetLink($imglink, $lnky, $page);
  18408. }
  18409. }
  18410. }
  18411. $border = 0;
  18412. if (isset($tag['border']) AND !empty($tag['border'])) {
  18413. // currently only support 1 (frame) or a combination of 'LTRB'
  18414. $border = $tag['border'];
  18415. }
  18416. $iw = '';
  18417. if (isset($tag['width'])) {
  18418. $iw = $this->getHTMLUnitToUnits($tag['width'], ($tag['fontsize'] / $this->k), 'px', false);
  18419. }
  18420. $ih = '';
  18421. if (isset($tag['height'])) {
  18422. $ih = $this->getHTMLUnitToUnits($tag['height'], ($tag['fontsize'] / $this->k), 'px', false);
  18423. }
  18424. if (($type == 'eps') OR ($type == 'ai')) {
  18425. $this->ImageEps($imgsrc, $xpos, $this->y, $iw, $ih, $imglink, true, $align, '', $border, true);
  18426. } elseif ($type == 'svg') {
  18427. $this->ImageSVG($imgsrc, $xpos, $this->y, $iw, $ih, $imglink, $align, '', $border, true);
  18428. } else {
  18429. $this->Image($imgsrc, $xpos, $this->y, $iw, $ih, '', $imglink, $align, false, 300, '', false, false, $border, false, false, true);
  18430. }
  18431. switch($align) {
  18432. case 'T': {
  18433. $this->y = $prevy;
  18434. break;
  18435. }
  18436. case 'M': {
  18437. $this->y = (($this->img_rb_y + $prevy - ($this->getCellHeight($tag['fontsize'] / $this->k))) / 2);
  18438. break;
  18439. }
  18440. case 'B': {
  18441. $this->y = $this->img_rb_y - ($this->getCellHeight($tag['fontsize'] / $this->k) - ($this->getFontDescent($tag['fontname'], $tag['fontstyle'], $tag['fontsize']) * $this->cell_height_ratio));
  18442. break;
  18443. }
  18444. }
  18445. break;
  18446. }
  18447. case 'dl': {
  18448. ++$this->listnum;
  18449. if ($this->listnum == 1) {
  18450. $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
  18451. } else {
  18452. $this->addHTMLVertSpace(0, 0, $cell, $firsttag);
  18453. }
  18454. break;
  18455. }
  18456. case 'dt': {
  18457. $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
  18458. break;
  18459. }
  18460. case 'dd': {
  18461. if ($this->rtl) {
  18462. $this->rMargin += $this->listindent;
  18463. } else {
  18464. $this->lMargin += $this->listindent;
  18465. }
  18466. ++$this->listindentlevel;
  18467. $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
  18468. break;
  18469. }
  18470. case 'ul':
  18471. case 'ol': {
  18472. ++$this->listnum;
  18473. if ($tag['value'] == 'ol') {
  18474. $this->listordered[$this->listnum] = true;
  18475. } else {
  18476. $this->listordered[$this->listnum] = false;
  18477. }
  18478. if (isset($tag['attribute']['start'])) {
  18479. $this->listcount[$this->listnum] = intval($tag['attribute']['start']) - 1;
  18480. } else {
  18481. $this->listcount[$this->listnum] = 0;
  18482. }
  18483. if ($this->rtl) {
  18484. $this->rMargin += $this->listindent;
  18485. $this->x -= $this->listindent;
  18486. } else {
  18487. $this->lMargin += $this->listindent;
  18488. $this->x += $this->listindent;
  18489. }
  18490. ++$this->listindentlevel;
  18491. if ($this->listnum == 1) {
  18492. if ($key > 1) {
  18493. $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
  18494. }
  18495. } else {
  18496. $this->addHTMLVertSpace(0, 0, $cell, $firsttag);
  18497. }
  18498. break;
  18499. }
  18500. case 'li': {
  18501. if ($key > 2) {
  18502. $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
  18503. }
  18504. if ($this->listordered[$this->listnum]) {
  18505. // ordered item
  18506. if (isset($parent['attribute']['type']) AND !TCPDF_STATIC::empty_string($parent['attribute']['type'])) {
  18507. $this->lispacer = $parent['attribute']['type'];
  18508. } elseif (isset($parent['listtype']) AND !TCPDF_STATIC::empty_string($parent['listtype'])) {
  18509. $this->lispacer = $parent['listtype'];
  18510. } elseif (isset($this->lisymbol) AND !TCPDF_STATIC::empty_string($this->lisymbol)) {
  18511. $this->lispacer = $this->lisymbol;
  18512. } else {
  18513. $this->lispacer = '#';
  18514. }
  18515. ++$this->listcount[$this->listnum];
  18516. if (isset($tag['attribute']['value'])) {
  18517. $this->listcount[$this->listnum] = intval($tag['attribute']['value']);
  18518. }
  18519. } else {
  18520. // unordered item
  18521. if (isset($parent['attribute']['type']) AND !TCPDF_STATIC::empty_string($parent['attribute']['type'])) {
  18522. $this->lispacer = $parent['attribute']['type'];
  18523. } elseif (isset($parent['listtype']) AND !TCPDF_STATIC::empty_string($parent['listtype'])) {
  18524. $this->lispacer = $parent['listtype'];
  18525. } elseif (isset($this->lisymbol) AND !TCPDF_STATIC::empty_string($this->lisymbol)) {
  18526. $this->lispacer = $this->lisymbol;
  18527. } else {
  18528. $this->lispacer = '!';
  18529. }
  18530. }
  18531. break;
  18532. }
  18533. case 'blockquote': {
  18534. if ($this->rtl) {
  18535. $this->rMargin += $this->listindent;
  18536. } else {
  18537. $this->lMargin += $this->listindent;
  18538. }
  18539. ++$this->listindentlevel;
  18540. $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
  18541. break;
  18542. }
  18543. case 'br': {
  18544. $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
  18545. break;
  18546. }
  18547. case 'div': {
  18548. $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
  18549. break;
  18550. }
  18551. case 'p': {
  18552. $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
  18553. break;
  18554. }
  18555. case 'pre': {
  18556. $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
  18557. $this->premode = true;
  18558. break;
  18559. }
  18560. case 'sup': {
  18561. $this->SetXY($this->GetX(), $this->GetY() - ((0.7 * $this->FontSizePt) / $this->k));
  18562. break;
  18563. }
  18564. case 'sub': {
  18565. $this->SetXY($this->GetX(), $this->GetY() + ((0.3 * $this->FontSizePt) / $this->k));
  18566. break;
  18567. }
  18568. case 'h1':
  18569. case 'h2':
  18570. case 'h3':
  18571. case 'h4':
  18572. case 'h5':
  18573. case 'h6': {
  18574. $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
  18575. break;
  18576. }
  18577. // Form fields (since 4.8.000 - 2009-09-07)
  18578. case 'form': {
  18579. if (isset($tag['attribute']['action'])) {
  18580. $this->form_action = $tag['attribute']['action'];
  18581. } else {
  18582. $this->Error('Please explicitly set action attribute path!');
  18583. }
  18584. if (isset($tag['attribute']['enctype'])) {
  18585. $this->form_enctype = $tag['attribute']['enctype'];
  18586. } else {
  18587. $this->form_enctype = 'application/x-www-form-urlencoded';
  18588. }
  18589. if (isset($tag['attribute']['method'])) {
  18590. $this->form_mode = $tag['attribute']['method'];
  18591. } else {
  18592. $this->form_mode = 'post';
  18593. }
  18594. break;
  18595. }
  18596. case 'input': {
  18597. if (isset($tag['attribute']['name']) AND !TCPDF_STATIC::empty_string($tag['attribute']['name'])) {
  18598. $name = $tag['attribute']['name'];
  18599. } else {
  18600. break;
  18601. }
  18602. $prop = array();
  18603. $opt = array();
  18604. if (isset($tag['attribute']['readonly']) AND !TCPDF_STATIC::empty_string($tag['attribute']['readonly'])) {
  18605. $prop['readonly'] = true;
  18606. }
  18607. if (isset($tag['attribute']['value']) AND !TCPDF_STATIC::empty_string($tag['attribute']['value'])) {
  18608. $value = $tag['attribute']['value'];
  18609. }
  18610. if (isset($tag['attribute']['maxlength']) AND !TCPDF_STATIC::empty_string($tag['attribute']['maxlength'])) {
  18611. $opt['maxlen'] = intval($tag['attribute']['maxlength']);
  18612. }
  18613. $h = $this->getCellHeight($this->FontSize);
  18614. if (isset($tag['attribute']['size']) AND !TCPDF_STATIC::empty_string($tag['attribute']['size'])) {
  18615. $w = intval($tag['attribute']['size']) * $this->GetStringWidth(chr(32)) * 2;
  18616. } else {
  18617. $w = $h;
  18618. }
  18619. if (isset($tag['attribute']['checked']) AND (($tag['attribute']['checked'] == 'checked') OR ($tag['attribute']['checked'] == 'true'))) {
  18620. $checked = true;
  18621. } else {
  18622. $checked = false;
  18623. }
  18624. if (isset($tag['align'])) {
  18625. switch ($tag['align']) {
  18626. case 'C': {
  18627. $opt['q'] = 1;
  18628. break;
  18629. }
  18630. case 'R': {
  18631. $opt['q'] = 2;
  18632. break;
  18633. }
  18634. case 'L':
  18635. default: {
  18636. break;
  18637. }
  18638. }
  18639. }
  18640. switch ($tag['attribute']['type']) {
  18641. case 'text': {
  18642. if (isset($value)) {
  18643. $opt['v'] = $value;
  18644. }
  18645. $this->TextField($name, $w, $h, $prop, $opt, '', '', false);
  18646. break;
  18647. }
  18648. case 'password': {
  18649. if (isset($value)) {
  18650. $opt['v'] = $value;
  18651. }
  18652. $prop['password'] = 'true';
  18653. $this->TextField($name, $w, $h, $prop, $opt, '', '', false);
  18654. break;
  18655. }
  18656. case 'checkbox': {
  18657. if (!isset($value)) {
  18658. break;
  18659. }
  18660. $this->CheckBox($name, $w, $checked, $prop, $opt, $value, '', '', false);
  18661. break;
  18662. }
  18663. case 'radio': {
  18664. if (!isset($value)) {
  18665. break;
  18666. }
  18667. $this->RadioButton($name, $w, $prop, $opt, $value, $checked, '', '', false);
  18668. break;
  18669. }
  18670. case 'submit': {
  18671. if (!isset($value)) {
  18672. $value = 'submit';
  18673. }
  18674. $w = $this->GetStringWidth($value) * 1.5;
  18675. $h *= 1.6;
  18676. $prop = array('lineWidth'=>1, 'borderStyle'=>'beveled', 'fillColor'=>array(196, 196, 196), 'strokeColor'=>array(255, 255, 255));
  18677. $action = array();
  18678. $action['S'] = 'SubmitForm';
  18679. $action['F'] = $this->form_action;
  18680. if ($this->form_enctype != 'FDF') {
  18681. $action['Flags'] = array('ExportFormat');
  18682. }
  18683. if ($this->form_mode == 'get') {
  18684. $action['Flags'] = array('GetMethod');
  18685. }
  18686. $this->Button($name, $w, $h, $value, $action, $prop, $opt, '', '', false);
  18687. break;
  18688. }
  18689. case 'reset': {
  18690. if (!isset($value)) {
  18691. $value = 'reset';
  18692. }
  18693. $w = $this->GetStringWidth($value) * 1.5;
  18694. $h *= 1.6;
  18695. $prop = array('lineWidth'=>1, 'borderStyle'=>'beveled', 'fillColor'=>array(196, 196, 196), 'strokeColor'=>array(255, 255, 255));
  18696. $this->Button($name, $w, $h, $value, array('S'=>'ResetForm'), $prop, $opt, '', '', false);
  18697. break;
  18698. }
  18699. case 'file': {
  18700. $prop['fileSelect'] = 'true';
  18701. $this->TextField($name, $w, $h, $prop, $opt, '', '', false);
  18702. if (!isset($value)) {
  18703. $value = '*';
  18704. }
  18705. $w = $this->GetStringWidth($value) * 2;
  18706. $h *= 1.2;
  18707. $prop = array('lineWidth'=>1, 'borderStyle'=>'beveled', 'fillColor'=>array(196, 196, 196), 'strokeColor'=>array(255, 255, 255));
  18708. $jsaction = 'var f=this.getField(\''.$name.'\'); f.browseForFileToSubmit();';
  18709. $this->Button('FB_'.$name, $w, $h, $value, $jsaction, $prop, $opt, '', '', false);
  18710. break;
  18711. }
  18712. case 'hidden': {
  18713. if (isset($value)) {
  18714. $opt['v'] = $value;
  18715. }
  18716. $opt['f'] = array('invisible', 'hidden');
  18717. $this->TextField($name, 0, 0, $prop, $opt, '', '', false);
  18718. break;
  18719. }
  18720. case 'image': {
  18721. // THIS TYPE MUST BE FIXED
  18722. if (isset($tag['attribute']['src']) AND !TCPDF_STATIC::empty_string($tag['attribute']['src'])) {
  18723. $img = $tag['attribute']['src'];
  18724. } else {
  18725. break;
  18726. }
  18727. $value = 'img';
  18728. //$opt['mk'] = array('i'=>$img, 'tp'=>1, 'if'=>array('sw'=>'A', 's'=>'A', 'fb'=>false));
  18729. if (isset($tag['attribute']['onclick']) AND !empty($tag['attribute']['onclick'])) {
  18730. $jsaction = $tag['attribute']['onclick'];
  18731. } else {
  18732. $jsaction = '';
  18733. }
  18734. $this->Button($name, $w, $h, $value, $jsaction, $prop, $opt, '', '', false);
  18735. break;
  18736. }
  18737. case 'button': {
  18738. if (!isset($value)) {
  18739. $value = ' ';
  18740. }
  18741. $w = $this->GetStringWidth($value) * 1.5;
  18742. $h *= 1.6;
  18743. $prop = array('lineWidth'=>1, 'borderStyle'=>'beveled', 'fillColor'=>array(196, 196, 196), 'strokeColor'=>array(255, 255, 255));
  18744. if (isset($tag['attribute']['onclick']) AND !empty($tag['attribute']['onclick'])) {
  18745. $jsaction = $tag['attribute']['onclick'];
  18746. } else {
  18747. $jsaction = '';
  18748. }
  18749. $this->Button($name, $w, $h, $value, $jsaction, $prop, $opt, '', '', false);
  18750. break;
  18751. }
  18752. }
  18753. break;
  18754. }
  18755. case 'textarea': {
  18756. $prop = array();
  18757. $opt = array();
  18758. if (isset($tag['attribute']['readonly']) AND !TCPDF_STATIC::empty_string($tag['attribute']['readonly'])) {
  18759. $prop['readonly'] = true;
  18760. }
  18761. if (isset($tag['attribute']['name']) AND !TCPDF_STATIC::empty_string($tag['attribute']['name'])) {
  18762. $name = $tag['attribute']['name'];
  18763. } else {
  18764. break;
  18765. }
  18766. if (isset($tag['attribute']['value']) AND !TCPDF_STATIC::empty_string($tag['attribute']['value'])) {
  18767. $opt['v'] = $tag['attribute']['value'];
  18768. }
  18769. if (isset($tag['attribute']['cols']) AND !TCPDF_STATIC::empty_string($tag['attribute']['cols'])) {
  18770. $w = intval($tag['attribute']['cols']) * $this->GetStringWidth(chr(32)) * 2;
  18771. } else {
  18772. $w = 40;
  18773. }
  18774. if (isset($tag['attribute']['rows']) AND !TCPDF_STATIC::empty_string($tag['attribute']['rows'])) {
  18775. $h = intval($tag['attribute']['rows']) * $this->getCellHeight($this->FontSize);
  18776. } else {
  18777. $h = 10;
  18778. }
  18779. $prop['multiline'] = 'true';
  18780. $this->TextField($name, $w, $h, $prop, $opt, '', '', false);
  18781. break;
  18782. }
  18783. case 'select': {
  18784. $h = $this->getCellHeight($this->FontSize);
  18785. if (isset($tag['attribute']['size']) AND !TCPDF_STATIC::empty_string($tag['attribute']['size'])) {
  18786. $h *= ($tag['attribute']['size'] + 1);
  18787. }
  18788. $prop = array();
  18789. $opt = array();
  18790. if (isset($tag['attribute']['name']) AND !TCPDF_STATIC::empty_string($tag['attribute']['name'])) {
  18791. $name = $tag['attribute']['name'];
  18792. } else {
  18793. break;
  18794. }
  18795. $w = 0;
  18796. if (isset($tag['attribute']['opt']) AND !TCPDF_STATIC::empty_string($tag['attribute']['opt'])) {
  18797. $options = explode('#!NwL!#', $tag['attribute']['opt']);
  18798. $values = array();
  18799. foreach ($options as $val) {
  18800. if (strpos($val, '#!TaB!#') !== false) {
  18801. $opts = explode('#!TaB!#', $val);
  18802. $values[] = $opts;
  18803. $w = max($w, $this->GetStringWidth($opts[1]));
  18804. } else {
  18805. $values[] = $val;
  18806. $w = max($w, $this->GetStringWidth($val));
  18807. }
  18808. }
  18809. } else {
  18810. break;
  18811. }
  18812. $w *= 2;
  18813. if (isset($tag['attribute']['multiple']) AND ($tag['attribute']['multiple']='multiple')) {
  18814. $prop['multipleSelection'] = 'true';
  18815. $this->ListBox($name, $w, $h, $values, $prop, $opt, '', '', false);
  18816. } else {
  18817. $this->ComboBox($name, $w, $h, $values, $prop, $opt, '', '', false);
  18818. }
  18819. break;
  18820. }
  18821. case 'tcpdf': {
  18822. if (defined('K_TCPDF_CALLS_IN_HTML') AND (K_TCPDF_CALLS_IN_HTML === true)) {
  18823. // Special tag used to call TCPDF methods
  18824. if (isset($tag['attribute']['method'])) {
  18825. $tcpdf_method = $tag['attribute']['method'];
  18826. if (method_exists($this, $tcpdf_method)) {
  18827. if (isset($tag['attribute']['params']) AND (!empty($tag['attribute']['params']))) {
  18828. $params = $this->unserializeTCPDFtagParameters($tag['attribute']['params']);
  18829. call_user_func_array(array($this, $tcpdf_method), $params);
  18830. } else {
  18831. $this->$tcpdf_method();
  18832. }
  18833. $this->newline = true;
  18834. }
  18835. }
  18836. }
  18837. break;
  18838. }
  18839. default: {
  18840. break;
  18841. }
  18842. }
  18843. // define tags that support borders and background colors
  18844. $bordertags = array('blockquote','br','dd','dl','div','dt','h1','h2','h3','h4','h5','h6','hr','li','ol','p','pre','ul','tcpdf','table');
  18845. if (in_array($tag['value'], $bordertags)) {
  18846. // set border
  18847. $dom[$key]['borderposition'] = $this->getBorderStartPosition();
  18848. }
  18849. if ($dom[$key]['self'] AND isset($dom[$key]['attribute']['pagebreakafter'])) {
  18850. $pba = $dom[$key]['attribute']['pagebreakafter'];
  18851. // check for pagebreak
  18852. if (($pba == 'true') OR ($pba == 'left') OR ($pba == 'right')) {
  18853. // add a page (or trig AcceptPageBreak() for multicolumn mode)
  18854. $this->checkPageBreak($this->PageBreakTrigger + 1);
  18855. }
  18856. if ((($pba == 'left') AND (((!$this->rtl) AND (($this->page % 2) == 0)) OR (($this->rtl) AND (($this->page % 2) != 0))))
  18857. OR (($pba == 'right') AND (((!$this->rtl) AND (($this->page % 2) != 0)) OR (($this->rtl) AND (($this->page % 2) == 0))))) {
  18858. // add a page (or trig AcceptPageBreak() for multicolumn mode)
  18859. $this->checkPageBreak($this->PageBreakTrigger + 1);
  18860. }
  18861. }
  18862. return $dom;
  18863. }
  18864. /**
  18865. * Process closing tags.
  18866. * @param $dom (array) html dom array
  18867. * @param $key (int) current element id
  18868. * @param $cell (boolean) if true add the default left (or right if RTL) padding to each new line (default false).
  18869. * @param $maxbottomliney (int) maximum y value of current line
  18870. * @return $dom array
  18871. * @protected
  18872. */
  18873. protected function closeHTMLTagHandler($dom, $key, $cell, $maxbottomliney=0) {
  18874. $tag = $dom[$key];
  18875. $parent = $dom[($dom[$key]['parent'])];
  18876. $lasttag = ((!isset($dom[($key + 1)])) OR ((!isset($dom[($key + 2)])) AND ($dom[($key + 1)]['value'] == 'marker')));
  18877. $in_table_head = false;
  18878. // maximum x position (used to draw borders)
  18879. if ($this->rtl) {
  18880. $xmax = $this->w;
  18881. } else {
  18882. $xmax = 0;
  18883. }
  18884. if ($tag['block']) {
  18885. $hbz = 0; // distance from y to line bottom
  18886. $hb = 0; // vertical space between block tags
  18887. // calculate vertical space for block tags
  18888. if (isset($this->tagvspaces[$tag['value']][1]['h']) && !empty($this->tagvspaces[$tag['value']][1]['h']) && ($this->tagvspaces[$tag['value']][1]['h'] >= 0)) {
  18889. $pre_h = $this->tagvspaces[$tag['value']][1]['h'];
  18890. } elseif (isset($parent['fontsize'])) {
  18891. $pre_h = $this->getCellHeight($parent['fontsize'] / $this->k);
  18892. } else {
  18893. $pre_h = $this->getCellHeight($this->FontSize);
  18894. }
  18895. if (isset($this->tagvspaces[$tag['value']][1]['n'])) {
  18896. $cn = $this->tagvspaces[$tag['value']][1]['n'];
  18897. } elseif (preg_match('/[h][0-9]/', $tag['value']) > 0) {
  18898. $cn = 0.6;
  18899. } else {
  18900. $cn = 1;
  18901. }
  18902. if ((!isset($this->tagvspaces[$tag['value']])) AND ($tag['value'] == 'div')) {
  18903. $hb = 0;
  18904. } else {
  18905. $hb = ($cn * $pre_h);
  18906. }
  18907. if ($maxbottomliney > $this->PageBreakTrigger) {
  18908. $hbz = $this->getCellHeight($this->FontSize);
  18909. } elseif ($this->y < $maxbottomliney) {
  18910. $hbz = ($maxbottomliney - $this->y);
  18911. }
  18912. }
  18913. // Closing tag
  18914. switch($tag['value']) {
  18915. case 'tr': {
  18916. $table_el = $dom[($dom[$key]['parent'])]['parent'];
  18917. if (!isset($parent['endy'])) {
  18918. $dom[($dom[$key]['parent'])]['endy'] = $this->y;
  18919. $parent['endy'] = $this->y;
  18920. }
  18921. if (!isset($parent['endpage'])) {
  18922. $dom[($dom[$key]['parent'])]['endpage'] = $this->page;
  18923. $parent['endpage'] = $this->page;
  18924. }
  18925. if (!isset($parent['endcolumn'])) {
  18926. $dom[($dom[$key]['parent'])]['endcolumn'] = $this->current_column;
  18927. $parent['endcolumn'] = $this->current_column;
  18928. }
  18929. // update row-spanned cells
  18930. if (isset($dom[$table_el]['rowspans'])) {
  18931. foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
  18932. $dom[$table_el]['rowspans'][$k]['rowspan'] -= 1;
  18933. if ($dom[$table_el]['rowspans'][$k]['rowspan'] == 0) {
  18934. if (($dom[$table_el]['rowspans'][$k]['endpage'] == $parent['endpage']) AND ($dom[$table_el]['rowspans'][$k]['endcolumn'] == $parent['endcolumn'])) {
  18935. $dom[($dom[$key]['parent'])]['endy'] = max($dom[$table_el]['rowspans'][$k]['endy'], $parent['endy']);
  18936. } elseif (($dom[$table_el]['rowspans'][$k]['endpage'] > $parent['endpage']) OR ($dom[$table_el]['rowspans'][$k]['endcolumn'] > $parent['endcolumn'])) {
  18937. $dom[($dom[$key]['parent'])]['endy'] = $dom[$table_el]['rowspans'][$k]['endy'];
  18938. $dom[($dom[$key]['parent'])]['endpage'] = $dom[$table_el]['rowspans'][$k]['endpage'];
  18939. $dom[($dom[$key]['parent'])]['endcolumn'] = $dom[$table_el]['rowspans'][$k]['endcolumn'];
  18940. }
  18941. }
  18942. }
  18943. // report new endy and endpage to the rowspanned cells
  18944. foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
  18945. if ($dom[$table_el]['rowspans'][$k]['rowspan'] == 0) {
  18946. $dom[$table_el]['rowspans'][$k]['endpage'] = max($dom[$table_el]['rowspans'][$k]['endpage'], $dom[($dom[$key]['parent'])]['endpage']);
  18947. $dom[($dom[$key]['parent'])]['endpage'] = $dom[$table_el]['rowspans'][$k]['endpage'];
  18948. $dom[$table_el]['rowspans'][$k]['endcolumn'] = max($dom[$table_el]['rowspans'][$k]['endcolumn'], $dom[($dom[$key]['parent'])]['endcolumn']);
  18949. $dom[($dom[$key]['parent'])]['endcolumn'] = $dom[$table_el]['rowspans'][$k]['endcolumn'];
  18950. $dom[$table_el]['rowspans'][$k]['endy'] = max($dom[$table_el]['rowspans'][$k]['endy'], $dom[($dom[$key]['parent'])]['endy']);
  18951. $dom[($dom[$key]['parent'])]['endy'] = $dom[$table_el]['rowspans'][$k]['endy'];
  18952. }
  18953. }
  18954. // update remaining rowspanned cells
  18955. foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
  18956. if ($dom[$table_el]['rowspans'][$k]['rowspan'] == 0) {
  18957. $dom[$table_el]['rowspans'][$k]['endpage'] = $dom[($dom[$key]['parent'])]['endpage'];
  18958. $dom[$table_el]['rowspans'][$k]['endcolumn'] = $dom[($dom[$key]['parent'])]['endcolumn'];
  18959. $dom[$table_el]['rowspans'][$k]['endy'] = $dom[($dom[$key]['parent'])]['endy'];
  18960. }
  18961. }
  18962. }
  18963. $prev_page = $this->page;
  18964. $this->setPage($dom[($dom[$key]['parent'])]['endpage']);
  18965. if ($this->num_columns > 1) {
  18966. if (($prev_page < $this->page)
  18967. AND ((($this->current_column == 0) AND ($dom[($dom[$key]['parent'])]['endcolumn'] == ($this->num_columns - 1)))
  18968. OR ($this->current_column == $dom[($dom[$key]['parent'])]['endcolumn']))) {
  18969. // page jump
  18970. $this->selectColumn(0);
  18971. $dom[($dom[$key]['parent'])]['endcolumn'] = 0;
  18972. $dom[($dom[$key]['parent'])]['endy'] = $this->y;
  18973. } else {
  18974. $this->selectColumn($dom[($dom[$key]['parent'])]['endcolumn']);
  18975. $this->y = $dom[($dom[$key]['parent'])]['endy'];
  18976. }
  18977. } else {
  18978. $this->y = $dom[($dom[$key]['parent'])]['endy'];
  18979. }
  18980. if (isset($dom[$table_el]['attribute']['cellspacing'])) {
  18981. $this->y += $this->getHTMLUnitToUnits($dom[$table_el]['attribute']['cellspacing'], 1, 'px');
  18982. } elseif (isset($dom[$table_el]['border-spacing'])) {
  18983. $this->y += $dom[$table_el]['border-spacing']['V'];
  18984. }
  18985. $this->Ln(0, $cell);
  18986. if ($this->current_column == $parent['startcolumn']) {
  18987. $this->x = $parent['startx'];
  18988. }
  18989. // account for booklet mode
  18990. if ($this->page > $parent['startpage']) {
  18991. if (($this->rtl) AND ($this->pagedim[$this->page]['orm'] != $this->pagedim[$parent['startpage']]['orm'])) {
  18992. $this->x -= ($this->pagedim[$this->page]['orm'] - $this->pagedim[$parent['startpage']]['orm']);
  18993. } elseif ((!$this->rtl) AND ($this->pagedim[$this->page]['olm'] != $this->pagedim[$parent['startpage']]['olm'])) {
  18994. $this->x += ($this->pagedim[$this->page]['olm'] - $this->pagedim[$parent['startpage']]['olm']);
  18995. }
  18996. }
  18997. break;
  18998. }
  18999. case 'tablehead':
  19000. // closing tag used for the thead part
  19001. $in_table_head = true;
  19002. $this->inthead = false;
  19003. case 'table': {
  19004. $table_el = $parent;
  19005. // set default border
  19006. if (isset($table_el['attribute']['border']) AND ($table_el['attribute']['border'] > 0)) {
  19007. // set default border
  19008. $border = array('LTRB' => array('width' => $this->getCSSBorderWidth($table_el['attribute']['border']), 'cap'=>'square', 'join'=>'miter', 'dash'=> 0, 'color'=>array(0,0,0)));
  19009. } else {
  19010. $border = 0;
  19011. }
  19012. $default_border = $border;
  19013. // fix bottom line alignment of last line before page break
  19014. foreach ($dom[($dom[$key]['parent'])]['trids'] as $j => $trkey) {
  19015. // update row-spanned cells
  19016. if (isset($dom[($dom[$key]['parent'])]['rowspans'])) {
  19017. foreach ($dom[($dom[$key]['parent'])]['rowspans'] as $k => $trwsp) {
  19018. if (isset($prevtrkey) AND ($trwsp['trid'] == $prevtrkey) AND ($trwsp['mrowspan'] > 0)) {
  19019. $dom[($dom[$key]['parent'])]['rowspans'][$k]['trid'] = $trkey;
  19020. }
  19021. if ($dom[($dom[$key]['parent'])]['rowspans'][$k]['trid'] == $trkey) {
  19022. $dom[($dom[$key]['parent'])]['rowspans'][$k]['mrowspan'] -= 1;
  19023. }
  19024. }
  19025. }
  19026. if (isset($prevtrkey) AND ($dom[$trkey]['startpage'] > $dom[$prevtrkey]['endpage'])) {
  19027. $pgendy = $this->pagedim[$dom[$prevtrkey]['endpage']]['hk'] - $this->pagedim[$dom[$prevtrkey]['endpage']]['bm'];
  19028. $dom[$prevtrkey]['endy'] = $pgendy;
  19029. // update row-spanned cells
  19030. if (isset($dom[($dom[$key]['parent'])]['rowspans'])) {
  19031. foreach ($dom[($dom[$key]['parent'])]['rowspans'] as $k => $trwsp) {
  19032. if (($trwsp['trid'] == $prevtrkey) AND ($trwsp['mrowspan'] >= 0) AND ($trwsp['endpage'] == $dom[$prevtrkey]['endpage'])) {
  19033. $dom[($dom[$key]['parent'])]['rowspans'][$k]['endy'] = $pgendy;
  19034. $dom[($dom[$key]['parent'])]['rowspans'][$k]['mrowspan'] = -1;
  19035. }
  19036. }
  19037. }
  19038. }
  19039. $prevtrkey = $trkey;
  19040. $table_el = $dom[($dom[$key]['parent'])];
  19041. }
  19042. // for each row
  19043. if (count($table_el['trids']) > 0) {
  19044. unset($xmax);
  19045. }
  19046. foreach ($table_el['trids'] as $j => $trkey) {
  19047. $parent = $dom[$trkey];
  19048. if (!isset($xmax)) {
  19049. $xmax = $parent['cellpos'][(count($parent['cellpos']) - 1)]['endx'];
  19050. }
  19051. // for each cell on the row
  19052. foreach ($parent['cellpos'] as $k => $cellpos) {
  19053. if (isset($cellpos['rowspanid']) AND ($cellpos['rowspanid'] >= 0)) {
  19054. $cellpos['startx'] = $table_el['rowspans'][($cellpos['rowspanid'])]['startx'];
  19055. $cellpos['endx'] = $table_el['rowspans'][($cellpos['rowspanid'])]['endx'];
  19056. $endy = $table_el['rowspans'][($cellpos['rowspanid'])]['endy'];
  19057. $startpage = $table_el['rowspans'][($cellpos['rowspanid'])]['startpage'];
  19058. $endpage = $table_el['rowspans'][($cellpos['rowspanid'])]['endpage'];
  19059. $startcolumn = $table_el['rowspans'][($cellpos['rowspanid'])]['startcolumn'];
  19060. $endcolumn = $table_el['rowspans'][($cellpos['rowspanid'])]['endcolumn'];
  19061. } else {
  19062. $endy = $parent['endy'];
  19063. $startpage = $parent['startpage'];
  19064. $endpage = $parent['endpage'];
  19065. $startcolumn = $parent['startcolumn'];
  19066. $endcolumn = $parent['endcolumn'];
  19067. }
  19068. if ($this->num_columns == 0) {
  19069. $this->num_columns = 1;
  19070. }
  19071. if (isset($cellpos['border'])) {
  19072. $border = $cellpos['border'];
  19073. }
  19074. if (isset($cellpos['bgcolor']) AND ($cellpos['bgcolor']) !== false) {
  19075. $this->SetFillColorArray($cellpos['bgcolor']);
  19076. $fill = true;
  19077. } else {
  19078. $fill = false;
  19079. }
  19080. $x = $cellpos['startx'];
  19081. $y = $parent['starty'];
  19082. $starty = $y;
  19083. $w = abs($cellpos['endx'] - $cellpos['startx']);
  19084. // get border modes
  19085. $border_start = TCPDF_STATIC::getBorderMode($border, $position='start', $this->opencell);
  19086. $border_end = TCPDF_STATIC::getBorderMode($border, $position='end', $this->opencell);
  19087. $border_middle = TCPDF_STATIC::getBorderMode($border, $position='middle', $this->opencell);
  19088. // design borders around HTML cells.
  19089. for ($page = $startpage; $page <= $endpage; ++$page) { // for each page
  19090. $ccode = '';
  19091. $this->setPage($page);
  19092. if ($this->num_columns < 2) {
  19093. // single-column mode
  19094. $this->x = $x;
  19095. $this->y = $this->tMargin;
  19096. }
  19097. // account for margin changes
  19098. if ($page > $startpage) {
  19099. if (($this->rtl) AND ($this->pagedim[$page]['orm'] != $this->pagedim[$startpage]['orm'])) {
  19100. $this->x -= ($this->pagedim[$page]['orm'] - $this->pagedim[$startpage]['orm']);
  19101. } elseif ((!$this->rtl) AND ($this->pagedim[$page]['olm'] != $this->pagedim[$startpage]['olm'])) {
  19102. $this->x += ($this->pagedim[$page]['olm'] - $this->pagedim[$startpage]['olm']);
  19103. }
  19104. }
  19105. if ($startpage == $endpage) { // single page
  19106. $deltacol = 0;
  19107. $deltath = 0;
  19108. for ($column = $startcolumn; $column <= $endcolumn; ++$column) { // for each column
  19109. $this->selectColumn($column);
  19110. if ($startcolumn == $endcolumn) { // single column
  19111. $cborder = $border;
  19112. $h = $endy - $parent['starty'];
  19113. $this->y = $y;
  19114. $this->x = $x;
  19115. } elseif ($column == $startcolumn) { // first column
  19116. $cborder = $border_start;
  19117. $this->y = $starty;
  19118. $this->x = $x;
  19119. $h = $this->h - $this->y - $this->bMargin;
  19120. if ($this->rtl) {
  19121. $deltacol = $this->x + $this->rMargin - $this->w;
  19122. } else {
  19123. $deltacol = $this->x - $this->lMargin;
  19124. }
  19125. } elseif ($column == $endcolumn) { // end column
  19126. $cborder = $border_end;
  19127. if (isset($this->columns[$column]['th']['\''.$page.'\''])) {
  19128. $this->y = $this->columns[$column]['th']['\''.$page.'\''];
  19129. }
  19130. $this->x += $deltacol;
  19131. $h = $endy - $this->y;
  19132. } else { // middle column
  19133. $cborder = $border_middle;
  19134. if (isset($this->columns[$column]['th']['\''.$page.'\''])) {
  19135. $this->y = $this->columns[$column]['th']['\''.$page.'\''];
  19136. }
  19137. $this->x += $deltacol;
  19138. $h = $this->h - $this->y - $this->bMargin;
  19139. }
  19140. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  19141. } // end for each column
  19142. } elseif ($page == $startpage) { // first page
  19143. $deltacol = 0;
  19144. $deltath = 0;
  19145. for ($column = $startcolumn; $column < $this->num_columns; ++$column) { // for each column
  19146. $this->selectColumn($column);
  19147. if ($column == $startcolumn) { // first column
  19148. $cborder = $border_start;
  19149. $this->y = $starty;
  19150. $this->x = $x;
  19151. $h = $this->h - $this->y - $this->bMargin;
  19152. if ($this->rtl) {
  19153. $deltacol = $this->x + $this->rMargin - $this->w;
  19154. } else {
  19155. $deltacol = $this->x - $this->lMargin;
  19156. }
  19157. } else { // middle column
  19158. $cborder = $border_middle;
  19159. if (isset($this->columns[$column]['th']['\''.$page.'\''])) {
  19160. $this->y = $this->columns[$column]['th']['\''.$page.'\''];
  19161. }
  19162. $this->x += $deltacol;
  19163. $h = $this->h - $this->y - $this->bMargin;
  19164. }
  19165. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  19166. } // end for each column
  19167. } elseif ($page == $endpage) { // last page
  19168. $deltacol = 0;
  19169. $deltath = 0;
  19170. for ($column = 0; $column <= $endcolumn; ++$column) { // for each column
  19171. $this->selectColumn($column);
  19172. if ($column == $endcolumn) { // end column
  19173. $cborder = $border_end;
  19174. if (isset($this->columns[$column]['th']['\''.$page.'\''])) {
  19175. $this->y = $this->columns[$column]['th']['\''.$page.'\''];
  19176. }
  19177. $this->x += $deltacol;
  19178. $h = $endy - $this->y;
  19179. } else { // middle column
  19180. $cborder = $border_middle;
  19181. if (isset($this->columns[$column]['th']['\''.$page.'\''])) {
  19182. $this->y = $this->columns[$column]['th']['\''.$page.'\''];
  19183. }
  19184. $this->x += $deltacol;
  19185. $h = $this->h - $this->y - $this->bMargin;
  19186. }
  19187. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  19188. } // end for each column
  19189. } else { // middle page
  19190. $deltacol = 0;
  19191. $deltath = 0;
  19192. for ($column = 0; $column < $this->num_columns; ++$column) { // for each column
  19193. $this->selectColumn($column);
  19194. $cborder = $border_middle;
  19195. if (isset($this->columns[$column]['th']['\''.$page.'\''])) {
  19196. $this->y = $this->columns[$column]['th']['\''.$page.'\''];
  19197. }
  19198. $this->x += $deltacol;
  19199. $h = $this->h - $this->y - $this->bMargin;
  19200. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  19201. } // end for each column
  19202. }
  19203. if (!empty($cborder) OR !empty($fill)) {
  19204. $offsetlen = strlen($ccode);
  19205. // draw border and fill
  19206. if ($this->inxobj) {
  19207. // we are inside an XObject template
  19208. if (end($this->xobjects[$this->xobjid]['transfmrk']) !== false) {
  19209. $pagemarkkey = key($this->xobjects[$this->xobjid]['transfmrk']);
  19210. $pagemark = $this->xobjects[$this->xobjid]['transfmrk'][$pagemarkkey];
  19211. $this->xobjects[$this->xobjid]['transfmrk'][$pagemarkkey] += $offsetlen;
  19212. } else {
  19213. $pagemark = $this->xobjects[$this->xobjid]['intmrk'];
  19214. $this->xobjects[$this->xobjid]['intmrk'] += $offsetlen;
  19215. }
  19216. $pagebuff = $this->xobjects[$this->xobjid]['outdata'];
  19217. $pstart = substr($pagebuff, 0, $pagemark);
  19218. $pend = substr($pagebuff, $pagemark);
  19219. $this->xobjects[$this->xobjid]['outdata'] = $pstart.$ccode.$pend;
  19220. } else {
  19221. // draw border and fill
  19222. if (end($this->transfmrk[$this->page]) !== false) {
  19223. $pagemarkkey = key($this->transfmrk[$this->page]);
  19224. $pagemark = $this->transfmrk[$this->page][$pagemarkkey];
  19225. } elseif ($this->InFooter) {
  19226. $pagemark = $this->footerpos[$this->page];
  19227. } else {
  19228. $pagemark = $this->intmrk[$this->page];
  19229. }
  19230. $pagebuff = $this->getPageBuffer($this->page);
  19231. $pstart = substr($pagebuff, 0, $pagemark);
  19232. $pend = substr($pagebuff, $pagemark);
  19233. $this->setPageBuffer($this->page, $pstart.$ccode.$pend);
  19234. }
  19235. }
  19236. } // end for each page
  19237. // restore default border
  19238. $border = $default_border;
  19239. } // end for each cell on the row
  19240. if (isset($table_el['attribute']['cellspacing'])) {
  19241. $this->y += $this->getHTMLUnitToUnits($table_el['attribute']['cellspacing'], 1, 'px');
  19242. } elseif (isset($table_el['border-spacing'])) {
  19243. $this->y += $table_el['border-spacing']['V'];
  19244. }
  19245. $this->Ln(0, $cell);
  19246. $this->x = $parent['startx'];
  19247. if ($endpage > $startpage) {
  19248. if (($this->rtl) AND ($this->pagedim[$endpage]['orm'] != $this->pagedim[$startpage]['orm'])) {
  19249. $this->x += ($this->pagedim[$endpage]['orm'] - $this->pagedim[$startpage]['orm']);
  19250. } elseif ((!$this->rtl) AND ($this->pagedim[$endpage]['olm'] != $this->pagedim[$startpage]['olm'])) {
  19251. $this->x += ($this->pagedim[$endpage]['olm'] - $this->pagedim[$startpage]['olm']);
  19252. }
  19253. }
  19254. }
  19255. if (!$in_table_head) { // we are not inside a thead section
  19256. $this->cell_padding = isset($table_el['old_cell_padding']) ? $table_el['old_cell_padding'] : null;
  19257. // reset row height
  19258. $this->resetLastH();
  19259. if (($this->page == ($this->numpages - 1)) AND ($this->pageopen[$this->numpages])) {
  19260. $plendiff = ($this->pagelen[$this->numpages] - $this->emptypagemrk[$this->numpages]);
  19261. if (($plendiff > 0) AND ($plendiff < 60)) {
  19262. $pagediff = substr($this->getPageBuffer($this->numpages), $this->emptypagemrk[$this->numpages], $plendiff);
  19263. if (substr($pagediff, 0, 5) == 'BT /F') {
  19264. // the difference is only a font setting
  19265. $plendiff = 0;
  19266. }
  19267. }
  19268. if ($plendiff == 0) {
  19269. // remove last blank page
  19270. $this->deletePage($this->numpages);
  19271. }
  19272. }
  19273. if (isset($this->theadMargins['top'])) {
  19274. // restore top margin
  19275. $this->tMargin = $this->theadMargins['top'];
  19276. }
  19277. if (!isset($table_el['attribute']['nested']) OR ($table_el['attribute']['nested'] != 'true')) {
  19278. // reset main table header
  19279. $this->thead = '';
  19280. $this->theadMargins = array();
  19281. $this->pagedim[$this->page]['tm'] = $this->tMargin;
  19282. }
  19283. }
  19284. $parent = $table_el;
  19285. break;
  19286. }
  19287. case 'a': {
  19288. $this->HREF = array();
  19289. break;
  19290. }
  19291. case 'sup': {
  19292. $this->SetXY($this->GetX(), $this->GetY() + ((0.7 * $parent['fontsize']) / $this->k));
  19293. break;
  19294. }
  19295. case 'sub': {
  19296. $this->SetXY($this->GetX(), $this->GetY() - ((0.3 * $parent['fontsize']) / $this->k));
  19297. break;
  19298. }
  19299. case 'div': {
  19300. $this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
  19301. break;
  19302. }
  19303. case 'blockquote': {
  19304. if ($this->rtl) {
  19305. $this->rMargin -= $this->listindent;
  19306. } else {
  19307. $this->lMargin -= $this->listindent;
  19308. }
  19309. --$this->listindentlevel;
  19310. $this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
  19311. break;
  19312. }
  19313. case 'p': {
  19314. $this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
  19315. break;
  19316. }
  19317. case 'pre': {
  19318. $this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
  19319. $this->premode = false;
  19320. break;
  19321. }
  19322. case 'dl': {
  19323. --$this->listnum;
  19324. if ($this->listnum <= 0) {
  19325. $this->listnum = 0;
  19326. $this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
  19327. } else {
  19328. $this->addHTMLVertSpace(0, 0, $cell, false, $lasttag);
  19329. }
  19330. $this->resetLastH();
  19331. break;
  19332. }
  19333. case 'dt': {
  19334. $this->lispacer = '';
  19335. $this->addHTMLVertSpace(0, 0, $cell, false, $lasttag);
  19336. break;
  19337. }
  19338. case 'dd': {
  19339. $this->lispacer = '';
  19340. if ($this->rtl) {
  19341. $this->rMargin -= $this->listindent;
  19342. } else {
  19343. $this->lMargin -= $this->listindent;
  19344. }
  19345. --$this->listindentlevel;
  19346. $this->addHTMLVertSpace(0, 0, $cell, false, $lasttag);
  19347. break;
  19348. }
  19349. case 'ul':
  19350. case 'ol': {
  19351. --$this->listnum;
  19352. $this->lispacer = '';
  19353. if ($this->rtl) {
  19354. $this->rMargin -= $this->listindent;
  19355. } else {
  19356. $this->lMargin -= $this->listindent;
  19357. }
  19358. --$this->listindentlevel;
  19359. if ($this->listnum <= 0) {
  19360. $this->listnum = 0;
  19361. $this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
  19362. } else {
  19363. $this->addHTMLVertSpace(0, 0, $cell, false, $lasttag);
  19364. }
  19365. $this->resetLastH();
  19366. break;
  19367. }
  19368. case 'li': {
  19369. $this->lispacer = '';
  19370. $this->addHTMLVertSpace(0, 0, $cell, false, $lasttag);
  19371. break;
  19372. }
  19373. case 'h1':
  19374. case 'h2':
  19375. case 'h3':
  19376. case 'h4':
  19377. case 'h5':
  19378. case 'h6': {
  19379. $this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
  19380. break;
  19381. }
  19382. // Form fields (since 4.8.000 - 2009-09-07)
  19383. case 'form': {
  19384. $this->form_action = '';
  19385. $this->form_enctype = 'application/x-www-form-urlencoded';
  19386. break;
  19387. }
  19388. default : {
  19389. break;
  19390. }
  19391. }
  19392. // draw border and background (if any)
  19393. $this->drawHTMLTagBorder($parent, $xmax);
  19394. if (isset($dom[($dom[$key]['parent'])]['attribute']['pagebreakafter'])) {
  19395. $pba = $dom[($dom[$key]['parent'])]['attribute']['pagebreakafter'];
  19396. // check for pagebreak
  19397. if (($pba == 'true') OR ($pba == 'left') OR ($pba == 'right')) {
  19398. // add a page (or trig AcceptPageBreak() for multicolumn mode)
  19399. $this->checkPageBreak($this->PageBreakTrigger + 1);
  19400. }
  19401. if ((($pba == 'left') AND (((!$this->rtl) AND (($this->page % 2) == 0)) OR (($this->rtl) AND (($this->page % 2) != 0))))
  19402. OR (($pba == 'right') AND (((!$this->rtl) AND (($this->page % 2) != 0)) OR (($this->rtl) AND (($this->page % 2) == 0))))) {
  19403. // add a page (or trig AcceptPageBreak() for multicolumn mode)
  19404. $this->checkPageBreak($this->PageBreakTrigger + 1);
  19405. }
  19406. }
  19407. $this->tmprtl = false;
  19408. return $dom;
  19409. }
  19410. /**
  19411. * Add vertical spaces if needed.
  19412. * @param $hbz (string) Distance between current y and line bottom.
  19413. * @param $hb (string) The height of the break.
  19414. * @param $cell (boolean) if true add the default left (or right if RTL) padding to each new line (default false).
  19415. * @param $firsttag (boolean) set to true when the tag is the first.
  19416. * @param $lasttag (boolean) set to true when the tag is the last.
  19417. * @protected
  19418. */
  19419. protected function addHTMLVertSpace($hbz=0, $hb=0, $cell=false, $firsttag=false, $lasttag=false) {
  19420. if ($firsttag) {
  19421. $this->Ln(0, $cell);
  19422. $this->htmlvspace = 0;
  19423. return;
  19424. }
  19425. if ($lasttag) {
  19426. $this->Ln($hbz, $cell);
  19427. $this->htmlvspace = 0;
  19428. return;
  19429. }
  19430. if ($hb < $this->htmlvspace) {
  19431. $hd = 0;
  19432. } else {
  19433. $hd = $hb - $this->htmlvspace;
  19434. $this->htmlvspace = $hb;
  19435. }
  19436. $this->Ln(($hbz + $hd), $cell);
  19437. }
  19438. /**
  19439. * Return the starting coordinates to draw an html border
  19440. * @return array containing top-left border coordinates
  19441. * @protected
  19442. * @since 5.7.000 (2010-08-03)
  19443. */
  19444. protected function getBorderStartPosition() {
  19445. if ($this->rtl) {
  19446. $xmax = $this->lMargin;
  19447. } else {
  19448. $xmax = $this->w - $this->rMargin;
  19449. }
  19450. return array('page' => $this->page, 'column' => $this->current_column, 'x' => $this->x, 'y' => $this->y, 'xmax' => $xmax);
  19451. }
  19452. /**
  19453. * Draw an HTML block border and fill
  19454. * @param $tag (array) array of tag properties.
  19455. * @param $xmax (int) end X coordinate for border.
  19456. * @protected
  19457. * @since 5.7.000 (2010-08-03)
  19458. */
  19459. protected function drawHTMLTagBorder($tag, $xmax) {
  19460. if (!isset($tag['borderposition'])) {
  19461. // nothing to draw
  19462. return;
  19463. }
  19464. $prev_x = $this->x;
  19465. $prev_y = $this->y;
  19466. $prev_lasth = $this->lasth;
  19467. $border = 0;
  19468. $fill = false;
  19469. $this->lasth = 0;
  19470. if (isset($tag['border']) AND !empty($tag['border'])) {
  19471. // get border style
  19472. $border = $tag['border'];
  19473. if (!TCPDF_STATIC::empty_string($this->thead) AND (!$this->inthead)) {
  19474. // border for table header
  19475. $border = TCPDF_STATIC::getBorderMode($border, $position='middle', $this->opencell);
  19476. }
  19477. }
  19478. if (isset($tag['bgcolor']) AND ($tag['bgcolor'] !== false)) {
  19479. // get background color
  19480. $old_bgcolor = $this->bgcolor;
  19481. $this->SetFillColorArray($tag['bgcolor']);
  19482. $fill = true;
  19483. }
  19484. if (!$border AND !$fill) {
  19485. // nothing to draw
  19486. return;
  19487. }
  19488. if (isset($tag['attribute']['cellspacing'])) {
  19489. $clsp = $this->getHTMLUnitToUnits($tag['attribute']['cellspacing'], 1, 'px');
  19490. $cellspacing = array('H' => $clsp, 'V' => $clsp);
  19491. } elseif (isset($tag['border-spacing'])) {
  19492. $cellspacing = $tag['border-spacing'];
  19493. } else {
  19494. $cellspacing = array('H' => 0, 'V' => 0);
  19495. }
  19496. if (($tag['value'] != 'table') AND (is_array($border)) AND (!empty($border))) {
  19497. // draw the border externally respect the sqare edge.
  19498. $border['mode'] = 'ext';
  19499. }
  19500. if ($this->rtl) {
  19501. if ($xmax >= $tag['borderposition']['x']) {
  19502. $xmax = $tag['borderposition']['xmax'];
  19503. }
  19504. $w = ($tag['borderposition']['x'] - $xmax);
  19505. } else {
  19506. if ($xmax <= $tag['borderposition']['x']) {
  19507. $xmax = $tag['borderposition']['xmax'];
  19508. }
  19509. $w = ($xmax - $tag['borderposition']['x']);
  19510. }
  19511. if ($w <= 0) {
  19512. return;
  19513. }
  19514. $w += $cellspacing['H'];
  19515. $startpage = $tag['borderposition']['page'];
  19516. $startcolumn = $tag['borderposition']['column'];
  19517. $x = $tag['borderposition']['x'];
  19518. $y = $tag['borderposition']['y'];
  19519. $endpage = $this->page;
  19520. $starty = $tag['borderposition']['y'] - $cellspacing['V'];
  19521. $currentY = $this->y;
  19522. $this->x = $x;
  19523. // get latest column
  19524. $endcolumn = $this->current_column;
  19525. if ($this->num_columns == 0) {
  19526. $this->num_columns = 1;
  19527. }
  19528. // get border modes
  19529. $border_start = TCPDF_STATIC::getBorderMode($border, $position='start', $this->opencell);
  19530. $border_end = TCPDF_STATIC::getBorderMode($border, $position='end', $this->opencell);
  19531. $border_middle = TCPDF_STATIC::getBorderMode($border, $position='middle', $this->opencell);
  19532. // temporary disable page regions
  19533. $temp_page_regions = $this->page_regions;
  19534. $this->page_regions = array();
  19535. // design borders around HTML cells.
  19536. for ($page = $startpage; $page <= $endpage; ++$page) { // for each page
  19537. $ccode = '';
  19538. $this->setPage($page);
  19539. if ($this->num_columns < 2) {
  19540. // single-column mode
  19541. $this->x = $x;
  19542. $this->y = $this->tMargin;
  19543. }
  19544. // account for margin changes
  19545. if ($page > $startpage) {
  19546. if (($this->rtl) AND ($this->pagedim[$page]['orm'] != $this->pagedim[$startpage]['orm'])) {
  19547. $this->x -= ($this->pagedim[$page]['orm'] - $this->pagedim[$startpage]['orm']);
  19548. } elseif ((!$this->rtl) AND ($this->pagedim[$page]['olm'] != $this->pagedim[$startpage]['olm'])) {
  19549. $this->x += ($this->pagedim[$page]['olm'] - $this->pagedim[$startpage]['olm']);
  19550. }
  19551. }
  19552. if ($startpage == $endpage) {
  19553. // single page
  19554. for ($column = $startcolumn; $column <= $endcolumn; ++$column) { // for each column
  19555. $this->selectColumn($column);
  19556. if ($startcolumn == $endcolumn) { // single column
  19557. $cborder = $border;
  19558. $h = ($currentY - $y) + $cellspacing['V'];
  19559. $this->y = $starty;
  19560. } elseif ($column == $startcolumn) { // first column
  19561. $cborder = $border_start;
  19562. $this->y = $starty;
  19563. $h = $this->h - $this->y - $this->bMargin;
  19564. } elseif ($column == $endcolumn) { // end column
  19565. $cborder = $border_end;
  19566. $h = $currentY - $this->y;
  19567. } else { // middle column
  19568. $cborder = $border_middle;
  19569. $h = $this->h - $this->y - $this->bMargin;
  19570. }
  19571. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  19572. } // end for each column
  19573. } elseif ($page == $startpage) { // first page
  19574. for ($column = $startcolumn; $column < $this->num_columns; ++$column) { // for each column
  19575. $this->selectColumn($column);
  19576. if ($column == $startcolumn) { // first column
  19577. $cborder = $border_start;
  19578. $this->y = $starty;
  19579. $h = $this->h - $this->y - $this->bMargin;
  19580. } else { // middle column
  19581. $cborder = $border_middle;
  19582. $h = $this->h - $this->y - $this->bMargin;
  19583. }
  19584. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  19585. } // end for each column
  19586. } elseif ($page == $endpage) { // last page
  19587. for ($column = 0; $column <= $endcolumn; ++$column) { // for each column
  19588. $this->selectColumn($column);
  19589. if ($column == $endcolumn) {
  19590. // end column
  19591. $cborder = $border_end;
  19592. $h = $currentY - $this->y;
  19593. } else {
  19594. // middle column
  19595. $cborder = $border_middle;
  19596. $h = $this->h - $this->y - $this->bMargin;
  19597. }
  19598. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  19599. } // end for each column
  19600. } else { // middle page
  19601. for ($column = 0; $column < $this->num_columns; ++$column) { // for each column
  19602. $this->selectColumn($column);
  19603. $cborder = $border_middle;
  19604. $h = $this->h - $this->y - $this->bMargin;
  19605. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  19606. } // end for each column
  19607. }
  19608. if ($cborder OR $fill) {
  19609. $offsetlen = strlen($ccode);
  19610. // draw border and fill
  19611. if ($this->inxobj) {
  19612. // we are inside an XObject template
  19613. if (end($this->xobjects[$this->xobjid]['transfmrk']) !== false) {
  19614. $pagemarkkey = key($this->xobjects[$this->xobjid]['transfmrk']);
  19615. $pagemark = $this->xobjects[$this->xobjid]['transfmrk'][$pagemarkkey];
  19616. $this->xobjects[$this->xobjid]['transfmrk'][$pagemarkkey] += $offsetlen;
  19617. } else {
  19618. $pagemark = $this->xobjects[$this->xobjid]['intmrk'];
  19619. $this->xobjects[$this->xobjid]['intmrk'] += $offsetlen;
  19620. }
  19621. $pagebuff = $this->xobjects[$this->xobjid]['outdata'];
  19622. $pstart = substr($pagebuff, 0, $pagemark);
  19623. $pend = substr($pagebuff, $pagemark);
  19624. $this->xobjects[$this->xobjid]['outdata'] = $pstart.$ccode.$pend;
  19625. } else {
  19626. if (end($this->transfmrk[$this->page]) !== false) {
  19627. $pagemarkkey = key($this->transfmrk[$this->page]);
  19628. $pagemark = $this->transfmrk[$this->page][$pagemarkkey];
  19629. } elseif ($this->InFooter) {
  19630. $pagemark = $this->footerpos[$this->page];
  19631. } else {
  19632. $pagemark = $this->intmrk[$this->page];
  19633. }
  19634. $pagebuff = $this->getPageBuffer($this->page);
  19635. $pstart = substr($pagebuff, 0, $pagemark);
  19636. $pend = substr($pagebuff, $pagemark);
  19637. $this->setPageBuffer($this->page, $pstart.$ccode.$pend);
  19638. $this->bordermrk[$this->page] += $offsetlen;
  19639. $this->cntmrk[$this->page] += $offsetlen;
  19640. }
  19641. }
  19642. } // end for each page
  19643. // restore page regions
  19644. $this->page_regions = $temp_page_regions;
  19645. if (isset($old_bgcolor)) {
  19646. // restore background color
  19647. $this->SetFillColorArray($old_bgcolor);
  19648. }
  19649. // restore pointer position
  19650. $this->x = $prev_x;
  19651. $this->y = $prev_y;
  19652. $this->lasth = $prev_lasth;
  19653. }
  19654. /**
  19655. * Set the default bullet to be used as LI bullet symbol
  19656. * @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')
  19657. * @public
  19658. * @since 4.0.028 (2008-09-26)
  19659. */
  19660. public function setLIsymbol($symbol='!') {
  19661. // check for custom image symbol
  19662. if (substr($symbol, 0, 4) == 'img|') {
  19663. $this->lisymbol = $symbol;
  19664. return;
  19665. }
  19666. $symbol = strtolower($symbol);
  19667. $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');
  19668. if (in_array($symbol, $valid_symbols)) {
  19669. $this->lisymbol = $symbol;
  19670. } else {
  19671. $this->lisymbol = '';
  19672. }
  19673. }
  19674. /**
  19675. * Set the booklet mode for double-sided pages.
  19676. * @param $booklet (boolean) true set the booklet mode on, false otherwise.
  19677. * @param $inner (float) Inner page margin.
  19678. * @param $outer (float) Outer page margin.
  19679. * @public
  19680. * @since 4.2.000 (2008-10-29)
  19681. */
  19682. public function SetBooklet($booklet=true, $inner=-1, $outer=-1) {
  19683. $this->booklet = $booklet;
  19684. if ($inner >= 0) {
  19685. $this->lMargin = $inner;
  19686. }
  19687. if ($outer >= 0) {
  19688. $this->rMargin = $outer;
  19689. }
  19690. }
  19691. /**
  19692. * Swap the left and right margins.
  19693. * @param $reverse (boolean) if true swap left and right margins.
  19694. * @protected
  19695. * @since 4.2.000 (2008-10-29)
  19696. */
  19697. protected function swapMargins($reverse=true) {
  19698. if ($reverse) {
  19699. // swap left and right margins
  19700. $mtemp = $this->original_lMargin;
  19701. $this->original_lMargin = $this->original_rMargin;
  19702. $this->original_rMargin = $mtemp;
  19703. $deltam = $this->original_lMargin - $this->original_rMargin;
  19704. $this->lMargin += $deltam;
  19705. $this->rMargin -= $deltam;
  19706. }
  19707. }
  19708. /**
  19709. * Set the vertical spaces for HTML tags.
  19710. * The array must have the following structure (example):
  19711. * $tagvs = array('h1' => array(0 => array('h' => '', 'n' => 2), 1 => array('h' => 1.3, 'n' => 1)));
  19712. * The first array level contains the tag names,
  19713. * the second level contains 0 for opening tags or 1 for closing tags,
  19714. * the third level contains the vertical space unit (h) and the number spaces to add (n).
  19715. * If the h parameter is not specified, default values are used.
  19716. * @param $tagvs (array) array of tags and relative vertical spaces.
  19717. * @public
  19718. * @since 4.2.001 (2008-10-30)
  19719. */
  19720. public function setHtmlVSpace($tagvs) {
  19721. $this->tagvspaces = $tagvs;
  19722. }
  19723. /**
  19724. * Set custom width for list indentation.
  19725. * @param $width (float) width of the indentation. Use negative value to disable it.
  19726. * @public
  19727. * @since 4.2.007 (2008-11-12)
  19728. */
  19729. public function setListIndentWidth($width) {
  19730. return $this->customlistindent = floatval($width);
  19731. }
  19732. /**
  19733. * Set the top/bottom cell sides to be open or closed when the cell cross the page.
  19734. * @param $isopen (boolean) if true keeps the top/bottom border open for the cell sides that cross the page.
  19735. * @public
  19736. * @since 4.2.010 (2008-11-14)
  19737. */
  19738. public function setOpenCell($isopen) {
  19739. $this->opencell = $isopen;
  19740. }
  19741. /**
  19742. * Set the color and font style for HTML links.
  19743. * @param $color (array) RGB array of colors
  19744. * @param $fontstyle (string) additional font styles to add
  19745. * @public
  19746. * @since 4.4.003 (2008-12-09)
  19747. */
  19748. public function setHtmlLinksStyle($color=array(0,0,255), $fontstyle='U') {
  19749. $this->htmlLinkColorArray = $color;
  19750. $this->htmlLinkFontStyle = $fontstyle;
  19751. }
  19752. /**
  19753. * Convert HTML string containing value and unit of measure to user's units or points.
  19754. * @param $htmlval (string) String containing values and unit.
  19755. * @param $refsize (string) Reference value in points.
  19756. * @param $defaultunit (string) Default unit (can be one of the following: %, em, ex, px, in, mm, pc, pt).
  19757. * @param $points (boolean) If true returns points, otherwise returns value in user's units.
  19758. * @return float value in user's unit or point if $points=true
  19759. * @public
  19760. * @since 4.4.004 (2008-12-10)
  19761. */
  19762. public function getHTMLUnitToUnits($htmlval, $refsize=1, $defaultunit='px', $points=false) {
  19763. $supportedunits = array('%', 'em', 'ex', 'px', 'in', 'cm', 'mm', 'pc', 'pt');
  19764. $retval = 0;
  19765. $value = 0;
  19766. $unit = 'px';
  19767. if ($points) {
  19768. $k = 1;
  19769. } else {
  19770. $k = $this->k;
  19771. }
  19772. if (in_array($defaultunit, $supportedunits)) {
  19773. $unit = $defaultunit;
  19774. }
  19775. if (is_numeric($htmlval)) {
  19776. $value = floatval($htmlval);
  19777. } elseif (preg_match('/([0-9\.\-\+]+)/', $htmlval, $mnum)) {
  19778. $value = floatval($mnum[1]);
  19779. if (preg_match('/([a-z%]+)/', $htmlval, $munit)) {
  19780. if (in_array($munit[1], $supportedunits)) {
  19781. $unit = $munit[1];
  19782. }
  19783. }
  19784. }
  19785. switch ($unit) {
  19786. // percentage
  19787. case '%': {
  19788. $retval = (($value * $refsize) / 100);
  19789. break;
  19790. }
  19791. // relative-size
  19792. case 'em': {
  19793. $retval = ($value * $refsize);
  19794. break;
  19795. }
  19796. // height of lower case 'x' (about half the font-size)
  19797. case 'ex': {
  19798. $retval = ($value * ($refsize / 2));
  19799. break;
  19800. }
  19801. // absolute-size
  19802. case 'in': {
  19803. $retval = (($value * $this->dpi) / $k);
  19804. break;
  19805. }
  19806. // centimeters
  19807. case 'cm': {
  19808. $retval = (($value / 2.54 * $this->dpi) / $k);
  19809. break;
  19810. }
  19811. // millimeters
  19812. case 'mm': {
  19813. $retval = (($value / 25.4 * $this->dpi) / $k);
  19814. break;
  19815. }
  19816. // one pica is 12 points
  19817. case 'pc': {
  19818. $retval = (($value * 12) / $k);
  19819. break;
  19820. }
  19821. // points
  19822. case 'pt': {
  19823. $retval = ($value / $k);
  19824. break;
  19825. }
  19826. // pixels
  19827. case 'px': {
  19828. $retval = $this->pixelsToUnits($value);
  19829. if ($points) {
  19830. $retval *= $this->k;
  19831. }
  19832. break;
  19833. }
  19834. }
  19835. return $retval;
  19836. }
  19837. /**
  19838. * Output an HTML list bullet or ordered item symbol
  19839. * @param $listdepth (int) list nesting level
  19840. * @param $listtype (string) type of list
  19841. * @param $size (float) current font size
  19842. * @protected
  19843. * @since 4.4.004 (2008-12-10)
  19844. */
  19845. protected function putHtmlListBullet($listdepth, $listtype='', $size=10) {
  19846. if ($this->state != 2) {
  19847. return;
  19848. }
  19849. $size /= $this->k;
  19850. $fill = '';
  19851. $bgcolor = $this->bgcolor;
  19852. $color = $this->fgcolor;
  19853. $strokecolor = $this->strokecolor;
  19854. $width = 0;
  19855. $textitem = '';
  19856. $tmpx = $this->x;
  19857. $lspace = $this->GetStringWidth(' ');
  19858. if ($listtype == '^') {
  19859. // special symbol used for avoid justification of rect bullet
  19860. $this->lispacer = '';
  19861. return;
  19862. } elseif ($listtype == '!') {
  19863. // set default list type for unordered list
  19864. $deftypes = array('disc', 'circle', 'square');
  19865. $listtype = $deftypes[($listdepth - 1) % 3];
  19866. } elseif ($listtype == '#') {
  19867. // set default list type for ordered list
  19868. $listtype = 'decimal';
  19869. } elseif (substr($listtype, 0, 4) == 'img|') {
  19870. // custom image type ('img|type|width|height|image.ext')
  19871. $img = explode('|', $listtype);
  19872. $listtype = 'img';
  19873. }
  19874. switch ($listtype) {
  19875. // unordered types
  19876. case 'none': {
  19877. break;
  19878. }
  19879. case 'disc': {
  19880. $r = $size / 6;
  19881. $lspace += (2 * $r);
  19882. if ($this->rtl) {
  19883. $this->x += $lspace;
  19884. } else {
  19885. $this->x -= $lspace;
  19886. }
  19887. $this->Circle(($this->x + $r), ($this->y + ($this->lasth / 2)), $r, 0, 360, 'F', array(), $color, 8);
  19888. break;
  19889. }
  19890. case 'circle': {
  19891. $r = $size / 6;
  19892. $lspace += (2 * $r);
  19893. if ($this->rtl) {
  19894. $this->x += $lspace;
  19895. } else {
  19896. $this->x -= $lspace;
  19897. }
  19898. $prev_line_style = $this->linestyleWidth.' '.$this->linestyleCap.' '.$this->linestyleJoin.' '.$this->linestyleDash.' '.$this->DrawColor;
  19899. $new_line_style = array('width' => ($r / 3), 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'phase' => 0, 'color'=>$color);
  19900. $this->Circle(($this->x + $r), ($this->y + ($this->lasth / 2)), ($r * (1 - (1/6))), 0, 360, 'D', $new_line_style, array(), 8);
  19901. $this->_out($prev_line_style); // restore line settings
  19902. break;
  19903. }
  19904. case 'square': {
  19905. $l = $size / 3;
  19906. $lspace += $l;
  19907. if ($this->rtl) {;
  19908. $this->x += $lspace;
  19909. } else {
  19910. $this->x -= $lspace;
  19911. }
  19912. $this->Rect($this->x, ($this->y + (($this->lasth - $l) / 2)), $l, $l, 'F', array(), $color);
  19913. break;
  19914. }
  19915. case 'img': {
  19916. // 1=>type, 2=>width, 3=>height, 4=>image.ext
  19917. $lspace += $img[2];
  19918. if ($this->rtl) {;
  19919. $this->x += $lspace;
  19920. } else {
  19921. $this->x -= $lspace;
  19922. }
  19923. $imgtype = strtolower($img[1]);
  19924. $prev_y = $this->y;
  19925. switch ($imgtype) {
  19926. case 'svg': {
  19927. $this->ImageSVG($img[4], $this->x, ($this->y + (($this->lasth - $img[3]) / 2)), $img[2], $img[3], '', 'T', '', 0, false);
  19928. break;
  19929. }
  19930. case 'ai':
  19931. case 'eps': {
  19932. $this->ImageEps($img[4], $this->x, ($this->y + (($this->lasth - $img[3]) / 2)), $img[2], $img[3], '', true, 'T', '', 0, false);
  19933. break;
  19934. }
  19935. default: {
  19936. $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);
  19937. break;
  19938. }
  19939. }
  19940. $this->y = $prev_y;
  19941. break;
  19942. }
  19943. // ordered types
  19944. // $this->listcount[$this->listnum];
  19945. // $textitem
  19946. case '1':
  19947. case 'decimal': {
  19948. $textitem = $this->listcount[$this->listnum];
  19949. break;
  19950. }
  19951. case 'decimal-leading-zero': {
  19952. $textitem = sprintf('%02d', $this->listcount[$this->listnum]);
  19953. break;
  19954. }
  19955. case 'i':
  19956. case 'lower-roman': {
  19957. $textitem = strtolower(TCPDF_STATIC::intToRoman($this->listcount[$this->listnum]));
  19958. break;
  19959. }
  19960. case 'I':
  19961. case 'upper-roman': {
  19962. $textitem = TCPDF_STATIC::intToRoman($this->listcount[$this->listnum]);
  19963. break;
  19964. }
  19965. case 'a':
  19966. case 'lower-alpha':
  19967. case 'lower-latin': {
  19968. $textitem = chr(97 + $this->listcount[$this->listnum] - 1);
  19969. break;
  19970. }
  19971. case 'A':
  19972. case 'upper-alpha':
  19973. case 'upper-latin': {
  19974. $textitem = chr(65 + $this->listcount[$this->listnum] - 1);
  19975. break;
  19976. }
  19977. case 'lower-greek': {
  19978. $textitem = TCPDF_FONTS::unichr((945 + $this->listcount[$this->listnum] - 1), $this->isunicode);
  19979. break;
  19980. }
  19981. /*
  19982. // Types to be implemented (special handling)
  19983. case 'hebrew': {
  19984. break;
  19985. }
  19986. case 'armenian': {
  19987. break;
  19988. }
  19989. case 'georgian': {
  19990. break;
  19991. }
  19992. case 'cjk-ideographic': {
  19993. break;
  19994. }
  19995. case 'hiragana': {
  19996. break;
  19997. }
  19998. case 'katakana': {
  19999. break;
  20000. }
  20001. case 'hiragana-iroha': {
  20002. break;
  20003. }
  20004. case 'katakana-iroha': {
  20005. break;
  20006. }
  20007. */
  20008. default: {
  20009. $textitem = $this->listcount[$this->listnum];
  20010. }
  20011. }
  20012. if (!TCPDF_STATIC::empty_string($textitem)) {
  20013. // Check whether we need a new page or new column
  20014. $prev_y = $this->y;
  20015. $h = $this->getCellHeight($this->FontSize);
  20016. if ($this->checkPageBreak($h) OR ($this->y < $prev_y)) {
  20017. $tmpx = $this->x;
  20018. }
  20019. // print ordered item
  20020. if ($this->rtl) {
  20021. $textitem = '.'.$textitem;
  20022. } else {
  20023. $textitem = $textitem.'.';
  20024. }
  20025. $lspace += $this->GetStringWidth($textitem);
  20026. if ($this->rtl) {
  20027. $this->x += $lspace;
  20028. } else {
  20029. $this->x -= $lspace;
  20030. }
  20031. $this->Write($this->lasth, $textitem, '', false, '', false, 0, false);
  20032. }
  20033. $this->x = $tmpx;
  20034. $this->lispacer = '^';
  20035. // restore colors
  20036. $this->SetFillColorArray($bgcolor);
  20037. $this->SetDrawColorArray($strokecolor);
  20038. $this->SettextColorArray($color);
  20039. }
  20040. /**
  20041. * Returns current graphic variables as array.
  20042. * @return array of graphic variables
  20043. * @protected
  20044. * @since 4.2.010 (2008-11-14)
  20045. */
  20046. protected function getGraphicVars() {
  20047. $grapvars = array(
  20048. 'FontFamily' => $this->FontFamily,
  20049. 'FontStyle' => $this->FontStyle,
  20050. 'FontSizePt' => $this->FontSizePt,
  20051. 'rMargin' => $this->rMargin,
  20052. 'lMargin' => $this->lMargin,
  20053. 'cell_padding' => $this->cell_padding,
  20054. 'cell_margin' => $this->cell_margin,
  20055. 'LineWidth' => $this->LineWidth,
  20056. 'linestyleWidth' => $this->linestyleWidth,
  20057. 'linestyleCap' => $this->linestyleCap,
  20058. 'linestyleJoin' => $this->linestyleJoin,
  20059. 'linestyleDash' => $this->linestyleDash,
  20060. 'textrendermode' => $this->textrendermode,
  20061. 'textstrokewidth' => $this->textstrokewidth,
  20062. 'DrawColor' => $this->DrawColor,
  20063. 'FillColor' => $this->FillColor,
  20064. 'TextColor' => $this->TextColor,
  20065. 'ColorFlag' => $this->ColorFlag,
  20066. 'bgcolor' => $this->bgcolor,
  20067. 'fgcolor' => $this->fgcolor,
  20068. 'htmlvspace' => $this->htmlvspace,
  20069. 'listindent' => $this->listindent,
  20070. 'listindentlevel' => $this->listindentlevel,
  20071. 'listnum' => $this->listnum,
  20072. 'listordered' => $this->listordered,
  20073. 'listcount' => $this->listcount,
  20074. 'lispacer' => $this->lispacer,
  20075. 'cell_height_ratio' => $this->cell_height_ratio,
  20076. 'font_stretching' => $this->font_stretching,
  20077. 'font_spacing' => $this->font_spacing,
  20078. 'alpha' => $this->alpha,
  20079. // extended
  20080. 'lasth' => $this->lasth,
  20081. 'tMargin' => $this->tMargin,
  20082. 'bMargin' => $this->bMargin,
  20083. 'AutoPageBreak' => $this->AutoPageBreak,
  20084. 'PageBreakTrigger' => $this->PageBreakTrigger,
  20085. 'x' => $this->x,
  20086. 'y' => $this->y,
  20087. 'w' => $this->w,
  20088. 'h' => $this->h,
  20089. 'wPt' => $this->wPt,
  20090. 'hPt' => $this->hPt,
  20091. 'fwPt' => $this->fwPt,
  20092. 'fhPt' => $this->fhPt,
  20093. 'page' => $this->page,
  20094. 'current_column' => $this->current_column,
  20095. 'num_columns' => $this->num_columns
  20096. );
  20097. return $grapvars;
  20098. }
  20099. /**
  20100. * Set graphic variables.
  20101. * @param $gvars (array) array of graphic variablesto restore
  20102. * @param $extended (boolean) if true restore extended graphic variables
  20103. * @protected
  20104. * @since 4.2.010 (2008-11-14)
  20105. */
  20106. protected function setGraphicVars($gvars, $extended=false) {
  20107. if ($this->state != 2) {
  20108. return;
  20109. }
  20110. $this->FontFamily = $gvars['FontFamily'];
  20111. $this->FontStyle = $gvars['FontStyle'];
  20112. $this->FontSizePt = $gvars['FontSizePt'];
  20113. $this->rMargin = $gvars['rMargin'];
  20114. $this->lMargin = $gvars['lMargin'];
  20115. $this->cell_padding = $gvars['cell_padding'];
  20116. $this->cell_margin = $gvars['cell_margin'];
  20117. $this->LineWidth = $gvars['LineWidth'];
  20118. $this->linestyleWidth = $gvars['linestyleWidth'];
  20119. $this->linestyleCap = $gvars['linestyleCap'];
  20120. $this->linestyleJoin = $gvars['linestyleJoin'];
  20121. $this->linestyleDash = $gvars['linestyleDash'];
  20122. $this->textrendermode = $gvars['textrendermode'];
  20123. $this->textstrokewidth = $gvars['textstrokewidth'];
  20124. $this->DrawColor = $gvars['DrawColor'];
  20125. $this->FillColor = $gvars['FillColor'];
  20126. $this->TextColor = $gvars['TextColor'];
  20127. $this->ColorFlag = $gvars['ColorFlag'];
  20128. $this->bgcolor = $gvars['bgcolor'];
  20129. $this->fgcolor = $gvars['fgcolor'];
  20130. $this->htmlvspace = $gvars['htmlvspace'];
  20131. $this->listindent = $gvars['listindent'];
  20132. $this->listindentlevel = $gvars['listindentlevel'];
  20133. $this->listnum = $gvars['listnum'];
  20134. $this->listordered = $gvars['listordered'];
  20135. $this->listcount = $gvars['listcount'];
  20136. $this->lispacer = $gvars['lispacer'];
  20137. $this->cell_height_ratio = $gvars['cell_height_ratio'];
  20138. $this->font_stretching = $gvars['font_stretching'];
  20139. $this->font_spacing = $gvars['font_spacing'];
  20140. $this->alpha = $gvars['alpha'];
  20141. if ($extended) {
  20142. // restore extended values
  20143. $this->lasth = $gvars['lasth'];
  20144. $this->tMargin = $gvars['tMargin'];
  20145. $this->bMargin = $gvars['bMargin'];
  20146. $this->AutoPageBreak = $gvars['AutoPageBreak'];
  20147. $this->PageBreakTrigger = $gvars['PageBreakTrigger'];
  20148. $this->x = $gvars['x'];
  20149. $this->y = $gvars['y'];
  20150. $this->w = $gvars['w'];
  20151. $this->h = $gvars['h'];
  20152. $this->wPt = $gvars['wPt'];
  20153. $this->hPt = $gvars['hPt'];
  20154. $this->fwPt = $gvars['fwPt'];
  20155. $this->fhPt = $gvars['fhPt'];
  20156. $this->page = $gvars['page'];
  20157. $this->current_column = $gvars['current_column'];
  20158. $this->num_columns = $gvars['num_columns'];
  20159. }
  20160. $this->_out(''.$this->linestyleWidth.' '.$this->linestyleCap.' '.$this->linestyleJoin.' '.$this->linestyleDash.' '.$this->DrawColor.' '.$this->FillColor.'');
  20161. if (!TCPDF_STATIC::empty_string($this->FontFamily)) {
  20162. $this->SetFont($this->FontFamily, $this->FontStyle, $this->FontSizePt);
  20163. }
  20164. }
  20165. /**
  20166. * Outputs the "save graphics state" operator 'q'
  20167. * @protected
  20168. */
  20169. protected function _outSaveGraphicsState() {
  20170. $this->_out('q');
  20171. }
  20172. /**
  20173. * Outputs the "restore graphics state" operator 'Q'
  20174. * @protected
  20175. */
  20176. protected function _outRestoreGraphicsState() {
  20177. $this->_out('Q');
  20178. }
  20179. /**
  20180. * Set buffer content (always append data).
  20181. * @param $data (string) data
  20182. * @protected
  20183. * @since 4.5.000 (2009-01-02)
  20184. */
  20185. protected function setBuffer($data) {
  20186. $this->bufferlen += strlen($data);
  20187. $this->buffer .= $data;
  20188. }
  20189. /**
  20190. * Replace the buffer content
  20191. * @param $data (string) data
  20192. * @protected
  20193. * @since 5.5.000 (2010-06-22)
  20194. */
  20195. protected function replaceBuffer($data) {
  20196. $this->bufferlen = strlen($data);
  20197. $this->buffer = $data;
  20198. }
  20199. /**
  20200. * Get buffer content.
  20201. * @return string buffer content
  20202. * @protected
  20203. * @since 4.5.000 (2009-01-02)
  20204. */
  20205. protected function getBuffer() {
  20206. return $this->buffer;
  20207. }
  20208. /**
  20209. * Set page buffer content.
  20210. * @param $page (int) page number
  20211. * @param $data (string) page data
  20212. * @param $append (boolean) if true append data, false replace.
  20213. * @protected
  20214. * @since 4.5.000 (2008-12-31)
  20215. */
  20216. protected function setPageBuffer($page, $data, $append=false) {
  20217. if ($append) {
  20218. $this->pages[$page] .= $data;
  20219. } else {
  20220. $this->pages[$page] = $data;
  20221. }
  20222. if ($append AND isset($this->pagelen[$page])) {
  20223. $this->pagelen[$page] += strlen($data);
  20224. } else {
  20225. $this->pagelen[$page] = strlen($data);
  20226. }
  20227. }
  20228. /**
  20229. * Get page buffer content.
  20230. * @param $page (int) page number
  20231. * @return string page buffer content or false in case of error
  20232. * @protected
  20233. * @since 4.5.000 (2008-12-31)
  20234. */
  20235. protected function getPageBuffer($page) {
  20236. if (isset($this->pages[$page])) {
  20237. return $this->pages[$page];
  20238. }
  20239. return false;
  20240. }
  20241. /**
  20242. * Set image buffer content.
  20243. * @param $image (string) image key
  20244. * @param $data (array) image data
  20245. * @return int image index number
  20246. * @protected
  20247. * @since 4.5.000 (2008-12-31)
  20248. */
  20249. protected function setImageBuffer($image, $data) {
  20250. if (($data['i'] = array_search($image, $this->imagekeys)) === FALSE) {
  20251. $this->imagekeys[$this->numimages] = $image;
  20252. $data['i'] = $this->numimages;
  20253. ++$this->numimages;
  20254. }
  20255. $this->images[$image] = $data;
  20256. return $data['i'];
  20257. }
  20258. /**
  20259. * Set image buffer content for a specified sub-key.
  20260. * @param $image (string) image key
  20261. * @param $key (string) image sub-key
  20262. * @param $data (array) image data
  20263. * @protected
  20264. * @since 4.5.000 (2008-12-31)
  20265. */
  20266. protected function setImageSubBuffer($image, $key, $data) {
  20267. if (!isset($this->images[$image])) {
  20268. $this->setImageBuffer($image, array());
  20269. }
  20270. $this->images[$image][$key] = $data;
  20271. }
  20272. /**
  20273. * Get image buffer content.
  20274. * @param $image (string) image key
  20275. * @return string image buffer content or false in case of error
  20276. * @protected
  20277. * @since 4.5.000 (2008-12-31)
  20278. */
  20279. protected function getImageBuffer($image) {
  20280. if (isset($this->images[$image])) {
  20281. return $this->images[$image];
  20282. }
  20283. return false;
  20284. }
  20285. /**
  20286. * Set font buffer content.
  20287. * @param $font (string) font key
  20288. * @param $data (array) font data
  20289. * @protected
  20290. * @since 4.5.000 (2009-01-02)
  20291. */
  20292. protected function setFontBuffer($font, $data) {
  20293. $this->fonts[$font] = $data;
  20294. if (!in_array($font, $this->fontkeys)) {
  20295. $this->fontkeys[] = $font;
  20296. // store object ID for current font
  20297. ++$this->n;
  20298. $this->font_obj_ids[$font] = $this->n;
  20299. $this->setFontSubBuffer($font, 'n', $this->n);
  20300. }
  20301. }
  20302. /**
  20303. * Set font buffer content.
  20304. * @param $font (string) font key
  20305. * @param $key (string) font sub-key
  20306. * @param $data (array) font data
  20307. * @protected
  20308. * @since 4.5.000 (2009-01-02)
  20309. */
  20310. protected function setFontSubBuffer($font, $key, $data) {
  20311. if (!isset($this->fonts[$font])) {
  20312. $this->setFontBuffer($font, array());
  20313. }
  20314. $this->fonts[$font][$key] = $data;
  20315. }
  20316. /**
  20317. * Get font buffer content.
  20318. * @param $font (string) font key
  20319. * @return string font buffer content or false in case of error
  20320. * @protected
  20321. * @since 4.5.000 (2009-01-02)
  20322. */
  20323. protected function getFontBuffer($font) {
  20324. if (isset($this->fonts[$font])) {
  20325. return $this->fonts[$font];
  20326. }
  20327. return false;
  20328. }
  20329. /**
  20330. * Move a page to a previous position.
  20331. * @param $frompage (int) number of the source page
  20332. * @param $topage (int) number of the destination page (must be less than $frompage)
  20333. * @return true in case of success, false in case of error.
  20334. * @public
  20335. * @since 4.5.000 (2009-01-02)
  20336. */
  20337. public function movePage($frompage, $topage) {
  20338. if (($frompage > $this->numpages) OR ($frompage <= $topage)) {
  20339. return false;
  20340. }
  20341. if ($frompage == $this->page) {
  20342. // close the page before moving it
  20343. $this->endPage();
  20344. }
  20345. // move all page-related states
  20346. $tmppage = $this->getPageBuffer($frompage);
  20347. $tmppagedim = $this->pagedim[$frompage];
  20348. $tmppagelen = $this->pagelen[$frompage];
  20349. $tmpintmrk = $this->intmrk[$frompage];
  20350. $tmpbordermrk = $this->bordermrk[$frompage];
  20351. $tmpcntmrk = $this->cntmrk[$frompage];
  20352. $tmppageobjects = $this->pageobjects[$frompage];
  20353. if (isset($this->footerpos[$frompage])) {
  20354. $tmpfooterpos = $this->footerpos[$frompage];
  20355. }
  20356. if (isset($this->footerlen[$frompage])) {
  20357. $tmpfooterlen = $this->footerlen[$frompage];
  20358. }
  20359. if (isset($this->transfmrk[$frompage])) {
  20360. $tmptransfmrk = $this->transfmrk[$frompage];
  20361. }
  20362. if (isset($this->PageAnnots[$frompage])) {
  20363. $tmpannots = $this->PageAnnots[$frompage];
  20364. }
  20365. if (isset($this->newpagegroup) AND !empty($this->newpagegroup)) {
  20366. for ($i = $frompage; $i > $topage; --$i) {
  20367. if (isset($this->newpagegroup[$i]) AND (($i + $this->pagegroups[$this->newpagegroup[$i]]) > $frompage)) {
  20368. --$this->pagegroups[$this->newpagegroup[$i]];
  20369. break;
  20370. }
  20371. }
  20372. for ($i = $topage; $i > 0; --$i) {
  20373. if (isset($this->newpagegroup[$i]) AND (($i + $this->pagegroups[$this->newpagegroup[$i]]) > $topage)) {
  20374. ++$this->pagegroups[$this->newpagegroup[$i]];
  20375. break;
  20376. }
  20377. }
  20378. }
  20379. for ($i = $frompage; $i > $topage; --$i) {
  20380. $j = $i - 1;
  20381. // shift pages down
  20382. $this->setPageBuffer($i, $this->getPageBuffer($j));
  20383. $this->pagedim[$i] = $this->pagedim[$j];
  20384. $this->pagelen[$i] = $this->pagelen[$j];
  20385. $this->intmrk[$i] = $this->intmrk[$j];
  20386. $this->bordermrk[$i] = $this->bordermrk[$j];
  20387. $this->cntmrk[$i] = $this->cntmrk[$j];
  20388. $this->pageobjects[$i] = $this->pageobjects[$j];
  20389. if (isset($this->footerpos[$j])) {
  20390. $this->footerpos[$i] = $this->footerpos[$j];
  20391. } elseif (isset($this->footerpos[$i])) {
  20392. unset($this->footerpos[$i]);
  20393. }
  20394. if (isset($this->footerlen[$j])) {
  20395. $this->footerlen[$i] = $this->footerlen[$j];
  20396. } elseif (isset($this->footerlen[$i])) {
  20397. unset($this->footerlen[$i]);
  20398. }
  20399. if (isset($this->transfmrk[$j])) {
  20400. $this->transfmrk[$i] = $this->transfmrk[$j];
  20401. } elseif (isset($this->transfmrk[$i])) {
  20402. unset($this->transfmrk[$i]);
  20403. }
  20404. if (isset($this->PageAnnots[$j])) {
  20405. $this->PageAnnots[$i] = $this->PageAnnots[$j];
  20406. } elseif (isset($this->PageAnnots[$i])) {
  20407. unset($this->PageAnnots[$i]);
  20408. }
  20409. if (isset($this->newpagegroup[$j])) {
  20410. $this->newpagegroup[$i] = $this->newpagegroup[$j];
  20411. unset($this->newpagegroup[$j]);
  20412. }
  20413. if ($this->currpagegroup == $j) {
  20414. $this->currpagegroup = $i;
  20415. }
  20416. }
  20417. $this->setPageBuffer($topage, $tmppage);
  20418. $this->pagedim[$topage] = $tmppagedim;
  20419. $this->pagelen[$topage] = $tmppagelen;
  20420. $this->intmrk[$topage] = $tmpintmrk;
  20421. $this->bordermrk[$topage] = $tmpbordermrk;
  20422. $this->cntmrk[$topage] = $tmpcntmrk;
  20423. $this->pageobjects[$topage] = $tmppageobjects;
  20424. if (isset($tmpfooterpos)) {
  20425. $this->footerpos[$topage] = $tmpfooterpos;
  20426. } elseif (isset($this->footerpos[$topage])) {
  20427. unset($this->footerpos[$topage]);
  20428. }
  20429. if (isset($tmpfooterlen)) {
  20430. $this->footerlen[$topage] = $tmpfooterlen;
  20431. } elseif (isset($this->footerlen[$topage])) {
  20432. unset($this->footerlen[$topage]);
  20433. }
  20434. if (isset($tmptransfmrk)) {
  20435. $this->transfmrk[$topage] = $tmptransfmrk;
  20436. } elseif (isset($this->transfmrk[$topage])) {
  20437. unset($this->transfmrk[$topage]);
  20438. }
  20439. if (isset($tmpannots)) {
  20440. $this->PageAnnots[$topage] = $tmpannots;
  20441. } elseif (isset($this->PageAnnots[$topage])) {
  20442. unset($this->PageAnnots[$topage]);
  20443. }
  20444. // adjust outlines
  20445. $tmpoutlines = $this->outlines;
  20446. foreach ($tmpoutlines as $key => $outline) {
  20447. if (!$outline['f']) {
  20448. if (($outline['p'] >= $topage) AND ($outline['p'] < $frompage)) {
  20449. $this->outlines[$key]['p'] = ($outline['p'] + 1);
  20450. } elseif ($outline['p'] == $frompage) {
  20451. $this->outlines[$key]['p'] = $topage;
  20452. }
  20453. }
  20454. }
  20455. // adjust dests
  20456. $tmpdests = $this->dests;
  20457. foreach ($tmpdests as $key => $dest) {
  20458. if (!$dest['f']) {
  20459. if (($dest['p'] >= $topage) AND ($dest['p'] < $frompage)) {
  20460. $this->dests[$key]['p'] = ($dest['p'] + 1);
  20461. } elseif ($dest['p'] == $frompage) {
  20462. $this->dests[$key]['p'] = $topage;
  20463. }
  20464. }
  20465. }
  20466. // adjust links
  20467. $tmplinks = $this->links;
  20468. foreach ($tmplinks as $key => $link) {
  20469. if (!$link['f']) {
  20470. if (($link['p'] >= $topage) AND ($link['p'] < $frompage)) {
  20471. $this->links[$key]['p'] = ($link['p'] + 1);
  20472. } elseif ($link['p'] == $frompage) {
  20473. $this->links[$key]['p'] = $topage;
  20474. }
  20475. }
  20476. }
  20477. // adjust javascript
  20478. $jfrompage = $frompage;
  20479. $jtopage = $topage;
  20480. if (preg_match_all('/this\.addField\(\'([^\']*)\',\'([^\']*)\',([0-9]+)/', $this->javascript, $pamatch) > 0) {
  20481. foreach($pamatch[0] as $pk => $pmatch) {
  20482. $pagenum = intval($pamatch[3][$pk]) + 1;
  20483. if (($pagenum >= $jtopage) AND ($pagenum < $jfrompage)) {
  20484. $newpage = ($pagenum + 1);
  20485. } elseif ($pagenum == $jfrompage) {
  20486. $newpage = $jtopage;
  20487. } else {
  20488. $newpage = $pagenum;
  20489. }
  20490. --$newpage;
  20491. $newjs = "this.addField(\'".$pamatch[1][$pk]."\',\'".$pamatch[2][$pk]."\',".$newpage;
  20492. $this->javascript = str_replace($pmatch, $newjs, $this->javascript);
  20493. }
  20494. unset($pamatch);
  20495. }
  20496. // return to last page
  20497. $this->lastPage(true);
  20498. return true;
  20499. }
  20500. /**
  20501. * Remove the specified page.
  20502. * @param $page (int) page to remove
  20503. * @return true in case of success, false in case of error.
  20504. * @public
  20505. * @since 4.6.004 (2009-04-23)
  20506. */
  20507. public function deletePage($page) {
  20508. if (($page < 1) OR ($page > $this->numpages)) {
  20509. return false;
  20510. }
  20511. // delete current page
  20512. unset($this->pages[$page]);
  20513. unset($this->pagedim[$page]);
  20514. unset($this->pagelen[$page]);
  20515. unset($this->intmrk[$page]);
  20516. unset($this->bordermrk[$page]);
  20517. unset($this->cntmrk[$page]);
  20518. foreach ($this->pageobjects[$page] as $oid) {
  20519. if (isset($this->offsets[$oid])){
  20520. unset($this->offsets[$oid]);
  20521. }
  20522. }
  20523. unset($this->pageobjects[$page]);
  20524. if (isset($this->footerpos[$page])) {
  20525. unset($this->footerpos[$page]);
  20526. }
  20527. if (isset($this->footerlen[$page])) {
  20528. unset($this->footerlen[$page]);
  20529. }
  20530. if (isset($this->transfmrk[$page])) {
  20531. unset($this->transfmrk[$page]);
  20532. }
  20533. if (isset($this->PageAnnots[$page])) {
  20534. unset($this->PageAnnots[$page]);
  20535. }
  20536. if (isset($this->newpagegroup) AND !empty($this->newpagegroup)) {
  20537. for ($i = $page; $i > 0; --$i) {
  20538. if (isset($this->newpagegroup[$i]) AND (($i + $this->pagegroups[$this->newpagegroup[$i]]) > $page)) {
  20539. --$this->pagegroups[$this->newpagegroup[$i]];
  20540. break;
  20541. }
  20542. }
  20543. }
  20544. if (isset($this->pageopen[$page])) {
  20545. unset($this->pageopen[$page]);
  20546. }
  20547. if ($page < $this->numpages) {
  20548. // update remaining pages
  20549. for ($i = $page; $i < $this->numpages; ++$i) {
  20550. $j = $i + 1;
  20551. // shift pages
  20552. $this->setPageBuffer($i, $this->getPageBuffer($j));
  20553. $this->pagedim[$i] = $this->pagedim[$j];
  20554. $this->pagelen[$i] = $this->pagelen[$j];
  20555. $this->intmrk[$i] = $this->intmrk[$j];
  20556. $this->bordermrk[$i] = $this->bordermrk[$j];
  20557. $this->cntmrk[$i] = $this->cntmrk[$j];
  20558. $this->pageobjects[$i] = $this->pageobjects[$j];
  20559. if (isset($this->footerpos[$j])) {
  20560. $this->footerpos[$i] = $this->footerpos[$j];
  20561. } elseif (isset($this->footerpos[$i])) {
  20562. unset($this->footerpos[$i]);
  20563. }
  20564. if (isset($this->footerlen[$j])) {
  20565. $this->footerlen[$i] = $this->footerlen[$j];
  20566. } elseif (isset($this->footerlen[$i])) {
  20567. unset($this->footerlen[$i]);
  20568. }
  20569. if (isset($this->transfmrk[$j])) {
  20570. $this->transfmrk[$i] = $this->transfmrk[$j];
  20571. } elseif (isset($this->transfmrk[$i])) {
  20572. unset($this->transfmrk[$i]);
  20573. }
  20574. if (isset($this->PageAnnots[$j])) {
  20575. $this->PageAnnots[$i] = $this->PageAnnots[$j];
  20576. } elseif (isset($this->PageAnnots[$i])) {
  20577. unset($this->PageAnnots[$i]);
  20578. }
  20579. if (isset($this->newpagegroup[$j])) {
  20580. $this->newpagegroup[$i] = $this->newpagegroup[$j];
  20581. unset($this->newpagegroup[$j]);
  20582. }
  20583. if ($this->currpagegroup == $j) {
  20584. $this->currpagegroup = $i;
  20585. }
  20586. if (isset($this->pageopen[$j])) {
  20587. $this->pageopen[$i] = $this->pageopen[$j];
  20588. } elseif (isset($this->pageopen[$i])) {
  20589. unset($this->pageopen[$i]);
  20590. }
  20591. }
  20592. // remove last page
  20593. unset($this->pages[$this->numpages]);
  20594. unset($this->pagedim[$this->numpages]);
  20595. unset($this->pagelen[$this->numpages]);
  20596. unset($this->intmrk[$this->numpages]);
  20597. unset($this->bordermrk[$this->numpages]);
  20598. unset($this->cntmrk[$this->numpages]);
  20599. foreach ($this->pageobjects[$this->numpages] as $oid) {
  20600. if (isset($this->offsets[$oid])){
  20601. unset($this->offsets[$oid]);
  20602. }
  20603. }
  20604. unset($this->pageobjects[$this->numpages]);
  20605. if (isset($this->footerpos[$this->numpages])) {
  20606. unset($this->footerpos[$this->numpages]);
  20607. }
  20608. if (isset($this->footerlen[$this->numpages])) {
  20609. unset($this->footerlen[$this->numpages]);
  20610. }
  20611. if (isset($this->transfmrk[$this->numpages])) {
  20612. unset($this->transfmrk[$this->numpages]);
  20613. }
  20614. if (isset($this->PageAnnots[$this->numpages])) {
  20615. unset($this->PageAnnots[$this->numpages]);
  20616. }
  20617. if (isset($this->newpagegroup[$this->numpages])) {
  20618. unset($this->newpagegroup[$this->numpages]);
  20619. }
  20620. if ($this->currpagegroup == $this->numpages) {
  20621. $this->currpagegroup = ($this->numpages - 1);
  20622. }
  20623. if (isset($this->pagegroups[$this->numpages])) {
  20624. unset($this->pagegroups[$this->numpages]);
  20625. }
  20626. if (isset($this->pageopen[$this->numpages])) {
  20627. unset($this->pageopen[$this->numpages]);
  20628. }
  20629. }
  20630. --$this->numpages;
  20631. $this->page = $this->numpages;
  20632. // adjust outlines
  20633. $tmpoutlines = $this->outlines;
  20634. foreach ($tmpoutlines as $key => $outline) {
  20635. if (!$outline['f']) {
  20636. if ($outline['p'] > $page) {
  20637. $this->outlines[$key]['p'] = $outline['p'] - 1;
  20638. } elseif ($outline['p'] == $page) {
  20639. unset($this->outlines[$key]);
  20640. }
  20641. }
  20642. }
  20643. // adjust dests
  20644. $tmpdests = $this->dests;
  20645. foreach ($tmpdests as $key => $dest) {
  20646. if (!$dest['f']) {
  20647. if ($dest['p'] > $page) {
  20648. $this->dests[$key]['p'] = $dest['p'] - 1;
  20649. } elseif ($dest['p'] == $page) {
  20650. unset($this->dests[$key]);
  20651. }
  20652. }
  20653. }
  20654. // adjust links
  20655. $tmplinks = $this->links;
  20656. foreach ($tmplinks as $key => $link) {
  20657. if (!$link['f']) {
  20658. if ($link['p'] > $page) {
  20659. $this->links[$key]['p'] = $link['p'] - 1;
  20660. } elseif ($link['p'] == $page) {
  20661. unset($this->links[$key]);
  20662. }
  20663. }
  20664. }
  20665. // adjust javascript
  20666. $jpage = $page;
  20667. if (preg_match_all('/this\.addField\(\'([^\']*)\',\'([^\']*)\',([0-9]+)/', $this->javascript, $pamatch) > 0) {
  20668. foreach($pamatch[0] as $pk => $pmatch) {
  20669. $pagenum = intval($pamatch[3][$pk]) + 1;
  20670. if ($pagenum >= $jpage) {
  20671. $newpage = ($pagenum - 1);
  20672. } elseif ($pagenum == $jpage) {
  20673. $newpage = 1;
  20674. } else {
  20675. $newpage = $pagenum;
  20676. }
  20677. --$newpage;
  20678. $newjs = "this.addField(\'".$pamatch[1][$pk]."\',\'".$pamatch[2][$pk]."\',".$newpage;
  20679. $this->javascript = str_replace($pmatch, $newjs, $this->javascript);
  20680. }
  20681. unset($pamatch);
  20682. }
  20683. // return to last page
  20684. if ($this->numpages > 0) {
  20685. $this->lastPage(true);
  20686. }
  20687. return true;
  20688. }
  20689. /**
  20690. * Clone the specified page to a new page.
  20691. * @param $page (int) number of page to copy (0 = current page)
  20692. * @return true in case of success, false in case of error.
  20693. * @public
  20694. * @since 4.9.015 (2010-04-20)
  20695. */
  20696. public function copyPage($page=0) {
  20697. if ($page == 0) {
  20698. // default value
  20699. $page = $this->page;
  20700. }
  20701. if (($page < 1) OR ($page > $this->numpages)) {
  20702. return false;
  20703. }
  20704. // close the last page
  20705. $this->endPage();
  20706. // copy all page-related states
  20707. ++$this->numpages;
  20708. $this->page = $this->numpages;
  20709. $this->setPageBuffer($this->page, $this->getPageBuffer($page));
  20710. $this->pagedim[$this->page] = $this->pagedim[$page];
  20711. $this->pagelen[$this->page] = $this->pagelen[$page];
  20712. $this->intmrk[$this->page] = $this->intmrk[$page];
  20713. $this->bordermrk[$this->page] = $this->bordermrk[$page];
  20714. $this->cntmrk[$this->page] = $this->cntmrk[$page];
  20715. $this->pageobjects[$this->page] = $this->pageobjects[$page];
  20716. $this->pageopen[$this->page] = false;
  20717. if (isset($this->footerpos[$page])) {
  20718. $this->footerpos[$this->page] = $this->footerpos[$page];
  20719. }
  20720. if (isset($this->footerlen[$page])) {
  20721. $this->footerlen[$this->page] = $this->footerlen[$page];
  20722. }
  20723. if (isset($this->transfmrk[$page])) {
  20724. $this->transfmrk[$this->page] = $this->transfmrk[$page];
  20725. }
  20726. if (isset($this->PageAnnots[$page])) {
  20727. $this->PageAnnots[$this->page] = $this->PageAnnots[$page];
  20728. }
  20729. if (isset($this->newpagegroup[$page])) {
  20730. // start a new group
  20731. $this->newpagegroup[$this->page] = sizeof($this->newpagegroup) + 1;
  20732. $this->currpagegroup = $this->newpagegroup[$this->page];
  20733. $this->pagegroups[$this->currpagegroup] = 1;
  20734. } elseif (isset($this->currpagegroup) AND ($this->currpagegroup > 0)) {
  20735. ++$this->pagegroups[$this->currpagegroup];
  20736. }
  20737. // copy outlines
  20738. $tmpoutlines = $this->outlines;
  20739. foreach ($tmpoutlines as $key => $outline) {
  20740. if ($outline['p'] == $page) {
  20741. $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']);
  20742. }
  20743. }
  20744. // copy links
  20745. $tmplinks = $this->links;
  20746. foreach ($tmplinks as $key => $link) {
  20747. if ($link['p'] == $page) {
  20748. $this->links[] = array('p' => $this->page, 'y' => $link['y'], 'f' => $link['f']);
  20749. }
  20750. }
  20751. // return to last page
  20752. $this->lastPage(true);
  20753. return true;
  20754. }
  20755. /**
  20756. * Output a Table of Content Index (TOC).
  20757. * This method must be called after all Bookmarks were set.
  20758. * Before calling this method you have to open the page using the addTOCPage() method.
  20759. * After calling this method you have to call endTOCPage() to close the TOC page.
  20760. * You can override this method to achieve different styles.
  20761. * @param $page (int) page number where this TOC should be inserted (leave empty for current page).
  20762. * @param $numbersfont (string) set the font for page numbers (please use monospaced font for better alignment).
  20763. * @param $filler (string) string used to fill the space between text and page number.
  20764. * @param $toc_name (string) name to use for TOC bookmark.
  20765. * @param $style (string) Font style for title: B = Bold, I = Italic, BI = Bold + Italic.
  20766. * @param $color (array) RGB color array for bookmark title (values from 0 to 255).
  20767. * @public
  20768. * @author Nicola Asuni
  20769. * @since 4.5.000 (2009-01-02)
  20770. * @see addTOCPage(), endTOCPage(), addHTMLTOC()
  20771. */
  20772. public function addTOC($page='', $numbersfont='', $filler='.', $toc_name='TOC', $style='', $color=array(0,0,0)) {
  20773. $fontsize = $this->FontSizePt;
  20774. $fontfamily = $this->FontFamily;
  20775. $fontstyle = $this->FontStyle;
  20776. $w = $this->w - $this->lMargin - $this->rMargin;
  20777. $spacer = $this->GetStringWidth(chr(32)) * 4;
  20778. $lmargin = $this->lMargin;
  20779. $rmargin = $this->rMargin;
  20780. $x_start = $this->GetX();
  20781. $page_first = $this->page;
  20782. $current_page = $this->page;
  20783. $page_fill_start = false;
  20784. $page_fill_end = false;
  20785. $current_column = $this->current_column;
  20786. if (TCPDF_STATIC::empty_string($numbersfont)) {
  20787. $numbersfont = $this->default_monospaced_font;
  20788. }
  20789. if (TCPDF_STATIC::empty_string($filler)) {
  20790. $filler = ' ';
  20791. }
  20792. if (TCPDF_STATIC::empty_string($page)) {
  20793. $gap = ' ';
  20794. } else {
  20795. $gap = '';
  20796. if ($page < 1) {
  20797. $page = 1;
  20798. }
  20799. }
  20800. $this->SetFont($numbersfont, $fontstyle, $fontsize);
  20801. $numwidth = $this->GetStringWidth('00000');
  20802. $maxpage = 0; //used for pages on attached documents
  20803. foreach ($this->outlines as $key => $outline) {
  20804. // check for extra pages (used for attachments)
  20805. if (($this->page > $page_first) AND ($outline['p'] >= $this->numpages)) {
  20806. $outline['p'] += ($this->page - $page_first);
  20807. }
  20808. if ($this->rtl) {
  20809. $aligntext = 'R';
  20810. $alignnum = 'L';
  20811. } else {
  20812. $aligntext = 'L';
  20813. $alignnum = 'R';
  20814. }
  20815. if ($outline['l'] == 0) {
  20816. $this->SetFont($fontfamily, $outline['s'].'B', $fontsize);
  20817. } else {
  20818. $this->SetFont($fontfamily, $outline['s'], $fontsize - $outline['l']);
  20819. }
  20820. $this->SetTextColorArray($outline['c']);
  20821. // check for page break
  20822. $this->checkPageBreak(2 * $this->getCellHeight($this->FontSize));
  20823. // set margins and X position
  20824. if (($this->page == $current_page) AND ($this->current_column == $current_column)) {
  20825. $this->lMargin = $lmargin;
  20826. $this->rMargin = $rmargin;
  20827. } else {
  20828. if ($this->current_column != $current_column) {
  20829. if ($this->rtl) {
  20830. $x_start = $this->w - $this->columns[$this->current_column]['x'];
  20831. } else {
  20832. $x_start = $this->columns[$this->current_column]['x'];
  20833. }
  20834. }
  20835. $lmargin = $this->lMargin;
  20836. $rmargin = $this->rMargin;
  20837. $current_page = $this->page;
  20838. $current_column = $this->current_column;
  20839. }
  20840. $this->SetX($x_start);
  20841. $indent = ($spacer * $outline['l']);
  20842. if ($this->rtl) {
  20843. $this->x -= $indent;
  20844. $this->rMargin = $this->w - $this->x;
  20845. } else {
  20846. $this->x += $indent;
  20847. $this->lMargin = $this->x;
  20848. }
  20849. $link = $this->AddLink();
  20850. $this->SetLink($link, $outline['y'], $outline['p']);
  20851. // write the text
  20852. if ($this->rtl) {
  20853. $txt = ' '.$outline['t'];
  20854. } else {
  20855. $txt = $outline['t'].' ';
  20856. }
  20857. $this->Write(0, $txt, $link, false, $aligntext, false, 0, false, false, 0, $numwidth, '');
  20858. if ($this->rtl) {
  20859. $tw = $this->x - $this->lMargin;
  20860. } else {
  20861. $tw = $this->w - $this->rMargin - $this->x;
  20862. }
  20863. $this->SetFont($numbersfont, $fontstyle, $fontsize);
  20864. if (TCPDF_STATIC::empty_string($page)) {
  20865. $pagenum = $outline['p'];
  20866. } else {
  20867. // placemark to be replaced with the correct number
  20868. $pagenum = '{#'.($outline['p']).'}';
  20869. if ($this->isUnicodeFont()) {
  20870. $pagenum = '{'.$pagenum.'}';
  20871. }
  20872. $maxpage = max($maxpage, $outline['p']);
  20873. }
  20874. $fw = ($tw - $this->GetStringWidth($pagenum.$filler));
  20875. $wfiller = $this->GetStringWidth($filler);
  20876. if ($wfiller > 0) {
  20877. $numfills = floor($fw / $wfiller);
  20878. } else {
  20879. $numfills = 0;
  20880. }
  20881. if ($numfills > 0) {
  20882. $rowfill = str_repeat($filler, $numfills);
  20883. } else {
  20884. $rowfill = '';
  20885. }
  20886. if ($this->rtl) {
  20887. $pagenum = $pagenum.$gap.$rowfill;
  20888. } else {
  20889. $pagenum = $rowfill.$gap.$pagenum;
  20890. }
  20891. // write the number
  20892. $this->Cell($tw, 0, $pagenum, 0, 1, $alignnum, 0, $link, 0);
  20893. }
  20894. $page_last = $this->getPage();
  20895. $numpages = ($page_last - $page_first + 1);
  20896. // account for booklet mode
  20897. if ($this->booklet) {
  20898. // check if a blank page is required before TOC
  20899. $page_fill_start = ((($page_first % 2) == 0) XOR (($page % 2) == 0));
  20900. $page_fill_end = (!((($numpages % 2) == 0) XOR ($page_fill_start)));
  20901. if ($page_fill_start) {
  20902. // add a page at the end (to be moved before TOC)
  20903. $this->addPage();
  20904. ++$page_last;
  20905. ++$numpages;
  20906. }
  20907. if ($page_fill_end) {
  20908. // add a page at the end
  20909. $this->addPage();
  20910. ++$page_last;
  20911. ++$numpages;
  20912. }
  20913. }
  20914. $maxpage = max($maxpage, $page_last);
  20915. if (!TCPDF_STATIC::empty_string($page)) {
  20916. for ($p = $page_first; $p <= $page_last; ++$p) {
  20917. // get page data
  20918. $temppage = $this->getPageBuffer($p);
  20919. for ($n = 1; $n <= $maxpage; ++$n) {
  20920. // update page numbers
  20921. $a = '{#'.$n.'}';
  20922. // get page number aliases
  20923. $pnalias = $this->getInternalPageNumberAliases($a);
  20924. // calculate replacement number
  20925. if (($n >= $page) AND ($n <= $this->numpages)) {
  20926. $np = $n + $numpages;
  20927. } else {
  20928. $np = $n;
  20929. }
  20930. $na = TCPDF_STATIC::formatTOCPageNumber(($this->starting_page_number + $np - 1));
  20931. $nu = TCPDF_FONTS::UTF8ToUTF16BE($na, false, $this->isunicode, $this->CurrentFont);
  20932. // replace aliases with numbers
  20933. foreach ($pnalias['u'] as $u) {
  20934. $sfill = str_repeat($filler, max(0, (strlen($u) - strlen($nu.' '))));
  20935. if ($this->rtl) {
  20936. $nr = $nu.TCPDF_FONTS::UTF8ToUTF16BE(' '.$sfill, false, $this->isunicode, $this->CurrentFont);
  20937. } else {
  20938. $nr = TCPDF_FONTS::UTF8ToUTF16BE($sfill.' ', false, $this->isunicode, $this->CurrentFont).$nu;
  20939. }
  20940. $temppage = str_replace($u, $nr, $temppage);
  20941. }
  20942. foreach ($pnalias['a'] as $a) {
  20943. $sfill = str_repeat($filler, max(0, (strlen($a) - strlen($na.' '))));
  20944. if ($this->rtl) {
  20945. $nr = $na.' '.$sfill;
  20946. } else {
  20947. $nr = $sfill.' '.$na;
  20948. }
  20949. $temppage = str_replace($a, $nr, $temppage);
  20950. }
  20951. }
  20952. // save changes
  20953. $this->setPageBuffer($p, $temppage);
  20954. }
  20955. // move pages
  20956. $this->Bookmark($toc_name, 0, 0, $page_first, $style, $color);
  20957. if ($page_fill_start) {
  20958. $this->movePage($page_last, $page_first);
  20959. }
  20960. for ($i = 0; $i < $numpages; ++$i) {
  20961. $this->movePage($page_last, $page);
  20962. }
  20963. }
  20964. }
  20965. /**
  20966. * Output a Table Of Content Index (TOC) using HTML templates.
  20967. * This method must be called after all Bookmarks were set.
  20968. * Before calling this method you have to open the page using the addTOCPage() method.
  20969. * After calling this method you have to call endTOCPage() to close the TOC page.
  20970. * @param $page (int) page number where this TOC should be inserted (leave empty for current page).
  20971. * @param $toc_name (string) name to use for TOC bookmark.
  20972. * @param $templates (array) array of html templates. Use: "#TOC_DESCRIPTION#" for bookmark title, "#TOC_PAGE_NUMBER#" for page number.
  20973. * @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)
  20974. * @param $style (string) Font style for title: B = Bold, I = Italic, BI = Bold + Italic.
  20975. * @param $color (array) RGB color array for title (values from 0 to 255).
  20976. * @public
  20977. * @author Nicola Asuni
  20978. * @since 5.0.001 (2010-05-06)
  20979. * @see addTOCPage(), endTOCPage(), addTOC()
  20980. */
  20981. public function addHTMLTOC($page='', $toc_name='TOC', $templates=array(), $correct_align=true, $style='', $color=array(0,0,0)) {
  20982. $filler = ' ';
  20983. $prev_htmlLinkColorArray = $this->htmlLinkColorArray;
  20984. $prev_htmlLinkFontStyle = $this->htmlLinkFontStyle;
  20985. // set new style for link
  20986. $this->htmlLinkColorArray = array();
  20987. $this->htmlLinkFontStyle = '';
  20988. $page_first = $this->getPage();
  20989. $page_fill_start = false;
  20990. $page_fill_end = false;
  20991. // get the font type used for numbers in each template
  20992. $current_font = $this->FontFamily;
  20993. foreach ($templates as $level => $html) {
  20994. $dom = $this->getHtmlDomArray($html);
  20995. foreach ($dom as $key => $value) {
  20996. if ($value['value'] == '#TOC_PAGE_NUMBER#') {
  20997. $this->SetFont($dom[($key - 1)]['fontname']);
  20998. $templates['F'.$level] = $this->isUnicodeFont();
  20999. }
  21000. }
  21001. }
  21002. $this->SetFont($current_font);
  21003. $maxpage = 0; //used for pages on attached documents
  21004. foreach ($this->outlines as $key => $outline) {
  21005. // get HTML template
  21006. $row = $templates[$outline['l']];
  21007. if (TCPDF_STATIC::empty_string($page)) {
  21008. $pagenum = $outline['p'];
  21009. } else {
  21010. // placemark to be replaced with the correct number
  21011. $pagenum = '{#'.($outline['p']).'}';
  21012. if (isset($templates['F'.$outline['l']]) && $templates['F'.$outline['l']]) {
  21013. $pagenum = '{'.$pagenum.'}';
  21014. }
  21015. $maxpage = max($maxpage, $outline['p']);
  21016. }
  21017. // replace templates with current values
  21018. $row = str_replace('#TOC_DESCRIPTION#', $outline['t'], $row);
  21019. $row = str_replace('#TOC_PAGE_NUMBER#', $pagenum, $row);
  21020. // add link to page
  21021. $row = '<a href="#'.$outline['p'].','.$outline['y'].'">'.$row.'</a>';
  21022. // write bookmark entry
  21023. $this->writeHTML($row, false, false, true, false, '');
  21024. }
  21025. // restore link styles
  21026. $this->htmlLinkColorArray = $prev_htmlLinkColorArray;
  21027. $this->htmlLinkFontStyle = $prev_htmlLinkFontStyle;
  21028. // move TOC page and replace numbers
  21029. $page_last = $this->getPage();
  21030. $numpages = ($page_last - $page_first + 1);
  21031. // account for booklet mode
  21032. if ($this->booklet) {
  21033. // check if a blank page is required before TOC
  21034. $page_fill_start = ((($page_first % 2) == 0) XOR (($page % 2) == 0));
  21035. $page_fill_end = (!((($numpages % 2) == 0) XOR ($page_fill_start)));
  21036. if ($page_fill_start) {
  21037. // add a page at the end (to be moved before TOC)
  21038. $this->addPage();
  21039. ++$page_last;
  21040. ++$numpages;
  21041. }
  21042. if ($page_fill_end) {
  21043. // add a page at the end
  21044. $this->addPage();
  21045. ++$page_last;
  21046. ++$numpages;
  21047. }
  21048. }
  21049. $maxpage = max($maxpage, $page_last);
  21050. if (!TCPDF_STATIC::empty_string($page)) {
  21051. for ($p = $page_first; $p <= $page_last; ++$p) {
  21052. // get page data
  21053. $temppage = $this->getPageBuffer($p);
  21054. for ($n = 1; $n <= $maxpage; ++$n) {
  21055. // update page numbers
  21056. $a = '{#'.$n.'}';
  21057. // get page number aliases
  21058. $pnalias = $this->getInternalPageNumberAliases($a);
  21059. // calculate replacement number
  21060. if ($n >= $page) {
  21061. $np = $n + $numpages;
  21062. } else {
  21063. $np = $n;
  21064. }
  21065. $na = TCPDF_STATIC::formatTOCPageNumber(($this->starting_page_number + $np - 1));
  21066. $nu = TCPDF_FONTS::UTF8ToUTF16BE($na, false, $this->isunicode, $this->CurrentFont);
  21067. // replace aliases with numbers
  21068. foreach ($pnalias['u'] as $u) {
  21069. if ($correct_align) {
  21070. $sfill = str_repeat($filler, (strlen($u) - strlen($nu.' ')));
  21071. if ($this->rtl) {
  21072. $nr = $nu.TCPDF_FONTS::UTF8ToUTF16BE(' '.$sfill, false, $this->isunicode, $this->CurrentFont);
  21073. } else {
  21074. $nr = TCPDF_FONTS::UTF8ToUTF16BE($sfill.' ', false, $this->isunicode, $this->CurrentFont).$nu;
  21075. }
  21076. } else {
  21077. $nr = $nu;
  21078. }
  21079. $temppage = str_replace($u, $nr, $temppage);
  21080. }
  21081. foreach ($pnalias['a'] as $a) {
  21082. if ($correct_align) {
  21083. $sfill = str_repeat($filler, (strlen($a) - strlen($na.' ')));
  21084. if ($this->rtl) {
  21085. $nr = $na.' '.$sfill;
  21086. } else {
  21087. $nr = $sfill.' '.$na;
  21088. }
  21089. } else {
  21090. $nr = $na;
  21091. }
  21092. $temppage = str_replace($a, $nr, $temppage);
  21093. }
  21094. }
  21095. // save changes
  21096. $this->setPageBuffer($p, $temppage);
  21097. }
  21098. // move pages
  21099. $this->Bookmark($toc_name, 0, 0, $page_first, $style, $color);
  21100. if ($page_fill_start) {
  21101. $this->movePage($page_last, $page_first);
  21102. }
  21103. for ($i = 0; $i < $numpages; ++$i) {
  21104. $this->movePage($page_last, $page);
  21105. }
  21106. }
  21107. }
  21108. /**
  21109. * Stores a copy of the current TCPDF object used for undo operation.
  21110. * @public
  21111. * @since 4.5.029 (2009-03-19)
  21112. */
  21113. public function startTransaction() {
  21114. if (isset($this->objcopy)) {
  21115. // remove previous copy
  21116. $this->commitTransaction();
  21117. }
  21118. // record current page number and Y position
  21119. $this->start_transaction_page = $this->page;
  21120. $this->start_transaction_y = $this->y;
  21121. // clone current object
  21122. $this->objcopy = TCPDF_STATIC::objclone($this);
  21123. }
  21124. /**
  21125. * Delete the copy of the current TCPDF object used for undo operation.
  21126. * @public
  21127. * @since 4.5.029 (2009-03-19)
  21128. */
  21129. public function commitTransaction() {
  21130. if (isset($this->objcopy)) {
  21131. $this->objcopy->_destroy(true, true);
  21132. /* The unique file_id should not be used during cleanup again */
  21133. $this->objcopy->file_id = NULL;
  21134. unset($this->objcopy);
  21135. }
  21136. }
  21137. /**
  21138. * This method allows to undo the latest transaction by returning the latest saved TCPDF object with startTransaction().
  21139. * @param $self (boolean) if true restores current class object to previous state without the need of reassignment via the returned value.
  21140. * @return TCPDF object.
  21141. * @public
  21142. * @since 4.5.029 (2009-03-19)
  21143. */
  21144. public function rollbackTransaction($self=false) {
  21145. if (isset($this->objcopy)) {
  21146. $objcopy = $this->objcopy;
  21147. $this->_destroy(true, true);
  21148. if ($self) {
  21149. $objvars = get_object_vars($objcopy);
  21150. foreach ($objvars as $key => $value) {
  21151. $this->$key = $value;
  21152. }
  21153. $objcopy->_destroy(true, true);
  21154. /* The unique file_id should not be used during cleanup again */
  21155. $objcopy->file_id = NULL;
  21156. unset($objcopy);
  21157. return $this;
  21158. }
  21159. /* The unique file_id should not be used during cleanup again */
  21160. $this->file_id = NULL;
  21161. return $objcopy;
  21162. }
  21163. return $this;
  21164. }
  21165. // --- MULTI COLUMNS METHODS -----------------------
  21166. /**
  21167. * Set multiple columns of the same size
  21168. * @param $numcols (int) number of columns (set to zero to disable columns mode)
  21169. * @param $width (int) column width
  21170. * @param $y (int) column starting Y position (leave empty for current Y position)
  21171. * @public
  21172. * @since 4.9.001 (2010-03-28)
  21173. */
  21174. public function setEqualColumns($numcols=0, $width=0, $y='') {
  21175. $this->columns = array();
  21176. if ($numcols < 2) {
  21177. $numcols = 0;
  21178. $this->columns = array();
  21179. } else {
  21180. // maximum column width
  21181. $maxwidth = ($this->w - $this->original_lMargin - $this->original_rMargin) / $numcols;
  21182. if (($width == 0) OR ($width > $maxwidth)) {
  21183. $width = $maxwidth;
  21184. }
  21185. if (TCPDF_STATIC::empty_string($y)) {
  21186. $y = $this->y;
  21187. }
  21188. // space between columns
  21189. $space = (($this->w - $this->original_lMargin - $this->original_rMargin - ($numcols * $width)) / ($numcols - 1));
  21190. // fill the columns array (with, space, starting Y position)
  21191. for ($i = 0; $i < $numcols; ++$i) {
  21192. $this->columns[$i] = array('w' => $width, 's' => $space, 'y' => $y);
  21193. }
  21194. }
  21195. $this->num_columns = $numcols;
  21196. $this->current_column = 0;
  21197. $this->column_start_page = $this->page;
  21198. $this->selectColumn(0);
  21199. }
  21200. /**
  21201. * Remove columns and reset page margins.
  21202. * @public
  21203. * @since 5.9.072 (2011-04-26)
  21204. */
  21205. public function resetColumns() {
  21206. $this->lMargin = $this->original_lMargin;
  21207. $this->rMargin = $this->original_rMargin;
  21208. $this->setEqualColumns();
  21209. }
  21210. /**
  21211. * Set columns array.
  21212. * Each column is represented by an array of arrays with the following keys: (w = width, s = space between columns, y = column top position).
  21213. * @param $columns (array)
  21214. * @public
  21215. * @since 4.9.001 (2010-03-28)
  21216. */
  21217. public function setColumnsArray($columns) {
  21218. $this->columns = $columns;
  21219. $this->num_columns = count($columns);
  21220. $this->current_column = 0;
  21221. $this->column_start_page = $this->page;
  21222. $this->selectColumn(0);
  21223. }
  21224. /**
  21225. * Set position at a given column
  21226. * @param $col (int) column number (from 0 to getNumberOfColumns()-1); empty string = current column.
  21227. * @public
  21228. * @since 4.9.001 (2010-03-28)
  21229. */
  21230. public function selectColumn($col='') {
  21231. if (is_string($col)) {
  21232. $col = $this->current_column;
  21233. } elseif ($col >= $this->num_columns) {
  21234. $col = 0;
  21235. }
  21236. $xshift = array('x' => 0, 's' => array('H' => 0, 'V' => 0), 'p' => array('L' => 0, 'T' => 0, 'R' => 0, 'B' => 0));
  21237. $enable_thead = false;
  21238. if ($this->num_columns > 1) {
  21239. if ($col != $this->current_column) {
  21240. // move Y pointer at the top of the column
  21241. if ($this->column_start_page == $this->page) {
  21242. $this->y = $this->columns[$col]['y'];
  21243. } else {
  21244. $this->y = $this->tMargin;
  21245. }
  21246. // Avoid to write table headers more than once
  21247. if (($this->page > $this->maxselcol['page']) OR (($this->page == $this->maxselcol['page']) AND ($col > $this->maxselcol['column']))) {
  21248. $enable_thead = true;
  21249. $this->maxselcol['page'] = $this->page;
  21250. $this->maxselcol['column'] = $col;
  21251. }
  21252. }
  21253. $xshift = $this->colxshift;
  21254. // set X position of the current column by case
  21255. $listindent = ($this->listindentlevel * $this->listindent);
  21256. // calculate column X position
  21257. $colpos = 0;
  21258. for ($i = 0; $i < $col; ++$i) {
  21259. $colpos += ($this->columns[$i]['w'] + $this->columns[$i]['s']);
  21260. }
  21261. if ($this->rtl) {
  21262. $x = $this->w - $this->original_rMargin - $colpos;
  21263. $this->rMargin = ($this->w - $x + $listindent);
  21264. $this->lMargin = ($x - $this->columns[$col]['w']);
  21265. $this->x = $x - $listindent;
  21266. } else {
  21267. $x = $this->original_lMargin + $colpos;
  21268. $this->lMargin = ($x + $listindent);
  21269. $this->rMargin = ($this->w - $x - $this->columns[$col]['w']);
  21270. $this->x = $x + $listindent;
  21271. }
  21272. $this->columns[$col]['x'] = $x;
  21273. }
  21274. $this->current_column = $col;
  21275. // fix for HTML mode
  21276. $this->newline = true;
  21277. // print HTML table header (if any)
  21278. if ((!TCPDF_STATIC::empty_string($this->thead)) AND (!$this->inthead)) {
  21279. if ($enable_thead) {
  21280. // print table header
  21281. $this->writeHTML($this->thead, false, false, false, false, '');
  21282. $this->y += $xshift['s']['V'];
  21283. // store end of header position
  21284. if (!isset($this->columns[$col]['th'])) {
  21285. $this->columns[$col]['th'] = array();
  21286. }
  21287. $this->columns[$col]['th']['\''.$this->page.'\''] = $this->y;
  21288. $this->lasth = 0;
  21289. } elseif (isset($this->columns[$col]['th']['\''.$this->page.'\''])) {
  21290. $this->y = $this->columns[$col]['th']['\''.$this->page.'\''];
  21291. }
  21292. }
  21293. // account for an html table cell over multiple columns
  21294. if ($this->rtl) {
  21295. $this->rMargin += $xshift['x'];
  21296. $this->x -= ($xshift['x'] + $xshift['p']['R']);
  21297. } else {
  21298. $this->lMargin += $xshift['x'];
  21299. $this->x += $xshift['x'] + $xshift['p']['L'];
  21300. }
  21301. }
  21302. /**
  21303. * Return the current column number
  21304. * @return int current column number
  21305. * @public
  21306. * @since 5.5.011 (2010-07-08)
  21307. */
  21308. public function getColumn() {
  21309. return $this->current_column;
  21310. }
  21311. /**
  21312. * Return the current number of columns.
  21313. * @return int number of columns
  21314. * @public
  21315. * @since 5.8.018 (2010-08-25)
  21316. */
  21317. public function getNumberOfColumns() {
  21318. return $this->num_columns;
  21319. }
  21320. /**
  21321. * Set Text rendering mode.
  21322. * @param $stroke (int) outline size in user units (0 = disable).
  21323. * @param $fill (boolean) if true fills the text (default).
  21324. * @param $clip (boolean) if true activate clipping mode
  21325. * @public
  21326. * @since 4.9.008 (2009-04-02)
  21327. */
  21328. public function setTextRenderingMode($stroke=0, $fill=true, $clip=false) {
  21329. // Ref.: PDF 32000-1:2008 - 9.3.6 Text Rendering Mode
  21330. // convert text rendering parameters
  21331. if ($stroke < 0) {
  21332. $stroke = 0;
  21333. }
  21334. if ($fill === true) {
  21335. if ($stroke > 0) {
  21336. if ($clip === true) {
  21337. // Fill, then stroke text and add to path for clipping
  21338. $textrendermode = 6;
  21339. } else {
  21340. // Fill, then stroke text
  21341. $textrendermode = 2;
  21342. }
  21343. $textstrokewidth = $stroke;
  21344. } else {
  21345. if ($clip === true) {
  21346. // Fill text and add to path for clipping
  21347. $textrendermode = 4;
  21348. } else {
  21349. // Fill text
  21350. $textrendermode = 0;
  21351. }
  21352. }
  21353. } else {
  21354. if ($stroke > 0) {
  21355. if ($clip === true) {
  21356. // Stroke text and add to path for clipping
  21357. $textrendermode = 5;
  21358. } else {
  21359. // Stroke text
  21360. $textrendermode = 1;
  21361. }
  21362. $textstrokewidth = $stroke;
  21363. } else {
  21364. if ($clip === true) {
  21365. // Add text to path for clipping
  21366. $textrendermode = 7;
  21367. } else {
  21368. // Neither fill nor stroke text (invisible)
  21369. $textrendermode = 3;
  21370. }
  21371. }
  21372. }
  21373. $this->textrendermode = $textrendermode;
  21374. $this->textstrokewidth = $stroke;
  21375. }
  21376. /**
  21377. * Set parameters for drop shadow effect for text.
  21378. * @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.
  21379. * @since 5.9.174 (2012-07-25)
  21380. * @public
  21381. */
  21382. public function setTextShadow($params=array('enabled'=>false, 'depth_w'=>0, 'depth_h'=>0, 'color'=>false, 'opacity'=>1, 'blend_mode'=>'Normal')) {
  21383. if (isset($params['enabled'])) {
  21384. $this->txtshadow['enabled'] = $params['enabled']?true:false;
  21385. } else {
  21386. $this->txtshadow['enabled'] = false;
  21387. }
  21388. if (isset($params['depth_w'])) {
  21389. $this->txtshadow['depth_w'] = floatval($params['depth_w']);
  21390. } else {
  21391. $this->txtshadow['depth_w'] = 0;
  21392. }
  21393. if (isset($params['depth_h'])) {
  21394. $this->txtshadow['depth_h'] = floatval($params['depth_h']);
  21395. } else {
  21396. $this->txtshadow['depth_h'] = 0;
  21397. }
  21398. if (isset($params['color']) AND ($params['color'] !== false) AND is_array($params['color'])) {
  21399. $this->txtshadow['color'] = $params['color'];
  21400. } else {
  21401. $this->txtshadow['color'] = $this->strokecolor;
  21402. }
  21403. if (isset($params['opacity'])) {
  21404. $this->txtshadow['opacity'] = min(1, max(0, floatval($params['opacity'])));
  21405. } else {
  21406. $this->txtshadow['opacity'] = 1;
  21407. }
  21408. 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'))) {
  21409. $this->txtshadow['blend_mode'] = $params['blend_mode'];
  21410. } else {
  21411. $this->txtshadow['blend_mode'] = 'Normal';
  21412. }
  21413. if ((($this->txtshadow['depth_w'] == 0) AND ($this->txtshadow['depth_h'] == 0)) OR ($this->txtshadow['opacity'] == 0)) {
  21414. $this->txtshadow['enabled'] = false;
  21415. }
  21416. }
  21417. /**
  21418. * Return the text shadow parameters array.
  21419. * @return Array of parameters.
  21420. * @since 5.9.174 (2012-07-25)
  21421. * @public
  21422. */
  21423. public function getTextShadow() {
  21424. return $this->txtshadow;
  21425. }
  21426. /**
  21427. * Returns an array of chars containing soft hyphens.
  21428. * @param $word (array) array of chars
  21429. * @param $patterns (array) Array of hypenation patterns.
  21430. * @param $dictionary (array) Array of words to be returned without applying the hyphenation algorithm.
  21431. * @param $leftmin (int) Minimum number of character to leave on the left of the word without applying the hyphens.
  21432. * @param $rightmin (int) Minimum number of character to leave on the right of the word without applying the hyphens.
  21433. * @param $charmin (int) Minimum word length to apply the hyphenation algorithm.
  21434. * @param $charmax (int) Maximum length of broken piece of word.
  21435. * @return array text with soft hyphens
  21436. * @author Nicola Asuni
  21437. * @since 4.9.012 (2010-04-12)
  21438. * @protected
  21439. */
  21440. protected function hyphenateWord($word, $patterns, $dictionary=array(), $leftmin=1, $rightmin=2, $charmin=1, $charmax=8) {
  21441. $hyphenword = array(); // hyphens positions
  21442. $numchars = count($word);
  21443. if ($numchars <= $charmin) {
  21444. return $word;
  21445. }
  21446. $word_string = TCPDF_FONTS::UTF8ArrSubString($word, '', '', $this->isunicode);
  21447. // some words will be returned as-is
  21448. $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})(\]?)$/';
  21449. if (preg_match($pattern, $word_string) > 0) {
  21450. // email
  21451. return $word;
  21452. }
  21453. $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})(\]?)$/';
  21454. if (preg_match($pattern, $word_string) > 0) {
  21455. // URL
  21456. return $word;
  21457. }
  21458. if (isset($dictionary[$word_string])) {
  21459. return TCPDF_FONTS::UTF8StringToArray($dictionary[$word_string], $this->isunicode, $this->CurrentFont);
  21460. }
  21461. // surround word with '_' characters
  21462. $tmpword = array_merge(array(46), $word, array(46));
  21463. $tmpnumchars = $numchars + 2;
  21464. $maxpos = $tmpnumchars - 1;
  21465. for ($pos = 0; $pos < $maxpos; ++$pos) {
  21466. $imax = min(($tmpnumchars - $pos), $charmax);
  21467. for ($i = 1; $i <= $imax; ++$i) {
  21468. $subword = strtolower(TCPDF_FONTS::UTF8ArrSubString($tmpword, $pos, ($pos + $i), $this->isunicode));
  21469. if (isset($patterns[$subword])) {
  21470. $pattern = TCPDF_FONTS::UTF8StringToArray($patterns[$subword], $this->isunicode, $this->CurrentFont);
  21471. $pattern_length = count($pattern);
  21472. $digits = 1;
  21473. for ($j = 0; $j < $pattern_length; ++$j) {
  21474. // check if $pattern[$j] is a number = hyphenation level (only numbers from 1 to 5 are valid)
  21475. if (($pattern[$j] >= 48) AND ($pattern[$j] <= 57)) {
  21476. if ($j == 0) {
  21477. $zero = $pos - 1;
  21478. } else {
  21479. $zero = $pos + $j - $digits;
  21480. }
  21481. // get hyphenation level
  21482. $level = ($pattern[$j] - 48);
  21483. // if two levels from two different patterns match at the same point, the higher one is selected.
  21484. if (!isset($hyphenword[$zero]) OR ($hyphenword[$zero] < $level)) {
  21485. $hyphenword[$zero] = $level;
  21486. }
  21487. ++$digits;
  21488. }
  21489. }
  21490. }
  21491. }
  21492. }
  21493. $inserted = 0;
  21494. $maxpos = $numchars - $rightmin;
  21495. for ($i = $leftmin; $i <= $maxpos; ++$i) {
  21496. // only odd levels indicate allowed hyphenation points
  21497. if (isset($hyphenword[$i]) AND (($hyphenword[$i] % 2) != 0)) {
  21498. // 173 = soft hyphen character
  21499. array_splice($word, $i + $inserted, 0, 173);
  21500. ++$inserted;
  21501. }
  21502. }
  21503. return $word;
  21504. }
  21505. /**
  21506. * Returns text with soft hyphens.
  21507. * @param $text (string) text to process
  21508. * @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/
  21509. * @param $dictionary (array) Array of words to be returned without applying the hyphenation algorithm.
  21510. * @param $leftmin (int) Minimum number of character to leave on the left of the word without applying the hyphens.
  21511. * @param $rightmin (int) Minimum number of character to leave on the right of the word without applying the hyphens.
  21512. * @param $charmin (int) Minimum word length to apply the hyphenation algorithm.
  21513. * @param $charmax (int) Maximum length of broken piece of word.
  21514. * @return array text with soft hyphens
  21515. * @author Nicola Asuni
  21516. * @since 4.9.012 (2010-04-12)
  21517. * @public
  21518. */
  21519. public function hyphenateText($text, $patterns, $dictionary=array(), $leftmin=1, $rightmin=2, $charmin=1, $charmax=8) {
  21520. $text = $this->unhtmlentities($text);
  21521. $word = array(); // last word
  21522. $txtarr = array(); // text to be returned
  21523. $intag = false; // true if we are inside an HTML tag
  21524. $skip = false; // true to skip hyphenation
  21525. if (!is_array($patterns)) {
  21526. $patterns = TCPDF_STATIC::getHyphenPatternsFromTEX($patterns);
  21527. }
  21528. // get array of characters
  21529. $unichars = TCPDF_FONTS::UTF8StringToArray($text, $this->isunicode, $this->CurrentFont);
  21530. // for each char
  21531. foreach ($unichars as $char) {
  21532. if ((!$intag) AND (!$skip) AND TCPDF_FONT_DATA::$uni_type[$char] == 'L') {
  21533. // letter character
  21534. $word[] = $char;
  21535. } else {
  21536. // other type of character
  21537. if (!TCPDF_STATIC::empty_string($word)) {
  21538. // hypenate the word
  21539. $txtarr = array_merge($txtarr, $this->hyphenateWord($word, $patterns, $dictionary, $leftmin, $rightmin, $charmin, $charmax));
  21540. $word = array();
  21541. }
  21542. $txtarr[] = $char;
  21543. if (chr($char) == '<') {
  21544. // we are inside an HTML tag
  21545. $intag = true;
  21546. } elseif ($intag AND (chr($char) == '>')) {
  21547. // end of HTML tag
  21548. $intag = false;
  21549. // check for style tag
  21550. $expected = array(115, 116, 121, 108, 101); // = 'style'
  21551. $current = array_slice($txtarr, -6, 5); // last 5 chars
  21552. $compare = array_diff($expected, $current);
  21553. if (empty($compare)) {
  21554. // check if it is a closing tag
  21555. $expected = array(47); // = '/'
  21556. $current = array_slice($txtarr, -7, 1);
  21557. $compare = array_diff($expected, $current);
  21558. if (empty($compare)) {
  21559. // closing style tag
  21560. $skip = false;
  21561. } else {
  21562. // opening style tag
  21563. $skip = true;
  21564. }
  21565. }
  21566. }
  21567. }
  21568. }
  21569. if (!TCPDF_STATIC::empty_string($word)) {
  21570. // hypenate the word
  21571. $txtarr = array_merge($txtarr, $this->hyphenateWord($word, $patterns, $dictionary, $leftmin, $rightmin, $charmin, $charmax));
  21572. }
  21573. // convert char array to string and return
  21574. return TCPDF_FONTS::UTF8ArrSubString($txtarr, '', '', $this->isunicode);
  21575. }
  21576. /**
  21577. * Enable/disable rasterization of vector images using ImageMagick library.
  21578. * @param $mode (boolean) if true enable rasterization, false otherwise.
  21579. * @public
  21580. * @since 5.0.000 (2010-04-27)
  21581. */
  21582. public function setRasterizeVectorImages($mode) {
  21583. $this->rasterize_vector_images = $mode;
  21584. }
  21585. /**
  21586. * Enable or disable default option for font subsetting.
  21587. * @param $enable (boolean) if true enable font subsetting by default.
  21588. * @author Nicola Asuni
  21589. * @public
  21590. * @since 5.3.002 (2010-06-07)
  21591. */
  21592. public function setFontSubsetting($enable=true) {
  21593. if ($this->pdfa_mode) {
  21594. $this->font_subsetting = false;
  21595. } else {
  21596. $this->font_subsetting = $enable ? true : false;
  21597. }
  21598. }
  21599. /**
  21600. * Return the default option for font subsetting.
  21601. * @return boolean default font subsetting state.
  21602. * @author Nicola Asuni
  21603. * @public
  21604. * @since 5.3.002 (2010-06-07)
  21605. */
  21606. public function getFontSubsetting() {
  21607. return $this->font_subsetting;
  21608. }
  21609. /**
  21610. * Left trim the input string
  21611. * @param $str (string) string to trim
  21612. * @param $replace (string) string that replace spaces.
  21613. * @return left trimmed string
  21614. * @author Nicola Asuni
  21615. * @public
  21616. * @since 5.8.000 (2010-08-11)
  21617. */
  21618. public function stringLeftTrim($str, $replace='') {
  21619. return preg_replace('/^'.$this->re_space['p'].'+/'.$this->re_space['m'], $replace, $str);
  21620. }
  21621. /**
  21622. * Right trim the input string
  21623. * @param $str (string) string to trim
  21624. * @param $replace (string) string that replace spaces.
  21625. * @return right trimmed string
  21626. * @author Nicola Asuni
  21627. * @public
  21628. * @since 5.8.000 (2010-08-11)
  21629. */
  21630. public function stringRightTrim($str, $replace='') {
  21631. return preg_replace('/'.$this->re_space['p'].'+$/'.$this->re_space['m'], $replace, $str);
  21632. }
  21633. /**
  21634. * Trim the input string
  21635. * @param $str (string) string to trim
  21636. * @param $replace (string) string that replace spaces.
  21637. * @return trimmed string
  21638. * @author Nicola Asuni
  21639. * @public
  21640. * @since 5.8.000 (2010-08-11)
  21641. */
  21642. public function stringTrim($str, $replace='') {
  21643. $str = $this->stringLeftTrim($str, $replace);
  21644. $str = $this->stringRightTrim($str, $replace);
  21645. return $str;
  21646. }
  21647. /**
  21648. * Return true if the current font is unicode type.
  21649. * @return true for unicode font, false otherwise.
  21650. * @author Nicola Asuni
  21651. * @public
  21652. * @since 5.8.002 (2010-08-14)
  21653. */
  21654. public function isUnicodeFont() {
  21655. return (($this->CurrentFont['type'] == 'TrueTypeUnicode') OR ($this->CurrentFont['type'] == 'cidfont0'));
  21656. }
  21657. /**
  21658. * Return normalized font name
  21659. * @param $fontfamily (string) property string containing font family names
  21660. * @return string normalized font name
  21661. * @author Nicola Asuni
  21662. * @public
  21663. * @since 5.8.004 (2010-08-17)
  21664. */
  21665. public function getFontFamilyName($fontfamily) {
  21666. // remove spaces and symbols
  21667. $fontfamily = preg_replace('/[^a-z0-9_\,]/', '', strtolower($fontfamily));
  21668. // extract all font names
  21669. $fontslist = preg_split('/[,]/', $fontfamily);
  21670. // find first valid font name
  21671. foreach ($fontslist as $font) {
  21672. // replace font variations
  21673. $font = preg_replace('/regular$/', '', $font);
  21674. $font = preg_replace('/italic$/', 'I', $font);
  21675. $font = preg_replace('/oblique$/', 'I', $font);
  21676. $font = preg_replace('/bold([I]?)$/', 'B\\1', $font);
  21677. // replace common family names and core fonts
  21678. $pattern = array();
  21679. $replacement = array();
  21680. $pattern[] = '/^serif|^cursive|^fantasy|^timesnewroman/';
  21681. $replacement[] = 'times';
  21682. $pattern[] = '/^sansserif/';
  21683. $replacement[] = 'helvetica';
  21684. $pattern[] = '/^monospace/';
  21685. $replacement[] = 'courier';
  21686. $font = preg_replace($pattern, $replacement, $font);
  21687. if (in_array(strtolower($font), $this->fontlist) OR in_array($font, $this->fontkeys)) {
  21688. return $font;
  21689. }
  21690. }
  21691. // return current font as default
  21692. return $this->CurrentFont['fontkey'];
  21693. }
  21694. /**
  21695. * Start a new XObject Template.
  21696. * 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).
  21697. * 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.
  21698. * Note: X,Y coordinates will be reset to 0,0.
  21699. * @param $w (int) Template width in user units (empty string or zero = page width less margins).
  21700. * @param $h (int) Template height in user units (empty string or zero = page height less margins).
  21701. * @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).
  21702. * @return int the XObject Template ID in case of success or false in case of error.
  21703. * @author Nicola Asuni
  21704. * @public
  21705. * @since 5.8.017 (2010-08-24)
  21706. * @see endTemplate(), printTemplate()
  21707. */
  21708. public function startTemplate($w=0, $h=0, $group=false) {
  21709. if ($this->inxobj) {
  21710. // we are already inside an XObject template
  21711. return false;
  21712. }
  21713. $this->inxobj = true;
  21714. ++$this->n;
  21715. // XObject ID
  21716. $this->xobjid = 'XT'.$this->n;
  21717. // object ID
  21718. $this->xobjects[$this->xobjid] = array('n' => $this->n);
  21719. // store current graphic state
  21720. $this->xobjects[$this->xobjid]['gvars'] = $this->getGraphicVars();
  21721. // initialize data
  21722. $this->xobjects[$this->xobjid]['intmrk'] = 0;
  21723. $this->xobjects[$this->xobjid]['transfmrk'] = array();
  21724. $this->xobjects[$this->xobjid]['outdata'] = '';
  21725. $this->xobjects[$this->xobjid]['xobjects'] = array();
  21726. $this->xobjects[$this->xobjid]['images'] = array();
  21727. $this->xobjects[$this->xobjid]['fonts'] = array();
  21728. $this->xobjects[$this->xobjid]['annotations'] = array();
  21729. $this->xobjects[$this->xobjid]['extgstates'] = array();
  21730. $this->xobjects[$this->xobjid]['gradients'] = array();
  21731. $this->xobjects[$this->xobjid]['spot_colors'] = array();
  21732. // set new environment
  21733. $this->num_columns = 1;
  21734. $this->current_column = 0;
  21735. $this->SetAutoPageBreak(false);
  21736. if (($w === '') OR ($w <= 0)) {
  21737. $w = $this->w - $this->lMargin - $this->rMargin;
  21738. }
  21739. if (($h === '') OR ($h <= 0)) {
  21740. $h = $this->h - $this->tMargin - $this->bMargin;
  21741. }
  21742. $this->xobjects[$this->xobjid]['x'] = 0;
  21743. $this->xobjects[$this->xobjid]['y'] = 0;
  21744. $this->xobjects[$this->xobjid]['w'] = $w;
  21745. $this->xobjects[$this->xobjid]['h'] = $h;
  21746. $this->w = $w;
  21747. $this->h = $h;
  21748. $this->wPt = $this->w * $this->k;
  21749. $this->hPt = $this->h * $this->k;
  21750. $this->fwPt = $this->wPt;
  21751. $this->fhPt = $this->hPt;
  21752. $this->x = 0;
  21753. $this->y = 0;
  21754. $this->lMargin = 0;
  21755. $this->rMargin = 0;
  21756. $this->tMargin = 0;
  21757. $this->bMargin = 0;
  21758. // set group mode
  21759. $this->xobjects[$this->xobjid]['group'] = $group;
  21760. return $this->xobjid;
  21761. }
  21762. /**
  21763. * End the current XObject Template started with startTemplate() and restore the previous graphic state.
  21764. * 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).
  21765. * 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.
  21766. * @return int the XObject Template ID in case of success or false in case of error.
  21767. * @author Nicola Asuni
  21768. * @public
  21769. * @since 5.8.017 (2010-08-24)
  21770. * @see startTemplate(), printTemplate()
  21771. */
  21772. public function endTemplate() {
  21773. if (!$this->inxobj) {
  21774. // we are not inside a template
  21775. return false;
  21776. }
  21777. $this->inxobj = false;
  21778. // restore previous graphic state
  21779. $this->setGraphicVars($this->xobjects[$this->xobjid]['gvars'], true);
  21780. return $this->xobjid;
  21781. }
  21782. /**
  21783. * Print an XObject Template.
  21784. * You can print an XObject Template inside the currently opened Template.
  21785. * 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).
  21786. * 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.
  21787. * @param $id (string) The ID of XObject Template to print.
  21788. * @param $x (int) X position in user units (empty string = current x position)
  21789. * @param $y (int) Y position in user units (empty string = current y position)
  21790. * @param $w (int) Width in user units (zero = remaining page width)
  21791. * @param $h (int) Height in user units (zero = remaining page height)
  21792. * @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>
  21793. * @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>
  21794. * @param $fitonpage (boolean) If true the template is resized to not exceed page dimensions.
  21795. * @author Nicola Asuni
  21796. * @public
  21797. * @since 5.8.017 (2010-08-24)
  21798. * @see startTemplate(), endTemplate()
  21799. */
  21800. public function printTemplate($id, $x='', $y='', $w=0, $h=0, $align='', $palign='', $fitonpage=false) {
  21801. if ($this->state != 2) {
  21802. return;
  21803. }
  21804. if (!isset($this->xobjects[$id])) {
  21805. $this->Error('The XObject Template \''.$id.'\' doesn\'t exist!');
  21806. }
  21807. if ($this->inxobj) {
  21808. if ($id == $this->xobjid) {
  21809. // close current template
  21810. $this->endTemplate();
  21811. } else {
  21812. // use the template as resource for the template currently opened
  21813. $this->xobjects[$this->xobjid]['xobjects'][$id] = $this->xobjects[$id];
  21814. }
  21815. }
  21816. // set default values
  21817. if ($x === '') {
  21818. $x = $this->x;
  21819. }
  21820. if ($y === '') {
  21821. $y = $this->y;
  21822. }
  21823. // check page for no-write regions and adapt page margins if necessary
  21824. list($x, $y) = $this->checkPageRegions($h, $x, $y);
  21825. $ow = $this->xobjects[$id]['w'];
  21826. if ($ow <= 0) {
  21827. $ow = 1;
  21828. }
  21829. $oh = $this->xobjects[$id]['h'];
  21830. if ($oh <= 0) {
  21831. $oh = 1;
  21832. }
  21833. // calculate template width and height on document
  21834. if (($w <= 0) AND ($h <= 0)) {
  21835. $w = $ow;
  21836. $h = $oh;
  21837. } elseif ($w <= 0) {
  21838. $w = $h * $ow / $oh;
  21839. } elseif ($h <= 0) {
  21840. $h = $w * $oh / $ow;
  21841. }
  21842. // fit the template on available space
  21843. list($w, $h, $x, $y) = $this->fitBlock($w, $h, $x, $y, $fitonpage);
  21844. // set page alignment
  21845. $rb_y = $y + $h;
  21846. // set alignment
  21847. if ($this->rtl) {
  21848. if ($palign == 'L') {
  21849. $xt = $this->lMargin;
  21850. } elseif ($palign == 'C') {
  21851. $xt = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
  21852. } elseif ($palign == 'R') {
  21853. $xt = $this->w - $this->rMargin - $w;
  21854. } else {
  21855. $xt = $x - $w;
  21856. }
  21857. $rb_x = $xt;
  21858. } else {
  21859. if ($palign == 'L') {
  21860. $xt = $this->lMargin;
  21861. } elseif ($palign == 'C') {
  21862. $xt = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
  21863. } elseif ($palign == 'R') {
  21864. $xt = $this->w - $this->rMargin - $w;
  21865. } else {
  21866. $xt = $x;
  21867. }
  21868. $rb_x = $xt + $w;
  21869. }
  21870. // print XObject Template + Transformation matrix
  21871. $this->StartTransform();
  21872. // translate and scale
  21873. $sx = ($w / $ow);
  21874. $sy = ($h / $oh);
  21875. $tm = array();
  21876. $tm[0] = $sx;
  21877. $tm[1] = 0;
  21878. $tm[2] = 0;
  21879. $tm[3] = $sy;
  21880. $tm[4] = $xt * $this->k;
  21881. $tm[5] = ($this->h - $h - $y) * $this->k;
  21882. $this->Transform($tm);
  21883. // set object
  21884. $this->_out('/'.$id.' Do');
  21885. $this->StopTransform();
  21886. // add annotations
  21887. if (!empty($this->xobjects[$id]['annotations'])) {
  21888. foreach ($this->xobjects[$id]['annotations'] as $annot) {
  21889. // transform original coordinates
  21890. $coordlt = TCPDF_STATIC::getTransformationMatrixProduct($tm, array(1, 0, 0, 1, ($annot['x'] * $this->k), (-$annot['y'] * $this->k)));
  21891. $ax = ($coordlt[4] / $this->k);
  21892. $ay = ($this->h - $h - ($coordlt[5] / $this->k));
  21893. $coordrb = TCPDF_STATIC::getTransformationMatrixProduct($tm, array(1, 0, 0, 1, (($annot['x'] + $annot['w']) * $this->k), ((-$annot['y'] - $annot['h']) * $this->k)));
  21894. $aw = ($coordrb[4] / $this->k) - $ax;
  21895. $ah = ($this->h - $h - ($coordrb[5] / $this->k)) - $ay;
  21896. $this->Annotation($ax, $ay, $aw, $ah, $annot['text'], $annot['opt'], $annot['spaces']);
  21897. }
  21898. }
  21899. // set pointer to align the next text/objects
  21900. switch($align) {
  21901. case 'T': {
  21902. $this->y = $y;
  21903. $this->x = $rb_x;
  21904. break;
  21905. }
  21906. case 'M': {
  21907. $this->y = $y + round($h/2);
  21908. $this->x = $rb_x;
  21909. break;
  21910. }
  21911. case 'B': {
  21912. $this->y = $rb_y;
  21913. $this->x = $rb_x;
  21914. break;
  21915. }
  21916. case 'N': {
  21917. $this->SetY($rb_y);
  21918. break;
  21919. }
  21920. default:{
  21921. break;
  21922. }
  21923. }
  21924. }
  21925. /**
  21926. * Set the percentage of character stretching.
  21927. * @param $perc (int) percentage of stretching (100 = no stretching)
  21928. * @author Nicola Asuni
  21929. * @public
  21930. * @since 5.9.000 (2010-09-29)
  21931. */
  21932. public function setFontStretching($perc=100) {
  21933. $this->font_stretching = $perc;
  21934. }
  21935. /**
  21936. * Get the percentage of character stretching.
  21937. * @return float stretching value
  21938. * @author Nicola Asuni
  21939. * @public
  21940. * @since 5.9.000 (2010-09-29)
  21941. */
  21942. public function getFontStretching() {
  21943. return $this->font_stretching;
  21944. }
  21945. /**
  21946. * Set the amount to increase or decrease the space between characters in a text.
  21947. * @param $spacing (float) amount to increase or decrease the space between characters in a text (0 = default spacing)
  21948. * @author Nicola Asuni
  21949. * @public
  21950. * @since 5.9.000 (2010-09-29)
  21951. */
  21952. public function setFontSpacing($spacing=0) {
  21953. $this->font_spacing = $spacing;
  21954. }
  21955. /**
  21956. * Get the amount to increase or decrease the space between characters in a text.
  21957. * @return int font spacing (tracking) value
  21958. * @author Nicola Asuni
  21959. * @public
  21960. * @since 5.9.000 (2010-09-29)
  21961. */
  21962. public function getFontSpacing() {
  21963. return $this->font_spacing;
  21964. }
  21965. /**
  21966. * Return an array of no-write page regions
  21967. * @return array of no-write page regions
  21968. * @author Nicola Asuni
  21969. * @public
  21970. * @since 5.9.003 (2010-10-13)
  21971. * @see setPageRegions(), addPageRegion()
  21972. */
  21973. public function getPageRegions() {
  21974. return $this->page_regions;
  21975. }
  21976. /**
  21977. * Set no-write regions on page.
  21978. * 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.
  21979. * A region is always aligned on the left or right side of the page ad is defined using a vertical segment.
  21980. * You can set multiple regions for the same page.
  21981. * @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.
  21982. * @author Nicola Asuni
  21983. * @public
  21984. * @since 5.9.003 (2010-10-13)
  21985. * @see addPageRegion(), getPageRegions()
  21986. */
  21987. public function setPageRegions($regions=array()) {
  21988. // empty current regions array
  21989. $this->page_regions = array();
  21990. // add regions
  21991. foreach ($regions as $data) {
  21992. $this->addPageRegion($data);
  21993. }
  21994. }
  21995. /**
  21996. * Add a single no-write region on selected page.
  21997. * 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.
  21998. * A region is always aligned on the left or right side of the page ad is defined using a vertical segment.
  21999. * You can set multiple regions for the same page.
  22000. * @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).
  22001. * @author Nicola Asuni
  22002. * @public
  22003. * @since 5.9.003 (2010-10-13)
  22004. * @see setPageRegions(), getPageRegions()
  22005. */
  22006. public function addPageRegion($region) {
  22007. if (!isset($region['page']) OR empty($region['page'])) {
  22008. $region['page'] = $this->page;
  22009. }
  22010. if (isset($region['xt']) AND isset($region['xb']) AND ($region['xt'] > 0) AND ($region['xb'] > 0)
  22011. AND isset($region['yt']) AND isset($region['yb']) AND ($region['yt'] >= 0) AND ($region['yt'] < $region['yb'])
  22012. AND isset($region['side']) AND (($region['side'] == 'L') OR ($region['side'] == 'R'))) {
  22013. $this->page_regions[] = $region;
  22014. }
  22015. }
  22016. /**
  22017. * Remove a single no-write region.
  22018. * @param $key (int) region key
  22019. * @author Nicola Asuni
  22020. * @public
  22021. * @since 5.9.003 (2010-10-13)
  22022. * @see setPageRegions(), getPageRegions()
  22023. */
  22024. public function removePageRegion($key) {
  22025. if (isset($this->page_regions[$key])) {
  22026. unset($this->page_regions[$key]);
  22027. }
  22028. }
  22029. /**
  22030. * Check page for no-write regions and adapt current coordinates and page margins if necessary.
  22031. * 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.
  22032. * A region is always aligned on the left or right side of the page ad is defined using a vertical segment.
  22033. * @param $h (float) height of the text/image/object to print in user units
  22034. * @param $x (float) current X coordinate in user units
  22035. * @param $y (float) current Y coordinate in user units
  22036. * @return array($x, $y)
  22037. * @author Nicola Asuni
  22038. * @protected
  22039. * @since 5.9.003 (2010-10-13)
  22040. */
  22041. protected function checkPageRegions($h, $x, $y) {
  22042. // set default values
  22043. if ($x === '') {
  22044. $x = $this->x;
  22045. }
  22046. if ($y === '') {
  22047. $y = $this->y;
  22048. }
  22049. if (!$this->check_page_regions OR empty($this->page_regions)) {
  22050. // no page regions defined
  22051. return array($x, $y);
  22052. }
  22053. if (empty($h)) {
  22054. $h = $this->getCellHeight($this->FontSize);
  22055. }
  22056. // check for page break
  22057. if ($this->checkPageBreak($h, $y)) {
  22058. // the content will be printed on a new page
  22059. $x = $this->x;
  22060. $y = $this->y;
  22061. }
  22062. if ($this->num_columns > 1) {
  22063. if ($this->rtl) {
  22064. $this->lMargin = ($this->columns[$this->current_column]['x'] - $this->columns[$this->current_column]['w']);
  22065. } else {
  22066. $this->rMargin = ($this->w - $this->columns[$this->current_column]['x'] - $this->columns[$this->current_column]['w']);
  22067. }
  22068. } else {
  22069. if ($this->rtl) {
  22070. $this->lMargin = max($this->clMargin, $this->original_lMargin);
  22071. } else {
  22072. $this->rMargin = max($this->crMargin, $this->original_rMargin);
  22073. }
  22074. }
  22075. // adjust coordinates and page margins
  22076. foreach ($this->page_regions as $regid => $regdata) {
  22077. if ($regdata['page'] == $this->page) {
  22078. // check region boundaries
  22079. if (($y > ($regdata['yt'] - $h)) AND ($y <= $regdata['yb'])) {
  22080. // Y is inside the region
  22081. $minv = ($regdata['xb'] - $regdata['xt']) / ($regdata['yb'] - $regdata['yt']); // inverse of angular coefficient
  22082. $yt = max($y, $regdata['yt']);
  22083. $yb = min(($yt + $h), $regdata['yb']);
  22084. $xt = (($yt - $regdata['yt']) * $minv) + $regdata['xt'];
  22085. $xb = (($yb - $regdata['yt']) * $minv) + $regdata['xt'];
  22086. if ($regdata['side'] == 'L') { // left side
  22087. $new_margin = max($xt, $xb);
  22088. if ($this->lMargin < $new_margin) {
  22089. if ($this->rtl) {
  22090. // adjust left page margin
  22091. $this->lMargin = max(0, $new_margin);
  22092. }
  22093. if ($x < $new_margin) {
  22094. // adjust x position
  22095. $x = $new_margin;
  22096. if ($new_margin > ($this->w - $this->rMargin)) {
  22097. // adjust y position
  22098. $y = $regdata['yb'] - $h;
  22099. }
  22100. }
  22101. }
  22102. } elseif ($regdata['side'] == 'R') { // right side
  22103. $new_margin = min($xt, $xb);
  22104. if (($this->w - $this->rMargin) > $new_margin) {
  22105. if (!$this->rtl) {
  22106. // adjust right page margin
  22107. $this->rMargin = max(0, ($this->w - $new_margin));
  22108. }
  22109. if ($x > $new_margin) {
  22110. // adjust x position
  22111. $x = $new_margin;
  22112. if ($new_margin > $this->lMargin) {
  22113. // adjust y position
  22114. $y = $regdata['yb'] - $h;
  22115. }
  22116. }
  22117. }
  22118. }
  22119. }
  22120. }
  22121. }
  22122. return array($x, $y);
  22123. }
  22124. // --- SVG METHODS ---------------------------------------------------------
  22125. /**
  22126. * Embedd a Scalable Vector Graphics (SVG) image.
  22127. * NOTE: SVG standard is not yet fully implemented, use the setRasterizeVectorImages() method to enable/disable rasterization of vector images using ImageMagick library.
  22128. * @param $file (string) Name of the SVG file or a '@' character followed by the SVG data string.
  22129. * @param $x (float) Abscissa of the upper-left corner.
  22130. * @param $y (float) Ordinate of the upper-left corner.
  22131. * @param $w (float) Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
  22132. * @param $h (float) Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
  22133. * @param $link (mixed) URL or identifier returned by AddLink().
  22134. * @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.
  22135. * @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>
  22136. * @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)))
  22137. * @param $fitonpage (boolean) if true the image is resized to not exceed page dimensions.
  22138. * @author Nicola Asuni
  22139. * @since 5.0.000 (2010-05-02)
  22140. * @public
  22141. */
  22142. public function ImageSVG($file, $x='', $y='', $w=0, $h=0, $link='', $align='', $palign='', $border=0, $fitonpage=false) {
  22143. if ($this->state != 2) {
  22144. return;
  22145. }
  22146. // reset SVG vars
  22147. $this->svggradients = array();
  22148. $this->svggradientid = 0;
  22149. $this->svgdefsmode = false;
  22150. $this->svgdefs = array();
  22151. $this->svgclipmode = false;
  22152. $this->svgclippaths = array();
  22153. $this->svgcliptm = array();
  22154. $this->svgclipid = 0;
  22155. $this->svgtext = '';
  22156. $this->svgtextmode = array();
  22157. if ($this->rasterize_vector_images AND ($w > 0) AND ($h > 0)) {
  22158. // convert SVG to raster image using GD or ImageMagick libraries
  22159. return $this->Image($file, $x, $y, $w, $h, 'SVG', $link, $align, true, 300, $palign, false, false, $border, false, false, false);
  22160. }
  22161. if ($file[0] === '@') { // image from string
  22162. $this->svgdir = '';
  22163. $svgdata = substr($file, 1);
  22164. } else { // SVG file
  22165. $this->svgdir = dirname($file);
  22166. $svgdata = $this->getCachedFileContents($file);
  22167. }
  22168. if ($svgdata === FALSE) {
  22169. $this->Error('SVG file not found: '.$file);
  22170. }
  22171. if ($x === '') {
  22172. $x = $this->x;
  22173. }
  22174. if ($y === '') {
  22175. $y = $this->y;
  22176. }
  22177. // check page for no-write regions and adapt page margins if necessary
  22178. list($x, $y) = $this->checkPageRegions($h, $x, $y);
  22179. $k = $this->k;
  22180. $ox = 0;
  22181. $oy = 0;
  22182. $ow = $w;
  22183. $oh = $h;
  22184. $aspect_ratio_align = 'xMidYMid';
  22185. $aspect_ratio_ms = 'meet';
  22186. $regs = array();
  22187. // get original image width and height
  22188. preg_match('/<svg([^\>]*)>/si', $svgdata, $regs);
  22189. if (isset($regs[1]) AND !empty($regs[1])) {
  22190. $tmp = array();
  22191. if (preg_match('/[\s]+x[\s]*=[\s]*"([^"]*)"/si', $regs[1], $tmp)) {
  22192. $ox = $this->getHTMLUnitToUnits($tmp[1], 0, $this->svgunit, false);
  22193. }
  22194. $tmp = array();
  22195. if (preg_match('/[\s]+y[\s]*=[\s]*"([^"]*)"/si', $regs[1], $tmp)) {
  22196. $oy = $this->getHTMLUnitToUnits($tmp[1], 0, $this->svgunit, false);
  22197. }
  22198. $tmp = array();
  22199. if (preg_match('/[\s]+width[\s]*=[\s]*"([^"]*)"/si', $regs[1], $tmp)) {
  22200. $ow = $this->getHTMLUnitToUnits($tmp[1], 1, $this->svgunit, false);
  22201. }
  22202. $tmp = array();
  22203. if (preg_match('/[\s]+height[\s]*=[\s]*"([^"]*)"/si', $regs[1], $tmp)) {
  22204. $oh = $this->getHTMLUnitToUnits($tmp[1], 1, $this->svgunit, false);
  22205. }
  22206. $tmp = array();
  22207. $view_box = array();
  22208. if (preg_match('/[\s]+viewBox[\s]*=[\s]*"[\s]*([0-9\.\-]+)[\s]+([0-9\.\-]+)[\s]+([0-9\.]+)[\s]+([0-9\.]+)[\s]*"/si', $regs[1], $tmp)) {
  22209. if (count($tmp) == 5) {
  22210. array_shift($tmp);
  22211. foreach ($tmp as $key => $val) {
  22212. $view_box[$key] = $this->getHTMLUnitToUnits($val, 0, $this->svgunit, false);
  22213. }
  22214. $ox = $view_box[0];
  22215. $oy = $view_box[1];
  22216. }
  22217. // get aspect ratio
  22218. $tmp = array();
  22219. if (preg_match('/[\s]+preserveAspectRatio[\s]*=[\s]*"([^"]*)"/si', $regs[1], $tmp)) {
  22220. $aspect_ratio = preg_split('/[\s]+/si', $tmp[1]);
  22221. switch (count($aspect_ratio)) {
  22222. case 3: {
  22223. $aspect_ratio_align = $aspect_ratio[1];
  22224. $aspect_ratio_ms = $aspect_ratio[2];
  22225. break;
  22226. }
  22227. case 2: {
  22228. $aspect_ratio_align = $aspect_ratio[0];
  22229. $aspect_ratio_ms = $aspect_ratio[1];
  22230. break;
  22231. }
  22232. case 1: {
  22233. $aspect_ratio_align = $aspect_ratio[0];
  22234. $aspect_ratio_ms = 'meet';
  22235. break;
  22236. }
  22237. }
  22238. }
  22239. }
  22240. }
  22241. if ($ow <= 0) {
  22242. $ow = 1;
  22243. }
  22244. if ($oh <= 0) {
  22245. $oh = 1;
  22246. }
  22247. // calculate image width and height on document
  22248. if (($w <= 0) AND ($h <= 0)) {
  22249. // convert image size to document unit
  22250. $w = $ow;
  22251. $h = $oh;
  22252. } elseif ($w <= 0) {
  22253. $w = $h * $ow / $oh;
  22254. } elseif ($h <= 0) {
  22255. $h = $w * $oh / $ow;
  22256. }
  22257. // fit the image on available space
  22258. list($w, $h, $x, $y) = $this->fitBlock($w, $h, $x, $y, $fitonpage);
  22259. if ($this->rasterize_vector_images) {
  22260. // convert SVG to raster image using GD or ImageMagick libraries
  22261. return $this->Image($file, $x, $y, $w, $h, 'SVG', $link, $align, true, 300, $palign, false, false, $border, false, false, false);
  22262. }
  22263. // set alignment
  22264. $this->img_rb_y = $y + $h;
  22265. // set alignment
  22266. if ($this->rtl) {
  22267. if ($palign == 'L') {
  22268. $ximg = $this->lMargin;
  22269. } elseif ($palign == 'C') {
  22270. $ximg = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
  22271. } elseif ($palign == 'R') {
  22272. $ximg = $this->w - $this->rMargin - $w;
  22273. } else {
  22274. $ximg = $x - $w;
  22275. }
  22276. $this->img_rb_x = $ximg;
  22277. } else {
  22278. if ($palign == 'L') {
  22279. $ximg = $this->lMargin;
  22280. } elseif ($palign == 'C') {
  22281. $ximg = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
  22282. } elseif ($palign == 'R') {
  22283. $ximg = $this->w - $this->rMargin - $w;
  22284. } else {
  22285. $ximg = $x;
  22286. }
  22287. $this->img_rb_x = $ximg + $w;
  22288. }
  22289. // store current graphic vars
  22290. $gvars = $this->getGraphicVars();
  22291. // store SVG position and scale factors
  22292. $svgoffset_x = ($ximg - $ox) * $this->k;
  22293. $svgoffset_y = -($y - $oy) * $this->k;
  22294. if (isset($view_box[2]) AND ($view_box[2] > 0) AND ($view_box[3] > 0)) {
  22295. $ow = $view_box[2];
  22296. $oh = $view_box[3];
  22297. } else {
  22298. if ($ow <= 0) {
  22299. $ow = $w;
  22300. }
  22301. if ($oh <= 0) {
  22302. $oh = $h;
  22303. }
  22304. }
  22305. $svgscale_x = $w / $ow;
  22306. $svgscale_y = $h / $oh;
  22307. // scaling and alignment
  22308. if ($aspect_ratio_align != 'none') {
  22309. // store current scaling values
  22310. $svgscale_old_x = $svgscale_x;
  22311. $svgscale_old_y = $svgscale_y;
  22312. // force uniform scaling
  22313. if ($aspect_ratio_ms == 'slice') {
  22314. // the entire viewport is covered by the viewBox
  22315. if ($svgscale_x > $svgscale_y) {
  22316. $svgscale_y = $svgscale_x;
  22317. } elseif ($svgscale_x < $svgscale_y) {
  22318. $svgscale_x = $svgscale_y;
  22319. }
  22320. } else { // meet
  22321. // the entire viewBox is visible within the viewport
  22322. if ($svgscale_x < $svgscale_y) {
  22323. $svgscale_y = $svgscale_x;
  22324. } elseif ($svgscale_x > $svgscale_y) {
  22325. $svgscale_x = $svgscale_y;
  22326. }
  22327. }
  22328. // correct X alignment
  22329. switch (substr($aspect_ratio_align, 1, 3)) {
  22330. case 'Min': {
  22331. // do nothing
  22332. break;
  22333. }
  22334. case 'Max': {
  22335. $svgoffset_x += (($w * $this->k) - ($ow * $this->k * $svgscale_x));
  22336. break;
  22337. }
  22338. default:
  22339. case 'Mid': {
  22340. $svgoffset_x += ((($w * $this->k) - ($ow * $this->k * $svgscale_x)) / 2);
  22341. break;
  22342. }
  22343. }
  22344. // correct Y alignment
  22345. switch (substr($aspect_ratio_align, 5)) {
  22346. case 'Min': {
  22347. // do nothing
  22348. break;
  22349. }
  22350. case 'Max': {
  22351. $svgoffset_y -= (($h * $this->k) - ($oh * $this->k * $svgscale_y));
  22352. break;
  22353. }
  22354. default:
  22355. case 'Mid': {
  22356. $svgoffset_y -= ((($h * $this->k) - ($oh * $this->k * $svgscale_y)) / 2);
  22357. break;
  22358. }
  22359. }
  22360. }
  22361. // store current page break mode
  22362. $page_break_mode = $this->AutoPageBreak;
  22363. $page_break_margin = $this->getBreakMargin();
  22364. $cell_padding = $this->cell_padding;
  22365. $this->SetCellPadding(0);
  22366. $this->SetAutoPageBreak(false);
  22367. // save the current graphic state
  22368. $this->_out('q'.$this->epsmarker);
  22369. // set initial clipping mask
  22370. $this->Rect($ximg, $y, $w, $h, 'CNZ', array(), array());
  22371. // scale and translate
  22372. $e = $ox * $this->k * (1 - $svgscale_x);
  22373. $f = ($this->h - $oy) * $this->k * (1 - $svgscale_y);
  22374. $this->_out(sprintf('%F %F %F %F %F %F cm', $svgscale_x, 0, 0, $svgscale_y, ($e + $svgoffset_x), ($f + $svgoffset_y)));
  22375. // creates a new XML parser to be used by the other XML functions
  22376. $parser = xml_parser_create('UTF-8');
  22377. // the following function allows to use parser inside object
  22378. xml_set_object($parser, $this);
  22379. // disable case-folding for this XML parser
  22380. xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
  22381. // sets the element handler functions for the XML parser
  22382. xml_set_element_handler($parser, 'startSVGElementHandler', 'endSVGElementHandler');
  22383. // sets the character data handler function for the XML parser
  22384. xml_set_character_data_handler($parser, 'segSVGContentHandler');
  22385. // start parsing an XML document
  22386. if (!xml_parse($parser, $svgdata)) {
  22387. $error_message = sprintf('SVG Error: %s at line %d', xml_error_string(xml_get_error_code($parser)), xml_get_current_line_number($parser));
  22388. $this->Error($error_message);
  22389. }
  22390. // free this XML parser
  22391. xml_parser_free($parser);
  22392. // >= PHP 7.0.0 "explicitly unset the reference to parser to avoid memory leaks"
  22393. unset($parser);
  22394. // restore previous graphic state
  22395. $this->_out($this->epsmarker.'Q');
  22396. // restore graphic vars
  22397. $this->setGraphicVars($gvars);
  22398. $this->lasth = $gvars['lasth'];
  22399. if (!empty($border)) {
  22400. $bx = $this->x;
  22401. $by = $this->y;
  22402. $this->x = $ximg;
  22403. if ($this->rtl) {
  22404. $this->x += $w;
  22405. }
  22406. $this->y = $y;
  22407. $this->Cell($w, $h, '', $border, 0, '', 0, '', 0, true);
  22408. $this->x = $bx;
  22409. $this->y = $by;
  22410. }
  22411. if ($link) {
  22412. $this->Link($ximg, $y, $w, $h, $link, 0);
  22413. }
  22414. // set pointer to align the next text/objects
  22415. switch($align) {
  22416. case 'T':{
  22417. $this->y = $y;
  22418. $this->x = $this->img_rb_x;
  22419. break;
  22420. }
  22421. case 'M':{
  22422. $this->y = $y + round($h/2);
  22423. $this->x = $this->img_rb_x;
  22424. break;
  22425. }
  22426. case 'B':{
  22427. $this->y = $this->img_rb_y;
  22428. $this->x = $this->img_rb_x;
  22429. break;
  22430. }
  22431. case 'N':{
  22432. $this->SetY($this->img_rb_y);
  22433. break;
  22434. }
  22435. default:{
  22436. // restore pointer to starting position
  22437. $this->x = $gvars['x'];
  22438. $this->y = $gvars['y'];
  22439. $this->page = $gvars['page'];
  22440. $this->current_column = $gvars['current_column'];
  22441. $this->tMargin = $gvars['tMargin'];
  22442. $this->bMargin = $gvars['bMargin'];
  22443. $this->w = $gvars['w'];
  22444. $this->h = $gvars['h'];
  22445. $this->wPt = $gvars['wPt'];
  22446. $this->hPt = $gvars['hPt'];
  22447. $this->fwPt = $gvars['fwPt'];
  22448. $this->fhPt = $gvars['fhPt'];
  22449. break;
  22450. }
  22451. }
  22452. $this->endlinex = $this->img_rb_x;
  22453. // restore page break
  22454. $this->SetAutoPageBreak($page_break_mode, $page_break_margin);
  22455. $this->cell_padding = $cell_padding;
  22456. }
  22457. /**
  22458. * Convert SVG transformation matrix to PDF.
  22459. * @param $tm (array) original SVG transformation matrix
  22460. * @return array transformation matrix
  22461. * @protected
  22462. * @since 5.0.000 (2010-05-02)
  22463. */
  22464. protected function convertSVGtMatrix($tm) {
  22465. $a = $tm[0];
  22466. $b = -$tm[1];
  22467. $c = -$tm[2];
  22468. $d = $tm[3];
  22469. $e = $this->getHTMLUnitToUnits($tm[4], 1, $this->svgunit, false) * $this->k;
  22470. $f = -$this->getHTMLUnitToUnits($tm[5], 1, $this->svgunit, false) * $this->k;
  22471. $x = 0;
  22472. $y = $this->h * $this->k;
  22473. $e = ($x * (1 - $a)) - ($y * $c) + $e;
  22474. $f = ($y * (1 - $d)) - ($x * $b) + $f;
  22475. return array($a, $b, $c, $d, $e, $f);
  22476. }
  22477. /**
  22478. * Apply SVG graphic transformation matrix.
  22479. * @param $tm (array) original SVG transformation matrix
  22480. * @protected
  22481. * @since 5.0.000 (2010-05-02)
  22482. */
  22483. protected function SVGTransform($tm) {
  22484. $this->Transform($this->convertSVGtMatrix($tm));
  22485. }
  22486. /**
  22487. * Apply the requested SVG styles (*** TO BE COMPLETED ***)
  22488. * @param $svgstyle (array) array of SVG styles to apply
  22489. * @param $prevsvgstyle (array) array of previous SVG style
  22490. * @param $x (int) X origin of the bounding box
  22491. * @param $y (int) Y origin of the bounding box
  22492. * @param $w (int) width of the bounding box
  22493. * @param $h (int) height of the bounding box
  22494. * @param $clip_function (string) clip function
  22495. * @param $clip_params (array) array of parameters for clipping function
  22496. * @return object style
  22497. * @author Nicola Asuni
  22498. * @since 5.0.000 (2010-05-02)
  22499. * @protected
  22500. */
  22501. protected function setSVGStyles($svgstyle, $prevsvgstyle, $x=0, $y=0, $w=1, $h=1, $clip_function='', $clip_params=array()) {
  22502. if ($this->state != 2) {
  22503. return;
  22504. }
  22505. $objstyle = '';
  22506. $minlen = (0.01 / $this->k); // minimum acceptable length
  22507. if (!isset($svgstyle['opacity'])) {
  22508. return $objstyle;
  22509. }
  22510. // clip-path
  22511. $regs = array();
  22512. if (preg_match('/url\([\s]*\#([^\)]*)\)/si', $svgstyle['clip-path'], $regs)) {
  22513. $clip_path = $this->svgclippaths[$regs[1]];
  22514. foreach ($clip_path as $cp) {
  22515. $this->startSVGElementHandler('clip-path', $cp['name'], $cp['attribs'], $cp['tm']);
  22516. }
  22517. }
  22518. // opacity
  22519. if ($svgstyle['opacity'] != 1) {
  22520. $this->setAlpha($svgstyle['opacity'], 'Normal', $svgstyle['opacity'], false);
  22521. }
  22522. // color
  22523. $fill_color = TCPDF_COLORS::convertHTMLColorToDec($svgstyle['color'], $this->spot_colors);
  22524. $this->SetFillColorArray($fill_color);
  22525. // text color
  22526. $text_color = TCPDF_COLORS::convertHTMLColorToDec($svgstyle['text-color'], $this->spot_colors);
  22527. $this->SetTextColorArray($text_color);
  22528. // clip
  22529. if (preg_match('/rect\(([a-z0-9\-\.]*)[\s]*([a-z0-9\-\.]*)[\s]*([a-z0-9\-\.]*)[\s]*([a-z0-9\-\.]*)\)/si', $svgstyle['clip'], $regs)) {
  22530. $top = (isset($regs[1])?$this->getHTMLUnitToUnits($regs[1], 0, $this->svgunit, false):0);
  22531. $right = (isset($regs[2])?$this->getHTMLUnitToUnits($regs[2], 0, $this->svgunit, false):0);
  22532. $bottom = (isset($regs[3])?$this->getHTMLUnitToUnits($regs[3], 0, $this->svgunit, false):0);
  22533. $left = (isset($regs[4])?$this->getHTMLUnitToUnits($regs[4], 0, $this->svgunit, false):0);
  22534. $cx = $x + $left;
  22535. $cy = $y + $top;
  22536. $cw = $w - $left - $right;
  22537. $ch = $h - $top - $bottom;
  22538. if ($svgstyle['clip-rule'] == 'evenodd') {
  22539. $clip_rule = 'CNZ';
  22540. } else {
  22541. $clip_rule = 'CEO';
  22542. }
  22543. $this->Rect($cx, $cy, $cw, $ch, $clip_rule, array(), array());
  22544. }
  22545. // fill
  22546. $regs = array();
  22547. if (preg_match('/url\([\s]*\#([^\)]*)\)/si', $svgstyle['fill'], $regs)) {
  22548. // gradient
  22549. $gradient = $this->svggradients[$regs[1]];
  22550. if (isset($gradient['xref'])) {
  22551. // reference to another gradient definition
  22552. $newgradient = $this->svggradients[$gradient['xref']];
  22553. $newgradient['coords'] = $gradient['coords'];
  22554. $newgradient['mode'] = $gradient['mode'];
  22555. $newgradient['type'] = $gradient['type'];
  22556. $newgradient['gradientUnits'] = $gradient['gradientUnits'];
  22557. if (isset($gradient['gradientTransform'])) {
  22558. $newgradient['gradientTransform'] = $gradient['gradientTransform'];
  22559. }
  22560. $gradient = $newgradient;
  22561. }
  22562. //save current Graphic State
  22563. $this->_outSaveGraphicsState();
  22564. //set clipping area
  22565. if (!empty($clip_function) AND method_exists($this, $clip_function)) {
  22566. $bbox = call_user_func_array(array($this, $clip_function), $clip_params);
  22567. if ((!isset($gradient['type']) OR ($gradient['type'] != 3)) AND is_array($bbox) AND (count($bbox) == 4)) {
  22568. list($x, $y, $w, $h) = $bbox;
  22569. }
  22570. }
  22571. if ($gradient['mode'] == 'measure') {
  22572. if (!isset($gradient['coords'][4])) {
  22573. $gradient['coords'][4] = 0.5;
  22574. }
  22575. if (isset($gradient['gradientTransform']) AND !empty($gradient['gradientTransform'])) {
  22576. $gtm = $gradient['gradientTransform'];
  22577. // apply transformation matrix
  22578. $xa = ($gtm[0] * $gradient['coords'][0]) + ($gtm[2] * $gradient['coords'][1]) + $gtm[4];
  22579. $ya = ($gtm[1] * $gradient['coords'][0]) + ($gtm[3] * $gradient['coords'][1]) + $gtm[5];
  22580. $xb = ($gtm[0] * $gradient['coords'][2]) + ($gtm[2] * $gradient['coords'][3]) + $gtm[4];
  22581. $yb = ($gtm[1] * $gradient['coords'][2]) + ($gtm[3] * $gradient['coords'][3]) + $gtm[5];
  22582. $r = sqrt(pow(($gtm[0] * $gradient['coords'][4]), 2) + pow(($gtm[1] * $gradient['coords'][4]), 2));
  22583. $gradient['coords'][0] = $xa;
  22584. $gradient['coords'][1] = $ya;
  22585. $gradient['coords'][2] = $xb;
  22586. $gradient['coords'][3] = $yb;
  22587. $gradient['coords'][4] = $r;
  22588. }
  22589. // convert SVG coordinates to user units
  22590. $gradient['coords'][0] = $this->getHTMLUnitToUnits($gradient['coords'][0], 0, $this->svgunit, false);
  22591. $gradient['coords'][1] = $this->getHTMLUnitToUnits($gradient['coords'][1], 0, $this->svgunit, false);
  22592. $gradient['coords'][2] = $this->getHTMLUnitToUnits($gradient['coords'][2], 0, $this->svgunit, false);
  22593. $gradient['coords'][3] = $this->getHTMLUnitToUnits($gradient['coords'][3], 0, $this->svgunit, false);
  22594. $gradient['coords'][4] = $this->getHTMLUnitToUnits($gradient['coords'][4], 0, $this->svgunit, false);
  22595. if ($w <= $minlen) {
  22596. $w = $minlen;
  22597. }
  22598. if ($h <= $minlen) {
  22599. $h = $minlen;
  22600. }
  22601. // shift units
  22602. if ($gradient['gradientUnits'] == 'objectBoundingBox') {
  22603. // convert to SVG coordinate system
  22604. $gradient['coords'][0] += $x;
  22605. $gradient['coords'][1] += $y;
  22606. $gradient['coords'][2] += $x;
  22607. $gradient['coords'][3] += $y;
  22608. }
  22609. // calculate percentages
  22610. $gradient['coords'][0] = (($gradient['coords'][0] - $x) / $w);
  22611. $gradient['coords'][1] = (($gradient['coords'][1] - $y) / $h);
  22612. $gradient['coords'][2] = (($gradient['coords'][2] - $x) / $w);
  22613. $gradient['coords'][3] = (($gradient['coords'][3] - $y) / $h);
  22614. $gradient['coords'][4] /= $w;
  22615. } elseif ($gradient['mode'] == 'percentage') {
  22616. foreach($gradient['coords'] as $key => $val) {
  22617. $gradient['coords'][$key] = (intval($val) / 100);
  22618. if ($val < 0) {
  22619. $gradient['coords'][$key] = 0;
  22620. } elseif ($val > 1) {
  22621. $gradient['coords'][$key] = 1;
  22622. }
  22623. }
  22624. }
  22625. if (($gradient['type'] == 2) AND ($gradient['coords'][0] == $gradient['coords'][2]) AND ($gradient['coords'][1] == $gradient['coords'][3])) {
  22626. // single color (no shading)
  22627. $gradient['coords'][0] = 1;
  22628. $gradient['coords'][1] = 0;
  22629. $gradient['coords'][2] = 0.999;
  22630. $gradient['coords'][3] = 0;
  22631. }
  22632. // swap Y coordinates
  22633. $tmp = $gradient['coords'][1];
  22634. $gradient['coords'][1] = $gradient['coords'][3];
  22635. $gradient['coords'][3] = $tmp;
  22636. // set transformation map for gradient
  22637. $cy = ($this->h - $y);
  22638. if ($gradient['type'] == 3) {
  22639. // circular gradient
  22640. $cy -= ($gradient['coords'][1] * ($w + $h));
  22641. $h = $w = max($w, $h);
  22642. } else {
  22643. $cy -= $h;
  22644. }
  22645. $this->_out(sprintf('%F 0 0 %F %F %F cm', ($w * $this->k), ($h * $this->k), ($x * $this->k), ($cy * $this->k)));
  22646. if (count($gradient['stops']) > 1) {
  22647. $this->Gradient($gradient['type'], $gradient['coords'], $gradient['stops'], array(), false);
  22648. }
  22649. } elseif ($svgstyle['fill'] != 'none') {
  22650. $fill_color = TCPDF_COLORS::convertHTMLColorToDec($svgstyle['fill'], $this->spot_colors);
  22651. if ($svgstyle['fill-opacity'] != 1) {
  22652. $this->setAlpha($this->alpha['CA'], 'Normal', $svgstyle['fill-opacity'], false);
  22653. }
  22654. $this->SetFillColorArray($fill_color);
  22655. if ($svgstyle['fill-rule'] == 'evenodd') {
  22656. $objstyle .= 'F*';
  22657. } else {
  22658. $objstyle .= 'F';
  22659. }
  22660. }
  22661. // stroke
  22662. if ($svgstyle['stroke'] != 'none') {
  22663. if ($svgstyle['stroke-opacity'] != 1) {
  22664. $this->setAlpha($svgstyle['stroke-opacity'], 'Normal', $this->alpha['ca'], false);
  22665. } elseif (preg_match('/rgba\(\d+%?,\s*\d+%?,\s*\d+%?,\s*(\d+(?:\.\d+)?)\)/i', $svgstyle['stroke'], $rgba_matches)) {
  22666. $this->setAlpha($rgba_matches[1], 'Normal', $this->alpha['ca'], false);
  22667. }
  22668. $stroke_style = array(
  22669. 'color' => TCPDF_COLORS::convertHTMLColorToDec($svgstyle['stroke'], $this->spot_colors),
  22670. 'width' => $this->getHTMLUnitToUnits($svgstyle['stroke-width'], 0, $this->svgunit, false),
  22671. 'cap' => $svgstyle['stroke-linecap'],
  22672. 'join' => $svgstyle['stroke-linejoin']
  22673. );
  22674. if (isset($svgstyle['stroke-dasharray']) AND !empty($svgstyle['stroke-dasharray']) AND ($svgstyle['stroke-dasharray'] != 'none')) {
  22675. $stroke_style['dash'] = $svgstyle['stroke-dasharray'];
  22676. }
  22677. $this->SetLineStyle($stroke_style);
  22678. $objstyle .= 'D';
  22679. }
  22680. // font
  22681. $regs = array();
  22682. if (!empty($svgstyle['font'])) {
  22683. if (preg_match('/font-family[\s]*:[\s]*([^\;\"]*)/si', $svgstyle['font'], $regs)) {
  22684. $font_family = $this->getFontFamilyName($regs[1]);
  22685. } else {
  22686. $font_family = $svgstyle['font-family'];
  22687. }
  22688. if (preg_match('/font-size[\s]*:[\s]*([^\s\;\"]*)/si', $svgstyle['font'], $regs)) {
  22689. $font_size = trim($regs[1]);
  22690. } else {
  22691. $font_size = $svgstyle['font-size'];
  22692. }
  22693. if (preg_match('/font-style[\s]*:[\s]*([^\s\;\"]*)/si', $svgstyle['font'], $regs)) {
  22694. $font_style = trim($regs[1]);
  22695. } else {
  22696. $font_style = $svgstyle['font-style'];
  22697. }
  22698. if (preg_match('/font-weight[\s]*:[\s]*([^\s\;\"]*)/si', $svgstyle['font'], $regs)) {
  22699. $font_weight = trim($regs[1]);
  22700. } else {
  22701. $font_weight = $svgstyle['font-weight'];
  22702. }
  22703. if (preg_match('/font-stretch[\s]*:[\s]*([^\s\;\"]*)/si', $svgstyle['font'], $regs)) {
  22704. $font_stretch = trim($regs[1]);
  22705. } else {
  22706. $font_stretch = $svgstyle['font-stretch'];
  22707. }
  22708. if (preg_match('/letter-spacing[\s]*:[\s]*([^\s\;\"]*)/si', $svgstyle['font'], $regs)) {
  22709. $font_spacing = trim($regs[1]);
  22710. } else {
  22711. $font_spacing = $svgstyle['letter-spacing'];
  22712. }
  22713. } else {
  22714. $font_family = $this->getFontFamilyName($svgstyle['font-family']);
  22715. $font_size = $svgstyle['font-size'];
  22716. $font_style = $svgstyle['font-style'];
  22717. $font_weight = $svgstyle['font-weight'];
  22718. $font_stretch = $svgstyle['font-stretch'];
  22719. $font_spacing = $svgstyle['letter-spacing'];
  22720. }
  22721. $font_size = $this->getHTMLFontUnits($font_size, $this->svgstyles[0]['font-size'], $prevsvgstyle['font-size'], $this->svgunit);
  22722. $font_stretch = $this->getCSSFontStretching($font_stretch, $svgstyle['font-stretch']);
  22723. $font_spacing = $this->getCSSFontSpacing($font_spacing, $svgstyle['letter-spacing']);
  22724. switch ($font_style) {
  22725. case 'italic': {
  22726. $font_style = 'I';
  22727. break;
  22728. }
  22729. case 'oblique': {
  22730. $font_style = 'I';
  22731. break;
  22732. }
  22733. default:
  22734. case 'normal': {
  22735. $font_style = '';
  22736. break;
  22737. }
  22738. }
  22739. switch ($font_weight) {
  22740. case 'bold':
  22741. case 'bolder': {
  22742. $font_style .= 'B';
  22743. break;
  22744. }
  22745. case 'normal': {
  22746. if ((substr($font_family, -1) == 'I') AND (substr($font_family, -2, 1) == 'B')) {
  22747. $font_family = substr($font_family, 0, -2).'I';
  22748. } elseif (substr($font_family, -1) == 'B') {
  22749. $font_family = substr($font_family, 0, -1);
  22750. }
  22751. break;
  22752. }
  22753. }
  22754. switch ($svgstyle['text-decoration']) {
  22755. case 'underline': {
  22756. $font_style .= 'U';
  22757. break;
  22758. }
  22759. case 'overline': {
  22760. $font_style .= 'O';
  22761. break;
  22762. }
  22763. case 'line-through': {
  22764. $font_style .= 'D';
  22765. break;
  22766. }
  22767. default:
  22768. case 'none': {
  22769. break;
  22770. }
  22771. }
  22772. $this->SetFont($font_family, $font_style, $font_size);
  22773. $this->setFontStretching($font_stretch);
  22774. $this->setFontSpacing($font_spacing);
  22775. return $objstyle;
  22776. }
  22777. /**
  22778. * Draws an SVG path
  22779. * @param $d (string) attribute d of the path SVG element
  22780. * @param $style (string) Style of rendering. Possible values are:
  22781. * <ul>
  22782. * <li>D or empty string: Draw (default).</li>
  22783. * <li>F: Fill.</li>
  22784. * <li>F*: Fill using the even-odd rule to determine which regions lie inside the clipping path.</li>
  22785. * <li>DF or FD: Draw and fill.</li>
  22786. * <li>DF* or FD*: Draw and fill using the even-odd rule to determine which regions lie inside the clipping path.</li>
  22787. * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
  22788. * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
  22789. * </ul>
  22790. * @return array of container box measures (x, y, w, h)
  22791. * @author Nicola Asuni
  22792. * @since 5.0.000 (2010-05-02)
  22793. * @protected
  22794. */
  22795. protected function SVGPath($d, $style='') {
  22796. if ($this->state != 2) {
  22797. return;
  22798. }
  22799. // set fill/stroke style
  22800. $op = TCPDF_STATIC::getPathPaintOperator($style, '');
  22801. if (empty($op)) {
  22802. return;
  22803. }
  22804. $paths = array();
  22805. $d = preg_replace('/([0-9ACHLMQSTVZ])([\-\+])/si', '\\1 \\2', $d);
  22806. $d = preg_replace('/(\.[0-9]+)(\.)/s', '\\1 \\2', $d);
  22807. preg_match_all('/([ACHLMQSTVZ])[\s]*([^ACHLMQSTVZ\"]*)/si', $d, $paths, PREG_SET_ORDER);
  22808. $x = 0;
  22809. $y = 0;
  22810. $x1 = 0;
  22811. $y1 = 0;
  22812. $x2 = 0;
  22813. $y2 = 0;
  22814. $xmin = 2147483647;
  22815. $xmax = 0;
  22816. $ymin = 2147483647;
  22817. $ymax = 0;
  22818. $xinitial = 0;
  22819. $yinitial = 0;
  22820. $relcoord = false;
  22821. $minlen = (0.01 / $this->k); // minimum acceptable length (3 point)
  22822. $firstcmd = true; // used to print first point
  22823. // draw curve pieces
  22824. foreach ($paths as $key => $val) {
  22825. // get curve type
  22826. $cmd = trim($val[1]);
  22827. if (strtolower($cmd) == $cmd) {
  22828. // use relative coordinated instead of absolute
  22829. $relcoord = true;
  22830. $xoffset = $x;
  22831. $yoffset = $y;
  22832. } else {
  22833. $relcoord = false;
  22834. $xoffset = 0;
  22835. $yoffset = 0;
  22836. }
  22837. $params = array();
  22838. if (isset($val[2])) {
  22839. // get curve parameters
  22840. $rawparams = preg_split('/([\,\s]+)/si', trim($val[2]));
  22841. $params = array();
  22842. foreach ($rawparams as $ck => $cp) {
  22843. $params[$ck] = $this->getHTMLUnitToUnits($cp, 0, $this->svgunit, false);
  22844. if (abs($params[$ck]) < $minlen) {
  22845. // approximate little values to zero
  22846. $params[$ck] = 0;
  22847. }
  22848. }
  22849. }
  22850. // store current origin point
  22851. $x0 = $x;
  22852. $y0 = $y;
  22853. switch (strtoupper($cmd)) {
  22854. case 'M': { // moveto
  22855. foreach ($params as $ck => $cp) {
  22856. if (($ck % 2) == 0) {
  22857. $x = $cp + $xoffset;
  22858. } else {
  22859. $y = $cp + $yoffset;
  22860. if ($firstcmd OR (abs($x0 - $x) >= $minlen) OR (abs($y0 - $y) >= $minlen)) {
  22861. if ($ck == 1) {
  22862. $this->_outPoint($x, $y);
  22863. $firstcmd = false;
  22864. $xinitial = $x;
  22865. $yinitial = $y;
  22866. } else {
  22867. $this->_outLine($x, $y);
  22868. }
  22869. $x0 = $x;
  22870. $y0 = $y;
  22871. }
  22872. $xmin = min($xmin, $x);
  22873. $ymin = min($ymin, $y);
  22874. $xmax = max($xmax, $x);
  22875. $ymax = max($ymax, $y);
  22876. if ($relcoord) {
  22877. $xoffset = $x;
  22878. $yoffset = $y;
  22879. }
  22880. }
  22881. }
  22882. break;
  22883. }
  22884. case 'L': { // lineto
  22885. foreach ($params as $ck => $cp) {
  22886. if (($ck % 2) == 0) {
  22887. $x = $cp + $xoffset;
  22888. } else {
  22889. $y = $cp + $yoffset;
  22890. if ((abs($x0 - $x) >= $minlen) OR (abs($y0 - $y) >= $minlen)) {
  22891. $this->_outLine($x, $y);
  22892. $x0 = $x;
  22893. $y0 = $y;
  22894. }
  22895. $xmin = min($xmin, $x);
  22896. $ymin = min($ymin, $y);
  22897. $xmax = max($xmax, $x);
  22898. $ymax = max($ymax, $y);
  22899. if ($relcoord) {
  22900. $xoffset = $x;
  22901. $yoffset = $y;
  22902. }
  22903. }
  22904. }
  22905. break;
  22906. }
  22907. case 'H': { // horizontal lineto
  22908. foreach ($params as $ck => $cp) {
  22909. $x = $cp + $xoffset;
  22910. if ((abs($x0 - $x) >= $minlen) OR (abs($y0 - $y) >= $minlen)) {
  22911. $this->_outLine($x, $y);
  22912. $x0 = $x;
  22913. $y0 = $y;
  22914. }
  22915. $xmin = min($xmin, $x);
  22916. $xmax = max($xmax, $x);
  22917. if ($relcoord) {
  22918. $xoffset = $x;
  22919. }
  22920. }
  22921. break;
  22922. }
  22923. case 'V': { // vertical lineto
  22924. foreach ($params as $ck => $cp) {
  22925. $y = $cp + $yoffset;
  22926. if ((abs($x0 - $x) >= $minlen) OR (abs($y0 - $y) >= $minlen)) {
  22927. $this->_outLine($x, $y);
  22928. $x0 = $x;
  22929. $y0 = $y;
  22930. }
  22931. $ymin = min($ymin, $y);
  22932. $ymax = max($ymax, $y);
  22933. if ($relcoord) {
  22934. $yoffset = $y;
  22935. }
  22936. }
  22937. break;
  22938. }
  22939. case 'C': { // curveto
  22940. foreach ($params as $ck => $cp) {
  22941. $params[$ck] = $cp;
  22942. if ((($ck + 1) % 6) == 0) {
  22943. $x1 = $params[($ck - 5)] + $xoffset;
  22944. $y1 = $params[($ck - 4)] + $yoffset;
  22945. $x2 = $params[($ck - 3)] + $xoffset;
  22946. $y2 = $params[($ck - 2)] + $yoffset;
  22947. $x = $params[($ck - 1)] + $xoffset;
  22948. $y = $params[($ck)] + $yoffset;
  22949. $this->_outCurve($x1, $y1, $x2, $y2, $x, $y);
  22950. $xmin = min($xmin, $x, $x1, $x2);
  22951. $ymin = min($ymin, $y, $y1, $y2);
  22952. $xmax = max($xmax, $x, $x1, $x2);
  22953. $ymax = max($ymax, $y, $y1, $y2);
  22954. if ($relcoord) {
  22955. $xoffset = $x;
  22956. $yoffset = $y;
  22957. }
  22958. }
  22959. }
  22960. break;
  22961. }
  22962. case 'S': { // shorthand/smooth curveto
  22963. foreach ($params as $ck => $cp) {
  22964. $params[$ck] = $cp;
  22965. if ((($ck + 1) % 4) == 0) {
  22966. if (($key > 0) AND ((strtoupper($paths[($key - 1)][1]) == 'C') OR (strtoupper($paths[($key - 1)][1]) == 'S'))) {
  22967. $x1 = (2 * $x) - $x2;
  22968. $y1 = (2 * $y) - $y2;
  22969. } else {
  22970. $x1 = $x;
  22971. $y1 = $y;
  22972. }
  22973. $x2 = $params[($ck - 3)] + $xoffset;
  22974. $y2 = $params[($ck - 2)] + $yoffset;
  22975. $x = $params[($ck - 1)] + $xoffset;
  22976. $y = $params[($ck)] + $yoffset;
  22977. $this->_outCurve($x1, $y1, $x2, $y2, $x, $y);
  22978. $xmin = min($xmin, $x, $x1, $x2);
  22979. $ymin = min($ymin, $y, $y1, $y2);
  22980. $xmax = max($xmax, $x, $x1, $x2);
  22981. $ymax = max($ymax, $y, $y1, $y2);
  22982. if ($relcoord) {
  22983. $xoffset = $x;
  22984. $yoffset = $y;
  22985. }
  22986. }
  22987. }
  22988. break;
  22989. }
  22990. case 'Q': { // quadratic Bezier curveto
  22991. foreach ($params as $ck => $cp) {
  22992. $params[$ck] = $cp;
  22993. if ((($ck + 1) % 4) == 0) {
  22994. // convert quadratic points to cubic points
  22995. $x1 = $params[($ck - 3)] + $xoffset;
  22996. $y1 = $params[($ck - 2)] + $yoffset;
  22997. $xa = ($x + (2 * $x1)) / 3;
  22998. $ya = ($y + (2 * $y1)) / 3;
  22999. $x = $params[($ck - 1)] + $xoffset;
  23000. $y = $params[($ck)] + $yoffset;
  23001. $xb = ($x + (2 * $x1)) / 3;
  23002. $yb = ($y + (2 * $y1)) / 3;
  23003. $this->_outCurve($xa, $ya, $xb, $yb, $x, $y);
  23004. $xmin = min($xmin, $x, $xa, $xb);
  23005. $ymin = min($ymin, $y, $ya, $yb);
  23006. $xmax = max($xmax, $x, $xa, $xb);
  23007. $ymax = max($ymax, $y, $ya, $yb);
  23008. if ($relcoord) {
  23009. $xoffset = $x;
  23010. $yoffset = $y;
  23011. }
  23012. }
  23013. }
  23014. break;
  23015. }
  23016. case 'T': { // shorthand/smooth quadratic Bezier curveto
  23017. foreach ($params as $ck => $cp) {
  23018. $params[$ck] = $cp;
  23019. if (($ck % 2) != 0) {
  23020. if (($key > 0) AND ((strtoupper($paths[($key - 1)][1]) == 'Q') OR (strtoupper($paths[($key - 1)][1]) == 'T'))) {
  23021. $x1 = (2 * $x) - $x1;
  23022. $y1 = (2 * $y) - $y1;
  23023. } else {
  23024. $x1 = $x;
  23025. $y1 = $y;
  23026. }
  23027. // convert quadratic points to cubic points
  23028. $xa = ($x + (2 * $x1)) / 3;
  23029. $ya = ($y + (2 * $y1)) / 3;
  23030. $x = $params[($ck - 1)] + $xoffset;
  23031. $y = $params[($ck)] + $yoffset;
  23032. $xb = ($x + (2 * $x1)) / 3;
  23033. $yb = ($y + (2 * $y1)) / 3;
  23034. $this->_outCurve($xa, $ya, $xb, $yb, $x, $y);
  23035. $xmin = min($xmin, $x, $xa, $xb);
  23036. $ymin = min($ymin, $y, $ya, $yb);
  23037. $xmax = max($xmax, $x, $xa, $xb);
  23038. $ymax = max($ymax, $y, $ya, $yb);
  23039. if ($relcoord) {
  23040. $xoffset = $x;
  23041. $yoffset = $y;
  23042. }
  23043. }
  23044. }
  23045. break;
  23046. }
  23047. case 'A': { // elliptical arc
  23048. foreach ($params as $ck => $cp) {
  23049. $params[$ck] = $cp;
  23050. if ((($ck + 1) % 7) == 0) {
  23051. $x0 = $x;
  23052. $y0 = $y;
  23053. $rx = max(abs($params[($ck - 6)]), .000000001);
  23054. $ry = max(abs($params[($ck - 5)]), .000000001);
  23055. $ang = -$rawparams[($ck - 4)];
  23056. $angle = deg2rad($ang);
  23057. $fa = $rawparams[($ck - 3)]; // large-arc-flag
  23058. $fs = $rawparams[($ck - 2)]; // sweep-flag
  23059. $x = $params[($ck - 1)] + $xoffset;
  23060. $y = $params[$ck] + $yoffset;
  23061. if ((abs($x0 - $x) < $minlen) AND (abs($y0 - $y) < $minlen)) {
  23062. // endpoints are almost identical
  23063. $xmin = min($xmin, $x);
  23064. $ymin = min($ymin, $y);
  23065. $xmax = max($xmax, $x);
  23066. $ymax = max($ymax, $y);
  23067. } else {
  23068. $cos_ang = cos($angle);
  23069. $sin_ang = sin($angle);
  23070. $a = (($x0 - $x) / 2);
  23071. $b = (($y0 - $y) / 2);
  23072. $xa = ($a * $cos_ang) - ($b * $sin_ang);
  23073. $ya = ($a * $sin_ang) + ($b * $cos_ang);
  23074. $rx2 = $rx * $rx;
  23075. $ry2 = $ry * $ry;
  23076. $xa2 = $xa * $xa;
  23077. $ya2 = $ya * $ya;
  23078. $delta = ($xa2 / $rx2) + ($ya2 / $ry2);
  23079. if ($delta > 1) {
  23080. $rx *= sqrt($delta);
  23081. $ry *= sqrt($delta);
  23082. $rx2 = $rx * $rx;
  23083. $ry2 = $ry * $ry;
  23084. }
  23085. $numerator = (($rx2 * $ry2) - ($rx2 * $ya2) - ($ry2 * $xa2));
  23086. if ($numerator < 0) {
  23087. $root = 0;
  23088. } else {
  23089. $root = sqrt($numerator / (($rx2 * $ya2) + ($ry2 * $xa2)));
  23090. }
  23091. if ($fa == $fs){
  23092. $root *= -1;
  23093. }
  23094. $cax = $root * (($rx * $ya) / $ry);
  23095. $cay = -$root * (($ry * $xa) / $rx);
  23096. // coordinates of ellipse center
  23097. $cx = ($cax * $cos_ang) - ($cay * $sin_ang) + (($x0 + $x) / 2);
  23098. $cy = ($cax * $sin_ang) + ($cay * $cos_ang) + (($y0 + $y) / 2);
  23099. // get angles
  23100. $angs = TCPDF_STATIC::getVectorsAngle(1, 0, (($xa - $cax) / $rx), (($cay - $ya) / $ry));
  23101. $dang = TCPDF_STATIC::getVectorsAngle((($xa - $cax) / $rx), (($ya - $cay) / $ry), ((-$xa - $cax) / $rx), ((-$ya - $cay) / $ry));
  23102. if (($fs == 0) AND ($dang > 0)) {
  23103. $dang -= (2 * M_PI);
  23104. } elseif (($fs == 1) AND ($dang < 0)) {
  23105. $dang += (2 * M_PI);
  23106. }
  23107. $angf = $angs - $dang;
  23108. if ((($fs == 0) AND ($angs > $angf)) OR (($fs == 1) AND ($angs < $angf))) {
  23109. // reverse angles
  23110. $tmp = $angs;
  23111. $angs = $angf;
  23112. $angf = $tmp;
  23113. }
  23114. $angs = round(rad2deg($angs), 6);
  23115. $angf = round(rad2deg($angf), 6);
  23116. // covent angles to positive values
  23117. if (($angs < 0) AND ($angf < 0)) {
  23118. $angs += 360;
  23119. $angf += 360;
  23120. }
  23121. $pie = false;
  23122. if (($key == 0) AND (isset($paths[($key + 1)][1])) AND (trim($paths[($key + 1)][1]) == 'z')) {
  23123. $pie = true;
  23124. }
  23125. list($axmin, $aymin, $axmax, $aymax) = $this->_outellipticalarc($cx, $cy, $rx, $ry, $ang, $angs, $angf, $pie, 2, false, ($fs == 0), true);
  23126. $xmin = min($xmin, $x, $axmin);
  23127. $ymin = min($ymin, $y, $aymin);
  23128. $xmax = max($xmax, $x, $axmax);
  23129. $ymax = max($ymax, $y, $aymax);
  23130. }
  23131. if ($relcoord) {
  23132. $xoffset = $x;
  23133. $yoffset = $y;
  23134. }
  23135. }
  23136. }
  23137. break;
  23138. }
  23139. case 'Z': {
  23140. $this->_out('h');
  23141. $x = $x0 = $xinitial;
  23142. $y = $y0 = $yinitial;
  23143. break;
  23144. }
  23145. }
  23146. $firstcmd = false;
  23147. } // end foreach
  23148. if (!empty($op)) {
  23149. $this->_out($op);
  23150. }
  23151. return array($xmin, $ymin, ($xmax - $xmin), ($ymax - $ymin));
  23152. }
  23153. /**
  23154. * Return the tag name without the namespace
  23155. * @param $name (string) Tag name
  23156. * @protected
  23157. */
  23158. protected function removeTagNamespace($name) {
  23159. if(strpos($name, ':') !== false) {
  23160. $parts = explode(':', $name);
  23161. return $parts[(sizeof($parts) - 1)];
  23162. }
  23163. return $name;
  23164. }
  23165. /**
  23166. * Sets the opening SVG element handler function for the XML parser. (*** TO BE COMPLETED ***)
  23167. * @param $parser (resource) The first parameter, parser, is a reference to the XML parser calling the handler.
  23168. * @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.
  23169. * @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.
  23170. * @param $ctm (array) tranformation matrix for clipping mode (starting transformation matrix).
  23171. * @author Nicola Asuni
  23172. * @since 5.0.000 (2010-05-02)
  23173. * @protected
  23174. */
  23175. protected function startSVGElementHandler($parser, $name, $attribs, $ctm=array()) {
  23176. $name = $this->removeTagNamespace($name);
  23177. // check if we are in clip mode
  23178. if ($this->svgclipmode) {
  23179. $this->svgclippaths[$this->svgclipid][] = array('name' => $name, 'attribs' => $attribs, 'tm' => $this->svgcliptm[$this->svgclipid]);
  23180. return;
  23181. }
  23182. if ($this->svgdefsmode AND !in_array($name, array('clipPath', 'linearGradient', 'radialGradient', 'stop'))) {
  23183. if (isset($attribs['id'])) {
  23184. $attribs['child_elements'] = array();
  23185. $this->svgdefs[$attribs['id']] = array('name' => $name, 'attribs' => $attribs);
  23186. return;
  23187. }
  23188. if (end($this->svgdefs) !== FALSE) {
  23189. $last_svgdefs_id = key($this->svgdefs);
  23190. if (isset($this->svgdefs[$last_svgdefs_id]['attribs']['child_elements'])) {
  23191. $attribs['id'] = 'DF_'.(count($this->svgdefs[$last_svgdefs_id]['attribs']['child_elements']) + 1);
  23192. $this->svgdefs[$last_svgdefs_id]['attribs']['child_elements'][$attribs['id']] = array('name' => $name, 'attribs' => $attribs);
  23193. return;
  23194. }
  23195. }
  23196. return;
  23197. }
  23198. $clipping = false;
  23199. if ($parser == 'clip-path') {
  23200. // set clipping mode
  23201. $clipping = true;
  23202. }
  23203. // get styling properties
  23204. $prev_svgstyle = $this->svgstyles[max(0,(count($this->svgstyles) - 1))]; // previous style
  23205. $svgstyle = $this->svgstyles[0]; // set default style
  23206. if ($clipping AND !isset($attribs['fill']) AND (!isset($attribs['style']) OR (!preg_match('/[;\"\s]{1}fill[\s]*:[\s]*([^;\"]*)/si', $attribs['style'], $attrval)))) {
  23207. // default fill attribute for clipping
  23208. $attribs['fill'] = 'none';
  23209. }
  23210. if (isset($attribs['style']) AND !TCPDF_STATIC::empty_string($attribs['style']) AND ($attribs['style'][0] != ';')) {
  23211. // fix style for regular expression
  23212. $attribs['style'] = ';'.$attribs['style'];
  23213. }
  23214. foreach ($prev_svgstyle as $key => $val) {
  23215. if (in_array($key, TCPDF_IMAGES::$svginheritprop)) {
  23216. // inherit previous value
  23217. $svgstyle[$key] = $val;
  23218. }
  23219. if (isset($attribs[$key]) AND !TCPDF_STATIC::empty_string($attribs[$key])) {
  23220. // specific attribute settings
  23221. if ($attribs[$key] == 'inherit') {
  23222. $svgstyle[$key] = $val;
  23223. } else {
  23224. $svgstyle[$key] = $attribs[$key];
  23225. }
  23226. } elseif (isset($attribs['style']) AND !TCPDF_STATIC::empty_string($attribs['style'])) {
  23227. // CSS style syntax
  23228. $attrval = array();
  23229. if (preg_match('/[;\"\s]{1}'.$key.'[\s]*:[\s]*([^;\"]*)/si', $attribs['style'], $attrval) AND isset($attrval[1])) {
  23230. if ($attrval[1] == 'inherit') {
  23231. $svgstyle[$key] = $val;
  23232. } else {
  23233. $svgstyle[$key] = $attrval[1];
  23234. }
  23235. }
  23236. }
  23237. }
  23238. // transformation matrix
  23239. if (!empty($ctm)) {
  23240. $tm = $ctm;
  23241. } else {
  23242. $tm = array(1,0,0,1,0,0);
  23243. }
  23244. if (isset($attribs['transform']) AND !empty($attribs['transform'])) {
  23245. $tm = TCPDF_STATIC::getTransformationMatrixProduct($tm, TCPDF_STATIC::getSVGTransformMatrix($attribs['transform']));
  23246. }
  23247. $svgstyle['transfmatrix'] = $tm;
  23248. $invisible = false;
  23249. if (($svgstyle['visibility'] == 'hidden') OR ($svgstyle['visibility'] == 'collapse') OR ($svgstyle['display'] == 'none')) {
  23250. // the current graphics element is invisible (nothing is painted)
  23251. $invisible = true;
  23252. }
  23253. // process tag
  23254. switch($name) {
  23255. case 'defs': {
  23256. $this->svgdefsmode = true;
  23257. break;
  23258. }
  23259. // clipPath
  23260. case 'clipPath': {
  23261. if ($invisible) {
  23262. break;
  23263. }
  23264. $this->svgclipmode = true;
  23265. if (!isset($attribs['id'])) {
  23266. $attribs['id'] = 'CP_'.(count($this->svgcliptm) + 1);
  23267. }
  23268. $this->svgclipid = $attribs['id'];
  23269. $this->svgclippaths[$this->svgclipid] = array();
  23270. $this->svgcliptm[$this->svgclipid] = $tm;
  23271. break;
  23272. }
  23273. case 'svg': {
  23274. // start of SVG object
  23275. if(++$this->svg_tag_depth <= 1) {
  23276. break;
  23277. }
  23278. // inner SVG
  23279. array_push($this->svgstyles, $svgstyle);
  23280. $this->StartTransform();
  23281. $svgX = (isset($attribs['x'])?$attribs['x']:0);
  23282. $svgY = (isset($attribs['y'])?$attribs['y']:0);
  23283. $svgW = (isset($attribs['width'])?$attribs['width']:0);
  23284. $svgH = (isset($attribs['height'])?$attribs['height']:0);
  23285. // set x, y position using transform matrix
  23286. $tm = TCPDF_STATIC::getTransformationMatrixProduct($tm, array( 1, 0, 0, 1, $svgX, $svgY));
  23287. $this->SVGTransform($tm);
  23288. // set clipping for width and height
  23289. $x = 0;
  23290. $y = 0;
  23291. $w = (isset($attribs['width'])?$this->getHTMLUnitToUnits($attribs['width'], 0, $this->svgunit, false):$this->w);
  23292. $h = (isset($attribs['height'])?$this->getHTMLUnitToUnits($attribs['height'], 0, $this->svgunit, false):$this->h);
  23293. // draw clipping rect
  23294. $this->Rect($x, $y, $w, $h, 'CNZ', array(), array());
  23295. // parse viewbox, calculate extra transformation matrix
  23296. if (isset($attribs['viewBox'])) {
  23297. $tmp = array();
  23298. preg_match_all("/[0-9]+/", $attribs['viewBox'], $tmp);
  23299. $tmp = $tmp[0];
  23300. if (sizeof($tmp) == 4) {
  23301. $vx = $tmp[0];
  23302. $vy = $tmp[1];
  23303. $vw = $tmp[2];
  23304. $vh = $tmp[3];
  23305. // get aspect ratio
  23306. $tmp = array();
  23307. $aspectX = 'xMid';
  23308. $aspectY = 'YMid';
  23309. $fit = 'meet';
  23310. if (isset($attribs['preserveAspectRatio'])) {
  23311. if($attribs['preserveAspectRatio'] == 'none') {
  23312. $fit = 'none';
  23313. } else {
  23314. preg_match_all('/[a-zA-Z]+/', $attribs['preserveAspectRatio'], $tmp);
  23315. $tmp = $tmp[0];
  23316. if ((sizeof($tmp) == 2) AND (strlen($tmp[0]) == 8) AND (in_array($tmp[1], array('meet', 'slice', 'none')))) {
  23317. $aspectX = substr($tmp[0], 0, 4);
  23318. $aspectY = substr($tmp[0], 4, 4);
  23319. $fit = $tmp[1];
  23320. }
  23321. }
  23322. }
  23323. $wr = ($svgW / $vw);
  23324. $hr = ($svgH / $vh);
  23325. $ax = $ay = 0;
  23326. if ((($fit == 'meet') AND ($hr < $wr)) OR (($fit == 'slice') AND ($hr > $wr))) {
  23327. if ($aspectX == 'xMax') {
  23328. $ax = (($vw * ($wr / $hr)) - $vw);
  23329. }
  23330. if ($aspectX == 'xMid') {
  23331. $ax = ((($vw * ($wr / $hr)) - $vw) / 2);
  23332. }
  23333. $wr = $hr;
  23334. } elseif ((($fit == 'meet') AND ($hr > $wr)) OR (($fit == 'slice') AND ($hr < $wr))) {
  23335. if ($aspectY == 'YMax') {
  23336. $ay = (($vh * ($hr / $wr)) - $vh);
  23337. }
  23338. if ($aspectY == 'YMid') {
  23339. $ay = ((($vh * ($hr / $wr)) - $vh) / 2);
  23340. }
  23341. $hr = $wr;
  23342. }
  23343. $newtm = array($wr, 0, 0, $hr, (($wr * ($ax - $vx)) - $svgX), (($hr * ($ay - $vy)) - $svgY));
  23344. $tm = TCPDF_STATIC::getTransformationMatrixProduct($tm, $newtm);
  23345. $this->SVGTransform($tm);
  23346. }
  23347. }
  23348. $this->setSVGStyles($svgstyle, $prev_svgstyle);
  23349. break;
  23350. }
  23351. case 'g': {
  23352. // group together related graphics elements
  23353. array_push($this->svgstyles, $svgstyle);
  23354. $this->StartTransform();
  23355. $x = (isset($attribs['x'])?$attribs['x']:0);
  23356. $y = (isset($attribs['y'])?$attribs['y']:0);
  23357. $w = 1;//(isset($attribs['width'])?$attribs['width']:1);
  23358. $h = 1;//(isset($attribs['height'])?$attribs['height']:1);
  23359. $tm = TCPDF_STATIC::getTransformationMatrixProduct($tm, array($w, 0, 0, $h, $x, $y));
  23360. $this->SVGTransform($tm);
  23361. $this->setSVGStyles($svgstyle, $prev_svgstyle);
  23362. break;
  23363. }
  23364. case 'linearGradient': {
  23365. if ($this->pdfa_mode) {
  23366. break;
  23367. }
  23368. if (!isset($attribs['id'])) {
  23369. $attribs['id'] = 'GR_'.(count($this->svggradients) + 1);
  23370. }
  23371. $this->svggradientid = $attribs['id'];
  23372. $this->svggradients[$this->svggradientid] = array();
  23373. $this->svggradients[$this->svggradientid]['type'] = 2;
  23374. $this->svggradients[$this->svggradientid]['stops'] = array();
  23375. if (isset($attribs['gradientUnits'])) {
  23376. $this->svggradients[$this->svggradientid]['gradientUnits'] = $attribs['gradientUnits'];
  23377. } else {
  23378. $this->svggradients[$this->svggradientid]['gradientUnits'] = 'objectBoundingBox';
  23379. }
  23380. //$attribs['spreadMethod']
  23381. if (((!isset($attribs['x1'])) AND (!isset($attribs['y1'])) AND (!isset($attribs['x2'])) AND (!isset($attribs['y2'])))
  23382. OR ((isset($attribs['x1']) AND (substr($attribs['x1'], -1) == '%'))
  23383. OR (isset($attribs['y1']) AND (substr($attribs['y1'], -1) == '%'))
  23384. OR (isset($attribs['x2']) AND (substr($attribs['x2'], -1) == '%'))
  23385. OR (isset($attribs['y2']) AND (substr($attribs['y2'], -1) == '%')))) {
  23386. $this->svggradients[$this->svggradientid]['mode'] = 'percentage';
  23387. } else {
  23388. $this->svggradients[$this->svggradientid]['mode'] = 'measure';
  23389. }
  23390. $x1 = (isset($attribs['x1'])?$attribs['x1']:'0');
  23391. $y1 = (isset($attribs['y1'])?$attribs['y1']:'0');
  23392. $x2 = (isset($attribs['x2'])?$attribs['x2']:'100');
  23393. $y2 = (isset($attribs['y2'])?$attribs['y2']:'0');
  23394. if (isset($attribs['gradientTransform'])) {
  23395. $this->svggradients[$this->svggradientid]['gradientTransform'] = TCPDF_STATIC::getSVGTransformMatrix($attribs['gradientTransform']);
  23396. }
  23397. $this->svggradients[$this->svggradientid]['coords'] = array($x1, $y1, $x2, $y2);
  23398. if (isset($attribs['xlink:href']) AND !empty($attribs['xlink:href'])) {
  23399. // gradient is defined on another place
  23400. $this->svggradients[$this->svggradientid]['xref'] = substr($attribs['xlink:href'], 1);
  23401. }
  23402. break;
  23403. }
  23404. case 'radialGradient': {
  23405. if ($this->pdfa_mode) {
  23406. break;
  23407. }
  23408. if (!isset($attribs['id'])) {
  23409. $attribs['id'] = 'GR_'.(count($this->svggradients) + 1);
  23410. }
  23411. $this->svggradientid = $attribs['id'];
  23412. $this->svggradients[$this->svggradientid] = array();
  23413. $this->svggradients[$this->svggradientid]['type'] = 3;
  23414. $this->svggradients[$this->svggradientid]['stops'] = array();
  23415. if (isset($attribs['gradientUnits'])) {
  23416. $this->svggradients[$this->svggradientid]['gradientUnits'] = $attribs['gradientUnits'];
  23417. } else {
  23418. $this->svggradients[$this->svggradientid]['gradientUnits'] = 'objectBoundingBox';
  23419. }
  23420. //$attribs['spreadMethod']
  23421. if (((!isset($attribs['cx'])) AND (!isset($attribs['cy'])))
  23422. OR ((isset($attribs['cx']) AND (substr($attribs['cx'], -1) == '%'))
  23423. OR (isset($attribs['cy']) AND (substr($attribs['cy'], -1) == '%')))) {
  23424. $this->svggradients[$this->svggradientid]['mode'] = 'percentage';
  23425. } elseif (isset($attribs['r']) AND is_numeric($attribs['r']) AND ($attribs['r']) <= 1) {
  23426. $this->svggradients[$this->svggradientid]['mode'] = 'ratio';
  23427. } else {
  23428. $this->svggradients[$this->svggradientid]['mode'] = 'measure';
  23429. }
  23430. $cx = (isset($attribs['cx']) ? $attribs['cx'] : 0.5);
  23431. $cy = (isset($attribs['cy']) ? $attribs['cy'] : 0.5);
  23432. $fx = (isset($attribs['fx']) ? $attribs['fx'] : $cx);
  23433. $fy = (isset($attribs['fy']) ? $attribs['fy'] : $cy);
  23434. $r = (isset($attribs['r']) ? $attribs['r'] : 0.5);
  23435. if (isset($attribs['gradientTransform'])) {
  23436. $this->svggradients[$this->svggradientid]['gradientTransform'] = TCPDF_STATIC::getSVGTransformMatrix($attribs['gradientTransform']);
  23437. }
  23438. $this->svggradients[$this->svggradientid]['coords'] = array($cx, $cy, $fx, $fy, $r);
  23439. if (isset($attribs['xlink:href']) AND !empty($attribs['xlink:href'])) {
  23440. // gradient is defined on another place
  23441. $this->svggradients[$this->svggradientid]['xref'] = substr($attribs['xlink:href'], 1);
  23442. }
  23443. break;
  23444. }
  23445. case 'stop': {
  23446. // gradient stops
  23447. if (substr($attribs['offset'], -1) == '%') {
  23448. $offset = floatval(substr($attribs['offset'], 0, -1)) / 100;
  23449. } else {
  23450. $offset = floatval($attribs['offset']);
  23451. if ($offset > 1) {
  23452. $offset /= 100;
  23453. }
  23454. }
  23455. $stop_color = isset($svgstyle['stop-color'])?TCPDF_COLORS::convertHTMLColorToDec($svgstyle['stop-color'], $this->spot_colors):'black';
  23456. $opacity = isset($svgstyle['stop-opacity'])?$svgstyle['stop-opacity']:1;
  23457. $this->svggradients[$this->svggradientid]['stops'][] = array('offset' => $offset, 'color' => $stop_color, 'opacity' => $opacity);
  23458. break;
  23459. }
  23460. // paths
  23461. case 'path': {
  23462. if ($invisible) {
  23463. break;
  23464. }
  23465. if (isset($attribs['d'])) {
  23466. $d = trim($attribs['d']);
  23467. if (!empty($d)) {
  23468. $x = (isset($attribs['x'])?$attribs['x']:0);
  23469. $y = (isset($attribs['y'])?$attribs['y']:0);
  23470. $w = (isset($attribs['width'])?$attribs['width']:1);
  23471. $h = (isset($attribs['height'])?$attribs['height']:1);
  23472. $tm = TCPDF_STATIC::getTransformationMatrixProduct($tm, array($w, 0, 0, $h, $x, $y));
  23473. if ($clipping) {
  23474. $this->SVGTransform($tm);
  23475. $this->SVGPath($d, 'CNZ');
  23476. } else {
  23477. $this->StartTransform();
  23478. $this->SVGTransform($tm);
  23479. $obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h, 'SVGPath', array($d, 'CNZ'));
  23480. if (!empty($obstyle)) {
  23481. $this->SVGPath($d, $obstyle);
  23482. }
  23483. $this->StopTransform();
  23484. }
  23485. }
  23486. }
  23487. break;
  23488. }
  23489. // shapes
  23490. case 'rect': {
  23491. if ($invisible) {
  23492. break;
  23493. }
  23494. $x = (isset($attribs['x'])?$this->getHTMLUnitToUnits($attribs['x'], 0, $this->svgunit, false):0);
  23495. $y = (isset($attribs['y'])?$this->getHTMLUnitToUnits($attribs['y'], 0, $this->svgunit, false):0);
  23496. $w = (isset($attribs['width'])?$this->getHTMLUnitToUnits($attribs['width'], 0, $this->svgunit, false):0);
  23497. $h = (isset($attribs['height'])?$this->getHTMLUnitToUnits($attribs['height'], 0, $this->svgunit, false):0);
  23498. $rx = (isset($attribs['rx'])?$this->getHTMLUnitToUnits($attribs['rx'], 0, $this->svgunit, false):0);
  23499. $ry = (isset($attribs['ry'])?$this->getHTMLUnitToUnits($attribs['ry'], 0, $this->svgunit, false):$rx);
  23500. if ($clipping) {
  23501. $this->SVGTransform($tm);
  23502. $this->RoundedRectXY($x, $y, $w, $h, $rx, $ry, '1111', 'CNZ', array(), array());
  23503. } else {
  23504. $this->StartTransform();
  23505. $this->SVGTransform($tm);
  23506. $obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h, 'RoundedRectXY', array($x, $y, $w, $h, $rx, $ry, '1111', 'CNZ'));
  23507. if (!empty($obstyle)) {
  23508. $this->RoundedRectXY($x, $y, $w, $h, $rx, $ry, '1111', $obstyle, array(), array());
  23509. }
  23510. $this->StopTransform();
  23511. }
  23512. break;
  23513. }
  23514. case 'circle': {
  23515. if ($invisible) {
  23516. break;
  23517. }
  23518. $r = (isset($attribs['r']) ? $this->getHTMLUnitToUnits($attribs['r'], 0, $this->svgunit, false) : 0);
  23519. $cx = (isset($attribs['cx']) ? $this->getHTMLUnitToUnits($attribs['cx'], 0, $this->svgunit, false) : (isset($attribs['x']) ? $this->getHTMLUnitToUnits($attribs['x'], 0, $this->svgunit, false) : 0));
  23520. $cy = (isset($attribs['cy']) ? $this->getHTMLUnitToUnits($attribs['cy'], 0, $this->svgunit, false) : (isset($attribs['y']) ? $this->getHTMLUnitToUnits($attribs['y'], 0, $this->svgunit, false) : 0));
  23521. $x = ($cx - $r);
  23522. $y = ($cy - $r);
  23523. $w = (2 * $r);
  23524. $h = $w;
  23525. if ($clipping) {
  23526. $this->SVGTransform($tm);
  23527. $this->Circle($cx, $cy, $r, 0, 360, 'CNZ', array(), array(), 8);
  23528. } else {
  23529. $this->StartTransform();
  23530. $this->SVGTransform($tm);
  23531. $obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h, 'Circle', array($cx, $cy, $r, 0, 360, 'CNZ'));
  23532. if (!empty($obstyle)) {
  23533. $this->Circle($cx, $cy, $r, 0, 360, $obstyle, array(), array(), 8);
  23534. }
  23535. $this->StopTransform();
  23536. }
  23537. break;
  23538. }
  23539. case 'ellipse': {
  23540. if ($invisible) {
  23541. break;
  23542. }
  23543. $rx = (isset($attribs['rx']) ? $this->getHTMLUnitToUnits($attribs['rx'], 0, $this->svgunit, false) : 0);
  23544. $ry = (isset($attribs['ry']) ? $this->getHTMLUnitToUnits($attribs['ry'], 0, $this->svgunit, false) : 0);
  23545. $cx = (isset($attribs['cx']) ? $this->getHTMLUnitToUnits($attribs['cx'], 0, $this->svgunit, false) : (isset($attribs['x']) ? $this->getHTMLUnitToUnits($attribs['x'], 0, $this->svgunit, false) : 0));
  23546. $cy = (isset($attribs['cy']) ? $this->getHTMLUnitToUnits($attribs['cy'], 0, $this->svgunit, false) : (isset($attribs['y']) ? $this->getHTMLUnitToUnits($attribs['y'], 0, $this->svgunit, false) : 0));
  23547. $x = ($cx - $rx);
  23548. $y = ($cy - $ry);
  23549. $w = (2 * $rx);
  23550. $h = (2 * $ry);
  23551. if ($clipping) {
  23552. $this->SVGTransform($tm);
  23553. $this->Ellipse($cx, $cy, $rx, $ry, 0, 0, 360, 'CNZ', array(), array(), 8);
  23554. } else {
  23555. $this->StartTransform();
  23556. $this->SVGTransform($tm);
  23557. $obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h, 'Ellipse', array($cx, $cy, $rx, $ry, 0, 0, 360, 'CNZ'));
  23558. if (!empty($obstyle)) {
  23559. $this->Ellipse($cx, $cy, $rx, $ry, 0, 0, 360, $obstyle, array(), array(), 8);
  23560. }
  23561. $this->StopTransform();
  23562. }
  23563. break;
  23564. }
  23565. case 'line': {
  23566. if ($invisible) {
  23567. break;
  23568. }
  23569. $x1 = (isset($attribs['x1'])?$this->getHTMLUnitToUnits($attribs['x1'], 0, $this->svgunit, false):0);
  23570. $y1 = (isset($attribs['y1'])?$this->getHTMLUnitToUnits($attribs['y1'], 0, $this->svgunit, false):0);
  23571. $x2 = (isset($attribs['x2'])?$this->getHTMLUnitToUnits($attribs['x2'], 0, $this->svgunit, false):0);
  23572. $y2 = (isset($attribs['y2'])?$this->getHTMLUnitToUnits($attribs['y2'], 0, $this->svgunit, false):0);
  23573. $x = $x1;
  23574. $y = $y1;
  23575. $w = abs($x2 - $x1);
  23576. $h = abs($y2 - $y1);
  23577. if (!$clipping) {
  23578. $this->StartTransform();
  23579. $this->SVGTransform($tm);
  23580. $obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h, 'Line', array($x1, $y1, $x2, $y2));
  23581. $this->Line($x1, $y1, $x2, $y2);
  23582. $this->StopTransform();
  23583. }
  23584. break;
  23585. }
  23586. case 'polyline':
  23587. case 'polygon': {
  23588. if ($invisible) {
  23589. break;
  23590. }
  23591. $points = (isset($attribs['points'])?$attribs['points']:'0 0');
  23592. $points = trim($points);
  23593. // note that point may use a complex syntax not covered here
  23594. $points = preg_split('/[\,\s]+/si', $points);
  23595. if (count($points) < 4) {
  23596. break;
  23597. }
  23598. $p = array();
  23599. $xmin = 2147483647;
  23600. $xmax = 0;
  23601. $ymin = 2147483647;
  23602. $ymax = 0;
  23603. foreach ($points as $key => $val) {
  23604. $p[$key] = $this->getHTMLUnitToUnits($val, 0, $this->svgunit, false);
  23605. if (($key % 2) == 0) {
  23606. // X coordinate
  23607. $xmin = min($xmin, $p[$key]);
  23608. $xmax = max($xmax, $p[$key]);
  23609. } else {
  23610. // Y coordinate
  23611. $ymin = min($ymin, $p[$key]);
  23612. $ymax = max($ymax, $p[$key]);
  23613. }
  23614. }
  23615. $x = $xmin;
  23616. $y = $ymin;
  23617. $w = ($xmax - $xmin);
  23618. $h = ($ymax - $ymin);
  23619. if ($name == 'polyline') {
  23620. $this->StartTransform();
  23621. $this->SVGTransform($tm);
  23622. $obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h, 'PolyLine', array($p, 'CNZ'));
  23623. if (!empty($obstyle)) {
  23624. $this->PolyLine($p, $obstyle, array(), array());
  23625. }
  23626. $this->StopTransform();
  23627. } else { // polygon
  23628. if ($clipping) {
  23629. $this->SVGTransform($tm);
  23630. $this->Polygon($p, 'CNZ', array(), array(), true);
  23631. } else {
  23632. $this->StartTransform();
  23633. $this->SVGTransform($tm);
  23634. $obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h, 'Polygon', array($p, 'CNZ'));
  23635. if (!empty($obstyle)) {
  23636. $this->Polygon($p, $obstyle, array(), array(), true);
  23637. }
  23638. $this->StopTransform();
  23639. }
  23640. }
  23641. break;
  23642. }
  23643. // image
  23644. case 'image': {
  23645. if ($invisible) {
  23646. break;
  23647. }
  23648. if (!isset($attribs['xlink:href']) OR empty($attribs['xlink:href'])) {
  23649. break;
  23650. }
  23651. $x = (isset($attribs['x'])?$this->getHTMLUnitToUnits($attribs['x'], 0, $this->svgunit, false):0);
  23652. $y = (isset($attribs['y'])?$this->getHTMLUnitToUnits($attribs['y'], 0, $this->svgunit, false):0);
  23653. $w = (isset($attribs['width'])?$this->getHTMLUnitToUnits($attribs['width'], 0, $this->svgunit, false):0);
  23654. $h = (isset($attribs['height'])?$this->getHTMLUnitToUnits($attribs['height'], 0, $this->svgunit, false):0);
  23655. $img = $attribs['xlink:href'];
  23656. if (!$clipping) {
  23657. $this->StartTransform();
  23658. $this->SVGTransform($tm);
  23659. $obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h);
  23660. if (preg_match('/^data:image\/[^;]+;base64,/', $img, $m) > 0) {
  23661. // embedded image encoded as base64
  23662. $img = '@'.base64_decode(substr($img, strlen($m[0])));
  23663. } else {
  23664. // fix image path
  23665. if (!TCPDF_STATIC::empty_string($this->svgdir) AND (($img[0] == '.') OR (basename($img) == $img))) {
  23666. // replace relative path with full server path
  23667. $img = $this->svgdir.'/'.$img;
  23668. }
  23669. if (($img[0] == '/') AND !empty($_SERVER['DOCUMENT_ROOT']) AND ($_SERVER['DOCUMENT_ROOT'] != '/')) {
  23670. $findroot = strpos($img, $_SERVER['DOCUMENT_ROOT']);
  23671. if (($findroot === false) OR ($findroot > 1)) {
  23672. if (substr($_SERVER['DOCUMENT_ROOT'], -1) == '/') {
  23673. $img = substr($_SERVER['DOCUMENT_ROOT'], 0, -1).$img;
  23674. } else {
  23675. $img = $_SERVER['DOCUMENT_ROOT'].$img;
  23676. }
  23677. }
  23678. }
  23679. $img = urldecode($img);
  23680. $testscrtype = @parse_url($img);
  23681. if (empty($testscrtype['query'])) {
  23682. // convert URL to server path
  23683. $img = str_replace(K_PATH_URL, K_PATH_MAIN, $img);
  23684. } elseif (preg_match('|^https?://|', $img) !== 1) {
  23685. // convert server path to URL
  23686. $img = str_replace(K_PATH_MAIN, K_PATH_URL, $img);
  23687. }
  23688. }
  23689. // get image type
  23690. $imgtype = TCPDF_IMAGES::getImageFileType($img);
  23691. if (($imgtype == 'eps') OR ($imgtype == 'ai')) {
  23692. $this->ImageEps($img, $x, $y, $w, $h);
  23693. } elseif ($imgtype == 'svg') {
  23694. // store SVG vars
  23695. $svggradients = $this->svggradients;
  23696. $svggradientid = $this->svggradientid;
  23697. $svgdefsmode = $this->svgdefsmode;
  23698. $svgdefs = $this->svgdefs;
  23699. $svgclipmode = $this->svgclipmode;
  23700. $svgclippaths = $this->svgclippaths;
  23701. $svgcliptm = $this->svgcliptm;
  23702. $svgclipid = $this->svgclipid;
  23703. $svgtext = $this->svgtext;
  23704. $svgtextmode = $this->svgtextmode;
  23705. $this->ImageSVG($img, $x, $y, $w, $h);
  23706. // restore SVG vars
  23707. $this->svggradients = $svggradients;
  23708. $this->svggradientid = $svggradientid;
  23709. $this->svgdefsmode = $svgdefsmode;
  23710. $this->svgdefs = $svgdefs;
  23711. $this->svgclipmode = $svgclipmode;
  23712. $this->svgclippaths = $svgclippaths;
  23713. $this->svgcliptm = $svgcliptm;
  23714. $this->svgclipid = $svgclipid;
  23715. $this->svgtext = $svgtext;
  23716. $this->svgtextmode = $svgtextmode;
  23717. } else {
  23718. $this->Image($img, $x, $y, $w, $h);
  23719. }
  23720. $this->StopTransform();
  23721. }
  23722. break;
  23723. }
  23724. // text
  23725. case 'text':
  23726. case 'tspan': {
  23727. if (isset($this->svgtextmode['text-anchor']) AND !empty($this->svgtext)) {
  23728. // @TODO: unsupported feature
  23729. }
  23730. // only basic support - advanced features must be implemented
  23731. $this->svgtextmode['invisible'] = $invisible;
  23732. if ($invisible) {
  23733. break;
  23734. }
  23735. array_push($this->svgstyles, $svgstyle);
  23736. if (isset($attribs['x'])) {
  23737. $x = $this->getHTMLUnitToUnits($attribs['x'], 0, $this->svgunit, false);
  23738. } elseif ($name == 'tspan') {
  23739. $x = $this->x;
  23740. } else {
  23741. $x = 0;
  23742. }
  23743. if (isset($attribs['dx'])) {
  23744. $x += $this->getHTMLUnitToUnits($attribs['dx'], 0, $this->svgunit, false);
  23745. }
  23746. if (isset($attribs['y'])) {
  23747. $y = $this->getHTMLUnitToUnits($attribs['y'], 0, $this->svgunit, false);
  23748. } elseif ($name == 'tspan') {
  23749. $y = $this->y;
  23750. } else {
  23751. $y = 0;
  23752. }
  23753. if (isset($attribs['dy'])) {
  23754. $y += $this->getHTMLUnitToUnits($attribs['dy'], 0, $this->svgunit, false);
  23755. }
  23756. $svgstyle['text-color'] = $svgstyle['fill'];
  23757. $this->svgtext = '';
  23758. if (isset($svgstyle['text-anchor'])) {
  23759. $this->svgtextmode['text-anchor'] = $svgstyle['text-anchor'];
  23760. } else {
  23761. $this->svgtextmode['text-anchor'] = 'start';
  23762. }
  23763. if (isset($svgstyle['direction'])) {
  23764. if ($svgstyle['direction'] == 'rtl') {
  23765. $this->svgtextmode['rtl'] = true;
  23766. } else {
  23767. $this->svgtextmode['rtl'] = false;
  23768. }
  23769. } else {
  23770. $this->svgtextmode['rtl'] = false;
  23771. }
  23772. if (isset($svgstyle['stroke']) AND ($svgstyle['stroke'] != 'none') AND isset($svgstyle['stroke-width']) AND ($svgstyle['stroke-width'] > 0)) {
  23773. $this->svgtextmode['stroke'] = $this->getHTMLUnitToUnits($svgstyle['stroke-width'], 0, $this->svgunit, false);
  23774. } else {
  23775. $this->svgtextmode['stroke'] = false;
  23776. }
  23777. $this->StartTransform();
  23778. $this->SVGTransform($tm);
  23779. $obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, 1, 1);
  23780. $this->x = $x;
  23781. $this->y = $y;
  23782. break;
  23783. }
  23784. // use
  23785. case 'use': {
  23786. if (isset($attribs['xlink:href']) AND !empty($attribs['xlink:href'])) {
  23787. $svgdefid = substr($attribs['xlink:href'], 1);
  23788. if (isset($this->svgdefs[$svgdefid])) {
  23789. $use = $this->svgdefs[$svgdefid];
  23790. if (isset($attribs['xlink:href'])) {
  23791. unset($attribs['xlink:href']);
  23792. }
  23793. if (isset($attribs['id'])) {
  23794. unset($attribs['id']);
  23795. }
  23796. if (isset($use['attribs']['x']) AND isset($attribs['x'])) {
  23797. $attribs['x'] += $use['attribs']['x'];
  23798. }
  23799. if (isset($use['attribs']['y']) AND isset($attribs['y'])) {
  23800. $attribs['y'] += $use['attribs']['y'];
  23801. }
  23802. if (empty($attribs['style'])) {
  23803. $attribs['style'] = '';
  23804. }
  23805. if (!empty($use['attribs']['style'])) {
  23806. // merge styles
  23807. $attribs['style'] = str_replace(';;',';',';'.$use['attribs']['style'].$attribs['style']);
  23808. }
  23809. $attribs = array_merge($use['attribs'], $attribs);
  23810. $this->startSVGElementHandler($parser, $use['name'], $attribs);
  23811. return;
  23812. }
  23813. }
  23814. break;
  23815. }
  23816. default: {
  23817. break;
  23818. }
  23819. } // end of switch
  23820. // process child elements
  23821. if (!empty($attribs['child_elements'])) {
  23822. $child_elements = $attribs['child_elements'];
  23823. unset($attribs['child_elements']);
  23824. foreach($child_elements as $child_element) {
  23825. if (empty($child_element['attribs']['closing_tag'])) {
  23826. $this->startSVGElementHandler('child-tag', $child_element['name'], $child_element['attribs']);
  23827. } else {
  23828. if (isset($child_element['attribs']['content'])) {
  23829. $this->svgtext = $child_element['attribs']['content'];
  23830. }
  23831. $this->endSVGElementHandler('child-tag', $child_element['name']);
  23832. }
  23833. }
  23834. }
  23835. }
  23836. /**
  23837. * Sets the closing SVG element handler function for the XML parser.
  23838. * @param $parser (resource) The first parameter, parser, is a reference to the XML parser calling the handler.
  23839. * @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.
  23840. * @author Nicola Asuni
  23841. * @since 5.0.000 (2010-05-02)
  23842. * @protected
  23843. */
  23844. protected function endSVGElementHandler($parser, $name) {
  23845. $name = $this->removeTagNamespace($name);
  23846. if ($this->svgdefsmode AND !in_array($name, array('defs', 'clipPath', 'linearGradient', 'radialGradient', 'stop'))) {;
  23847. if (end($this->svgdefs) !== FALSE) {
  23848. $last_svgdefs_id = key($this->svgdefs);
  23849. if (isset($this->svgdefs[$last_svgdefs_id]['attribs']['child_elements'])) {
  23850. foreach($this->svgdefs[$last_svgdefs_id]['attribs']['child_elements'] as $child_element) {
  23851. if (isset($child_element['attribs']['id']) AND ($child_element['name'] == $name)) {
  23852. $this->svgdefs[$last_svgdefs_id]['attribs']['child_elements'][$child_element['attribs']['id'].'_CLOSE'] = array('name' => $name, 'attribs' => array('closing_tag' => TRUE, 'content' => $this->svgtext));
  23853. return;
  23854. }
  23855. }
  23856. if ($this->svgdefs[$last_svgdefs_id]['name'] == $name) {
  23857. $this->svgdefs[$last_svgdefs_id]['attribs']['child_elements'][$last_svgdefs_id.'_CLOSE'] = array('name' => $name, 'attribs' => array('closing_tag' => TRUE, 'content' => $this->svgtext));
  23858. return;
  23859. }
  23860. }
  23861. }
  23862. return;
  23863. }
  23864. switch($name) {
  23865. case 'defs': {
  23866. $this->svgdefsmode = false;
  23867. break;
  23868. }
  23869. // clipPath
  23870. case 'clipPath': {
  23871. $this->svgclipmode = false;
  23872. break;
  23873. }
  23874. case 'svg': {
  23875. if (--$this->svg_tag_depth <= 0) {
  23876. break;
  23877. }
  23878. }
  23879. case 'g': {
  23880. // ungroup: remove last style from array
  23881. array_pop($this->svgstyles);
  23882. $this->StopTransform();
  23883. break;
  23884. }
  23885. case 'text':
  23886. case 'tspan': {
  23887. if ($this->svgtextmode['invisible']) {
  23888. // This implementation must be fixed to following the rule:
  23889. // 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.
  23890. break;
  23891. }
  23892. // print text
  23893. $text = $this->svgtext;
  23894. //$text = $this->stringTrim($text);
  23895. $textlen = $this->GetStringWidth($text);
  23896. if ($this->svgtextmode['text-anchor'] != 'start') {
  23897. // check if string is RTL text
  23898. if ($this->svgtextmode['text-anchor'] == 'end') {
  23899. if ($this->svgtextmode['rtl']) {
  23900. $this->x += $textlen;
  23901. } else {
  23902. $this->x -= $textlen;
  23903. }
  23904. } elseif ($this->svgtextmode['text-anchor'] == 'middle') {
  23905. if ($this->svgtextmode['rtl']) {
  23906. $this->x += ($textlen / 2);
  23907. } else {
  23908. $this->x -= ($textlen / 2);
  23909. }
  23910. }
  23911. }
  23912. $textrendermode = $this->textrendermode;
  23913. $textstrokewidth = $this->textstrokewidth;
  23914. $this->setTextRenderingMode($this->svgtextmode['stroke'], true, false);
  23915. if ($name == 'text') {
  23916. // store current coordinates
  23917. $tmpx = $this->x;
  23918. $tmpy = $this->y;
  23919. }
  23920. // print the text
  23921. $this->Cell($textlen, 0, $text, 0, 0, '', false, '', 0, false, 'L', 'T');
  23922. if ($name == 'text') {
  23923. // restore coordinates
  23924. $this->x = $tmpx;
  23925. $this->y = $tmpy;
  23926. }
  23927. // restore previous rendering mode
  23928. $this->textrendermode = $textrendermode;
  23929. $this->textstrokewidth = $textstrokewidth;
  23930. $this->svgtext = '';
  23931. $this->StopTransform();
  23932. if (!$this->svgdefsmode) {
  23933. array_pop($this->svgstyles);
  23934. }
  23935. break;
  23936. }
  23937. default: {
  23938. break;
  23939. }
  23940. }
  23941. }
  23942. /**
  23943. * Sets the character data handler function for the XML parser.
  23944. * @param $parser (resource) The first parameter, parser, is a reference to the XML parser calling the handler.
  23945. * @param $data (string) The second parameter, data, contains the character data as a string.
  23946. * @author Nicola Asuni
  23947. * @since 5.0.000 (2010-05-02)
  23948. * @protected
  23949. */
  23950. protected function segSVGContentHandler($parser, $data) {
  23951. $this->svgtext .= $data;
  23952. }
  23953. // --- END SVG METHODS -----------------------------------------------------
  23954. /**
  23955. * Keeps files in memory, so it doesn't need to downloaded everytime in a loop
  23956. * @param string $file
  23957. * @return string
  23958. */
  23959. protected function getCachedFileContents($file)
  23960. {
  23961. if (!isset($this->fileContentCache[$file])) {
  23962. $this->fileContentCache[$file] = TCPDF_STATIC::fileGetContents($file);
  23963. }
  23964. return $this->fileContentCache[$file];
  23965. }
  23966. /**
  23967. * Avoid multiple calls to an external server to see if a file exists
  23968. * @param string $file
  23969. * @return bool
  23970. */
  23971. protected function fileExists($file)
  23972. {
  23973. if (isset($this->fileContentCache[$file]) || false !== $this->getImageBuffer($file)) {
  23974. return true;
  23975. }
  23976. return TCPDF_STATIC::file_exists($file);
  23977. }
  23978. } // END OF TCPDF CLASS
  23979. //============================================================+
  23980. // END OF FILE
  23981. //============================================================+