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

24578 lines
880 KiB

4 years ago
  1. <?php
  2. //============================================================+
  3. // File name : tcpdf.php
  4. // Version : 6.3.2
  5. // Begin : 2002-08-03
  6. // Last Update : 2019-09-20
  7. // Author : Nicola Asuni - Tecnick.com LTD - www.tecnick.com - info@tecnick.com
  8. // License : GNU-LGPL v3 (http://www.gnu.org/copyleft/lesser.html)
  9. // -------------------------------------------------------------------
  10. // Copyright (C) 2002-2019 Nicola Asuni - Tecnick.com LTD
  11. //
  12. // This file is part of TCPDF software library.
  13. //
  14. // TCPDF is free software: you can redistribute it and/or modify it
  15. // under the terms of the GNU Lesser General Public License as
  16. // published by the Free Software Foundation, either version 3 of the
  17. // License, or (at your option) any later version.
  18. //
  19. // TCPDF is distributed in the hope that it will be useful, but
  20. // WITHOUT ANY WARRANTY; without even the implied warranty of
  21. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  22. // See the GNU Lesser General Public License for more details.
  23. //
  24. // You should have received a copy of the License
  25. // along with TCPDF. If not, see
  26. // <http://www.tecnick.com/pagefiles/tcpdf/LICENSE.TXT>.
  27. //
  28. // See LICENSE.TXT file for more information.
  29. // -------------------------------------------------------------------
  30. //
  31. // Description :
  32. // This is a PHP class for generating PDF documents without requiring external extensions.
  33. //
  34. // NOTE:
  35. // This class was originally derived in 2002 from the Public
  36. // Domain FPDF class by Olivier Plathey (http://www.fpdf.org),
  37. // but now is almost entirely rewritten and contains thousands of
  38. // new lines of code and hundreds new features.
  39. //
  40. // Main features:
  41. // * no external libraries are required for the basic functions;
  42. // * all standard page formats, custom page formats, custom margins and units of measure;
  43. // * UTF-8 Unicode and Right-To-Left languages;
  44. // * TrueTypeUnicode, TrueType, Type1 and CID-0 fonts;
  45. // * font subsetting;
  46. // * methods to publish some XHTML + CSS code, Javascript and Forms;
  47. // * images, graphic (geometric figures) and transformation methods;
  48. // * supports JPEG, PNG and SVG images natively, all images supported by GD (GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM) and all images supported via ImageMagick (http://www.imagemagick.org/www/formats.html)
  49. // * 1D and 2D barcodes: CODE 39, ANSI MH10.8M-1983, USD-3, 3 of 9, CODE 93, USS-93, Standard 2 of 5, Interleaved 2 of 5, CODE 128 A/B/C, 2 and 5 Digits UPC-Based Extension, EAN 8, EAN 13, UPC-A, UPC-E, MSI, POSTNET, PLANET, RMS4CC (Royal Mail 4-state Customer Code), CBC (Customer Bar Code), KIX (Klant index - Customer index), Intelligent Mail Barcode, Onecode, USPS-B-3200, CODABAR, CODE 11, PHARMACODE, PHARMACODE TWO-TRACKS, Datamatrix, QR-Code, PDF417;
  50. // * JPEG and PNG ICC profiles, Grayscale, RGB, CMYK, Spot Colors and Transparencies;
  51. // * automatic page header and footer management;
  52. // * document encryption up to 256 bit and digital signature certifications;
  53. // * transactions to UNDO commands;
  54. // * PDF annotations, including links, text and file attachments;
  55. // * text rendering modes (fill, stroke and clipping);
  56. // * multiple columns mode;
  57. // * no-write page regions;
  58. // * bookmarks, named destinations and table of content;
  59. // * text hyphenation;
  60. // * text stretching and spacing (tracking);
  61. // * automatic page break, line break and text alignments including justification;
  62. // * automatic page numbering and page groups;
  63. // * move and delete pages;
  64. // * page compression (requires php-zlib extension);
  65. // * XOBject Templates;
  66. // * Layers and object visibility.
  67. // * PDF/A-1b support
  68. //============================================================+
  69. /**
  70. * @file
  71. * This is a PHP class for generating PDF documents without requiring external extensions.<br>
  72. * TCPDF project (http://www.tcpdf.org) was originally derived in 2002 from the Public Domain FPDF class by Olivier Plathey (http://www.fpdf.org), but now is almost entirely rewritten.<br>
  73. * <h3>TCPDF main features are:</h3>
  74. * <ul>
  75. * <li>no external libraries are required for the basic functions;</li>
  76. * <li>all standard page formats, custom page formats, custom margins and units of measure;</li>
  77. * <li>UTF-8 Unicode and Right-To-Left languages;</li>
  78. * <li>TrueTypeUnicode, TrueType, Type1 and CID-0 fonts;</li>
  79. * <li>font subsetting;</li>
  80. * <li>methods to publish some XHTML + CSS code, Javascript and Forms;</li>
  81. * <li>images, graphic (geometric figures) and transformation methods;
  82. * <li>supports JPEG, PNG and SVG images natively, all images supported by GD (GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM) and all images supported via ImageMagick (http://www.imagemagick.org/www/formats.html)</li>
  83. * <li>1D and 2D barcodes: CODE 39, ANSI MH10.8M-1983, USD-3, 3 of 9, CODE 93, USS-93, Standard 2 of 5, Interleaved 2 of 5, CODE 128 A/B/C, 2 and 5 Digits UPC-Based Extension, EAN 8, EAN 13, UPC-A, UPC-E, MSI, POSTNET, PLANET, RMS4CC (Royal Mail 4-state Customer Code), CBC (Customer Bar Code), KIX (Klant index - Customer index), Intelligent Mail Barcode, Onecode, USPS-B-3200, CODABAR, CODE 11, PHARMACODE, PHARMACODE TWO-TRACKS, Datamatrix, QR-Code, PDF417;</li>
  84. * <li>JPEG and PNG ICC profiles, Grayscale, RGB, CMYK, Spot Colors and Transparencies;</li>
  85. * <li>automatic page header and footer management;</li>
  86. * <li>document encryption up to 256 bit and digital signature certifications;</li>
  87. * <li>transactions to UNDO commands;</li>
  88. * <li>PDF annotations, including links, text and file attachments;</li>
  89. * <li>text rendering modes (fill, stroke and clipping);</li>
  90. * <li>multiple columns mode;</li>
  91. * <li>no-write page regions;</li>
  92. * <li>bookmarks, named destinations and table of content;</li>
  93. * <li>text hyphenation;</li>
  94. * <li>text stretching and spacing (tracking);</li>
  95. * <li>automatic page break, line break and text alignments including justification;</li>
  96. * <li>automatic page numbering and page groups;</li>
  97. * <li>move and delete pages;</li>
  98. * <li>page compression (requires php-zlib extension);</li>
  99. * <li>XOBject Templates;</li>
  100. * <li>Layers and object visibility;</li>
  101. * <li>PDF/A-1b support.</li>
  102. * </ul>
  103. * Tools to encode your unicode fonts are on fonts/utils directory.</p>
  104. * @package com.tecnick.tcpdf
  105. * @author Nicola Asuni
  106. * @version 6.3.2
  107. */
  108. // TCPDF configuration
  109. require_once(dirname(__FILE__).'/tcpdf_autoconfig.php');
  110. // TCPDF static font methods and data
  111. require_once(dirname(__FILE__).'/include/tcpdf_font_data.php');
  112. // TCPDF static font methods and data
  113. require_once(dirname(__FILE__).'/include/tcpdf_fonts.php');
  114. // TCPDF static color methods and data
  115. require_once(dirname(__FILE__).'/include/tcpdf_colors.php');
  116. // TCPDF static image methods and data
  117. require_once(dirname(__FILE__).'/include/tcpdf_images.php');
  118. // TCPDF static methods and data
  119. require_once(dirname(__FILE__).'/include/tcpdf_static.php');
  120. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  121. /**
  122. * @class TCPDF
  123. * PHP class for generating PDF documents without requiring external extensions.
  124. * TCPDF project (http://www.tcpdf.org) has been originally derived in 2002 from the Public Domain FPDF class by Olivier Plathey (http://www.fpdf.org), but now is almost entirely rewritten.<br>
  125. * @package com.tecnick.tcpdf
  126. * @brief PHP class for generating PDF documents without requiring external extensions.
  127. * @version 6.3.2
  128. * @author Nicola Asuni - info@tecnick.com
  129. * @IgnoreAnnotation("protected")
  130. * @IgnoreAnnotation("public")
  131. * @IgnoreAnnotation("pre")
  132. */
  133. class TCPDF {
  134. // Protected properties
  135. /**
  136. * Current page number.
  137. * @protected
  138. */
  139. protected $page;
  140. /**
  141. * Current object number.
  142. * @protected
  143. */
  144. protected $n;
  145. /**
  146. * Array of object offsets.
  147. * @protected
  148. */
  149. protected $offsets = array();
  150. /**
  151. * Array of object IDs for each page.
  152. * @protected
  153. */
  154. protected $pageobjects = array();
  155. /**
  156. * Buffer holding in-memory PDF.
  157. * @protected
  158. */
  159. protected $buffer;
  160. /**
  161. * Array containing pages.
  162. * @protected
  163. */
  164. protected $pages = array();
  165. /**
  166. * Current document state.
  167. * @protected
  168. */
  169. protected $state;
  170. /**
  171. * Compression flag.
  172. * @protected
  173. */
  174. protected $compress;
  175. /**
  176. * Current page orientation (P = Portrait, L = Landscape).
  177. * @protected
  178. */
  179. protected $CurOrientation;
  180. /**
  181. * Page dimensions.
  182. * @protected
  183. */
  184. protected $pagedim = array();
  185. /**
  186. * Scale factor (number of points in user unit).
  187. * @protected
  188. */
  189. protected $k;
  190. /**
  191. * Width of page format in points.
  192. * @protected
  193. */
  194. protected $fwPt;
  195. /**
  196. * Height of page format in points.
  197. * @protected
  198. */
  199. protected $fhPt;
  200. /**
  201. * Current width of page in points.
  202. * @protected
  203. */
  204. protected $wPt;
  205. /**
  206. * Current height of page in points.
  207. * @protected
  208. */
  209. protected $hPt;
  210. /**
  211. * Current width of page in user unit.
  212. * @protected
  213. */
  214. protected $w;
  215. /**
  216. * Current height of page in user unit.
  217. * @protected
  218. */
  219. protected $h;
  220. /**
  221. * Left margin.
  222. * @protected
  223. */
  224. protected $lMargin;
  225. /**
  226. * Right margin.
  227. * @protected
  228. */
  229. protected $rMargin;
  230. /**
  231. * Cell left margin (used by regions).
  232. * @protected
  233. */
  234. protected $clMargin;
  235. /**
  236. * Cell right margin (used by regions).
  237. * @protected
  238. */
  239. protected $crMargin;
  240. /**
  241. * Top margin.
  242. * @protected
  243. */
  244. protected $tMargin;
  245. /**
  246. * Page break margin.
  247. * @protected
  248. */
  249. protected $bMargin;
  250. /**
  251. * Array of cell internal paddings ('T' => top, 'R' => right, 'B' => bottom, 'L' => left).
  252. * @since 5.9.000 (2010-10-03)
  253. * @protected
  254. */
  255. protected $cell_padding = array('T' => 0, 'R' => 0, 'B' => 0, 'L' => 0);
  256. /**
  257. * Array of cell margins ('T' => top, 'R' => right, 'B' => bottom, 'L' => left).
  258. * @since 5.9.000 (2010-10-04)
  259. * @protected
  260. */
  261. protected $cell_margin = array('T' => 0, 'R' => 0, 'B' => 0, 'L' => 0);
  262. /**
  263. * Current horizontal position in user unit for cell positioning.
  264. * @protected
  265. */
  266. protected $x;
  267. /**
  268. * Current vertical position in user unit for cell positioning.
  269. * @protected
  270. */
  271. protected $y;
  272. /**
  273. * Height of last cell printed.
  274. * @protected
  275. */
  276. protected $lasth;
  277. /**
  278. * Line width in user unit.
  279. * @protected
  280. */
  281. protected $LineWidth;
  282. /**
  283. * Array of standard font names.
  284. * @protected
  285. */
  286. protected $CoreFonts;
  287. /**
  288. * Array of used fonts.
  289. * @protected
  290. */
  291. protected $fonts = array();
  292. /**
  293. * Array of font files.
  294. * @protected
  295. */
  296. protected $FontFiles = array();
  297. /**
  298. * Array of encoding differences.
  299. * @protected
  300. */
  301. protected $diffs = array();
  302. /**
  303. * Array of used images.
  304. * @protected
  305. */
  306. protected $images = array();
  307. /**
  308. * Depth of the svg tag, to keep track if the svg tag is a subtag or the root tag.
  309. * @protected
  310. */
  311. protected $svg_tag_depth = 0;
  312. /**
  313. * Array of Annotations in pages.
  314. * @protected
  315. */
  316. protected $PageAnnots = array();
  317. /**
  318. * Array of internal links.
  319. * @protected
  320. */
  321. protected $links = array();
  322. /**
  323. * Current font family.
  324. * @protected
  325. */
  326. protected $FontFamily;
  327. /**
  328. * Current font style.
  329. * @protected
  330. */
  331. protected $FontStyle;
  332. /**
  333. * Current font ascent (distance between font top and baseline).
  334. * @protected
  335. * @since 2.8.000 (2007-03-29)
  336. */
  337. protected $FontAscent;
  338. /**
  339. * Current font descent (distance between font bottom and baseline).
  340. * @protected
  341. * @since 2.8.000 (2007-03-29)
  342. */
  343. protected $FontDescent;
  344. /**
  345. * Underlining flag.
  346. * @protected
  347. */
  348. protected $underline;
  349. /**
  350. * Overlining flag.
  351. * @protected
  352. */
  353. protected $overline;
  354. /**
  355. * Current font info.
  356. * @protected
  357. */
  358. protected $CurrentFont;
  359. /**
  360. * Current font size in points.
  361. * @protected
  362. */
  363. protected $FontSizePt;
  364. /**
  365. * Current font size in user unit.
  366. * @protected
  367. */
  368. protected $FontSize;
  369. /**
  370. * Commands for drawing color.
  371. * @protected
  372. */
  373. protected $DrawColor;
  374. /**
  375. * Commands for filling color.
  376. * @protected
  377. */
  378. protected $FillColor;
  379. /**
  380. * Commands for text color.
  381. * @protected
  382. */
  383. protected $TextColor;
  384. /**
  385. * Indicates whether fill and text colors are different.
  386. * @protected
  387. */
  388. protected $ColorFlag;
  389. /**
  390. * Automatic page breaking.
  391. * @protected
  392. */
  393. protected $AutoPageBreak;
  394. /**
  395. * Threshold used to trigger page breaks.
  396. * @protected
  397. */
  398. protected $PageBreakTrigger;
  399. /**
  400. * Flag set when processing page header.
  401. * @protected
  402. */
  403. protected $InHeader = false;
  404. /**
  405. * Flag set when processing page footer.
  406. * @protected
  407. */
  408. protected $InFooter = false;
  409. /**
  410. * Zoom display mode.
  411. * @protected
  412. */
  413. protected $ZoomMode;
  414. /**
  415. * Layout display mode.
  416. * @protected
  417. */
  418. protected $LayoutMode;
  419. /**
  420. * If true set the document information dictionary in Unicode.
  421. * @protected
  422. */
  423. protected $docinfounicode = true;
  424. /**
  425. * Document title.
  426. * @protected
  427. */
  428. protected $title = '';
  429. /**
  430. * Document subject.
  431. * @protected
  432. */
  433. protected $subject = '';
  434. /**
  435. * Document author.
  436. * @protected
  437. */
  438. protected $author = '';
  439. /**
  440. * Document keywords.
  441. * @protected
  442. */
  443. protected $keywords = '';
  444. /**
  445. * Document creator.
  446. * @protected
  447. */
  448. protected $creator = '';
  449. /**
  450. * Starting page number.
  451. * @protected
  452. */
  453. protected $starting_page_number = 1;
  454. /**
  455. * The right-bottom (or left-bottom for RTL) corner X coordinate of last inserted image.
  456. * @since 2002-07-31
  457. * @author Nicola Asuni
  458. * @protected
  459. */
  460. protected $img_rb_x;
  461. /**
  462. * The right-bottom corner Y coordinate of last inserted image.
  463. * @since 2002-07-31
  464. * @author Nicola Asuni
  465. * @protected
  466. */
  467. protected $img_rb_y;
  468. /**
  469. * Adjusting factor to convert pixels to user units.
  470. * @since 2004-06-14
  471. * @author Nicola Asuni
  472. * @protected
  473. */
  474. protected $imgscale = 1;
  475. /**
  476. * Boolean flag set to true when the input text is unicode (require unicode fonts).
  477. * @since 2005-01-02
  478. * @author Nicola Asuni
  479. * @protected
  480. */
  481. protected $isunicode = false;
  482. /**
  483. * PDF version.
  484. * @since 1.5.3
  485. * @protected
  486. */
  487. protected $PDFVersion = '1.7';
  488. /**
  489. * ID of the stored default header template (-1 = not set).
  490. * @protected
  491. */
  492. protected $header_xobjid = false;
  493. /**
  494. * If true reset the Header Xobject template at each page
  495. * @protected
  496. */
  497. protected $header_xobj_autoreset = false;
  498. /**
  499. * Minimum distance between header and top page margin.
  500. * @protected
  501. */
  502. protected $header_margin;
  503. /**
  504. * Minimum distance between footer and bottom page margin.
  505. * @protected
  506. */
  507. protected $footer_margin;
  508. /**
  509. * Original left margin value.
  510. * @protected
  511. * @since 1.53.0.TC013
  512. */
  513. protected $original_lMargin;
  514. /**
  515. * Original right margin value.
  516. * @protected
  517. * @since 1.53.0.TC013
  518. */
  519. protected $original_rMargin;
  520. /**
  521. * Default font used on page header.
  522. * @protected
  523. */
  524. protected $header_font;
  525. /**
  526. * Default font used on page footer.
  527. * @protected
  528. */
  529. protected $footer_font;
  530. /**
  531. * Language templates.
  532. * @protected
  533. */
  534. protected $l;
  535. /**
  536. * Barcode to print on page footer (only if set).
  537. * @protected
  538. */
  539. protected $barcode = false;
  540. /**
  541. * Boolean flag to print/hide page header.
  542. * @protected
  543. */
  544. protected $print_header = true;
  545. /**
  546. * Boolean flag to print/hide page footer.
  547. * @protected
  548. */
  549. protected $print_footer = true;
  550. /**
  551. * Header image logo.
  552. * @protected
  553. */
  554. protected $header_logo = '';
  555. /**
  556. * Width of header image logo in user units.
  557. * @protected
  558. */
  559. protected $header_logo_width = 30;
  560. /**
  561. * Title to be printed on default page header.
  562. * @protected
  563. */
  564. protected $header_title = '';
  565. /**
  566. * String to pring on page header after title.
  567. * @protected
  568. */
  569. protected $header_string = '';
  570. /**
  571. * Color for header text (RGB array).
  572. * @since 5.9.174 (2012-07-25)
  573. * @protected
  574. */
  575. protected $header_text_color = array(0,0,0);
  576. /**
  577. * Color for header line (RGB array).
  578. * @since 5.9.174 (2012-07-25)
  579. * @protected
  580. */
  581. protected $header_line_color = array(0,0,0);
  582. /**
  583. * Color for footer text (RGB array).
  584. * @since 5.9.174 (2012-07-25)
  585. * @protected
  586. */
  587. protected $footer_text_color = array(0,0,0);
  588. /**
  589. * Color for footer line (RGB array).
  590. * @since 5.9.174 (2012-07-25)
  591. * @protected
  592. */
  593. protected $footer_line_color = array(0,0,0);
  594. /**
  595. * Text shadow data array.
  596. * @since 5.9.174 (2012-07-25)
  597. * @protected
  598. */
  599. protected $txtshadow = array('enabled'=>false, 'depth_w'=>0, 'depth_h'=>0, 'color'=>false, 'opacity'=>1, 'blend_mode'=>'Normal');
  600. /**
  601. * Default number of columns for html table.
  602. * @protected
  603. */
  604. protected $default_table_columns = 4;
  605. // variables for html parser
  606. /**
  607. * HTML PARSER: array to store current link and rendering styles.
  608. * @protected
  609. */
  610. protected $HREF = array();
  611. /**
  612. * List of available fonts on filesystem.
  613. * @protected
  614. */
  615. protected $fontlist = array();
  616. /**
  617. * Current foreground color.
  618. * @protected
  619. */
  620. protected $fgcolor;
  621. /**
  622. * HTML PARSER: array of boolean values, true in case of ordered list (OL), false otherwise.
  623. * @protected
  624. */
  625. protected $listordered = array();
  626. /**
  627. * HTML PARSER: array count list items on nested lists.
  628. * @protected
  629. */
  630. protected $listcount = array();
  631. /**
  632. * HTML PARSER: current list nesting level.
  633. * @protected
  634. */
  635. protected $listnum = 0;
  636. /**
  637. * HTML PARSER: indent amount for lists.
  638. * @protected
  639. */
  640. protected $listindent = 0;
  641. /**
  642. * HTML PARSER: current list indententation level.
  643. * @protected
  644. */
  645. protected $listindentlevel = 0;
  646. /**
  647. * Current background color.
  648. * @protected
  649. */
  650. protected $bgcolor;
  651. /**
  652. * Temporary font size in points.
  653. * @protected
  654. */
  655. protected $tempfontsize = 10;
  656. /**
  657. * Spacer string for LI tags.
  658. * @protected
  659. */
  660. protected $lispacer = '';
  661. /**
  662. * Default encoding.
  663. * @protected
  664. * @since 1.53.0.TC010
  665. */
  666. protected $encoding = 'UTF-8';
  667. /**
  668. * PHP internal encoding.
  669. * @protected
  670. * @since 1.53.0.TC016
  671. */
  672. protected $internal_encoding;
  673. /**
  674. * Boolean flag to indicate if the document language is Right-To-Left.
  675. * @protected
  676. * @since 2.0.000
  677. */
  678. protected $rtl = false;
  679. /**
  680. * Boolean flag used to force RTL or LTR string direction.
  681. * @protected
  682. * @since 2.0.000
  683. */
  684. protected $tmprtl = false;
  685. // --- Variables used for document encryption:
  686. /**
  687. * IBoolean flag indicating whether document is protected.
  688. * @protected
  689. * @since 2.0.000 (2008-01-02)
  690. */
  691. protected $encrypted;
  692. /**
  693. * Array containing encryption settings.
  694. * @protected
  695. * @since 5.0.005 (2010-05-11)
  696. */
  697. protected $encryptdata = array();
  698. /**
  699. * Last RC4 key encrypted (cached for optimisation).
  700. * @protected
  701. * @since 2.0.000 (2008-01-02)
  702. */
  703. protected $last_enc_key;
  704. /**
  705. * Last RC4 computed key.
  706. * @protected
  707. * @since 2.0.000 (2008-01-02)
  708. */
  709. protected $last_enc_key_c;
  710. /**
  711. * File ID (used on document trailer).
  712. * @protected
  713. * @since 5.0.005 (2010-05-12)
  714. */
  715. protected $file_id;
  716. // --- bookmark ---
  717. /**
  718. * Outlines for bookmark.
  719. * @protected
  720. * @since 2.1.002 (2008-02-12)
  721. */
  722. protected $outlines = array();
  723. /**
  724. * Outline root for bookmark.
  725. * @protected
  726. * @since 2.1.002 (2008-02-12)
  727. */
  728. protected $OutlineRoot;
  729. // --- javascript and form ---
  730. /**
  731. * Javascript code.
  732. * @protected
  733. * @since 2.1.002 (2008-02-12)
  734. */
  735. protected $javascript = '';
  736. /**
  737. * Javascript counter.
  738. * @protected
  739. * @since 2.1.002 (2008-02-12)
  740. */
  741. protected $n_js;
  742. /**
  743. * line through state
  744. * @protected
  745. * @since 2.8.000 (2008-03-19)
  746. */
  747. protected $linethrough;
  748. /**
  749. * Array with additional document-wide usage rights for the document.
  750. * @protected
  751. * @since 5.8.014 (2010-08-23)
  752. */
  753. protected $ur = array();
  754. /**
  755. * DPI (Dot Per Inch) Document Resolution (do not change).
  756. * @protected
  757. * @since 3.0.000 (2008-03-27)
  758. */
  759. protected $dpi = 72;
  760. /**
  761. * Array of page numbers were a new page group was started (the page numbers are the keys of the array).
  762. * @protected
  763. * @since 3.0.000 (2008-03-27)
  764. */
  765. protected $newpagegroup = array();
  766. /**
  767. * Array that contains the number of pages in each page group.
  768. * @protected
  769. * @since 3.0.000 (2008-03-27)
  770. */
  771. protected $pagegroups = array();
  772. /**
  773. * Current page group number.
  774. * @protected
  775. * @since 3.0.000 (2008-03-27)
  776. */
  777. protected $currpagegroup = 0;
  778. /**
  779. * Array of transparency objects and parameters.
  780. * @protected
  781. * @since 3.0.000 (2008-03-27)
  782. */
  783. protected $extgstates;
  784. /**
  785. * Set the default JPEG compression quality (1-100).
  786. * @protected
  787. * @since 3.0.000 (2008-03-27)
  788. */
  789. protected $jpeg_quality;
  790. /**
  791. * Default cell height ratio.
  792. * @protected
  793. * @since 3.0.014 (2008-05-23)
  794. */
  795. protected $cell_height_ratio = K_CELL_HEIGHT_RATIO;
  796. /**
  797. * PDF viewer preferences.
  798. * @protected
  799. * @since 3.1.000 (2008-06-09)
  800. */
  801. protected $viewer_preferences;
  802. /**
  803. * A name object specifying how the document should be displayed when opened.
  804. * @protected
  805. * @since 3.1.000 (2008-06-09)
  806. */
  807. protected $PageMode;
  808. /**
  809. * Array for storing gradient information.
  810. * @protected
  811. * @since 3.1.000 (2008-06-09)
  812. */
  813. protected $gradients = array();
  814. /**
  815. * Array used to store positions inside the pages buffer (keys are the page numbers).
  816. * @protected
  817. * @since 3.2.000 (2008-06-26)
  818. */
  819. protected $intmrk = array();
  820. /**
  821. * Array used to store positions inside the pages buffer (keys are the page numbers).
  822. * @protected
  823. * @since 5.7.000 (2010-08-03)
  824. */
  825. protected $bordermrk = array();
  826. /**
  827. * Array used to store page positions to track empty pages (keys are the page numbers).
  828. * @protected
  829. * @since 5.8.007 (2010-08-18)
  830. */
  831. protected $emptypagemrk = array();
  832. /**
  833. * Array used to store content positions inside the pages buffer (keys are the page numbers).
  834. * @protected
  835. * @since 4.6.021 (2009-07-20)
  836. */
  837. protected $cntmrk = array();
  838. /**
  839. * Array used to store footer positions of each page.
  840. * @protected
  841. * @since 3.2.000 (2008-07-01)
  842. */
  843. protected $footerpos = array();
  844. /**
  845. * Array used to store footer length of each page.
  846. * @protected
  847. * @since 4.0.014 (2008-07-29)
  848. */
  849. protected $footerlen = array();
  850. /**
  851. * Boolean flag to indicate if a new line is created.
  852. * @protected
  853. * @since 3.2.000 (2008-07-01)
  854. */
  855. protected $newline = true;
  856. /**
  857. * End position of the latest inserted line.
  858. * @protected
  859. * @since 3.2.000 (2008-07-01)
  860. */
  861. protected $endlinex = 0;
  862. /**
  863. * PDF string for width value of the last line.
  864. * @protected
  865. * @since 4.0.006 (2008-07-16)
  866. */
  867. protected $linestyleWidth = '';
  868. /**
  869. * PDF string for CAP value of the last line.
  870. * @protected
  871. * @since 4.0.006 (2008-07-16)
  872. */
  873. protected $linestyleCap = '0 J';
  874. /**
  875. * PDF string for join value of the last line.
  876. * @protected
  877. * @since 4.0.006 (2008-07-16)
  878. */
  879. protected $linestyleJoin = '0 j';
  880. /**
  881. * PDF string for dash value of the last line.
  882. * @protected
  883. * @since 4.0.006 (2008-07-16)
  884. */
  885. protected $linestyleDash = '[] 0 d';
  886. /**
  887. * Boolean flag to indicate if marked-content sequence is open.
  888. * @protected
  889. * @since 4.0.013 (2008-07-28)
  890. */
  891. protected $openMarkedContent = false;
  892. /**
  893. * Count the latest inserted vertical spaces on HTML.
  894. * @protected
  895. * @since 4.0.021 (2008-08-24)
  896. */
  897. protected $htmlvspace = 0;
  898. /**
  899. * Array of Spot colors.
  900. * @protected
  901. * @since 4.0.024 (2008-09-12)
  902. */
  903. protected $spot_colors = array();
  904. /**
  905. * Symbol used for HTML unordered list items.
  906. * @protected
  907. * @since 4.0.028 (2008-09-26)
  908. */
  909. protected $lisymbol = '';
  910. /**
  911. * String used to mark the beginning and end of EPS image blocks.
  912. * @protected
  913. * @since 4.1.000 (2008-10-18)
  914. */
  915. protected $epsmarker = 'x#!#EPS#!#x';
  916. /**
  917. * Array of transformation matrix.
  918. * @protected
  919. * @since 4.2.000 (2008-10-29)
  920. */
  921. protected $transfmatrix = array();
  922. /**
  923. * Current key for transformation matrix.
  924. * @protected
  925. * @since 4.8.005 (2009-09-17)
  926. */
  927. protected $transfmatrix_key = 0;
  928. /**
  929. * Booklet mode for double-sided pages.
  930. * @protected
  931. * @since 4.2.000 (2008-10-29)
  932. */
  933. protected $booklet = false;
  934. /**
  935. * Epsilon value used for float calculations.
  936. * @protected
  937. * @since 4.2.000 (2008-10-29)
  938. */
  939. protected $feps = 0.005;
  940. /**
  941. * Array used for custom vertical spaces for HTML tags.
  942. * @protected
  943. * @since 4.2.001 (2008-10-30)
  944. */
  945. protected $tagvspaces = array();
  946. /**
  947. * HTML PARSER: custom indent amount for lists. Negative value means disabled.
  948. * @protected
  949. * @since 4.2.007 (2008-11-12)
  950. */
  951. protected $customlistindent = -1;
  952. /**
  953. * Boolean flag to indicate if the border of the cell sides that cross the page should be removed.
  954. * @protected
  955. * @since 4.2.010 (2008-11-14)
  956. */
  957. protected $opencell = true;
  958. /**
  959. * Array of files to embedd.
  960. * @protected
  961. * @since 4.4.000 (2008-12-07)
  962. */
  963. protected $embeddedfiles = array();
  964. /**
  965. * Boolean flag to indicate if we are inside a PRE tag.
  966. * @protected
  967. * @since 4.4.001 (2008-12-08)
  968. */
  969. protected $premode = false;
  970. /**
  971. * Array used to store positions of graphics transformation blocks inside the page buffer.
  972. * keys are the page numbers
  973. * @protected
  974. * @since 4.4.002 (2008-12-09)
  975. */
  976. protected $transfmrk = array();
  977. /**
  978. * Default color for html links.
  979. * @protected
  980. * @since 4.4.003 (2008-12-09)
  981. */
  982. protected $htmlLinkColorArray = array(0, 0, 255);
  983. /**
  984. * Default font style to add to html links.
  985. * @protected
  986. * @since 4.4.003 (2008-12-09)
  987. */
  988. protected $htmlLinkFontStyle = 'U';
  989. /**
  990. * Counts the number of pages.
  991. * @protected
  992. * @since 4.5.000 (2008-12-31)
  993. */
  994. protected $numpages = 0;
  995. /**
  996. * Array containing page lengths in bytes.
  997. * @protected
  998. * @since 4.5.000 (2008-12-31)
  999. */
  1000. protected $pagelen = array();
  1001. /**
  1002. * Counts the number of pages.
  1003. * @protected
  1004. * @since 4.5.000 (2008-12-31)
  1005. */
  1006. protected $numimages = 0;
  1007. /**
  1008. * Store the image keys.
  1009. * @protected
  1010. * @since 4.5.000 (2008-12-31)
  1011. */
  1012. protected $imagekeys = array();
  1013. /**
  1014. * Length of the buffer in bytes.
  1015. * @protected
  1016. * @since 4.5.000 (2008-12-31)
  1017. */
  1018. protected $bufferlen = 0;
  1019. /**
  1020. * Counts the number of fonts.
  1021. * @protected
  1022. * @since 4.5.000 (2009-01-02)
  1023. */
  1024. protected $numfonts = 0;
  1025. /**
  1026. * Store the font keys.
  1027. * @protected
  1028. * @since 4.5.000 (2009-01-02)
  1029. */
  1030. protected $fontkeys = array();
  1031. /**
  1032. * Store the font object IDs.
  1033. * @protected
  1034. * @since 4.8.001 (2009-09-09)
  1035. */
  1036. protected $font_obj_ids = array();
  1037. /**
  1038. * Store the fage status (true when opened, false when closed).
  1039. * @protected
  1040. * @since 4.5.000 (2009-01-02)
  1041. */
  1042. protected $pageopen = array();
  1043. /**
  1044. * Default monospace font.
  1045. * @protected
  1046. * @since 4.5.025 (2009-03-10)
  1047. */
  1048. protected $default_monospaced_font = 'courier';
  1049. /**
  1050. * Cloned copy of the current class object.
  1051. * @protected
  1052. * @since 4.5.029 (2009-03-19)
  1053. */
  1054. protected $objcopy;
  1055. /**
  1056. * Array used to store the lengths of cache files.
  1057. * @protected
  1058. * @since 4.5.029 (2009-03-19)
  1059. */
  1060. protected $cache_file_length = array();
  1061. /**
  1062. * Table header content to be repeated on each new page.
  1063. * @protected
  1064. * @since 4.5.030 (2009-03-20)
  1065. */
  1066. protected $thead = '';
  1067. /**
  1068. * Margins used for table header.
  1069. * @protected
  1070. * @since 4.5.030 (2009-03-20)
  1071. */
  1072. protected $theadMargins = array();
  1073. /**
  1074. * Boolean flag to enable document digital signature.
  1075. * @protected
  1076. * @since 4.6.005 (2009-04-24)
  1077. */
  1078. protected $sign = false;
  1079. /**
  1080. * Digital signature data.
  1081. * @protected
  1082. * @since 4.6.005 (2009-04-24)
  1083. */
  1084. protected $signature_data = array();
  1085. /**
  1086. * Digital signature max length.
  1087. * @protected
  1088. * @since 4.6.005 (2009-04-24)
  1089. */
  1090. protected $signature_max_length = 11742;
  1091. /**
  1092. * Data for digital signature appearance.
  1093. * @protected
  1094. * @since 5.3.011 (2010-06-16)
  1095. */
  1096. protected $signature_appearance = array('page' => 1, 'rect' => '0 0 0 0');
  1097. /**
  1098. * Array of empty digital signature appearances.
  1099. * @protected
  1100. * @since 5.9.101 (2011-07-06)
  1101. */
  1102. protected $empty_signature_appearance = array();
  1103. /**
  1104. * Boolean flag to enable document timestamping with TSA.
  1105. * @protected
  1106. * @since 6.0.085 (2014-06-19)
  1107. */
  1108. protected $tsa_timestamp = false;
  1109. /**
  1110. * Timestamping data.
  1111. * @protected
  1112. * @since 6.0.085 (2014-06-19)
  1113. */
  1114. protected $tsa_data = array();
  1115. /**
  1116. * Regular expression used to find blank characters (required for word-wrapping).
  1117. * @protected
  1118. * @since 4.6.006 (2009-04-28)
  1119. */
  1120. protected $re_spaces = '/[^\S\xa0]/';
  1121. /**
  1122. * Array of $re_spaces parts.
  1123. * @protected
  1124. * @since 5.5.011 (2010-07-09)
  1125. */
  1126. protected $re_space = array('p' => '[^\S\xa0]', 'm' => '');
  1127. /**
  1128. * Digital signature object ID.
  1129. * @protected
  1130. * @since 4.6.022 (2009-06-23)
  1131. */
  1132. protected $sig_obj_id = 0;
  1133. /**
  1134. * ID of page objects.
  1135. * @protected
  1136. * @since 4.7.000 (2009-08-29)
  1137. */
  1138. protected $page_obj_id = array();
  1139. /**
  1140. * List of form annotations IDs.
  1141. * @protected
  1142. * @since 4.8.000 (2009-09-07)
  1143. */
  1144. protected $form_obj_id = array();
  1145. /**
  1146. * Deafult Javascript field properties. Possible values are described on official Javascript for Acrobat API reference. Annotation options can be directly specified using the 'aopt' entry.
  1147. * @protected
  1148. * @since 4.8.000 (2009-09-07)
  1149. */
  1150. protected $default_form_prop = array('lineWidth'=>1, 'borderStyle'=>'solid', 'fillColor'=>array(255, 255, 255), 'strokeColor'=>array(128, 128, 128));
  1151. /**
  1152. * Javascript objects array.
  1153. * @protected
  1154. * @since 4.8.000 (2009-09-07)
  1155. */
  1156. protected $js_objects = array();
  1157. /**
  1158. * Current form action (used during XHTML rendering).
  1159. * @protected
  1160. * @since 4.8.000 (2009-09-07)
  1161. */
  1162. protected $form_action = '';
  1163. /**
  1164. * Current form encryption type (used during XHTML rendering).
  1165. * @protected
  1166. * @since 4.8.000 (2009-09-07)
  1167. */
  1168. protected $form_enctype = 'application/x-www-form-urlencoded';
  1169. /**
  1170. * Current method to submit forms.
  1171. * @protected
  1172. * @since 4.8.000 (2009-09-07)
  1173. */
  1174. protected $form_mode = 'post';
  1175. /**
  1176. * List of fonts used on form fields (fontname => fontkey).
  1177. * @protected
  1178. * @since 4.8.001 (2009-09-09)
  1179. */
  1180. protected $annotation_fonts = array();
  1181. /**
  1182. * List of radio buttons parent objects.
  1183. * @protected
  1184. * @since 4.8.001 (2009-09-09)
  1185. */
  1186. protected $radiobutton_groups = array();
  1187. /**
  1188. * List of radio group objects IDs.
  1189. * @protected
  1190. * @since 4.8.001 (2009-09-09)
  1191. */
  1192. protected $radio_groups = array();
  1193. /**
  1194. * Text indentation value (used for text-indent CSS attribute).
  1195. * @protected
  1196. * @since 4.8.006 (2009-09-23)
  1197. */
  1198. protected $textindent = 0;
  1199. /**
  1200. * Store page number when startTransaction() is called.
  1201. * @protected
  1202. * @since 4.8.006 (2009-09-23)
  1203. */
  1204. protected $start_transaction_page = 0;
  1205. /**
  1206. * Store Y position when startTransaction() is called.
  1207. * @protected
  1208. * @since 4.9.001 (2010-03-28)
  1209. */
  1210. protected $start_transaction_y = 0;
  1211. /**
  1212. * True when we are printing the thead section on a new page.
  1213. * @protected
  1214. * @since 4.8.027 (2010-01-25)
  1215. */
  1216. protected $inthead = false;
  1217. /**
  1218. * Array of column measures (width, space, starting Y position).
  1219. * @protected
  1220. * @since 4.9.001 (2010-03-28)
  1221. */
  1222. protected $columns = array();
  1223. /**
  1224. * Number of colums.
  1225. * @protected
  1226. * @since 4.9.001 (2010-03-28)
  1227. */
  1228. protected $num_columns = 1;
  1229. /**
  1230. * Current column number.
  1231. * @protected
  1232. * @since 4.9.001 (2010-03-28)
  1233. */
  1234. protected $current_column = 0;
  1235. /**
  1236. * Starting page for columns.
  1237. * @protected
  1238. * @since 4.9.001 (2010-03-28)
  1239. */
  1240. protected $column_start_page = 0;
  1241. /**
  1242. * Maximum page and column selected.
  1243. * @protected
  1244. * @since 5.8.000 (2010-08-11)
  1245. */
  1246. protected $maxselcol = array('page' => 0, 'column' => 0);
  1247. /**
  1248. * Array of: X difference between table cell x start and starting page margin, cellspacing, cellpadding.
  1249. * @protected
  1250. * @since 5.8.000 (2010-08-11)
  1251. */
  1252. protected $colxshift = array('x' => 0, 's' => array('H' => 0, 'V' => 0), 'p' => array('L' => 0, 'T' => 0, 'R' => 0, 'B' => 0));
  1253. /**
  1254. * Text rendering mode: 0 = Fill text; 1 = Stroke text; 2 = Fill, then stroke text; 3 = Neither fill nor stroke text (invisible); 4 = Fill text and add to path for clipping; 5 = Stroke text and add to path for clipping; 6 = Fill, then stroke text and add to path for clipping; 7 = Add text to path for clipping.
  1255. * @protected
  1256. * @since 4.9.008 (2010-04-03)
  1257. */
  1258. protected $textrendermode = 0;
  1259. /**
  1260. * Text stroke width in doc units.
  1261. * @protected
  1262. * @since 4.9.008 (2010-04-03)
  1263. */
  1264. protected $textstrokewidth = 0;
  1265. /**
  1266. * Current stroke color.
  1267. * @protected
  1268. * @since 4.9.008 (2010-04-03)
  1269. */
  1270. protected $strokecolor;
  1271. /**
  1272. * Default unit of measure for document.
  1273. * @protected
  1274. * @since 5.0.000 (2010-04-22)
  1275. */
  1276. protected $pdfunit = 'mm';
  1277. /**
  1278. * Boolean flag true when we are on TOC (Table Of Content) page.
  1279. * @protected
  1280. */
  1281. protected $tocpage = false;
  1282. /**
  1283. * Boolean flag: if true convert vector images (SVG, EPS) to raster image using GD or ImageMagick library.
  1284. * @protected
  1285. * @since 5.0.000 (2010-04-26)
  1286. */
  1287. protected $rasterize_vector_images = false;
  1288. /**
  1289. * Boolean flag: if true enables font subsetting by default.
  1290. * @protected
  1291. * @since 5.3.002 (2010-06-07)
  1292. */
  1293. protected $font_subsetting = true;
  1294. /**
  1295. * Array of default graphic settings.
  1296. * @protected
  1297. * @since 5.5.008 (2010-07-02)
  1298. */
  1299. protected $default_graphic_vars = array();
  1300. /**
  1301. * Array of XObjects.
  1302. * @protected
  1303. * @since 5.8.014 (2010-08-23)
  1304. */
  1305. protected $xobjects = array();
  1306. /**
  1307. * Boolean value true when we are inside an XObject.
  1308. * @protected
  1309. * @since 5.8.017 (2010-08-24)
  1310. */
  1311. protected $inxobj = false;
  1312. /**
  1313. * Current XObject ID.
  1314. * @protected
  1315. * @since 5.8.017 (2010-08-24)
  1316. */
  1317. protected $xobjid = '';
  1318. /**
  1319. * Percentage of character stretching.
  1320. * @protected
  1321. * @since 5.9.000 (2010-09-29)
  1322. */
  1323. protected $font_stretching = 100;
  1324. /**
  1325. * Increases or decreases the space between characters in a text by the specified amount (tracking).
  1326. * @protected
  1327. * @since 5.9.000 (2010-09-29)
  1328. */
  1329. protected $font_spacing = 0;
  1330. /**
  1331. * Array of no-write regions.
  1332. * ('page' => page number or empy for current page, 'xt' => X top, 'yt' => Y top, 'xb' => X bottom, 'yb' => Y bottom, 'side' => page side 'L' = left or 'R' = right)
  1333. * @protected
  1334. * @since 5.9.003 (2010-10-14)
  1335. */
  1336. protected $page_regions = array();
  1337. /**
  1338. * Boolean value true when page region check is active.
  1339. * @protected
  1340. */
  1341. protected $check_page_regions = true;
  1342. /**
  1343. * Array of PDF layers data.
  1344. * @protected
  1345. * @since 5.9.102 (2011-07-13)
  1346. */
  1347. protected $pdflayers = array();
  1348. /**
  1349. * A dictionary of names and corresponding destinations (Dests key on document Catalog).
  1350. * @protected
  1351. * @since 5.9.097 (2011-06-23)
  1352. */
  1353. protected $dests = array();
  1354. /**
  1355. * Object ID for Named Destinations
  1356. * @protected
  1357. * @since 5.9.097 (2011-06-23)
  1358. */
  1359. protected $n_dests;
  1360. /**
  1361. * Embedded Files Names
  1362. * @protected
  1363. * @since 5.9.204 (2013-01-23)
  1364. */
  1365. protected $efnames = array();
  1366. /**
  1367. * Directory used for the last SVG image.
  1368. * @protected
  1369. * @since 5.0.000 (2010-05-05)
  1370. */
  1371. protected $svgdir = '';
  1372. /**
  1373. * Deafult unit of measure for SVG.
  1374. * @protected
  1375. * @since 5.0.000 (2010-05-02)
  1376. */
  1377. protected $svgunit = 'px';
  1378. /**
  1379. * Array of SVG gradients.
  1380. * @protected
  1381. * @since 5.0.000 (2010-05-02)
  1382. */
  1383. protected $svggradients = array();
  1384. /**
  1385. * ID of last SVG gradient.
  1386. * @protected
  1387. * @since 5.0.000 (2010-05-02)
  1388. */
  1389. protected $svggradientid = 0;
  1390. /**
  1391. * Boolean value true when in SVG defs group.
  1392. * @protected
  1393. * @since 5.0.000 (2010-05-02)
  1394. */
  1395. protected $svgdefsmode = false;
  1396. /**
  1397. * Array of SVG defs.
  1398. * @protected
  1399. * @since 5.0.000 (2010-05-02)
  1400. */
  1401. protected $svgdefs = array();
  1402. /**
  1403. * Boolean value true when in SVG clipPath tag.
  1404. * @protected
  1405. * @since 5.0.000 (2010-04-26)
  1406. */
  1407. protected $svgclipmode = false;
  1408. /**
  1409. * Array of SVG clipPath commands.
  1410. * @protected
  1411. * @since 5.0.000 (2010-05-02)
  1412. */
  1413. protected $svgclippaths = array();
  1414. /**
  1415. * Array of SVG clipPath tranformation matrix.
  1416. * @protected
  1417. * @since 5.8.022 (2010-08-31)
  1418. */
  1419. protected $svgcliptm = array();
  1420. /**
  1421. * ID of last SVG clipPath.
  1422. * @protected
  1423. * @since 5.0.000 (2010-05-02)
  1424. */
  1425. protected $svgclipid = 0;
  1426. /**
  1427. * SVG text.
  1428. * @protected
  1429. * @since 5.0.000 (2010-05-02)
  1430. */
  1431. protected $svgtext = '';
  1432. /**
  1433. * SVG text properties.
  1434. * @protected
  1435. * @since 5.8.013 (2010-08-23)
  1436. */
  1437. protected $svgtextmode = array();
  1438. /**
  1439. * Array of SVG properties.
  1440. * @protected
  1441. * @since 5.0.000 (2010-05-02)
  1442. */
  1443. protected $svgstyles = array(array(
  1444. 'alignment-baseline' => 'auto',
  1445. 'baseline-shift' => 'baseline',
  1446. 'clip' => 'auto',
  1447. 'clip-path' => 'none',
  1448. 'clip-rule' => 'nonzero',
  1449. 'color' => 'black',
  1450. 'color-interpolation' => 'sRGB',
  1451. 'color-interpolation-filters' => 'linearRGB',
  1452. 'color-profile' => 'auto',
  1453. 'color-rendering' => 'auto',
  1454. 'cursor' => 'auto',
  1455. 'direction' => 'ltr',
  1456. 'display' => 'inline',
  1457. 'dominant-baseline' => 'auto',
  1458. 'enable-background' => 'accumulate',
  1459. 'fill' => 'black',
  1460. 'fill-opacity' => 1,
  1461. 'fill-rule' => 'nonzero',
  1462. 'filter' => 'none',
  1463. 'flood-color' => 'black',
  1464. 'flood-opacity' => 1,
  1465. 'font' => '',
  1466. 'font-family' => 'helvetica',
  1467. 'font-size' => 'medium',
  1468. 'font-size-adjust' => 'none',
  1469. 'font-stretch' => 'normal',
  1470. 'font-style' => 'normal',
  1471. 'font-variant' => 'normal',
  1472. 'font-weight' => 'normal',
  1473. 'glyph-orientation-horizontal' => '0deg',
  1474. 'glyph-orientation-vertical' => 'auto',
  1475. 'image-rendering' => 'auto',
  1476. 'kerning' => 'auto',
  1477. 'letter-spacing' => 'normal',
  1478. 'lighting-color' => 'white',
  1479. 'marker' => '',
  1480. 'marker-end' => 'none',
  1481. 'marker-mid' => 'none',
  1482. 'marker-start' => 'none',
  1483. 'mask' => 'none',
  1484. 'opacity' => 1,
  1485. 'overflow' => 'auto',
  1486. 'pointer-events' => 'visiblePainted',
  1487. 'shape-rendering' => 'auto',
  1488. 'stop-color' => 'black',
  1489. 'stop-opacity' => 1,
  1490. 'stroke' => 'none',
  1491. 'stroke-dasharray' => 'none',
  1492. 'stroke-dashoffset' => 0,
  1493. 'stroke-linecap' => 'butt',
  1494. 'stroke-linejoin' => 'miter',
  1495. 'stroke-miterlimit' => 4,
  1496. 'stroke-opacity' => 1,
  1497. 'stroke-width' => 1,
  1498. 'text-anchor' => 'start',
  1499. 'text-decoration' => 'none',
  1500. 'text-rendering' => 'auto',
  1501. 'unicode-bidi' => 'normal',
  1502. 'visibility' => 'visible',
  1503. 'word-spacing' => 'normal',
  1504. 'writing-mode' => 'lr-tb',
  1505. 'text-color' => 'black',
  1506. 'transfmatrix' => array(1, 0, 0, 1, 0, 0)
  1507. ));
  1508. /**
  1509. * If true force sRGB color profile for all document.
  1510. * @protected
  1511. * @since 5.9.121 (2011-09-28)
  1512. */
  1513. protected $force_srgb = false;
  1514. /**
  1515. * If true set the document to PDF/A mode.
  1516. * @protected
  1517. * @since 5.9.121 (2011-09-27)
  1518. */
  1519. protected $pdfa_mode = false;
  1520. /**
  1521. * version of PDF/A mode (1 - 3).
  1522. * @protected
  1523. * @since 6.2.26 (2019-03-12)
  1524. */
  1525. protected $pdfa_version = 1;
  1526. /**
  1527. * Document creation date-time
  1528. * @protected
  1529. * @since 5.9.152 (2012-03-22)
  1530. */
  1531. protected $doc_creation_timestamp;
  1532. /**
  1533. * Document modification date-time
  1534. * @protected
  1535. * @since 5.9.152 (2012-03-22)
  1536. */
  1537. protected $doc_modification_timestamp;
  1538. /**
  1539. * Custom XMP data.
  1540. * @protected
  1541. * @since 5.9.128 (2011-10-06)
  1542. */
  1543. protected $custom_xmp = '';
  1544. /**
  1545. * Custom XMP RDF data.
  1546. * @protected
  1547. * @since 6.3.0 (2019-09-19)
  1548. */
  1549. protected $custom_xmp_rdf = '';
  1550. /**
  1551. * Overprint mode array.
  1552. * (Check the "Entries in a Graphics State Parameter Dictionary" on PDF 32000-1:2008).
  1553. * @protected
  1554. * @since 5.9.152 (2012-03-23)
  1555. */
  1556. protected $overprint = array('OP' => false, 'op' => false, 'OPM' => 0);
  1557. /**
  1558. * Alpha mode array.
  1559. * (Check the "Entries in a Graphics State Parameter Dictionary" on PDF 32000-1:2008).
  1560. * @protected
  1561. * @since 5.9.152 (2012-03-23)
  1562. */
  1563. protected $alpha = array('CA' => 1, 'ca' => 1, 'BM' => '/Normal', 'AIS' => false);
  1564. /**
  1565. * Define the page boundaries boxes to be set on document.
  1566. * @protected
  1567. * @since 5.9.152 (2012-03-23)
  1568. */
  1569. protected $page_boxes = array('MediaBox', 'CropBox', 'BleedBox', 'TrimBox', 'ArtBox');
  1570. /**
  1571. * If true print TCPDF meta link.
  1572. * @protected
  1573. * @since 5.9.152 (2012-03-23)
  1574. */
  1575. protected $tcpdflink = true;
  1576. /**
  1577. * Cache array for computed GD gamma values.
  1578. * @protected
  1579. * @since 5.9.1632 (2012-06-05)
  1580. */
  1581. protected $gdgammacache = array();
  1582. //------------------------------------------------------------
  1583. // METHODS
  1584. //------------------------------------------------------------
  1585. /**
  1586. * This is the class constructor.
  1587. * It allows to set up the page format, the orientation and the measure unit used in all the methods (except for the font sizes).
  1588. *
  1589. * IMPORTANT: Please note that this method sets the mb_internal_encoding to ASCII, so if you are using the mbstring module functions with TCPDF you need to correctly set/unset the mb_internal_encoding when needed.
  1590. *
  1591. * @param $orientation (string) page orientation. Possible values are (case insensitive):<ul><li>P or Portrait (default)</li><li>L or Landscape</li><li>'' (empty string) for automatic orientation</li></ul>
  1592. * @param $unit (string) User measure unit. Possible values are:<ul><li>pt: point</li><li>mm: millimeter (default)</li><li>cm: centimeter</li><li>in: inch</li></ul><br />A point equals 1/72 of inch, that is to say about 0.35 mm (an inch being 2.54 cm). This is a very common unit in typography; font sizes are expressed in that unit.
  1593. * @param $format (mixed) The format used for pages. It can be either: one of the string values specified at getPageSizeFromFormat() or an array of parameters specified at setPageFormat().
  1594. * @param $unicode (boolean) TRUE means that the input text is unicode (default = true)
  1595. * @param $encoding (string) Charset encoding (used only when converting back html entities); default is UTF-8.
  1596. * @param $diskcache (boolean) DEPRECATED FEATURE
  1597. * @param $pdfa (integer) If not false, set the document to PDF/A mode and the good version (1 or 3).
  1598. * @public
  1599. * @see getPageSizeFromFormat(), setPageFormat()
  1600. */
  1601. public function __construct($orientation='P', $unit='mm', $format='A4', $unicode=true, $encoding='UTF-8', $diskcache=false, $pdfa=false) {
  1602. /* Set internal character encoding to ASCII */
  1603. if (function_exists('mb_internal_encoding') AND mb_internal_encoding()) {
  1604. $this->internal_encoding = mb_internal_encoding();
  1605. mb_internal_encoding('ASCII');
  1606. }
  1607. // set file ID for trailer
  1608. $serformat = (is_array($format) ? json_encode($format) : $format);
  1609. $this->file_id = md5(TCPDF_STATIC::getRandomSeed('TCPDF'.$orientation.$unit.$serformat.$encoding));
  1610. $this->font_obj_ids = array();
  1611. $this->page_obj_id = array();
  1612. $this->form_obj_id = array();
  1613. // set pdf/a mode
  1614. if ($pdfa != false) {
  1615. $this->pdfa_mode = true;
  1616. $this->pdfa_version = $pdfa; // 1 or 3
  1617. } else
  1618. $this->pdfa_mode = false;
  1619. $this->force_srgb = false;
  1620. // set language direction
  1621. $this->rtl = false;
  1622. $this->tmprtl = false;
  1623. // some checks
  1624. $this->_dochecks();
  1625. // initialization of properties
  1626. $this->isunicode = $unicode;
  1627. $this->page = 0;
  1628. $this->transfmrk[0] = array();
  1629. $this->pagedim = array();
  1630. $this->n = 2;
  1631. $this->buffer = '';
  1632. $this->pages = array();
  1633. $this->state = 0;
  1634. $this->fonts = array();
  1635. $this->FontFiles = array();
  1636. $this->diffs = array();
  1637. $this->images = array();
  1638. $this->links = array();
  1639. $this->gradients = array();
  1640. $this->InFooter = false;
  1641. $this->lasth = 0;
  1642. $this->FontFamily = defined('PDF_FONT_NAME_MAIN')?PDF_FONT_NAME_MAIN:'helvetica';
  1643. $this->FontStyle = '';
  1644. $this->FontSizePt = 12;
  1645. $this->underline = false;
  1646. $this->overline = false;
  1647. $this->linethrough = false;
  1648. $this->DrawColor = '0 G';
  1649. $this->FillColor = '0 g';
  1650. $this->TextColor = '0 g';
  1651. $this->ColorFlag = false;
  1652. $this->pdflayers = array();
  1653. // encryption values
  1654. $this->encrypted = false;
  1655. $this->last_enc_key = '';
  1656. // standard Unicode fonts
  1657. $this->CoreFonts = array(
  1658. 'courier'=>'Courier',
  1659. 'courierB'=>'Courier-Bold',
  1660. 'courierI'=>'Courier-Oblique',
  1661. 'courierBI'=>'Courier-BoldOblique',
  1662. 'helvetica'=>'Helvetica',
  1663. 'helveticaB'=>'Helvetica-Bold',
  1664. 'helveticaI'=>'Helvetica-Oblique',
  1665. 'helveticaBI'=>'Helvetica-BoldOblique',
  1666. 'times'=>'Times-Roman',
  1667. 'timesB'=>'Times-Bold',
  1668. 'timesI'=>'Times-Italic',
  1669. 'timesBI'=>'Times-BoldItalic',
  1670. 'symbol'=>'Symbol',
  1671. 'zapfdingbats'=>'ZapfDingbats'
  1672. );
  1673. // set scale factor
  1674. $this->setPageUnit($unit);
  1675. // set page format and orientation
  1676. $this->setPageFormat($format, $orientation);
  1677. // page margins (1 cm)
  1678. $margin = 28.35 / $this->k;
  1679. $this->SetMargins($margin, $margin);
  1680. $this->clMargin = $this->lMargin;
  1681. $this->crMargin = $this->rMargin;
  1682. // internal cell padding
  1683. $cpadding = $margin / 10;
  1684. $this->setCellPaddings($cpadding, 0, $cpadding, 0);
  1685. // cell margins
  1686. $this->setCellMargins(0, 0, 0, 0);
  1687. // line width (0.2 mm)
  1688. $this->LineWidth = 0.57 / $this->k;
  1689. $this->linestyleWidth = sprintf('%F w', ($this->LineWidth * $this->k));
  1690. $this->linestyleCap = '0 J';
  1691. $this->linestyleJoin = '0 j';
  1692. $this->linestyleDash = '[] 0 d';
  1693. // automatic page break
  1694. $this->SetAutoPageBreak(true, (2 * $margin));
  1695. // full width display mode
  1696. $this->SetDisplayMode('fullwidth');
  1697. // compression
  1698. $this->SetCompression();
  1699. // set default PDF version number
  1700. $this->setPDFVersion();
  1701. $this->tcpdflink = true;
  1702. $this->encoding = $encoding;
  1703. $this->HREF = array();
  1704. $this->getFontsList();
  1705. $this->fgcolor = array('R' => 0, 'G' => 0, 'B' => 0);
  1706. $this->strokecolor = array('R' => 0, 'G' => 0, 'B' => 0);
  1707. $this->bgcolor = array('R' => 255, 'G' => 255, 'B' => 255);
  1708. $this->extgstates = array();
  1709. $this->setTextShadow();
  1710. // signature
  1711. $this->sign = false;
  1712. $this->tsa_timestamp = false;
  1713. $this->tsa_data = array();
  1714. $this->signature_appearance = array('page' => 1, 'rect' => '0 0 0 0', 'name' => 'Signature');
  1715. $this->empty_signature_appearance = array();
  1716. // user's rights
  1717. $this->ur['enabled'] = false;
  1718. $this->ur['document'] = '/FullSave';
  1719. $this->ur['annots'] = '/Create/Delete/Modify/Copy/Import/Export';
  1720. $this->ur['form'] = '/Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate';
  1721. $this->ur['signature'] = '/Modify';
  1722. $this->ur['ef'] = '/Create/Delete/Modify/Import';
  1723. $this->ur['formex'] = '';
  1724. // set default JPEG quality
  1725. $this->jpeg_quality = 75;
  1726. // initialize some settings
  1727. TCPDF_FONTS::utf8Bidi(array(), '', false, $this->isunicode, $this->CurrentFont);
  1728. // set default font
  1729. $this->SetFont($this->FontFamily, $this->FontStyle, $this->FontSizePt);
  1730. $this->setHeaderFont(array($this->FontFamily, $this->FontStyle, $this->FontSizePt));
  1731. $this->setFooterFont(array($this->FontFamily, $this->FontStyle, $this->FontSizePt));
  1732. // check if PCRE Unicode support is enabled
  1733. if ($this->isunicode AND (@preg_match('/\pL/u', 'a') == 1)) {
  1734. // PCRE unicode support is turned ON
  1735. // \s : any whitespace character
  1736. // \p{Z} : any separator
  1737. // \p{Lo} : Unicode letter or ideograph that does not have lowercase and uppercase variants. Is used to chunk chinese words.
  1738. // \xa0 : Unicode Character 'NO-BREAK SPACE' (U+00A0)
  1739. //$this->setSpacesRE('/(?!\xa0)[\s\p{Z}\p{Lo}]/u');
  1740. $this->setSpacesRE('/(?!\xa0)[\s\p{Z}]/u');
  1741. } else {
  1742. // PCRE unicode support is turned OFF
  1743. $this->setSpacesRE('/[^\S\xa0]/');
  1744. }
  1745. $this->default_form_prop = array('lineWidth'=>1, 'borderStyle'=>'solid', 'fillColor'=>array(255, 255, 255), 'strokeColor'=>array(128, 128, 128));
  1746. // set document creation and modification timestamp
  1747. $this->doc_creation_timestamp = time();
  1748. $this->doc_modification_timestamp = $this->doc_creation_timestamp;
  1749. // get default graphic vars
  1750. $this->default_graphic_vars = $this->getGraphicVars();
  1751. $this->header_xobj_autoreset = false;
  1752. $this->custom_xmp = '';
  1753. $this->custom_xmp_rdf = '';
  1754. // Call cleanup method after script execution finishes or exit() is called.
  1755. // NOTE: This will not be executed if the process is killed with a SIGTERM or SIGKILL signal.
  1756. register_shutdown_function(array($this, '_destroy'), true);
  1757. }
  1758. /**
  1759. * Default destructor.
  1760. * @public
  1761. * @since 1.53.0.TC016
  1762. */
  1763. public function __destruct() {
  1764. // cleanup
  1765. $this->_destroy(true);
  1766. }
  1767. /**
  1768. * Set the units of measure for the document.
  1769. * @param $unit (string) User measure unit. Possible values are:<ul><li>pt: point</li><li>mm: millimeter (default)</li><li>cm: centimeter</li><li>in: inch</li></ul><br />A point equals 1/72 of inch, that is to say about 0.35 mm (an inch being 2.54 cm). This is a very common unit in typography; font sizes are expressed in that unit.
  1770. * @public
  1771. * @since 3.0.015 (2008-06-06)
  1772. */
  1773. public function setPageUnit($unit) {
  1774. $unit = strtolower($unit);
  1775. //Set scale factor
  1776. switch ($unit) {
  1777. // points
  1778. case 'px':
  1779. case 'pt': {
  1780. $this->k = 1;
  1781. break;
  1782. }
  1783. // millimeters
  1784. case 'mm': {
  1785. $this->k = $this->dpi / 25.4;
  1786. break;
  1787. }
  1788. // centimeters
  1789. case 'cm': {
  1790. $this->k = $this->dpi / 2.54;
  1791. break;
  1792. }
  1793. // inches
  1794. case 'in': {
  1795. $this->k = $this->dpi;
  1796. break;
  1797. }
  1798. // unsupported unit
  1799. default : {
  1800. $this->Error('Incorrect unit: '.$unit);
  1801. break;
  1802. }
  1803. }
  1804. $this->pdfunit = $unit;
  1805. if (isset($this->CurOrientation)) {
  1806. $this->setPageOrientation($this->CurOrientation);
  1807. }
  1808. }
  1809. /**
  1810. * Change the format of the current page
  1811. * @param $format (mixed) The format used for pages. It can be either: one of the string values specified at getPageSizeFromFormat() documentation or an array of two numbers (width, height) or an array containing the following measures and options:<ul>
  1812. * <li>['format'] = page format name (one of the above);</li>
  1813. * <li>['Rotate'] : The number of degrees by which the page shall be rotated clockwise when displayed or printed. The value shall be a multiple of 90.</li>
  1814. * <li>['PZ'] : The page's preferred zoom (magnification) factor.</li>
  1815. * <li>['MediaBox'] : the boundaries of the physical medium on which the page shall be displayed or printed:</li>
  1816. * <li>['MediaBox']['llx'] : lower-left x coordinate</li>
  1817. * <li>['MediaBox']['lly'] : lower-left y coordinate</li>
  1818. * <li>['MediaBox']['urx'] : upper-right x coordinate</li>
  1819. * <li>['MediaBox']['ury'] : upper-right y coordinate</li>
  1820. * <li>['CropBox'] : the visible region of default user space:</li>
  1821. * <li>['CropBox']['llx'] : lower-left x coordinate</li>
  1822. * <li>['CropBox']['lly'] : lower-left y coordinate</li>
  1823. * <li>['CropBox']['urx'] : upper-right x coordinate</li>
  1824. * <li>['CropBox']['ury'] : upper-right y coordinate</li>
  1825. * <li>['BleedBox'] : the region to which the contents of the page shall be clipped when output in a production environment:</li>
  1826. * <li>['BleedBox']['llx'] : lower-left x coordinate</li>
  1827. * <li>['BleedBox']['lly'] : lower-left y coordinate</li>
  1828. * <li>['BleedBox']['urx'] : upper-right x coordinate</li>
  1829. * <li>['BleedBox']['ury'] : upper-right y coordinate</li>
  1830. * <li>['TrimBox'] : the intended dimensions of the finished page after trimming:</li>
  1831. * <li>['TrimBox']['llx'] : lower-left x coordinate</li>
  1832. * <li>['TrimBox']['lly'] : lower-left y coordinate</li>
  1833. * <li>['TrimBox']['urx'] : upper-right x coordinate</li>
  1834. * <li>['TrimBox']['ury'] : upper-right y coordinate</li>
  1835. * <li>['ArtBox'] : the extent of the page's meaningful content:</li>
  1836. * <li>['ArtBox']['llx'] : lower-left x coordinate</li>
  1837. * <li>['ArtBox']['lly'] : lower-left y coordinate</li>
  1838. * <li>['ArtBox']['urx'] : upper-right x coordinate</li>
  1839. * <li>['ArtBox']['ury'] : upper-right y coordinate</li>
  1840. * <li>['BoxColorInfo'] :specify the colours and other visual characteristics that should be used in displaying guidelines on the screen for each of the possible page boundaries other than the MediaBox:</li>
  1841. * <li>['BoxColorInfo'][BOXTYPE]['C'] : an array of three numbers in the range 0-255, representing the components in the DeviceRGB colour space.</li>
  1842. * <li>['BoxColorInfo'][BOXTYPE]['W'] : the guideline width in default user units</li>
  1843. * <li>['BoxColorInfo'][BOXTYPE]['S'] : the guideline style: S = Solid; D = Dashed</li>
  1844. * <li>['BoxColorInfo'][BOXTYPE]['D'] : dash array defining a pattern of dashes and gaps to be used in drawing dashed guidelines</li>
  1845. * <li>['trans'] : the style and duration of the visual transition to use when moving from another page to the given page during a presentation</li>
  1846. * <li>['trans']['Dur'] : The page's display duration (also called its advance timing): the maximum length of time, in seconds, that the page shall be displayed during presentations before the viewer application shall automatically advance to the next page.</li>
  1847. * <li>['trans']['S'] : transition style : Split, Blinds, Box, Wipe, Dissolve, Glitter, R, Fly, Push, Cover, Uncover, Fade</li>
  1848. * <li>['trans']['D'] : The duration of the transition effect, in seconds.</li>
  1849. * <li>['trans']['Dm'] : (Split and Blinds transition styles only) The dimension in which the specified transition effect shall occur: H = Horizontal, V = Vertical. Default value: H.</li>
  1850. * <li>['trans']['M'] : (Split, Box and Fly transition styles only) The direction of motion for the specified transition effect: I = Inward from the edges of the page, O = Outward from the center of the pageDefault value: I.</li>
  1851. * <li>['trans']['Di'] : (Wipe, Glitter, Fly, Cover, Uncover and Push transition styles only) The direction in which the specified transition effect shall moves, expressed in degrees counterclockwise starting from a left-to-right direction. If the value is a number, it shall be one of: 0 = Left to right, 90 = Bottom to top (Wipe only), 180 = Right to left (Wipe only), 270 = Top to bottom, 315 = Top-left to bottom-right (Glitter only). If the value is a name, it shall be None, which is relevant only for the Fly transition when the value of SS is not 1.0. Default value: 0.</li>
  1852. * <li>['trans']['SS'] : (Fly transition style only) The starting or ending scale at which the changes shall be drawn. If M specifies an inward transition, the scale of the changes drawn shall progress from SS to 1.0 over the course of the transition. If M specifies an outward transition, the scale of the changes drawn shall progress from 1.0 to SS over the course of the transition. Default: 1.0.</li>
  1853. * <li>['trans']['B'] : (Fly transition style only) If true, the area that shall be flown in is rectangular and opaque. Default: false.</li>
  1854. * </ul>
  1855. * @param $orientation (string) page orientation. Possible values are (case insensitive):<ul>
  1856. * <li>P or Portrait (default)</li>
  1857. * <li>L or Landscape</li>
  1858. * <li>'' (empty string) for automatic orientation</li>
  1859. * </ul>
  1860. * @protected
  1861. * @since 3.0.015 (2008-06-06)
  1862. * @see getPageSizeFromFormat()
  1863. */
  1864. protected function setPageFormat($format, $orientation='P') {
  1865. if (!empty($format) AND isset($this->pagedim[$this->page])) {
  1866. // remove inherited values
  1867. unset($this->pagedim[$this->page]);
  1868. }
  1869. if (is_string($format)) {
  1870. // get page measures from format name
  1871. $pf = TCPDF_STATIC::getPageSizeFromFormat($format);
  1872. $this->fwPt = $pf[0];
  1873. $this->fhPt = $pf[1];
  1874. } else {
  1875. // the boundaries of the physical medium on which the page shall be displayed or printed
  1876. if (isset($format['MediaBox'])) {
  1877. $this->pagedim = TCPDF_STATIC::setPageBoxes($this->page, 'MediaBox', $format['MediaBox']['llx'], $format['MediaBox']['lly'], $format['MediaBox']['urx'], $format['MediaBox']['ury'], false, $this->k, $this->pagedim);
  1878. $this->fwPt = (($format['MediaBox']['urx'] - $format['MediaBox']['llx']) * $this->k);
  1879. $this->fhPt = (($format['MediaBox']['ury'] - $format['MediaBox']['lly']) * $this->k);
  1880. } else {
  1881. if (isset($format[0]) AND is_numeric($format[0]) AND isset($format[1]) AND is_numeric($format[1])) {
  1882. $pf = array(($format[0] * $this->k), ($format[1] * $this->k));
  1883. } else {
  1884. if (!isset($format['format'])) {
  1885. // default value
  1886. $format['format'] = 'A4';
  1887. }
  1888. $pf = TCPDF_STATIC::getPageSizeFromFormat($format['format']);
  1889. }
  1890. $this->fwPt = $pf[0];
  1891. $this->fhPt = $pf[1];
  1892. $this->pagedim = TCPDF_STATIC::setPageBoxes($this->page, 'MediaBox', 0, 0, $this->fwPt, $this->fhPt, true, $this->k, $this->pagedim);
  1893. }
  1894. // the visible region of default user space
  1895. if (isset($format['CropBox'])) {
  1896. $this->pagedim = TCPDF_STATIC::setPageBoxes($this->page, 'CropBox', $format['CropBox']['llx'], $format['CropBox']['lly'], $format['CropBox']['urx'], $format['CropBox']['ury'], false, $this->k, $this->pagedim);
  1897. }
  1898. // the region to which the contents of the page shall be clipped when output in a production environment
  1899. if (isset($format['BleedBox'])) {
  1900. $this->pagedim = TCPDF_STATIC::setPageBoxes($this->page, 'BleedBox', $format['BleedBox']['llx'], $format['BleedBox']['lly'], $format['BleedBox']['urx'], $format['BleedBox']['ury'], false, $this->k, $this->pagedim);
  1901. }
  1902. // the intended dimensions of the finished page after trimming
  1903. if (isset($format['TrimBox'])) {
  1904. $this->pagedim = TCPDF_STATIC::setPageBoxes($this->page, 'TrimBox', $format['TrimBox']['llx'], $format['TrimBox']['lly'], $format['TrimBox']['urx'], $format['TrimBox']['ury'], false, $this->k, $this->pagedim);
  1905. }
  1906. // the page's meaningful content (including potential white space)
  1907. if (isset($format['ArtBox'])) {
  1908. $this->pagedim = TCPDF_STATIC::setPageBoxes($this->page, 'ArtBox', $format['ArtBox']['llx'], $format['ArtBox']['lly'], $format['ArtBox']['urx'], $format['ArtBox']['ury'], false, $this->k, $this->pagedim);
  1909. }
  1910. // specify the colours and other visual characteristics that should be used in displaying guidelines on the screen for the various page boundaries
  1911. if (isset($format['BoxColorInfo'])) {
  1912. $this->pagedim[$this->page]['BoxColorInfo'] = $format['BoxColorInfo'];
  1913. }
  1914. if (isset($format['Rotate']) AND (($format['Rotate'] % 90) == 0)) {
  1915. // The number of degrees by which the page shall be rotated clockwise when displayed or printed. The value shall be a multiple of 90.
  1916. $this->pagedim[$this->page]['Rotate'] = intval($format['Rotate']);
  1917. }
  1918. if (isset($format['PZ'])) {
  1919. // The page's preferred zoom (magnification) factor
  1920. $this->pagedim[$this->page]['PZ'] = floatval($format['PZ']);
  1921. }
  1922. if (isset($format['trans'])) {
  1923. // The style and duration of the visual transition to use when moving from another page to the given page during a presentation
  1924. if (isset($format['trans']['Dur'])) {
  1925. // The page's display duration
  1926. $this->pagedim[$this->page]['trans']['Dur'] = floatval($format['trans']['Dur']);
  1927. }
  1928. $stansition_styles = array('Split', 'Blinds', 'Box', 'Wipe', 'Dissolve', 'Glitter', 'R', 'Fly', 'Push', 'Cover', 'Uncover', 'Fade');
  1929. if (isset($format['trans']['S']) AND in_array($format['trans']['S'], $stansition_styles)) {
  1930. // The transition style that shall be used when moving to this page from another during a presentation
  1931. $this->pagedim[$this->page]['trans']['S'] = $format['trans']['S'];
  1932. $valid_effect = array('Split', 'Blinds');
  1933. $valid_vals = array('H', 'V');
  1934. if (isset($format['trans']['Dm']) AND in_array($format['trans']['S'], $valid_effect) AND in_array($format['trans']['Dm'], $valid_vals)) {
  1935. $this->pagedim[$this->page]['trans']['Dm'] = $format['trans']['Dm'];
  1936. }
  1937. $valid_effect = array('Split', 'Box', 'Fly');
  1938. $valid_vals = array('I', 'O');
  1939. if (isset($format['trans']['M']) AND in_array($format['trans']['S'], $valid_effect) AND in_array($format['trans']['M'], $valid_vals)) {
  1940. $this->pagedim[$this->page]['trans']['M'] = $format['trans']['M'];
  1941. }
  1942. $valid_effect = array('Wipe', 'Glitter', 'Fly', 'Cover', 'Uncover', 'Push');
  1943. if (isset($format['trans']['Di']) AND in_array($format['trans']['S'], $valid_effect)) {
  1944. if (((($format['trans']['Di'] == 90) OR ($format['trans']['Di'] == 180)) AND ($format['trans']['S'] == 'Wipe'))
  1945. OR (($format['trans']['Di'] == 315) AND ($format['trans']['S'] == 'Glitter'))
  1946. OR (($format['trans']['Di'] == 0) OR ($format['trans']['Di'] == 270))) {
  1947. $this->pagedim[$this->page]['trans']['Di'] = intval($format['trans']['Di']);
  1948. }
  1949. }
  1950. if (isset($format['trans']['SS']) AND ($format['trans']['S'] == 'Fly')) {
  1951. $this->pagedim[$this->page]['trans']['SS'] = floatval($format['trans']['SS']);
  1952. }
  1953. if (isset($format['trans']['B']) AND ($format['trans']['B'] === true) AND ($format['trans']['S'] == 'Fly')) {
  1954. $this->pagedim[$this->page]['trans']['B'] = 'true';
  1955. }
  1956. } else {
  1957. $this->pagedim[$this->page]['trans']['S'] = 'R';
  1958. }
  1959. if (isset($format['trans']['D'])) {
  1960. // The duration of the transition effect, in seconds
  1961. $this->pagedim[$this->page]['trans']['D'] = floatval($format['trans']['D']);
  1962. } else {
  1963. $this->pagedim[$this->page]['trans']['D'] = 1;
  1964. }
  1965. }
  1966. }
  1967. $this->setPageOrientation($orientation);
  1968. }
  1969. /**
  1970. * Set page orientation.
  1971. * @param $orientation (string) page orientation. Possible values are (case insensitive):<ul><li>P or Portrait (default)</li><li>L or Landscape</li><li>'' (empty string) for automatic orientation</li></ul>
  1972. * @param $autopagebreak (boolean) Boolean indicating if auto-page-break mode should be on or off.
  1973. * @param $bottommargin (float) bottom margin of the page.
  1974. * @public
  1975. * @since 3.0.015 (2008-06-06)
  1976. */
  1977. public function setPageOrientation($orientation, $autopagebreak='', $bottommargin='') {
  1978. if (!isset($this->pagedim[$this->page]['MediaBox'])) {
  1979. // the boundaries of the physical medium on which the page shall be displayed or printed
  1980. $this->pagedim = TCPDF_STATIC::setPageBoxes($this->page, 'MediaBox', 0, 0, $this->fwPt, $this->fhPt, true, $this->k, $this->pagedim);
  1981. }
  1982. if (!isset($this->pagedim[$this->page]['CropBox'])) {
  1983. // the visible region of default user space
  1984. $this->pagedim = TCPDF_STATIC::setPageBoxes($this->page, 'CropBox', $this->pagedim[$this->page]['MediaBox']['llx'], $this->pagedim[$this->page]['MediaBox']['lly'], $this->pagedim[$this->page]['MediaBox']['urx'], $this->pagedim[$this->page]['MediaBox']['ury'], true, $this->k, $this->pagedim);
  1985. }
  1986. if (!isset($this->pagedim[$this->page]['BleedBox'])) {
  1987. // the region to which the contents of the page shall be clipped when output in a production environment
  1988. $this->pagedim = TCPDF_STATIC::setPageBoxes($this->page, 'BleedBox', $this->pagedim[$this->page]['CropBox']['llx'], $this->pagedim[$this->page]['CropBox']['lly'], $this->pagedim[$this->page]['CropBox']['urx'], $this->pagedim[$this->page]['CropBox']['ury'], true, $this->k, $this->pagedim);
  1989. }
  1990. if (!isset($this->pagedim[$this->page]['TrimBox'])) {
  1991. // the intended dimensions of the finished page after trimming
  1992. $this->pagedim = TCPDF_STATIC::setPageBoxes($this->page, 'TrimBox', $this->pagedim[$this->page]['CropBox']['llx'], $this->pagedim[$this->page]['CropBox']['lly'], $this->pagedim[$this->page]['CropBox']['urx'], $this->pagedim[$this->page]['CropBox']['ury'], true, $this->k, $this->pagedim);
  1993. }
  1994. if (!isset($this->pagedim[$this->page]['ArtBox'])) {
  1995. // the page's meaningful content (including potential white space)
  1996. $this->pagedim = TCPDF_STATIC::setPageBoxes($this->page, 'ArtBox', $this->pagedim[$this->page]['CropBox']['llx'], $this->pagedim[$this->page]['CropBox']['lly'], $this->pagedim[$this->page]['CropBox']['urx'], $this->pagedim[$this->page]['CropBox']['ury'], true, $this->k, $this->pagedim);
  1997. }
  1998. if (!isset($this->pagedim[$this->page]['Rotate'])) {
  1999. // The number of degrees by which the page shall be rotated clockwise when displayed or printed. The value shall be a multiple of 90.
  2000. $this->pagedim[$this->page]['Rotate'] = 0;
  2001. }
  2002. if (!isset($this->pagedim[$this->page]['PZ'])) {
  2003. // The page's preferred zoom (magnification) factor
  2004. $this->pagedim[$this->page]['PZ'] = 1;
  2005. }
  2006. if ($this->fwPt > $this->fhPt) {
  2007. // landscape
  2008. $default_orientation = 'L';
  2009. } else {
  2010. // portrait
  2011. $default_orientation = 'P';
  2012. }
  2013. $valid_orientations = array('P', 'L');
  2014. if (empty($orientation)) {
  2015. $orientation = $default_orientation;
  2016. } else {
  2017. $orientation = strtoupper($orientation[0]);
  2018. }
  2019. if (in_array($orientation, $valid_orientations) AND ($orientation != $default_orientation)) {
  2020. $this->CurOrientation = $orientation;
  2021. $this->wPt = $this->fhPt;
  2022. $this->hPt = $this->fwPt;
  2023. } else {
  2024. $this->CurOrientation = $default_orientation;
  2025. $this->wPt = $this->fwPt;
  2026. $this->hPt = $this->fhPt;
  2027. }
  2028. if ((abs($this->pagedim[$this->page]['MediaBox']['urx'] - $this->hPt) < $this->feps) AND (abs($this->pagedim[$this->page]['MediaBox']['ury'] - $this->wPt) < $this->feps)){
  2029. // swap X and Y coordinates (change page orientation)
  2030. $this->pagedim = TCPDF_STATIC::swapPageBoxCoordinates($this->page, $this->pagedim);
  2031. }
  2032. $this->w = ($this->wPt / $this->k);
  2033. $this->h = ($this->hPt / $this->k);
  2034. if (TCPDF_STATIC::empty_string($autopagebreak)) {
  2035. if (isset($this->AutoPageBreak)) {
  2036. $autopagebreak = $this->AutoPageBreak;
  2037. } else {
  2038. $autopagebreak = true;
  2039. }
  2040. }
  2041. if (TCPDF_STATIC::empty_string($bottommargin)) {
  2042. if (isset($this->bMargin)) {
  2043. $bottommargin = $this->bMargin;
  2044. } else {
  2045. // default value = 2 cm
  2046. $bottommargin = 2 * 28.35 / $this->k;
  2047. }
  2048. }
  2049. $this->SetAutoPageBreak($autopagebreak, $bottommargin);
  2050. // store page dimensions
  2051. $this->pagedim[$this->page]['w'] = $this->wPt;
  2052. $this->pagedim[$this->page]['h'] = $this->hPt;
  2053. $this->pagedim[$this->page]['wk'] = $this->w;
  2054. $this->pagedim[$this->page]['hk'] = $this->h;
  2055. $this->pagedim[$this->page]['tm'] = $this->tMargin;
  2056. $this->pagedim[$this->page]['bm'] = $bottommargin;
  2057. $this->pagedim[$this->page]['lm'] = $this->lMargin;
  2058. $this->pagedim[$this->page]['rm'] = $this->rMargin;
  2059. $this->pagedim[$this->page]['pb'] = $autopagebreak;
  2060. $this->pagedim[$this->page]['or'] = $this->CurOrientation;
  2061. $this->pagedim[$this->page]['olm'] = $this->original_lMargin;
  2062. $this->pagedim[$this->page]['orm'] = $this->original_rMargin;
  2063. }
  2064. /**
  2065. * Set regular expression to detect withespaces or word separators.
  2066. * The pattern delimiter must be the forward-slash character "/".
  2067. * Some example patterns are:
  2068. * <pre>
  2069. * Non-Unicode or missing PCRE unicode support: "/[^\S\xa0]/"
  2070. * Unicode and PCRE unicode support: "/(?!\xa0)[\s\p{Z}]/u"
  2071. * Unicode and PCRE unicode support in Chinese mode: "/(?!\xa0)[\s\p{Z}\p{Lo}]/u"
  2072. * if PCRE unicode support is turned ON ("\P" is the negate class of "\p"):
  2073. * \s : any whitespace character
  2074. * \p{Z} : any separator
  2075. * \p{Lo} : Unicode letter or ideograph that does not have lowercase and uppercase variants. Is used to chunk chinese words.
  2076. * \xa0 : Unicode Character 'NO-BREAK SPACE' (U+00A0)
  2077. * </pre>
  2078. * @param $re (string) regular expression (leave empty for default).
  2079. * @public
  2080. * @since 4.6.016 (2009-06-15)
  2081. */
  2082. public function setSpacesRE($re='/[^\S\xa0]/') {
  2083. $this->re_spaces = $re;
  2084. $re_parts = explode('/', $re);
  2085. // get pattern parts
  2086. $this->re_space = array();
  2087. if (isset($re_parts[1]) AND !empty($re_parts[1])) {
  2088. $this->re_space['p'] = $re_parts[1];
  2089. } else {
  2090. $this->re_space['p'] = '[\s]';
  2091. }
  2092. // set pattern modifiers
  2093. if (isset($re_parts[2]) AND !empty($re_parts[2])) {
  2094. $this->re_space['m'] = $re_parts[2];
  2095. } else {
  2096. $this->re_space['m'] = '';
  2097. }
  2098. }
  2099. /**
  2100. * Enable or disable Right-To-Left language mode
  2101. * @param $enable (Boolean) if true enable Right-To-Left language mode.
  2102. * @param $resetx (Boolean) if true reset the X position on direction change.
  2103. * @public
  2104. * @since 2.0.000 (2008-01-03)
  2105. */
  2106. public function setRTL($enable, $resetx=true) {
  2107. $enable = $enable ? true : false;
  2108. $resetx = ($resetx AND ($enable != $this->rtl));
  2109. $this->rtl = $enable;
  2110. $this->tmprtl = false;
  2111. if ($resetx) {
  2112. $this->Ln(0);
  2113. }
  2114. }
  2115. /**
  2116. * Return the RTL status
  2117. * @return boolean
  2118. * @public
  2119. * @since 4.0.012 (2008-07-24)
  2120. */
  2121. public function getRTL() {
  2122. return $this->rtl;
  2123. }
  2124. /**
  2125. * Force temporary RTL language direction
  2126. * @param $mode (mixed) can be false, 'L' for LTR or 'R' for RTL
  2127. * @public
  2128. * @since 2.1.000 (2008-01-09)
  2129. */
  2130. public function setTempRTL($mode) {
  2131. $newmode = false;
  2132. switch (strtoupper($mode)) {
  2133. case 'LTR':
  2134. case 'L': {
  2135. if ($this->rtl) {
  2136. $newmode = 'L';
  2137. }
  2138. break;
  2139. }
  2140. case 'RTL':
  2141. case 'R': {
  2142. if (!$this->rtl) {
  2143. $newmode = 'R';
  2144. }
  2145. break;
  2146. }
  2147. case false:
  2148. default: {
  2149. $newmode = false;
  2150. break;
  2151. }
  2152. }
  2153. $this->tmprtl = $newmode;
  2154. }
  2155. /**
  2156. * Return the current temporary RTL status
  2157. * @return boolean
  2158. * @public
  2159. * @since 4.8.014 (2009-11-04)
  2160. */
  2161. public function isRTLTextDir() {
  2162. return ($this->rtl OR ($this->tmprtl == 'R'));
  2163. }
  2164. /**
  2165. * Set the last cell height.
  2166. * @param $h (float) cell height.
  2167. * @author Nicola Asuni
  2168. * @public
  2169. * @since 1.53.0.TC034
  2170. */
  2171. public function setLastH($h) {
  2172. $this->lasth = $h;
  2173. }
  2174. /**
  2175. * Return the cell height
  2176. * @param $fontsize (int) Font size in internal units
  2177. * @param $padding (boolean) If true add cell padding
  2178. * @public
  2179. */
  2180. public function getCellHeight($fontsize, $padding=TRUE) {
  2181. $height = ($fontsize * $this->cell_height_ratio);
  2182. if ($padding) {
  2183. $height += ($this->cell_padding['T'] + $this->cell_padding['B']);
  2184. }
  2185. return round($height, 6);
  2186. }
  2187. /**
  2188. * Reset the last cell height.
  2189. * @public
  2190. * @since 5.9.000 (2010-10-03)
  2191. */
  2192. public function resetLastH() {
  2193. $this->lasth = $this->getCellHeight($this->FontSize);
  2194. }
  2195. /**
  2196. * Get the last cell height.
  2197. * @return last cell height
  2198. * @public
  2199. * @since 4.0.017 (2008-08-05)
  2200. */
  2201. public function getLastH() {
  2202. return $this->lasth;
  2203. }
  2204. /**
  2205. * Set the adjusting factor to convert pixels to user units.
  2206. * @param $scale (float) adjusting factor to convert pixels to user units.
  2207. * @author Nicola Asuni
  2208. * @public
  2209. * @since 1.5.2
  2210. */
  2211. public function setImageScale($scale) {
  2212. $this->imgscale = $scale;
  2213. }
  2214. /**
  2215. * Returns the adjusting factor to convert pixels to user units.
  2216. * @return float adjusting factor to convert pixels to user units.
  2217. * @author Nicola Asuni
  2218. * @public
  2219. * @since 1.5.2
  2220. */
  2221. public function getImageScale() {
  2222. return $this->imgscale;
  2223. }
  2224. /**
  2225. * Returns an array of page dimensions:
  2226. * <ul><li>$this->pagedim[$this->page]['w'] = page width in points</li><li>$this->pagedim[$this->page]['h'] = height in points</li><li>$this->pagedim[$this->page]['wk'] = page width in user units</li><li>$this->pagedim[$this->page]['hk'] = page height in user units</li><li>$this->pagedim[$this->page]['tm'] = top margin</li><li>$this->pagedim[$this->page]['bm'] = bottom margin</li><li>$this->pagedim[$this->page]['lm'] = left margin</li><li>$this->pagedim[$this->page]['rm'] = right margin</li><li>$this->pagedim[$this->page]['pb'] = auto page break</li><li>$this->pagedim[$this->page]['or'] = page orientation</li><li>$this->pagedim[$this->page]['olm'] = original left margin</li><li>$this->pagedim[$this->page]['orm'] = original right margin</li><li>$this->pagedim[$this->page]['Rotate'] = The number of degrees by which the page shall be rotated clockwise when displayed or printed. The value shall be a multiple of 90.</li><li>$this->pagedim[$this->page]['PZ'] = The page's preferred zoom (magnification) factor.</li><li>$this->pagedim[$this->page]['trans'] : the style and duration of the visual transition to use when moving from another page to the given page during a presentation<ul><li>$this->pagedim[$this->page]['trans']['Dur'] = The page's display duration (also called its advance timing): the maximum length of time, in seconds, that the page shall be displayed during presentations before the viewer application shall automatically advance to the next page.</li><li>$this->pagedim[$this->page]['trans']['S'] = transition style : Split, Blinds, Box, Wipe, Dissolve, Glitter, R, Fly, Push, Cover, Uncover, Fade</li><li>$this->pagedim[$this->page]['trans']['D'] = The duration of the transition effect, in seconds.</li><li>$this->pagedim[$this->page]['trans']['Dm'] = (Split and Blinds transition styles only) The dimension in which the specified transition effect shall occur: H = Horizontal, V = Vertical. Default value: H.</li><li>$this->pagedim[$this->page]['trans']['M'] = (Split, Box and Fly transition styles only) The direction of motion for the specified transition effect: I = Inward from the edges of the page, O = Outward from the center of the pageDefault value: I.</li><li>$this->pagedim[$this->page]['trans']['Di'] = (Wipe, Glitter, Fly, Cover, Uncover and Push transition styles only) The direction in which the specified transition effect shall moves, expressed in degrees counterclockwise starting from a left-to-right direction. If the value is a number, it shall be one of: 0 = Left to right, 90 = Bottom to top (Wipe only), 180 = Right to left (Wipe only), 270 = Top to bottom, 315 = Top-left to bottom-right (Glitter only). If the value is a name, it shall be None, which is relevant only for the Fly transition when the value of SS is not 1.0. Default value: 0.</li><li>$this->pagedim[$this->page]['trans']['SS'] = (Fly transition style only) The starting or ending scale at which the changes shall be drawn. If M specifies an inward transition, the scale of the changes drawn shall progress from SS to 1.0 over the course of the transition. If M specifies an outward transition, the scale of the changes drawn shall progress from 1.0 to SS over the course of the transition. Default: 1.0. </li><li>$this->pagedim[$this->page]['trans']['B'] = (Fly transition style only) If true, the area that shall be flown in is rectangular and opaque. Default: false.</li></ul></li><li>$this->pagedim[$this->page]['MediaBox'] : the boundaries of the physical medium on which the page shall be displayed or printed<ul><li>$this->pagedim[$this->page]['MediaBox']['llx'] = lower-left x coordinate in points</li><li>$this->pagedim[$this->page]['MediaBox']['lly'] = lower-left y coordinate in points</li><li>$this->pagedim[$this->page]['MediaBox']['urx'] = upper-right x coordinate in points</li><li>$this->pagedim[$this->page]['MediaBox']['ury'] = upper-right y coordinate in points</li></ul></li><li>$this->pagedim[$this->page]['CropBox'] : the visible region of default user space<ul><li>$this->pagedim[$this->page]['CropBox']['llx'] = lower-left x coordinate in points</
  2227. * @param $pagenum (int) page number (empty = current page)
  2228. * @return array of page dimensions.
  2229. * @author Nicola Asuni
  2230. * @public
  2231. * @since 4.5.027 (2009-03-16)
  2232. */
  2233. public function getPageDimensions($pagenum='') {
  2234. if (empty($pagenum)) {
  2235. $pagenum = $this->page;
  2236. }
  2237. return $this->pagedim[$pagenum];
  2238. }
  2239. /**
  2240. * Returns the page width in units.
  2241. * @param $pagenum (int) page number (empty = current page)
  2242. * @return int page width.
  2243. * @author Nicola Asuni
  2244. * @public
  2245. * @since 1.5.2
  2246. * @see getPageDimensions()
  2247. */
  2248. public function getPageWidth($pagenum='') {
  2249. if (empty($pagenum)) {
  2250. return $this->w;
  2251. }
  2252. return $this->pagedim[$pagenum]['w'];
  2253. }
  2254. /**
  2255. * Returns the page height in units.
  2256. * @param $pagenum (int) page number (empty = current page)
  2257. * @return int page height.
  2258. * @author Nicola Asuni
  2259. * @public
  2260. * @since 1.5.2
  2261. * @see getPageDimensions()
  2262. */
  2263. public function getPageHeight($pagenum='') {
  2264. if (empty($pagenum)) {
  2265. return $this->h;
  2266. }
  2267. return $this->pagedim[$pagenum]['h'];
  2268. }
  2269. /**
  2270. * Returns the page break margin.
  2271. * @param $pagenum (int) page number (empty = current page)
  2272. * @return int page break margin.
  2273. * @author Nicola Asuni
  2274. * @public
  2275. * @since 1.5.2
  2276. * @see getPageDimensions()
  2277. */
  2278. public function getBreakMargin($pagenum='') {
  2279. if (empty($pagenum)) {
  2280. return $this->bMargin;
  2281. }
  2282. return $this->pagedim[$pagenum]['bm'];
  2283. }
  2284. /**
  2285. * Returns the scale factor (number of points in user unit).
  2286. * @return int scale factor.
  2287. * @author Nicola Asuni
  2288. * @public
  2289. * @since 1.5.2
  2290. */
  2291. public function getScaleFactor() {
  2292. return $this->k;
  2293. }
  2294. /**
  2295. * Defines the left, top and right margins.
  2296. * @param $left (float) Left margin.
  2297. * @param $top (float) Top margin.
  2298. * @param $right (float) Right margin. Default value is the left one.
  2299. * @param $keepmargins (boolean) if true overwrites the default page margins
  2300. * @public
  2301. * @since 1.0
  2302. * @see SetLeftMargin(), SetTopMargin(), SetRightMargin(), SetAutoPageBreak()
  2303. */
  2304. public function SetMargins($left, $top, $right=-1, $keepmargins=false) {
  2305. //Set left, top and right margins
  2306. $this->lMargin = $left;
  2307. $this->tMargin = $top;
  2308. if ($right == -1) {
  2309. $right = $left;
  2310. }
  2311. $this->rMargin = $right;
  2312. if ($keepmargins) {
  2313. // overwrite original values
  2314. $this->original_lMargin = $this->lMargin;
  2315. $this->original_rMargin = $this->rMargin;
  2316. }
  2317. }
  2318. /**
  2319. * Defines the left margin. The method can be called before creating the first page. If the current abscissa gets out of page, it is brought back to the margin.
  2320. * @param $margin (float) The margin.
  2321. * @public
  2322. * @since 1.4
  2323. * @see SetTopMargin(), SetRightMargin(), SetAutoPageBreak(), SetMargins()
  2324. */
  2325. public function SetLeftMargin($margin) {
  2326. //Set left margin
  2327. $this->lMargin = $margin;
  2328. if (($this->page > 0) AND ($this->x < $margin)) {
  2329. $this->x = $margin;
  2330. }
  2331. }
  2332. /**
  2333. * Defines the top margin. The method can be called before creating the first page.
  2334. * @param $margin (float) The margin.
  2335. * @public
  2336. * @since 1.5
  2337. * @see SetLeftMargin(), SetRightMargin(), SetAutoPageBreak(), SetMargins()
  2338. */
  2339. public function SetTopMargin($margin) {
  2340. //Set top margin
  2341. $this->tMargin = $margin;
  2342. if (($this->page > 0) AND ($this->y < $margin)) {
  2343. $this->y = $margin;
  2344. }
  2345. }
  2346. /**
  2347. * Defines the right margin. The method can be called before creating the first page.
  2348. * @param $margin (float) The margin.
  2349. * @public
  2350. * @since 1.5
  2351. * @see SetLeftMargin(), SetTopMargin(), SetAutoPageBreak(), SetMargins()
  2352. */
  2353. public function SetRightMargin($margin) {
  2354. $this->rMargin = $margin;
  2355. if (($this->page > 0) AND ($this->x > ($this->w - $margin))) {
  2356. $this->x = $this->w - $margin;
  2357. }
  2358. }
  2359. /**
  2360. * Set the same internal Cell padding for top, right, bottom, left-
  2361. * @param $pad (float) internal padding.
  2362. * @public
  2363. * @since 2.1.000 (2008-01-09)
  2364. * @see getCellPaddings(), setCellPaddings()
  2365. */
  2366. public function SetCellPadding($pad) {
  2367. if ($pad >= 0) {
  2368. $this->cell_padding['L'] = $pad;
  2369. $this->cell_padding['T'] = $pad;
  2370. $this->cell_padding['R'] = $pad;
  2371. $this->cell_padding['B'] = $pad;
  2372. }
  2373. }
  2374. /**
  2375. * Set the internal Cell paddings.
  2376. * @param $left (float) left padding
  2377. * @param $top (float) top padding
  2378. * @param $right (float) right padding
  2379. * @param $bottom (float) bottom padding
  2380. * @public
  2381. * @since 5.9.000 (2010-10-03)
  2382. * @see getCellPaddings(), SetCellPadding()
  2383. */
  2384. public function setCellPaddings($left='', $top='', $right='', $bottom='') {
  2385. if (($left !== '') AND ($left >= 0)) {
  2386. $this->cell_padding['L'] = $left;
  2387. }
  2388. if (($top !== '') AND ($top >= 0)) {
  2389. $this->cell_padding['T'] = $top;
  2390. }
  2391. if (($right !== '') AND ($right >= 0)) {
  2392. $this->cell_padding['R'] = $right;
  2393. }
  2394. if (($bottom !== '') AND ($bottom >= 0)) {
  2395. $this->cell_padding['B'] = $bottom;
  2396. }
  2397. }
  2398. /**
  2399. * Get the internal Cell padding array.
  2400. * @return array of padding values
  2401. * @public
  2402. * @since 5.9.000 (2010-10-03)
  2403. * @see setCellPaddings(), SetCellPadding()
  2404. */
  2405. public function getCellPaddings() {
  2406. return $this->cell_padding;
  2407. }
  2408. /**
  2409. * Set the internal Cell margins.
  2410. * @param $left (float) left margin
  2411. * @param $top (float) top margin
  2412. * @param $right (float) right margin
  2413. * @param $bottom (float) bottom margin
  2414. * @public
  2415. * @since 5.9.000 (2010-10-03)
  2416. * @see getCellMargins()
  2417. */
  2418. public function setCellMargins($left='', $top='', $right='', $bottom='') {
  2419. if (($left !== '') AND ($left >= 0)) {
  2420. $this->cell_margin['L'] = $left;
  2421. }
  2422. if (($top !== '') AND ($top >= 0)) {
  2423. $this->cell_margin['T'] = $top;
  2424. }
  2425. if (($right !== '') AND ($right >= 0)) {
  2426. $this->cell_margin['R'] = $right;
  2427. }
  2428. if (($bottom !== '') AND ($bottom >= 0)) {
  2429. $this->cell_margin['B'] = $bottom;
  2430. }
  2431. }
  2432. /**
  2433. * Get the internal Cell margin array.
  2434. * @return array of margin values
  2435. * @public
  2436. * @since 5.9.000 (2010-10-03)
  2437. * @see setCellMargins()
  2438. */
  2439. public function getCellMargins() {
  2440. return $this->cell_margin;
  2441. }
  2442. /**
  2443. * Adjust the internal Cell padding array to take account of the line width.
  2444. * @param $brd (mixed) Indicates if borders must be drawn around the cell. The value can be a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul> or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul> or an array of line styles for each border group - for example: array('LTRB' => array('width' => 2, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0)))
  2445. * @return array of adjustments
  2446. * @public
  2447. * @since 5.9.000 (2010-10-03)
  2448. */
  2449. protected function adjustCellPadding($brd=0) {
  2450. if (empty($brd)) {
  2451. return;
  2452. }
  2453. if (is_string($brd)) {
  2454. // convert string to array
  2455. $slen = strlen($brd);
  2456. $newbrd = array();
  2457. for ($i = 0; $i < $slen; ++$i) {
  2458. $newbrd[$brd[$i]] = true;
  2459. }
  2460. $brd = $newbrd;
  2461. } elseif (($brd === 1) OR ($brd === true) OR (is_numeric($brd) AND (intval($brd) > 0))) {
  2462. $brd = array('LRTB' => true);
  2463. }
  2464. if (!is_array($brd)) {
  2465. return;
  2466. }
  2467. // store current cell padding
  2468. $cp = $this->cell_padding;
  2469. // select border mode
  2470. if (isset($brd['mode'])) {
  2471. $mode = $brd['mode'];
  2472. unset($brd['mode']);
  2473. } else {
  2474. $mode = 'normal';
  2475. }
  2476. // process borders
  2477. foreach ($brd as $border => $style) {
  2478. $line_width = $this->LineWidth;
  2479. if (is_array($style) AND isset($style['width'])) {
  2480. // get border width
  2481. $line_width = $style['width'];
  2482. }
  2483. $adj = 0; // line width inside the cell
  2484. switch ($mode) {
  2485. case 'ext': {
  2486. $adj = 0;
  2487. break;
  2488. }
  2489. case 'int': {
  2490. $adj = $line_width;
  2491. break;
  2492. }
  2493. case 'normal':
  2494. default: {
  2495. $adj = ($line_width / 2);
  2496. break;
  2497. }
  2498. }
  2499. // correct internal cell padding if required to avoid overlap between text and lines
  2500. if ((strpos($border,'T') !== false) AND ($this->cell_padding['T'] < $adj)) {
  2501. $this->cell_padding['T'] = $adj;
  2502. }
  2503. if ((strpos($border,'R') !== false) AND ($this->cell_padding['R'] < $adj)) {
  2504. $this->cell_padding['R'] = $adj;
  2505. }
  2506. if ((strpos($border,'B') !== false) AND ($this->cell_padding['B'] < $adj)) {
  2507. $this->cell_padding['B'] = $adj;
  2508. }
  2509. if ((strpos($border,'L') !== false) AND ($this->cell_padding['L'] < $adj)) {
  2510. $this->cell_padding['L'] = $adj;
  2511. }
  2512. }
  2513. return array('T' => ($this->cell_padding['T'] - $cp['T']), 'R' => ($this->cell_padding['R'] - $cp['R']), 'B' => ($this->cell_padding['B'] - $cp['B']), 'L' => ($this->cell_padding['L'] - $cp['L']));
  2514. }
  2515. /**
  2516. * Enables or disables the automatic page breaking mode. When enabling, the second parameter is the distance from the bottom of the page that defines the triggering limit. By default, the mode is on and the margin is 2 cm.
  2517. * @param $auto (boolean) Boolean indicating if mode should be on or off.
  2518. * @param $margin (float) Distance from the bottom of the page.
  2519. * @public
  2520. * @since 1.0
  2521. * @see Cell(), MultiCell(), AcceptPageBreak()
  2522. */
  2523. public function SetAutoPageBreak($auto, $margin=0) {
  2524. $this->AutoPageBreak = $auto ? true : false;
  2525. $this->bMargin = $margin;
  2526. $this->PageBreakTrigger = $this->h - $margin;
  2527. }
  2528. /**
  2529. * Return the auto-page-break mode (true or false).
  2530. * @return boolean auto-page-break mode
  2531. * @public
  2532. * @since 5.9.088
  2533. */
  2534. public function getAutoPageBreak() {
  2535. return $this->AutoPageBreak;
  2536. }
  2537. /**
  2538. * Defines the way the document is to be displayed by the viewer.
  2539. * @param $zoom (mixed) The zoom to use. It can be one of the following string values or a number indicating the zooming factor to use. <ul><li>fullpage: displays the entire page on screen </li><li>fullwidth: uses maximum width of window</li><li>real: uses real size (equivalent to 100% zoom)</li><li>default: uses viewer default mode</li></ul>
  2540. * @param $layout (string) The page layout. Possible values are:<ul><li>SinglePage Display one page at a time</li><li>OneColumn Display the pages in one column</li><li>TwoColumnLeft Display the pages in two columns, with odd-numbered pages on the left</li><li>TwoColumnRight Display the pages in two columns, with odd-numbered pages on the right</li><li>TwoPageLeft (PDF 1.5) Display the pages two at a time, with odd-numbered pages on the left</li><li>TwoPageRight (PDF 1.5) Display the pages two at a time, with odd-numbered pages on the right</li></ul>
  2541. * @param $mode (string) A name object specifying how the document should be displayed when opened:<ul><li>UseNone Neither document outline nor thumbnail images visible</li><li>UseOutlines Document outline visible</li><li>UseThumbs Thumbnail images visible</li><li>FullScreen Full-screen mode, with no menu bar, window controls, or any other window visible</li><li>UseOC (PDF 1.5) Optional content group panel visible</li><li>UseAttachments (PDF 1.6) Attachments panel visible</li></ul>
  2542. * @public
  2543. * @since 1.2
  2544. */
  2545. public function SetDisplayMode($zoom, $layout='SinglePage', $mode='UseNone') {
  2546. if (($zoom == 'fullpage') OR ($zoom == 'fullwidth') OR ($zoom == 'real') OR ($zoom == 'default') OR (!is_string($zoom))) {
  2547. $this->ZoomMode = $zoom;
  2548. } else {
  2549. $this->Error('Incorrect zoom display mode: '.$zoom);
  2550. }
  2551. $this->LayoutMode = TCPDF_STATIC::getPageLayoutMode($layout);
  2552. $this->PageMode = TCPDF_STATIC::getPageMode($mode);
  2553. }
  2554. /**
  2555. * Activates or deactivates page compression. When activated, the internal representation of each page is compressed, which leads to a compression ratio of about 2 for the resulting document. Compression is on by default.
  2556. * Note: the Zlib extension is required for this feature. If not present, compression will be turned off.
  2557. * @param $compress (boolean) Boolean indicating if compression must be enabled.
  2558. * @public
  2559. * @since 1.4
  2560. */
  2561. public function SetCompression($compress=true) {
  2562. $this->compress = false;
  2563. if (function_exists('gzcompress')) {
  2564. if ($compress) {
  2565. if ( !$this->pdfa_mode) {
  2566. $this->compress = true;
  2567. }
  2568. }
  2569. }
  2570. }
  2571. /**
  2572. * Set flag to force sRGB_IEC61966-2.1 black scaled ICC color profile for the whole document.
  2573. * @param $mode (boolean) If true force sRGB output intent.
  2574. * @public
  2575. * @since 5.9.121 (2011-09-28)
  2576. */
  2577. public function setSRGBmode($mode=false) {
  2578. $this->force_srgb = $mode ? true : false;
  2579. }
  2580. /**
  2581. * Turn on/off Unicode mode for document information dictionary (meta tags).
  2582. * This has effect only when unicode mode is set to false.
  2583. * @param $unicode (boolean) if true set the meta information in Unicode
  2584. * @since 5.9.027 (2010-12-01)
  2585. * @public
  2586. */
  2587. public function SetDocInfoUnicode($unicode=true) {
  2588. $this->docinfounicode = $unicode ? true : false;
  2589. }
  2590. /**
  2591. * Defines the title of the document.
  2592. * @param $title (string) The title.
  2593. * @public
  2594. * @since 1.2
  2595. * @see SetAuthor(), SetCreator(), SetKeywords(), SetSubject()
  2596. */
  2597. public function SetTitle($title) {
  2598. $this->title = $title;
  2599. }
  2600. /**
  2601. * Defines the subject of the document.
  2602. * @param $subject (string) The subject.
  2603. * @public
  2604. * @since 1.2
  2605. * @see SetAuthor(), SetCreator(), SetKeywords(), SetTitle()
  2606. */
  2607. public function SetSubject($subject) {
  2608. $this->subject = $subject;
  2609. }
  2610. /**
  2611. * Defines the author of the document.
  2612. * @param $author (string) The name of the author.
  2613. * @public
  2614. * @since 1.2
  2615. * @see SetCreator(), SetKeywords(), SetSubject(), SetTitle()
  2616. */
  2617. public function SetAuthor($author) {
  2618. $this->author = $author;
  2619. }
  2620. /**
  2621. * Associates keywords with the document, generally in the form 'keyword1 keyword2 ...'.
  2622. * @param $keywords (string) The list of keywords.
  2623. * @public
  2624. * @since 1.2
  2625. * @see SetAuthor(), SetCreator(), SetSubject(), SetTitle()
  2626. */
  2627. public function SetKeywords($keywords) {
  2628. $this->keywords = $keywords;
  2629. }
  2630. /**
  2631. * Defines the creator of the document. This is typically the name of the application that generates the PDF.
  2632. * @param $creator (string) The name of the creator.
  2633. * @public
  2634. * @since 1.2
  2635. * @see SetAuthor(), SetKeywords(), SetSubject(), SetTitle()
  2636. */
  2637. public function SetCreator($creator) {
  2638. $this->creator = $creator;
  2639. }
  2640. /**
  2641. * Throw an exception or print an error message and die if the K_TCPDF_PARSER_THROW_EXCEPTION_ERROR constant is set to true.
  2642. * @param $msg (string) The error message
  2643. * @public
  2644. * @since 1.0
  2645. */
  2646. public function Error($msg) {
  2647. // unset all class variables
  2648. $this->_destroy(true);
  2649. if (defined('K_TCPDF_THROW_EXCEPTION_ERROR') AND !K_TCPDF_THROW_EXCEPTION_ERROR) {
  2650. die('<strong>TCPDF ERROR: </strong>'.$msg);
  2651. } else {
  2652. throw new Exception('TCPDF ERROR: '.$msg);
  2653. }
  2654. }
  2655. /**
  2656. * This method begins the generation of the PDF document.
  2657. * It is not necessary to call it explicitly because AddPage() does it automatically.
  2658. * Note: no page is created by this method
  2659. * @public
  2660. * @since 1.0
  2661. * @see AddPage(), Close()
  2662. */
  2663. public function Open() {
  2664. $this->state = 1;
  2665. }
  2666. /**
  2667. * Terminates the PDF document.
  2668. * It is not necessary to call this method explicitly because Output() does it automatically.
  2669. * If the document contains no page, AddPage() is called to prevent from getting an invalid document.
  2670. * @public
  2671. * @since 1.0
  2672. * @see Open(), Output()
  2673. */
  2674. public function Close() {
  2675. if ($this->state == 3) {
  2676. return;
  2677. }
  2678. if ($this->page == 0) {
  2679. $this->AddPage();
  2680. }
  2681. $this->endLayer();
  2682. if ($this->tcpdflink) {
  2683. // save current graphic settings
  2684. $gvars = $this->getGraphicVars();
  2685. $this->setEqualColumns();
  2686. $this->lastpage(true);
  2687. $this->SetAutoPageBreak(false);
  2688. $this->x = 0;
  2689. $this->y = $this->h - (1 / $this->k);
  2690. $this->lMargin = 0;
  2691. $this->_outSaveGraphicsState();
  2692. $font = defined('PDF_FONT_NAME_MAIN')?PDF_FONT_NAME_MAIN:'helvetica';
  2693. $this->SetFont($font, '', 1);
  2694. $this->setTextRenderingMode(0, false, false);
  2695. $msg = "\x50\x6f\x77\x65\x72\x65\x64\x20\x62\x79\x20\x54\x43\x50\x44\x46\x20\x28\x77\x77\x77\x2e\x74\x63\x70\x64\x66\x2e\x6f\x72\x67\x29";
  2696. $lnk = "\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x74\x63\x70\x64\x66\x2e\x6f\x72\x67";
  2697. $this->Cell(0, 0, $msg, 0, 0, 'L', 0, $lnk, 0, false, 'D', 'B');
  2698. $this->_outRestoreGraphicsState();
  2699. // restore graphic settings
  2700. $this->setGraphicVars($gvars);
  2701. }
  2702. // close page
  2703. $this->endPage();
  2704. // close document
  2705. $this->_enddoc();
  2706. // unset all class variables (except critical ones)
  2707. $this->_destroy(false);
  2708. }
  2709. /**
  2710. * Move pointer at the specified document page and update page dimensions.
  2711. * @param $pnum (int) page number (1 ... numpages)
  2712. * @param $resetmargins (boolean) if true reset left, right, top margins and Y position.
  2713. * @public
  2714. * @since 2.1.000 (2008-01-07)
  2715. * @see getPage(), lastpage(), getNumPages()
  2716. */
  2717. public function setPage($pnum, $resetmargins=false) {
  2718. if (($pnum == $this->page) AND ($this->state == 2)) {
  2719. return;
  2720. }
  2721. if (($pnum > 0) AND ($pnum <= $this->numpages)) {
  2722. $this->state = 2;
  2723. // save current graphic settings
  2724. //$gvars = $this->getGraphicVars();
  2725. $oldpage = $this->page;
  2726. $this->page = $pnum;
  2727. $this->wPt = $this->pagedim[$this->page]['w'];
  2728. $this->hPt = $this->pagedim[$this->page]['h'];
  2729. $this->w = $this->pagedim[$this->page]['wk'];
  2730. $this->h = $this->pagedim[$this->page]['hk'];
  2731. $this->tMargin = $this->pagedim[$this->page]['tm'];
  2732. $this->bMargin = $this->pagedim[$this->page]['bm'];
  2733. $this->original_lMargin = $this->pagedim[$this->page]['olm'];
  2734. $this->original_rMargin = $this->pagedim[$this->page]['orm'];
  2735. $this->AutoPageBreak = $this->pagedim[$this->page]['pb'];
  2736. $this->CurOrientation = $this->pagedim[$this->page]['or'];
  2737. $this->SetAutoPageBreak($this->AutoPageBreak, $this->bMargin);
  2738. // restore graphic settings
  2739. //$this->setGraphicVars($gvars);
  2740. if ($resetmargins) {
  2741. $this->lMargin = $this->pagedim[$this->page]['olm'];
  2742. $this->rMargin = $this->pagedim[$this->page]['orm'];
  2743. $this->SetY($this->tMargin);
  2744. } else {
  2745. // account for booklet mode
  2746. if ($this->pagedim[$this->page]['olm'] != $this->pagedim[$oldpage]['olm']) {
  2747. $deltam = $this->pagedim[$this->page]['olm'] - $this->pagedim[$this->page]['orm'];
  2748. $this->lMargin += $deltam;
  2749. $this->rMargin -= $deltam;
  2750. }
  2751. }
  2752. } else {
  2753. $this->Error('Wrong page number on setPage() function: '.$pnum);
  2754. }
  2755. }
  2756. /**
  2757. * Reset pointer to the last document page.
  2758. * @param $resetmargins (boolean) if true reset left, right, top margins and Y position.
  2759. * @public
  2760. * @since 2.0.000 (2008-01-04)
  2761. * @see setPage(), getPage(), getNumPages()
  2762. */
  2763. public function lastPage($resetmargins=false) {
  2764. $this->setPage($this->getNumPages(), $resetmargins);
  2765. }
  2766. /**
  2767. * Get current document page number.
  2768. * @return int page number
  2769. * @public
  2770. * @since 2.1.000 (2008-01-07)
  2771. * @see setPage(), lastpage(), getNumPages()
  2772. */
  2773. public function getPage() {
  2774. return $this->page;
  2775. }
  2776. /**
  2777. * Get the total number of insered pages.
  2778. * @return int number of pages
  2779. * @public
  2780. * @since 2.1.000 (2008-01-07)
  2781. * @see setPage(), getPage(), lastpage()
  2782. */
  2783. public function getNumPages() {
  2784. return $this->numpages;
  2785. }
  2786. /**
  2787. * Adds a new TOC (Table Of Content) page to the document.
  2788. * @param $orientation (string) page orientation.
  2789. * @param $format (mixed) The format used for pages. It can be either: one of the string values specified at getPageSizeFromFormat() or an array of parameters specified at setPageFormat().
  2790. * @param $keepmargins (boolean) if true overwrites the default page margins with the current margins
  2791. * @public
  2792. * @since 5.0.001 (2010-05-06)
  2793. * @see AddPage(), startPage(), endPage(), endTOCPage()
  2794. */
  2795. public function addTOCPage($orientation='', $format='', $keepmargins=false) {
  2796. $this->AddPage($orientation, $format, $keepmargins, true);
  2797. }
  2798. /**
  2799. * Terminate the current TOC (Table Of Content) page
  2800. * @public
  2801. * @since 5.0.001 (2010-05-06)
  2802. * @see AddPage(), startPage(), endPage(), addTOCPage()
  2803. */
  2804. public function endTOCPage() {
  2805. $this->endPage(true);
  2806. }
  2807. /**
  2808. * Adds a new page to the document. If a page is already present, the Footer() method is called first to output the footer (if enabled). Then the page is added, the current position set to the top-left corner according to the left and top margins (or top-right if in RTL mode), and Header() is called to display the header (if enabled).
  2809. * The origin of the coordinate system is at the top-left corner (or top-right for RTL) and increasing ordinates go downwards.
  2810. * @param $orientation (string) page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
  2811. * @param $format (mixed) The format used for pages. It can be either: one of the string values specified at getPageSizeFromFormat() or an array of parameters specified at setPageFormat().
  2812. * @param $keepmargins (boolean) if true overwrites the default page margins with the current margins
  2813. * @param $tocpage (boolean) if true set the tocpage state to true (the added page will be used to display Table Of Content).
  2814. * @public
  2815. * @since 1.0
  2816. * @see startPage(), endPage(), addTOCPage(), endTOCPage(), getPageSizeFromFormat(), setPageFormat()
  2817. */
  2818. public function AddPage($orientation='', $format='', $keepmargins=false, $tocpage=false) {
  2819. if ($this->inxobj) {
  2820. // we are inside an XObject template
  2821. return;
  2822. }
  2823. if (!isset($this->original_lMargin) OR $keepmargins) {
  2824. $this->original_lMargin = $this->lMargin;
  2825. }
  2826. if (!isset($this->original_rMargin) OR $keepmargins) {
  2827. $this->original_rMargin = $this->rMargin;
  2828. }
  2829. // terminate previous page
  2830. $this->endPage();
  2831. // start new page
  2832. $this->startPage($orientation, $format, $tocpage);
  2833. }
  2834. /**
  2835. * Terminate the current page
  2836. * @param $tocpage (boolean) if true set the tocpage state to false (end the page used to display Table Of Content).
  2837. * @public
  2838. * @since 4.2.010 (2008-11-14)
  2839. * @see AddPage(), startPage(), addTOCPage(), endTOCPage()
  2840. */
  2841. public function endPage($tocpage=false) {
  2842. // check if page is already closed
  2843. if (($this->page == 0) OR ($this->numpages > $this->page) OR (!$this->pageopen[$this->page])) {
  2844. return;
  2845. }
  2846. // print page footer
  2847. $this->setFooter();
  2848. // close page
  2849. $this->_endpage();
  2850. // mark page as closed
  2851. $this->pageopen[$this->page] = false;
  2852. if ($tocpage) {
  2853. $this->tocpage = false;
  2854. }
  2855. }
  2856. /**
  2857. * Starts a new page to the document. The page must be closed using the endPage() function.
  2858. * The origin of the coordinate system is at the top-left corner and increasing ordinates go downwards.
  2859. * @param $orientation (string) page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
  2860. * @param $format (mixed) The format used for pages. It can be either: one of the string values specified at getPageSizeFromFormat() or an array of parameters specified at setPageFormat().
  2861. * @param $tocpage (boolean) if true the page is designated to contain the Table-Of-Content.
  2862. * @since 4.2.010 (2008-11-14)
  2863. * @see AddPage(), endPage(), addTOCPage(), endTOCPage(), getPageSizeFromFormat(), setPageFormat()
  2864. * @public
  2865. */
  2866. public function startPage($orientation='', $format='', $tocpage=false) {
  2867. if ($tocpage) {
  2868. $this->tocpage = true;
  2869. }
  2870. // move page numbers of documents to be attached
  2871. if ($this->tocpage) {
  2872. // move reference to unexistent pages (used for page attachments)
  2873. // adjust outlines
  2874. $tmpoutlines = $this->outlines;
  2875. foreach ($tmpoutlines as $key => $outline) {
  2876. if (!$outline['f'] AND ($outline['p'] > $this->numpages)) {
  2877. $this->outlines[$key]['p'] = ($outline['p'] + 1);
  2878. }
  2879. }
  2880. // adjust dests
  2881. $tmpdests = $this->dests;
  2882. foreach ($tmpdests as $key => $dest) {
  2883. if (!$dest['f'] AND ($dest['p'] > $this->numpages)) {
  2884. $this->dests[$key]['p'] = ($dest['p'] + 1);
  2885. }
  2886. }
  2887. // adjust links
  2888. $tmplinks = $this->links;
  2889. foreach ($tmplinks as $key => $link) {
  2890. if (!$link['f'] AND ($link['p'] > $this->numpages)) {
  2891. $this->links[$key]['p'] = ($link['p'] + 1);
  2892. }
  2893. }
  2894. }
  2895. if ($this->numpages > $this->page) {
  2896. // this page has been already added
  2897. $this->setPage($this->page + 1);
  2898. $this->SetY($this->tMargin);
  2899. return;
  2900. }
  2901. // start a new page
  2902. if ($this->state == 0) {
  2903. $this->Open();
  2904. }
  2905. ++$this->numpages;
  2906. $this->swapMargins($this->booklet);
  2907. // save current graphic settings
  2908. $gvars = $this->getGraphicVars();
  2909. // start new page
  2910. $this->_beginpage($orientation, $format);
  2911. // mark page as open
  2912. $this->pageopen[$this->page] = true;
  2913. // restore graphic settings
  2914. $this->setGraphicVars($gvars);
  2915. // mark this point
  2916. $this->setPageMark();
  2917. // print page header
  2918. $this->setHeader();
  2919. // restore graphic settings
  2920. $this->setGraphicVars($gvars);
  2921. // mark this point
  2922. $this->setPageMark();
  2923. // print table header (if any)
  2924. $this->setTableHeader();
  2925. // set mark for empty page check
  2926. $this->emptypagemrk[$this->page]= $this->pagelen[$this->page];
  2927. }
  2928. /**
  2929. * Set start-writing mark on current page stream used to put borders and fills.
  2930. * Borders and fills are always created after content and inserted on the position marked by this method.
  2931. * This function must be called after calling Image() function for a background image.
  2932. * Background images must be always inserted before calling Multicell() or WriteHTMLCell() or WriteHTML() functions.
  2933. * @public
  2934. * @since 4.0.016 (2008-07-30)
  2935. */
  2936. public function setPageMark() {
  2937. $this->intmrk[$this->page] = $this->pagelen[$this->page];
  2938. $this->bordermrk[$this->page] = $this->intmrk[$this->page];
  2939. $this->setContentMark();
  2940. }
  2941. /**
  2942. * Set start-writing mark on selected page.
  2943. * Borders and fills are always created after content and inserted on the position marked by this method.
  2944. * @param $page (int) page number (default is the current page)
  2945. * @protected
  2946. * @since 4.6.021 (2009-07-20)
  2947. */
  2948. protected function setContentMark($page=0) {
  2949. if ($page <= 0) {
  2950. $page = $this->page;
  2951. }
  2952. if (isset($this->footerlen[$page])) {
  2953. $this->cntmrk[$page] = $this->pagelen[$page] - $this->footerlen[$page];
  2954. } else {
  2955. $this->cntmrk[$page] = $this->pagelen[$page];
  2956. }
  2957. }
  2958. /**
  2959. * Set header data.
  2960. * @param $ln (string) header image logo
  2961. * @param $lw (string) header image logo width in mm
  2962. * @param $ht (string) string to print as title on document header
  2963. * @param $hs (string) string to print on document header
  2964. * @param $tc (array) RGB array color for text.
  2965. * @param $lc (array) RGB array color for line.
  2966. * @public
  2967. */
  2968. public function setHeaderData($ln='', $lw=0, $ht='', $hs='', $tc=array(0,0,0), $lc=array(0,0,0)) {
  2969. $this->header_logo = $ln;
  2970. $this->header_logo_width = $lw;
  2971. $this->header_title = $ht;
  2972. $this->header_string = $hs;
  2973. $this->header_text_color = $tc;
  2974. $this->header_line_color = $lc;
  2975. }
  2976. /**
  2977. * Set footer data.
  2978. * @param $tc (array) RGB array color for text.
  2979. * @param $lc (array) RGB array color for line.
  2980. * @public
  2981. */
  2982. public function setFooterData($tc=array(0,0,0), $lc=array(0,0,0)) {
  2983. $this->footer_text_color = $tc;
  2984. $this->footer_line_color = $lc;
  2985. }
  2986. /**
  2987. * Returns header data:
  2988. * <ul><li>$ret['logo'] = logo image</li><li>$ret['logo_width'] = width of the image logo in user units</li><li>$ret['title'] = header title</li><li>$ret['string'] = header description string</li></ul>
  2989. * @return array()
  2990. * @public
  2991. * @since 4.0.012 (2008-07-24)
  2992. */
  2993. public function getHeaderData() {
  2994. $ret = array();
  2995. $ret['logo'] = $this->header_logo;
  2996. $ret['logo_width'] = $this->header_logo_width;
  2997. $ret['title'] = $this->header_title;
  2998. $ret['string'] = $this->header_string;
  2999. $ret['text_color'] = $this->header_text_color;
  3000. $ret['line_color'] = $this->header_line_color;
  3001. return $ret;
  3002. }
  3003. /**
  3004. * Set header margin.
  3005. * (minimum distance between header and top page margin)
  3006. * @param $hm (int) distance in user units
  3007. * @public
  3008. */
  3009. public function setHeaderMargin($hm=10) {
  3010. $this->header_margin = $hm;
  3011. }
  3012. /**
  3013. * Returns header margin in user units.
  3014. * @return float
  3015. * @since 4.0.012 (2008-07-24)
  3016. * @public
  3017. */
  3018. public function getHeaderMargin() {
  3019. return $this->header_margin;
  3020. }
  3021. /**
  3022. * Set footer margin.
  3023. * (minimum distance between footer and bottom page margin)
  3024. * @param $fm (int) distance in user units
  3025. * @public
  3026. */
  3027. public function setFooterMargin($fm=10) {
  3028. $this->footer_margin = $fm;
  3029. }
  3030. /**
  3031. * Returns footer margin in user units.
  3032. * @return float
  3033. * @since 4.0.012 (2008-07-24)
  3034. * @public
  3035. */
  3036. public function getFooterMargin() {
  3037. return $this->footer_margin;
  3038. }
  3039. /**
  3040. * Set a flag to print page header.
  3041. * @param $val (boolean) set to true to print the page header (default), false otherwise.
  3042. * @public
  3043. */
  3044. public function setPrintHeader($val=true) {
  3045. $this->print_header = $val ? true : false;
  3046. }
  3047. /**
  3048. * Set a flag to print page footer.
  3049. * @param $val (boolean) set to true to print the page footer (default), false otherwise.
  3050. * @public
  3051. */
  3052. public function setPrintFooter($val=true) {
  3053. $this->print_footer = $val ? true : false;
  3054. }
  3055. /**
  3056. * Return the right-bottom (or left-bottom for RTL) corner X coordinate of last inserted image
  3057. * @return float
  3058. * @public
  3059. */
  3060. public function getImageRBX() {
  3061. return $this->img_rb_x;
  3062. }
  3063. /**
  3064. * Return the right-bottom (or left-bottom for RTL) corner Y coordinate of last inserted image
  3065. * @return float
  3066. * @public
  3067. */
  3068. public function getImageRBY() {
  3069. return $this->img_rb_y;
  3070. }
  3071. /**
  3072. * Reset the xobject template used by Header() method.
  3073. * @public
  3074. */
  3075. public function resetHeaderTemplate() {
  3076. $this->header_xobjid = false;
  3077. }
  3078. /**
  3079. * Set a flag to automatically reset the xobject template used by Header() method at each page.
  3080. * @param $val (boolean) set to true to reset Header xobject template at each page, false otherwise.
  3081. * @public
  3082. */
  3083. public function setHeaderTemplateAutoreset($val=true) {
  3084. $this->header_xobj_autoreset = $val ? true : false;
  3085. }
  3086. /**
  3087. * This method is used to render the page header.
  3088. * It is automatically called by AddPage() and could be overwritten in your own inherited class.
  3089. * @public
  3090. */
  3091. public function Header() {
  3092. if ($this->header_xobjid === false) {
  3093. // start a new XObject Template
  3094. $this->header_xobjid = $this->startTemplate($this->w, $this->tMargin);
  3095. $headerfont = $this->getHeaderFont();
  3096. $headerdata = $this->getHeaderData();
  3097. $this->y = $this->header_margin;
  3098. if ($this->rtl) {
  3099. $this->x = $this->w - $this->original_rMargin;
  3100. } else {
  3101. $this->x = $this->original_lMargin;
  3102. }
  3103. if (($headerdata['logo']) AND ($headerdata['logo'] != K_BLANK_IMAGE)) {
  3104. $imgtype = TCPDF_IMAGES::getImageFileType(K_PATH_IMAGES.$headerdata['logo']);
  3105. if (($imgtype == 'eps') OR ($imgtype == 'ai')) {
  3106. $this->ImageEps(K_PATH_IMAGES.$headerdata['logo'], '', '', $headerdata['logo_width']);
  3107. } elseif ($imgtype == 'svg') {
  3108. $this->ImageSVG(K_PATH_IMAGES.$headerdata['logo'], '', '', $headerdata['logo_width']);
  3109. } else {
  3110. $this->Image(K_PATH_IMAGES.$headerdata['logo'], '', '', $headerdata['logo_width']);
  3111. }
  3112. $imgy = $this->getImageRBY();
  3113. } else {
  3114. $imgy = $this->y;
  3115. }
  3116. $cell_height = $this->getCellHeight($headerfont[2] / $this->k);
  3117. // set starting margin for text data cell
  3118. if ($this->getRTL()) {
  3119. $header_x = $this->original_rMargin + ($headerdata['logo_width'] * 1.1);
  3120. } else {
  3121. $header_x = $this->original_lMargin + ($headerdata['logo_width'] * 1.1);
  3122. }
  3123. $cw = $this->w - $this->original_lMargin - $this->original_rMargin - ($headerdata['logo_width'] * 1.1);
  3124. $this->SetTextColorArray($this->header_text_color);
  3125. // header title
  3126. $this->SetFont($headerfont[0], 'B', $headerfont[2] + 1);
  3127. $this->SetX($header_x);
  3128. $this->Cell($cw, $cell_height, $headerdata['title'], 0, 1, '', 0, '', 0);
  3129. // header string
  3130. $this->SetFont($headerfont[0], $headerfont[1], $headerfont[2]);
  3131. $this->SetX($header_x);
  3132. $this->MultiCell($cw, $cell_height, $headerdata['string'], 0, '', 0, 1, '', '', true, 0, false, true, 0, 'T', false);
  3133. // print an ending header line
  3134. $this->SetLineStyle(array('width' => 0.85 / $this->k, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => $headerdata['line_color']));
  3135. $this->SetY((2.835 / $this->k) + max($imgy, $this->y));
  3136. if ($this->rtl) {
  3137. $this->SetX($this->original_rMargin);
  3138. } else {
  3139. $this->SetX($this->original_lMargin);
  3140. }
  3141. $this->Cell(($this->w - $this->original_lMargin - $this->original_rMargin), 0, '', 'T', 0, 'C');
  3142. $this->endTemplate();
  3143. }
  3144. // print header template
  3145. $x = 0;
  3146. $dx = 0;
  3147. if (!$this->header_xobj_autoreset AND $this->booklet AND (($this->page % 2) == 0)) {
  3148. // adjust margins for booklet mode
  3149. $dx = ($this->original_lMargin - $this->original_rMargin);
  3150. }
  3151. if ($this->rtl) {
  3152. $x = $this->w + $dx;
  3153. } else {
  3154. $x = 0 + $dx;
  3155. }
  3156. $this->printTemplate($this->header_xobjid, $x, 0, 0, 0, '', '', false);
  3157. if ($this->header_xobj_autoreset) {
  3158. // reset header xobject template at each page
  3159. $this->header_xobjid = false;
  3160. }
  3161. }
  3162. /**
  3163. * This method is used to render the page footer.
  3164. * It is automatically called by AddPage() and could be overwritten in your own inherited class.
  3165. * @public
  3166. */
  3167. public function Footer() {
  3168. $cur_y = $this->y;
  3169. $this->SetTextColorArray($this->footer_text_color);
  3170. //set style for cell border
  3171. $line_width = (0.85 / $this->k);
  3172. $this->SetLineStyle(array('width' => $line_width, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => $this->footer_line_color));
  3173. //print document barcode
  3174. $barcode = $this->getBarcode();
  3175. if (!empty($barcode)) {
  3176. $this->Ln($line_width);
  3177. $barcode_width = round(($this->w - $this->original_lMargin - $this->original_rMargin) / 3);
  3178. $style = array(
  3179. 'position' => $this->rtl?'R':'L',
  3180. 'align' => $this->rtl?'R':'L',
  3181. 'stretch' => false,
  3182. 'fitwidth' => true,
  3183. 'cellfitalign' => '',
  3184. 'border' => false,
  3185. 'padding' => 0,
  3186. 'fgcolor' => array(0,0,0),
  3187. 'bgcolor' => false,
  3188. 'text' => false
  3189. );
  3190. $this->write1DBarcode($barcode, 'C128', '', $cur_y + $line_width, '', (($this->footer_margin / 3) - $line_width), 0.3, $style, '');
  3191. }
  3192. $w_page = isset($this->l['w_page']) ? $this->l['w_page'].' ' : '';
  3193. if (empty($this->pagegroups)) {
  3194. $pagenumtxt = $w_page.$this->getAliasNumPage().' / '.$this->getAliasNbPages();
  3195. } else {
  3196. $pagenumtxt = $w_page.$this->getPageNumGroupAlias().' / '.$this->getPageGroupAlias();
  3197. }
  3198. $this->SetY($cur_y);
  3199. //Print page number
  3200. if ($this->getRTL()) {
  3201. $this->SetX($this->original_rMargin);
  3202. $this->Cell(0, 0, $pagenumtxt, 'T', 0, 'L');
  3203. } else {
  3204. $this->SetX($this->original_lMargin);
  3205. $this->Cell(0, 0, $this->getAliasRightShift().$pagenumtxt, 'T', 0, 'R');
  3206. }
  3207. }
  3208. /**
  3209. * This method is used to render the page header.
  3210. * @protected
  3211. * @since 4.0.012 (2008-07-24)
  3212. */
  3213. protected function setHeader() {
  3214. if (!$this->print_header OR ($this->state != 2)) {
  3215. return;
  3216. }
  3217. $this->InHeader = true;
  3218. $this->setGraphicVars($this->default_graphic_vars);
  3219. $temp_thead = $this->thead;
  3220. $temp_theadMargins = $this->theadMargins;
  3221. $lasth = $this->lasth;
  3222. $newline = $this->newline;
  3223. $this->_outSaveGraphicsState();
  3224. $this->rMargin = $this->original_rMargin;
  3225. $this->lMargin = $this->original_lMargin;
  3226. $this->SetCellPadding(0);
  3227. //set current position
  3228. if ($this->rtl) {
  3229. $this->SetXY($this->original_rMargin, $this->header_margin);
  3230. } else {
  3231. $this->SetXY($this->original_lMargin, $this->header_margin);
  3232. }
  3233. $this->SetFont($this->header_font[0], $this->header_font[1], $this->header_font[2]);
  3234. $this->Header();
  3235. //restore position
  3236. if ($this->rtl) {
  3237. $this->SetXY($this->original_rMargin, $this->tMargin);
  3238. } else {
  3239. $this->SetXY($this->original_lMargin, $this->tMargin);
  3240. }
  3241. $this->_outRestoreGraphicsState();
  3242. $this->lasth = $lasth;
  3243. $this->thead = $temp_thead;
  3244. $this->theadMargins = $temp_theadMargins;
  3245. $this->newline = $newline;
  3246. $this->InHeader = false;
  3247. }
  3248. /**
  3249. * This method is used to render the page footer.
  3250. * @protected
  3251. * @since 4.0.012 (2008-07-24)
  3252. */
  3253. protected function setFooter() {
  3254. if ($this->state != 2) {
  3255. return;
  3256. }
  3257. $this->InFooter = true;
  3258. // save current graphic settings
  3259. $gvars = $this->getGraphicVars();
  3260. // mark this point
  3261. $this->footerpos[$this->page] = $this->pagelen[$this->page];
  3262. $this->_out("\n");
  3263. if ($this->print_footer) {
  3264. $this->setGraphicVars($this->default_graphic_vars);
  3265. $this->current_column = 0;
  3266. $this->num_columns = 1;
  3267. $temp_thead = $this->thead;
  3268. $temp_theadMargins = $this->theadMargins;
  3269. $lasth = $this->lasth;
  3270. $this->_outSaveGraphicsState();
  3271. $this->rMargin = $this->original_rMargin;
  3272. $this->lMargin = $this->original_lMargin;
  3273. $this->SetCellPadding(0);
  3274. //set current position
  3275. $footer_y = $this->h - $this->footer_margin;
  3276. if ($this->rtl) {
  3277. $this->SetXY($this->original_rMargin, $footer_y);
  3278. } else {
  3279. $this->SetXY($this->original_lMargin, $footer_y);
  3280. }
  3281. $this->SetFont($this->footer_font[0], $this->footer_font[1], $this->footer_font[2]);
  3282. $this->Footer();
  3283. //restore position
  3284. if ($this->rtl) {
  3285. $this->SetXY($this->original_rMargin, $this->tMargin);
  3286. } else {
  3287. $this->SetXY($this->original_lMargin, $this->tMargin);
  3288. }
  3289. $this->_outRestoreGraphicsState();
  3290. $this->lasth = $lasth;
  3291. $this->thead = $temp_thead;
  3292. $this->theadMargins = $temp_theadMargins;
  3293. }
  3294. // restore graphic settings
  3295. $this->setGraphicVars($gvars);
  3296. $this->current_column = $gvars['current_column'];
  3297. $this->num_columns = $gvars['num_columns'];
  3298. // calculate footer length
  3299. $this->footerlen[$this->page] = $this->pagelen[$this->page] - $this->footerpos[$this->page] + 1;
  3300. $this->InFooter = false;
  3301. }
  3302. /**
  3303. * Check if we are on the page body (excluding page header and footer).
  3304. * @return true if we are not in page header nor in page footer, false otherwise.
  3305. * @protected
  3306. * @since 5.9.091 (2011-06-15)
  3307. */
  3308. protected function inPageBody() {
  3309. return (($this->InHeader === false) AND ($this->InFooter === false));
  3310. }
  3311. /**
  3312. * This method is used to render the table header on new page (if any).
  3313. * @protected
  3314. * @since 4.5.030 (2009-03-25)
  3315. */
  3316. protected function setTableHeader() {
  3317. if ($this->num_columns > 1) {
  3318. // multi column mode
  3319. return;
  3320. }
  3321. if (isset($this->theadMargins['top'])) {
  3322. // restore the original top-margin
  3323. $this->tMargin = $this->theadMargins['top'];
  3324. $this->pagedim[$this->page]['tm'] = $this->tMargin;
  3325. $this->y = $this->tMargin;
  3326. }
  3327. if (!TCPDF_STATIC::empty_string($this->thead) AND (!$this->inthead)) {
  3328. // set margins
  3329. $prev_lMargin = $this->lMargin;
  3330. $prev_rMargin = $this->rMargin;
  3331. $prev_cell_padding = $this->cell_padding;
  3332. $this->lMargin = $this->theadMargins['lmargin'] + ($this->pagedim[$this->page]['olm'] - $this->pagedim[$this->theadMargins['page']]['olm']);
  3333. $this->rMargin = $this->theadMargins['rmargin'] + ($this->pagedim[$this->page]['orm'] - $this->pagedim[$this->theadMargins['page']]['orm']);
  3334. $this->cell_padding = $this->theadMargins['cell_padding'];
  3335. if ($this->rtl) {
  3336. $this->x = $this->w - $this->rMargin;
  3337. } else {
  3338. $this->x = $this->lMargin;
  3339. }
  3340. // account for special "cell" mode
  3341. if ($this->theadMargins['cell']) {
  3342. if ($this->rtl) {
  3343. $this->x -= $this->cell_padding['R'];
  3344. } else {
  3345. $this->x += $this->cell_padding['L'];
  3346. }
  3347. }
  3348. $gvars = $this->getGraphicVars();
  3349. if (!empty($this->theadMargins['gvars'])) {
  3350. // set the correct graphic style
  3351. $this->setGraphicVars($this->theadMargins['gvars']);
  3352. $this->rMargin = $gvars['rMargin'];
  3353. $this->lMargin = $gvars['lMargin'];
  3354. }
  3355. // print table header
  3356. $this->writeHTML($this->thead, false, false, false, false, '');
  3357. $this->setGraphicVars($gvars);
  3358. // set new top margin to skip the table headers
  3359. if (!isset($this->theadMargins['top'])) {
  3360. $this->theadMargins['top'] = $this->tMargin;
  3361. }
  3362. // store end of header position
  3363. if (!isset($this->columns[0]['th'])) {
  3364. $this->columns[0]['th'] = array();
  3365. }
  3366. $this->columns[0]['th']['\''.$this->page.'\''] = $this->y;
  3367. $this->tMargin = $this->y;
  3368. $this->pagedim[$this->page]['tm'] = $this->tMargin;
  3369. $this->lasth = 0;
  3370. $this->lMargin = $prev_lMargin;
  3371. $this->rMargin = $prev_rMargin;
  3372. $this->cell_padding = $prev_cell_padding;
  3373. }
  3374. }
  3375. /**
  3376. * Returns the current page number.
  3377. * @return int page number
  3378. * @public
  3379. * @since 1.0
  3380. * @see getAliasNbPages()
  3381. */
  3382. public function PageNo() {
  3383. return $this->page;
  3384. }
  3385. /**
  3386. * Returns the array of spot colors.
  3387. * @return (array) Spot colors array.
  3388. * @public
  3389. * @since 6.0.038 (2013-09-30)
  3390. */
  3391. public function getAllSpotColors() {
  3392. return $this->spot_colors;
  3393. }
  3394. /**
  3395. * Defines a new spot color.
  3396. * It can be expressed in RGB components or gray scale.
  3397. * The method can be called before the first page is created and the value is retained from page to page.
  3398. * @param $name (string) Full name of the spot color.
  3399. * @param $c (float) Cyan color for CMYK. Value between 0 and 100.
  3400. * @param $m (float) Magenta color for CMYK. Value between 0 and 100.
  3401. * @param $y (float) Yellow color for CMYK. Value between 0 and 100.
  3402. * @param $k (float) Key (Black) color for CMYK. Value between 0 and 100.
  3403. * @public
  3404. * @since 4.0.024 (2008-09-12)
  3405. * @see SetDrawSpotColor(), SetFillSpotColor(), SetTextSpotColor()
  3406. */
  3407. public function AddSpotColor($name, $c, $m, $y, $k) {
  3408. if (!isset($this->spot_colors[$name])) {
  3409. $i = (1 + count($this->spot_colors));
  3410. $this->spot_colors[$name] = array('C' => $c, 'M' => $m, 'Y' => $y, 'K' => $k, 'name' => $name, 'i' => $i);
  3411. }
  3412. }
  3413. /**
  3414. * Set the spot color for the specified type ('draw', 'fill', 'text').
  3415. * @param $type (string) Type of object affected by this color: ('draw', 'fill', 'text').
  3416. * @param $name (string) Name of the spot color.
  3417. * @param $tint (float) Intensity of the color (from 0 to 100 ; 100 = full intensity by default).
  3418. * @return (string) PDF color command.
  3419. * @public
  3420. * @since 5.9.125 (2011-10-03)
  3421. */
  3422. public function setSpotColor($type, $name, $tint=100) {
  3423. $spotcolor = TCPDF_COLORS::getSpotColor($name, $this->spot_colors);
  3424. if ($spotcolor === false) {
  3425. $this->Error('Undefined spot color: '.$name.', you must add it using the AddSpotColor() method.');
  3426. }
  3427. $tint = (max(0, min(100, $tint)) / 100);
  3428. $pdfcolor = sprintf('/CS%d ', $this->spot_colors[$name]['i']);
  3429. switch ($type) {
  3430. case 'draw': {
  3431. $pdfcolor .= sprintf('CS %F SCN', $tint);
  3432. $this->DrawColor = $pdfcolor;
  3433. $this->strokecolor = $spotcolor;
  3434. break;
  3435. }
  3436. case 'fill': {
  3437. $pdfcolor .= sprintf('cs %F scn', $tint);
  3438. $this->FillColor = $pdfcolor;
  3439. $this->bgcolor = $spotcolor;
  3440. break;
  3441. }
  3442. case 'text': {
  3443. $pdfcolor .= sprintf('cs %F scn', $tint);
  3444. $this->TextColor = $pdfcolor;
  3445. $this->fgcolor = $spotcolor;
  3446. break;
  3447. }
  3448. }
  3449. $this->ColorFlag = ($this->FillColor != $this->TextColor);
  3450. if ($this->state == 2) {
  3451. $this->_out($pdfcolor);
  3452. }
  3453. if ($this->inxobj) {
  3454. // we are inside an XObject template
  3455. $this->xobjects[$this->xobjid]['spot_colors'][$name] = $this->spot_colors[$name];
  3456. }
  3457. return $pdfcolor;
  3458. }
  3459. /**
  3460. * Defines the spot color used for all drawing operations (lines, rectangles and cell borders).
  3461. * @param $name (string) Name of the spot color.
  3462. * @param $tint (float) Intensity of the color (from 0 to 100 ; 100 = full intensity by default).
  3463. * @public
  3464. * @since 4.0.024 (2008-09-12)
  3465. * @see AddSpotColor(), SetFillSpotColor(), SetTextSpotColor()
  3466. */
  3467. public function SetDrawSpotColor($name, $tint=100) {
  3468. $this->setSpotColor('draw', $name, $tint);
  3469. }
  3470. /**
  3471. * Defines the spot color used for all filling operations (filled rectangles and cell backgrounds).
  3472. * @param $name (string) Name of the spot color.
  3473. * @param $tint (float) Intensity of the color (from 0 to 100 ; 100 = full intensity by default).
  3474. * @public
  3475. * @since 4.0.024 (2008-09-12)
  3476. * @see AddSpotColor(), SetDrawSpotColor(), SetTextSpotColor()
  3477. */
  3478. public function SetFillSpotColor($name, $tint=100) {
  3479. $this->setSpotColor('fill', $name, $tint);
  3480. }
  3481. /**
  3482. * Defines the spot color used for text.
  3483. * @param $name (string) Name of the spot color.
  3484. * @param $tint (int) Intensity of the color (from 0 to 100 ; 100 = full intensity by default).
  3485. * @public
  3486. * @since 4.0.024 (2008-09-12)
  3487. * @see AddSpotColor(), SetDrawSpotColor(), SetFillSpotColor()
  3488. */
  3489. public function SetTextSpotColor($name, $tint=100) {
  3490. $this->setSpotColor('text', $name, $tint);
  3491. }
  3492. /**
  3493. * Set the color array for the specified type ('draw', 'fill', 'text').
  3494. * It can be expressed in RGB, CMYK or GRAY SCALE components.
  3495. * The method can be called before the first page is created and the value is retained from page to page.
  3496. * @param $type (string) Type of object affected by this color: ('draw', 'fill', 'text').
  3497. * @param $color (array) Array of colors (1=gray, 3=RGB, 4=CMYK or 5=spotcolor=CMYK+name values).
  3498. * @param $ret (boolean) If true do not send the PDF command.
  3499. * @return (string) The PDF command or empty string.
  3500. * @public
  3501. * @since 3.1.000 (2008-06-11)
  3502. */
  3503. public function setColorArray($type, $color, $ret=false) {
  3504. if (is_array($color)) {
  3505. $color = array_values($color);
  3506. // component: grey, RGB red or CMYK cyan
  3507. $c = isset($color[0]) ? $color[0] : -1;
  3508. // component: RGB green or CMYK magenta
  3509. $m = isset($color[1]) ? $color[1] : -1;
  3510. // component: RGB blue or CMYK yellow
  3511. $y = isset($color[2]) ? $color[2] : -1;
  3512. // component: CMYK black
  3513. $k = isset($color[3]) ? $color[3] : -1;
  3514. // color name
  3515. $name = isset($color[4]) ? $color[4] : '';
  3516. if ($c >= 0) {
  3517. return $this->setColor($type, $c, $m, $y, $k, $ret, $name);
  3518. }
  3519. }
  3520. return '';
  3521. }
  3522. /**
  3523. * Defines the color used for all drawing operations (lines, rectangles and cell borders).
  3524. * It can be expressed in RGB, CMYK or GRAY SCALE components.
  3525. * The method can be called before the first page is created and the value is retained from page to page.
  3526. * @param $color (array) Array of colors (1, 3 or 4 values).
  3527. * @param $ret (boolean) If true do not send the PDF command.
  3528. * @return string the PDF command
  3529. * @public
  3530. * @since 3.1.000 (2008-06-11)
  3531. * @see SetDrawColor()
  3532. */
  3533. public function SetDrawColorArray($color, $ret=false) {
  3534. return $this->setColorArray('draw', $color, $ret);
  3535. }
  3536. /**
  3537. * Defines the color used for all filling operations (filled rectangles and cell backgrounds).
  3538. * It can be expressed in RGB, CMYK or GRAY SCALE components.
  3539. * The method can be called before the first page is created and the value is retained from page to page.
  3540. * @param $color (array) Array of colors (1, 3 or 4 values).
  3541. * @param $ret (boolean) If true do not send the PDF command.
  3542. * @public
  3543. * @since 3.1.000 (2008-6-11)
  3544. * @see SetFillColor()
  3545. */
  3546. public function SetFillColorArray($color, $ret=false) {
  3547. return $this->setColorArray('fill', $color, $ret);
  3548. }
  3549. /**
  3550. * Defines the color used for text. It can be expressed in RGB components or gray scale.
  3551. * The method can be called before the first page is created and the value is retained from page to page.
  3552. * @param $color (array) Array of colors (1, 3 or 4 values).
  3553. * @param $ret (boolean) If true do not send the PDF command.
  3554. * @public
  3555. * @since 3.1.000 (2008-6-11)
  3556. * @see SetFillColor()
  3557. */
  3558. public function SetTextColorArray($color, $ret=false) {
  3559. return $this->setColorArray('text', $color, $ret);
  3560. }
  3561. /**
  3562. * Defines the color used by the specified type ('draw', 'fill', 'text').
  3563. * @param $type (string) Type of object affected by this color: ('draw', 'fill', 'text').
  3564. * @param $col1 (float) GRAY level for single color, or Red color for RGB (0-255), or CYAN color for CMYK (0-100).
  3565. * @param $col2 (float) GREEN color for RGB (0-255), or MAGENTA color for CMYK (0-100).
  3566. * @param $col3 (float) BLUE color for RGB (0-255), or YELLOW color for CMYK (0-100).
  3567. * @param $col4 (float) KEY (BLACK) color for CMYK (0-100).
  3568. * @param $ret (boolean) If true do not send the command.
  3569. * @param $name (string) spot color name (if any)
  3570. * @return (string) The PDF command or empty string.
  3571. * @public
  3572. * @since 5.9.125 (2011-10-03)
  3573. */
  3574. public function setColor($type, $col1=0, $col2=-1, $col3=-1, $col4=-1, $ret=false, $name='') {
  3575. // set default values
  3576. if (!is_numeric($col1)) {
  3577. $col1 = 0;
  3578. }
  3579. if (!is_numeric($col2)) {
  3580. $col2 = -1;
  3581. }
  3582. if (!is_numeric($col3)) {
  3583. $col3 = -1;
  3584. }
  3585. if (!is_numeric($col4)) {
  3586. $col4 = -1;
  3587. }
  3588. // set color by case
  3589. $suffix = '';
  3590. if (($col2 == -1) AND ($col3 == -1) AND ($col4 == -1)) {
  3591. // Grey scale
  3592. $col1 = max(0, min(255, $col1));
  3593. $intcolor = array('G' => $col1);
  3594. $pdfcolor = sprintf('%F ', ($col1 / 255));
  3595. $suffix = 'g';
  3596. } elseif ($col4 == -1) {
  3597. // RGB
  3598. $col1 = max(0, min(255, $col1));
  3599. $col2 = max(0, min(255, $col2));
  3600. $col3 = max(0, min(255, $col3));
  3601. $intcolor = array('R' => $col1, 'G' => $col2, 'B' => $col3);
  3602. $pdfcolor = sprintf('%F %F %F ', ($col1 / 255), ($col2 / 255), ($col3 / 255));
  3603. $suffix = 'rg';
  3604. } else {
  3605. $col1 = max(0, min(100, $col1));
  3606. $col2 = max(0, min(100, $col2));
  3607. $col3 = max(0, min(100, $col3));
  3608. $col4 = max(0, min(100, $col4));
  3609. if (empty($name)) {
  3610. // CMYK
  3611. $intcolor = array('C' => $col1, 'M' => $col2, 'Y' => $col3, 'K' => $col4);
  3612. $pdfcolor = sprintf('%F %F %F %F ', ($col1 / 100), ($col2 / 100), ($col3 / 100), ($col4 / 100));
  3613. $suffix = 'k';
  3614. } else {
  3615. // SPOT COLOR
  3616. $intcolor = array('C' => $col1, 'M' => $col2, 'Y' => $col3, 'K' => $col4, 'name' => $name);
  3617. $this->AddSpotColor($name, $col1, $col2, $col3, $col4);
  3618. $pdfcolor = $this->setSpotColor($type, $name, 100);
  3619. }
  3620. }
  3621. switch ($type) {
  3622. case 'draw': {
  3623. $pdfcolor .= strtoupper($suffix);
  3624. $this->DrawColor = $pdfcolor;
  3625. $this->strokecolor = $intcolor;
  3626. break;
  3627. }
  3628. case 'fill': {
  3629. $pdfcolor .= $suffix;
  3630. $this->FillColor = $pdfcolor;
  3631. $this->bgcolor = $intcolor;
  3632. break;
  3633. }
  3634. case 'text': {
  3635. $pdfcolor .= $suffix;
  3636. $this->TextColor = $pdfcolor;
  3637. $this->fgcolor = $intcolor;
  3638. break;
  3639. }
  3640. }
  3641. $this->ColorFlag = ($this->FillColor != $this->TextColor);
  3642. if (($type != 'text') AND ($this->state == 2)) {
  3643. if (!$ret) {
  3644. $this->_out($pdfcolor);
  3645. }
  3646. return $pdfcolor;
  3647. }
  3648. return '';
  3649. }
  3650. /**
  3651. * Defines the color used for all drawing operations (lines, rectangles and cell borders). It can be expressed in RGB components or gray scale. The method can be called before the first page is created and the value is retained from page to page.
  3652. * @param $col1 (float) GRAY level for single color, or Red color for RGB (0-255), or CYAN color for CMYK (0-100).
  3653. * @param $col2 (float) GREEN color for RGB (0-255), or MAGENTA color for CMYK (0-100).
  3654. * @param $col3 (float) BLUE color for RGB (0-255), or YELLOW color for CMYK (0-100).
  3655. * @param $col4 (float) KEY (BLACK) color for CMYK (0-100).
  3656. * @param $ret (boolean) If true do not send the command.
  3657. * @param $name (string) spot color name (if any)
  3658. * @return string the PDF command
  3659. * @public
  3660. * @since 1.3
  3661. * @see SetDrawColorArray(), SetFillColor(), SetTextColor(), Line(), Rect(), Cell(), MultiCell()
  3662. */
  3663. public function SetDrawColor($col1=0, $col2=-1, $col3=-1, $col4=-1, $ret=false, $name='') {
  3664. return $this->setColor('draw', $col1, $col2, $col3, $col4, $ret, $name);
  3665. }
  3666. /**
  3667. * Defines the color used for all filling operations (filled rectangles and cell backgrounds). It can be expressed in RGB components or gray scale. The method can be called before the first page is created and the value is retained from page to page.
  3668. * @param $col1 (float) GRAY level for single color, or Red color for RGB (0-255), or CYAN color for CMYK (0-100).
  3669. * @param $col2 (float) GREEN color for RGB (0-255), or MAGENTA color for CMYK (0-100).
  3670. * @param $col3 (float) BLUE color for RGB (0-255), or YELLOW color for CMYK (0-100).
  3671. * @param $col4 (float) KEY (BLACK) color for CMYK (0-100).
  3672. * @param $ret (boolean) If true do not send the command.
  3673. * @param $name (string) Spot color name (if any).
  3674. * @return (string) The PDF command.
  3675. * @public
  3676. * @since 1.3
  3677. * @see SetFillColorArray(), SetDrawColor(), SetTextColor(), Rect(), Cell(), MultiCell()
  3678. */
  3679. public function SetFillColor($col1=0, $col2=-1, $col3=-1, $col4=-1, $ret=false, $name='') {
  3680. return $this->setColor('fill', $col1, $col2, $col3, $col4, $ret, $name);
  3681. }
  3682. /**
  3683. * Defines the color used for text. It can be expressed in RGB components or gray scale. The method can be called before the first page is created and the value is retained from page to page.
  3684. * @param $col1 (float) GRAY level for single color, or Red color for RGB (0-255), or CYAN color for CMYK (0-100).
  3685. * @param $col2 (float) GREEN color for RGB (0-255), or MAGENTA color for CMYK (0-100).
  3686. * @param $col3 (float) BLUE color for RGB (0-255), or YELLOW color for CMYK (0-100).
  3687. * @param $col4 (float) KEY (BLACK) color for CMYK (0-100).
  3688. * @param $ret (boolean) If true do not send the command.
  3689. * @param $name (string) Spot color name (if any).
  3690. * @return (string) Empty string.
  3691. * @public
  3692. * @since 1.3
  3693. * @see SetTextColorArray(), SetDrawColor(), SetFillColor(), Text(), Cell(), MultiCell()
  3694. */
  3695. public function SetTextColor($col1=0, $col2=-1, $col3=-1, $col4=-1, $ret=false, $name='') {
  3696. return $this->setColor('text', $col1, $col2, $col3, $col4, $ret, $name);
  3697. }
  3698. /**
  3699. * Returns the length of a string in user unit. A font must be selected.<br>
  3700. * @param $s (string) The string whose length is to be computed
  3701. * @param $fontname (string) Family font. It can be either a name defined by AddFont() or one of the standard families. It is also possible to pass an empty string, in that case, the current family is retained.
  3702. * @param $fontstyle (string) Font style. Possible values are (case insensitive):<ul><li>empty string: regular</li><li>B: bold</li><li>I: italic</li><li>U: underline</li><li>D: line-through</li><li>O: overline</li></ul> or any combination. The default value is regular.
  3703. * @param $fontsize (float) Font size in points. The default value is the current size.
  3704. * @param $getarray (boolean) if true returns an array of characters widths, if false returns the total length.
  3705. * @return mixed int total string length or array of characted widths
  3706. * @author Nicola Asuni
  3707. * @public
  3708. * @since 1.2
  3709. */
  3710. public function GetStringWidth($s, $fontname='', $fontstyle='', $fontsize=0, $getarray=false) {
  3711. return $this->GetArrStringWidth(TCPDF_FONTS::utf8Bidi(TCPDF_FONTS::UTF8StringToArray($s, $this->isunicode, $this->CurrentFont), $s, $this->tmprtl, $this->isunicode, $this->CurrentFont), $fontname, $fontstyle, $fontsize, $getarray);
  3712. }
  3713. /**
  3714. * Returns the string length of an array of chars in user unit or an array of characters widths. A font must be selected.<br>
  3715. * @param $sa (string) The array of chars whose total length is to be computed
  3716. * @param $fontname (string) Family font. It can be either a name defined by AddFont() or one of the standard families. It is also possible to pass an empty string, in that case, the current family is retained.
  3717. * @param $fontstyle (string) Font style. Possible values are (case insensitive):<ul><li>empty string: regular</li><li>B: bold</li><li>I: italic</li><li>U: underline</li><li>D: line through</li><li>O: overline</li></ul> or any combination. The default value is regular.
  3718. * @param $fontsize (float) Font size in points. The default value is the current size.
  3719. * @param $getarray (boolean) if true returns an array of characters widths, if false returns the total length.
  3720. * @return mixed int total string length or array of characted widths
  3721. * @author Nicola Asuni
  3722. * @public
  3723. * @since 2.4.000 (2008-03-06)
  3724. */
  3725. public function GetArrStringWidth($sa, $fontname='', $fontstyle='', $fontsize=0, $getarray=false) {
  3726. // store current values
  3727. if (!TCPDF_STATIC::empty_string($fontname)) {
  3728. $prev_FontFamily = $this->FontFamily;
  3729. $prev_FontStyle = $this->FontStyle;
  3730. $prev_FontSizePt = $this->FontSizePt;
  3731. $this->SetFont($fontname, $fontstyle, $fontsize, '', 'default', false);
  3732. }
  3733. // convert UTF-8 array to Latin1 if required
  3734. if ($this->isunicode AND (!$this->isUnicodeFont())) {
  3735. $sa = TCPDF_FONTS::UTF8ArrToLatin1Arr($sa);
  3736. }
  3737. $w = 0; // total width
  3738. $wa = array(); // array of characters widths
  3739. foreach ($sa as $ck => $char) {
  3740. // character width
  3741. $cw = $this->GetCharWidth($char, isset($sa[($ck + 1)]));
  3742. $wa[] = $cw;
  3743. $w += $cw;
  3744. }
  3745. // restore previous values
  3746. if (!TCPDF_STATIC::empty_string($fontname)) {
  3747. $this->SetFont($prev_FontFamily, $prev_FontStyle, $prev_FontSizePt, '', 'default', false);
  3748. }
  3749. if ($getarray) {
  3750. return $wa;
  3751. }
  3752. return $w;
  3753. }
  3754. /**
  3755. * Returns the length of the char in user unit for the current font considering current stretching and spacing (tracking).
  3756. * @param $char (int) The char code whose length is to be returned
  3757. * @param $notlast (boolean) If false ignore the font-spacing.
  3758. * @return float char width
  3759. * @author Nicola Asuni
  3760. * @public
  3761. * @since 2.4.000 (2008-03-06)
  3762. */
  3763. public function GetCharWidth($char, $notlast=true) {
  3764. // get raw width
  3765. $chw = $this->getRawCharWidth($char);
  3766. if (($this->font_spacing < 0) OR (($this->font_spacing > 0) AND $notlast)) {
  3767. // increase/decrease font spacing
  3768. $chw += $this->font_spacing;
  3769. }
  3770. if ($this->font_stretching != 100) {
  3771. // fixed stretching mode
  3772. $chw *= ($this->font_stretching / 100);
  3773. }
  3774. return $chw;
  3775. }
  3776. /**
  3777. * Returns the length of the char in user unit for the current font.
  3778. * @param $char (int) The char code whose length is to be returned
  3779. * @return float char width
  3780. * @author Nicola Asuni
  3781. * @public
  3782. * @since 5.9.000 (2010-09-28)
  3783. */
  3784. public function getRawCharWidth($char) {
  3785. if ($char == 173) {
  3786. // SHY character will not be printed
  3787. return (0);
  3788. }
  3789. if (isset($this->CurrentFont['cw'][$char])) {
  3790. $w = $this->CurrentFont['cw'][$char];
  3791. } elseif (isset($this->CurrentFont['dw'])) {
  3792. // default width
  3793. $w = $this->CurrentFont['dw'];
  3794. } elseif (isset($this->CurrentFont['cw'][32])) {
  3795. // default width
  3796. $w = $this->CurrentFont['cw'][32];
  3797. } else {
  3798. $w = 600;
  3799. }
  3800. return $this->getAbsFontMeasure($w);
  3801. }
  3802. /**
  3803. * Returns the numbero of characters in a string.
  3804. * @param $s (string) The input string.
  3805. * @return int number of characters
  3806. * @public
  3807. * @since 2.0.0001 (2008-01-07)
  3808. */
  3809. public function GetNumChars($s) {
  3810. if ($this->isUnicodeFont()) {
  3811. return count(TCPDF_FONTS::UTF8StringToArray($s, $this->isunicode, $this->CurrentFont));
  3812. }
  3813. return strlen($s);
  3814. }
  3815. /**
  3816. * Fill the list of available fonts ($this->fontlist).
  3817. * @protected
  3818. * @since 4.0.013 (2008-07-28)
  3819. */
  3820. protected function getFontsList() {
  3821. if (($fontsdir = opendir(TCPDF_FONTS::_getfontpath())) !== false) {
  3822. while (($file = readdir($fontsdir)) !== false) {
  3823. if (substr($file, -4) == '.php') {
  3824. array_push($this->fontlist, strtolower(basename($file, '.php')));
  3825. }
  3826. }
  3827. closedir($fontsdir);
  3828. }
  3829. }
  3830. /**
  3831. * Imports a TrueType, Type1, core, or CID0 font and makes it available.
  3832. * It is necessary to generate a font definition file first (read /fonts/utils/README.TXT).
  3833. * The definition file (and the font file itself when embedding) must be present either in the current directory or in the one indicated by K_PATH_FONTS if the constant is defined. If it could not be found, the error "Could not include font definition file" is generated.
  3834. * @param $family (string) Font family. The name can be chosen arbitrarily. If it is a standard family name, it will override the corresponding font.
  3835. * @param $style (string) Font style. Possible values are (case insensitive):<ul><li>empty string: regular (default)</li><li>B: bold</li><li>I: italic</li><li>BI or IB: bold italic</li></ul>
  3836. * @param $fontfile (string) The font definition file. By default, the name is built from the family and style, in lower case with no spaces.
  3837. * @return array containing the font data, or false in case of error.
  3838. * @param $subset (mixed) if true embedd only a subset of the font (stores only the information related to the used characters); if false embedd full font; if 'default' uses the default value set using setFontSubsetting(). This option is valid only for TrueTypeUnicode fonts. If you want to enable users to change the document, set this parameter to false. If you subset the font, the person who receives your PDF would need to have your same font in order to make changes to your PDF. The file size of the PDF would also be smaller because you are embedding only part of a font.
  3839. * @public
  3840. * @since 1.5
  3841. * @see SetFont(), setFontSubsetting()
  3842. */
  3843. public function AddFont($family, $style='', $fontfile='', $subset='default') {
  3844. if ($subset === 'default') {
  3845. $subset = $this->font_subsetting;
  3846. }
  3847. if ($this->pdfa_mode) {
  3848. $subset = false;
  3849. }
  3850. if (TCPDF_STATIC::empty_string($family)) {
  3851. if (!TCPDF_STATIC::empty_string($this->FontFamily)) {
  3852. $family = $this->FontFamily;
  3853. } else {
  3854. $this->Error('Empty font family');
  3855. }
  3856. }
  3857. // move embedded styles on $style
  3858. if (substr($family, -1) == 'I') {
  3859. $style .= 'I';
  3860. $family = substr($family, 0, -1);
  3861. }
  3862. if (substr($family, -1) == 'B') {
  3863. $style .= 'B';
  3864. $family = substr($family, 0, -1);
  3865. }
  3866. // normalize family name
  3867. $family = strtolower($family);
  3868. if ((!$this->isunicode) AND ($family == 'arial')) {
  3869. $family = 'helvetica';
  3870. }
  3871. if (($family == 'symbol') OR ($family == 'zapfdingbats')) {
  3872. $style = '';
  3873. }
  3874. if ($this->pdfa_mode AND (isset($this->CoreFonts[$family]))) {
  3875. // all fonts must be embedded
  3876. $family = 'pdfa'.$family;
  3877. }
  3878. $tempstyle = strtoupper($style);
  3879. $style = '';
  3880. // underline
  3881. if (strpos($tempstyle, 'U') !== false) {
  3882. $this->underline = true;
  3883. } else {
  3884. $this->underline = false;
  3885. }
  3886. // line-through (deleted)
  3887. if (strpos($tempstyle, 'D') !== false) {
  3888. $this->linethrough = true;
  3889. } else {
  3890. $this->linethrough = false;
  3891. }
  3892. // overline
  3893. if (strpos($tempstyle, 'O') !== false) {
  3894. $this->overline = true;
  3895. } else {
  3896. $this->overline = false;
  3897. }
  3898. // bold
  3899. if (strpos($tempstyle, 'B') !== false) {
  3900. $style .= 'B';
  3901. }
  3902. // oblique
  3903. if (strpos($tempstyle, 'I') !== false) {
  3904. $style .= 'I';
  3905. }
  3906. $bistyle = $style;
  3907. $fontkey = $family.$style;
  3908. $font_style = $style.($this->underline ? 'U' : '').($this->linethrough ? 'D' : '').($this->overline ? 'O' : '');
  3909. $fontdata = array('fontkey' => $fontkey, 'family' => $family, 'style' => $font_style);
  3910. // check if the font has been already added
  3911. $fb = $this->getFontBuffer($fontkey);
  3912. if ($fb !== false) {
  3913. if ($this->inxobj) {
  3914. // we are inside an XObject template
  3915. $this->xobjects[$this->xobjid]['fonts'][$fontkey] = $fb['i'];
  3916. }
  3917. return $fontdata;
  3918. }
  3919. // get specified font directory (if any)
  3920. $fontdir = false;
  3921. if (!TCPDF_STATIC::empty_string($fontfile)) {
  3922. $fontdir = dirname($fontfile);
  3923. if (TCPDF_STATIC::empty_string($fontdir) OR ($fontdir == '.')) {
  3924. $fontdir = '';
  3925. } else {
  3926. $fontdir .= '/';
  3927. }
  3928. }
  3929. // true when the font style variation is missing
  3930. $missing_style = false;
  3931. // search and include font file
  3932. if (TCPDF_STATIC::empty_string($fontfile) OR (!@TCPDF_STATIC::file_exists($fontfile))) {
  3933. // build a standard filenames for specified font
  3934. $tmp_fontfile = str_replace(' ', '', $family).strtolower($style).'.php';
  3935. $fontfile = TCPDF_FONTS::getFontFullPath($tmp_fontfile, $fontdir);
  3936. if (TCPDF_STATIC::empty_string($fontfile)) {
  3937. $missing_style = true;
  3938. // try to remove the style part
  3939. $tmp_fontfile = str_replace(' ', '', $family).'.php';
  3940. $fontfile = TCPDF_FONTS::getFontFullPath($tmp_fontfile, $fontdir);
  3941. }
  3942. }
  3943. // include font file
  3944. if (!TCPDF_STATIC::empty_string($fontfile) AND (@TCPDF_STATIC::file_exists($fontfile))) {
  3945. include($fontfile);
  3946. } else {
  3947. $this->Error('Could not include font definition file: '.$family.'');
  3948. }
  3949. // check font parameters
  3950. if ((!isset($type)) OR (!isset($cw))) {
  3951. $this->Error('The font definition file has a bad format: '.$fontfile.'');
  3952. }
  3953. // SET default parameters
  3954. if (!isset($file) OR TCPDF_STATIC::empty_string($file)) {
  3955. $file = '';
  3956. }
  3957. if (!isset($enc) OR TCPDF_STATIC::empty_string($enc)) {
  3958. $enc = '';
  3959. }
  3960. if (!isset($cidinfo) OR TCPDF_STATIC::empty_string($cidinfo)) {
  3961. $cidinfo = array('Registry'=>'Adobe', 'Ordering'=>'Identity', 'Supplement'=>0);
  3962. $cidinfo['uni2cid'] = array();
  3963. }
  3964. if (!isset($ctg) OR TCPDF_STATIC::empty_string($ctg)) {
  3965. $ctg = '';
  3966. }
  3967. if (!isset($desc) OR TCPDF_STATIC::empty_string($desc)) {
  3968. $desc = array();
  3969. }
  3970. if (!isset($up) OR TCPDF_STATIC::empty_string($up)) {
  3971. $up = -100;
  3972. }
  3973. if (!isset($ut) OR TCPDF_STATIC::empty_string($ut)) {
  3974. $ut = 50;
  3975. }
  3976. if (!isset($cw) OR TCPDF_STATIC::empty_string($cw)) {
  3977. $cw = array();
  3978. }
  3979. if (!isset($dw) OR TCPDF_STATIC::empty_string($dw)) {
  3980. // set default width
  3981. if (isset($desc['MissingWidth']) AND ($desc['MissingWidth'] > 0)) {
  3982. $dw = $desc['MissingWidth'];
  3983. } elseif (isset($cw[32])) {
  3984. $dw = $cw[32];
  3985. } else {
  3986. $dw = 600;
  3987. }
  3988. }
  3989. ++$this->numfonts;
  3990. if ($type == 'core') {
  3991. $name = $this->CoreFonts[$fontkey];
  3992. $subset = false;
  3993. } elseif (($type == 'TrueType') OR ($type == 'Type1')) {
  3994. $subset = false;
  3995. } elseif ($type == 'TrueTypeUnicode') {
  3996. $enc = 'Identity-H';
  3997. } elseif ($type == 'cidfont0') {
  3998. if ($this->pdfa_mode) {
  3999. $this->Error('All fonts must be embedded in PDF/A mode!');
  4000. }
  4001. } else {
  4002. $this->Error('Unknow font type: '.$type.'');
  4003. }
  4004. // set name if unset
  4005. if (!isset($name) OR empty($name)) {
  4006. $name = $fontkey;
  4007. }
  4008. // create artificial font style variations if missing (only works with non-embedded fonts)
  4009. if (($type != 'core') AND $missing_style) {
  4010. // style variations
  4011. $styles = array('' => '', 'B' => ',Bold', 'I' => ',Italic', 'BI' => ',BoldItalic');
  4012. $name .= $styles[$bistyle];
  4013. // artificial bold
  4014. if (strpos($bistyle, 'B') !== false) {
  4015. if (isset($desc['StemV'])) {
  4016. // from normal to bold
  4017. $desc['StemV'] = round($desc['StemV'] * 1.75);
  4018. } else {
  4019. // bold
  4020. $desc['StemV'] = 123;
  4021. }
  4022. }
  4023. // artificial italic
  4024. if (strpos($bistyle, 'I') !== false) {
  4025. if (isset($desc['ItalicAngle'])) {
  4026. $desc['ItalicAngle'] -= 11;
  4027. } else {
  4028. $desc['ItalicAngle'] = -11;
  4029. }
  4030. if (isset($desc['Flags'])) {
  4031. $desc['Flags'] |= 64; //bit 7
  4032. } else {
  4033. $desc['Flags'] = 64;
  4034. }
  4035. }
  4036. }
  4037. // check if the array of characters bounding boxes is defined
  4038. if (!isset($cbbox)) {
  4039. $cbbox = array();
  4040. }
  4041. // initialize subsetchars
  4042. $subsetchars = array_fill(0, 255, true);
  4043. $this->setFontBuffer($fontkey, array('fontkey' => $fontkey, 'i' => $this->numfonts, 'type' => $type, 'name' => $name, 'desc' => $desc, 'up' => $up, 'ut' => $ut, 'cw' => $cw, 'cbbox' => $cbbox, 'dw' => $dw, 'enc' => $enc, 'cidinfo' => $cidinfo, 'file' => $file, 'ctg' => $ctg, 'subset' => $subset, 'subsetchars' => $subsetchars));
  4044. if ($this->inxobj) {
  4045. // we are inside an XObject template
  4046. $this->xobjects[$this->xobjid]['fonts'][$fontkey] = $this->numfonts;
  4047. }
  4048. if (isset($diff) AND (!empty($diff))) {
  4049. //Search existing encodings
  4050. $d = 0;
  4051. $nb = count($this->diffs);
  4052. for ($i=1; $i <= $nb; ++$i) {
  4053. if ($this->diffs[$i] == $diff) {
  4054. $d = $i;
  4055. break;
  4056. }
  4057. }
  4058. if ($d == 0) {
  4059. $d = $nb + 1;
  4060. $this->diffs[$d] = $diff;
  4061. }
  4062. $this->setFontSubBuffer($fontkey, 'diff', $d);
  4063. }
  4064. if (!TCPDF_STATIC::empty_string($file)) {
  4065. if (!isset($this->FontFiles[$file])) {
  4066. if ((strcasecmp($type,'TrueType') == 0) OR (strcasecmp($type, 'TrueTypeUnicode') == 0)) {
  4067. $this->FontFiles[$file] = array('length1' => $originalsize, 'fontdir' => $fontdir, 'subset' => $subset, 'fontkeys' => array($fontkey));
  4068. } elseif ($type != 'core') {
  4069. $this->FontFiles[$file] = array('length1' => $size1, 'length2' => $size2, 'fontdir' => $fontdir, 'subset' => $subset, 'fontkeys' => array($fontkey));
  4070. }
  4071. } else {
  4072. // update fontkeys that are sharing this font file
  4073. $this->FontFiles[$file]['subset'] = ($this->FontFiles[$file]['subset'] AND $subset);
  4074. if (!in_array($fontkey, $this->FontFiles[$file]['fontkeys'])) {
  4075. $this->FontFiles[$file]['fontkeys'][] = $fontkey;
  4076. }
  4077. }
  4078. }
  4079. return $fontdata;
  4080. }
  4081. /**
  4082. * Sets the font used to print character strings.
  4083. * The font can be either a standard one or a font added via the AddFont() method. Standard fonts use Windows encoding cp1252 (Western Europe).
  4084. * The method can be called before the first page is created and the font is retained from page to page.
  4085. * If you just wish to change the current font size, it is simpler to call SetFontSize().
  4086. * Note: for the standard fonts, the font metric files must be accessible. There are three possibilities for this:<ul><li>They are in the current directory (the one where the running script lies)</li><li>They are in one of the directories defined by the include_path parameter</li><li>They are in the directory defined by the K_PATH_FONTS constant</li></ul><br />
  4087. * @param $family (string) Family font. It can be either a name defined by AddFont() or one of the standard Type1 families (case insensitive):<ul><li>times (Times-Roman)</li><li>timesb (Times-Bold)</li><li>timesi (Times-Italic)</li><li>timesbi (Times-BoldItalic)</li><li>helvetica (Helvetica)</li><li>helveticab (Helvetica-Bold)</li><li>helveticai (Helvetica-Oblique)</li><li>helveticabi (Helvetica-BoldOblique)</li><li>courier (Courier)</li><li>courierb (Courier-Bold)</li><li>courieri (Courier-Oblique)</li><li>courierbi (Courier-BoldOblique)</li><li>symbol (Symbol)</li><li>zapfdingbats (ZapfDingbats)</li></ul> It is also possible to pass an empty string. In that case, the current family is retained.
  4088. * @param $style (string) Font style. Possible values are (case insensitive):<ul><li>empty string: regular</li><li>B: bold</li><li>I: italic</li><li>U: underline</li><li>D: line through</li><li>O: overline</li></ul> or any combination. The default value is regular. Bold and italic styles do not apply to Symbol and ZapfDingbats basic fonts or other fonts when not defined.
  4089. * @param $size (float) Font size in points. The default value is the current size. If no size has been specified since the beginning of the document, the value taken is 12
  4090. * @param $fontfile (string) The font definition file. By default, the name is built from the family and style, in lower case with no spaces.
  4091. * @param $subset (mixed) if true embedd only a subset of the font (stores only the information related to the used characters); if false embedd full font; if 'default' uses the default value set using setFontSubsetting(). This option is valid only for TrueTypeUnicode fonts. If you want to enable users to change the document, set this parameter to false. If you subset the font, the person who receives your PDF would need to have your same font in order to make changes to your PDF. The file size of the PDF would also be smaller because you are embedding only part of a font.
  4092. * @param $out (boolean) if true output the font size command, otherwise only set the font properties.
  4093. * @author Nicola Asuni
  4094. * @public
  4095. * @since 1.0
  4096. * @see AddFont(), SetFontSize()
  4097. */
  4098. public function SetFont($family, $style='', $size=null, $fontfile='', $subset='default', $out=true) {
  4099. //Select a font; size given in points
  4100. if ($size === null) {
  4101. $size = $this->FontSizePt;
  4102. }
  4103. if ($size < 0) {
  4104. $size = 0;
  4105. }
  4106. // try to add font (if not already added)
  4107. $fontdata = $this->AddFont($family, $style, $fontfile, $subset);
  4108. $this->FontFamily = $fontdata['family'];
  4109. $this->FontStyle = $fontdata['style'];
  4110. if (isset($this->CurrentFont['fontkey']) AND isset($this->CurrentFont['subsetchars'])) {
  4111. // save subset chars of the previous font
  4112. $this->setFontSubBuffer($this->CurrentFont['fontkey'], 'subsetchars', $this->CurrentFont['subsetchars']);
  4113. }
  4114. $this->CurrentFont = $this->getFontBuffer($fontdata['fontkey']);
  4115. $this->SetFontSize($size, $out);
  4116. }
  4117. /**
  4118. * Defines the size of the current font.
  4119. * @param $size (float) The font size in points.
  4120. * @param $out (boolean) if true output the font size command, otherwise only set the font properties.
  4121. * @public
  4122. * @since 1.0
  4123. * @see SetFont()
  4124. */
  4125. public function SetFontSize($size, $out=true) {
  4126. $size = (float)$size;
  4127. // font size in points
  4128. $this->FontSizePt = $size;
  4129. // font size in user units
  4130. $this->FontSize = $size / $this->k;
  4131. // calculate some font metrics
  4132. if (isset($this->CurrentFont['desc']['FontBBox'])) {
  4133. $bbox = explode(' ', substr($this->CurrentFont['desc']['FontBBox'], 1, -1));
  4134. $font_height = ((intval($bbox[3]) - intval($bbox[1])) * $size / 1000);
  4135. } else {
  4136. $font_height = $size * 1.219;
  4137. }
  4138. if (isset($this->CurrentFont['desc']['Ascent']) AND ($this->CurrentFont['desc']['Ascent'] > 0)) {
  4139. $font_ascent = ($this->CurrentFont['desc']['Ascent'] * $size / 1000);
  4140. }
  4141. if (isset($this->CurrentFont['desc']['Descent']) AND ($this->CurrentFont['desc']['Descent'] <= 0)) {
  4142. $font_descent = (- $this->CurrentFont['desc']['Descent'] * $size / 1000);
  4143. }
  4144. if (!isset($font_ascent) AND !isset($font_descent)) {
  4145. // core font
  4146. $font_ascent = 0.76 * $font_height;
  4147. $font_descent = $font_height - $font_ascent;
  4148. } elseif (!isset($font_descent)) {
  4149. $font_descent = $font_height - $font_ascent;
  4150. } elseif (!isset($font_ascent)) {
  4151. $font_ascent = $font_height - $font_descent;
  4152. }
  4153. $this->FontAscent = ($font_ascent / $this->k);
  4154. $this->FontDescent = ($font_descent / $this->k);
  4155. if ($out AND ($this->page > 0) AND (isset($this->CurrentFont['i'])) AND ($this->state == 2)) {
  4156. $this->_out(sprintf('BT /F%d %F Tf ET', $this->CurrentFont['i'], $this->FontSizePt));
  4157. }
  4158. }
  4159. /**
  4160. * Returns the bounding box of the current font in user units.
  4161. * @return array
  4162. * @public
  4163. * @since 5.9.152 (2012-03-23)
  4164. */
  4165. public function getFontBBox() {
  4166. $fbbox = array();
  4167. if (isset($this->CurrentFont['desc']['FontBBox'])) {
  4168. $tmpbbox = explode(' ', substr($this->CurrentFont['desc']['FontBBox'], 1, -1));
  4169. $fbbox = array_map(array($this,'getAbsFontMeasure'), $tmpbbox);
  4170. } else {
  4171. // Find max width
  4172. if (isset($this->CurrentFont['desc']['MaxWidth'])) {
  4173. $maxw = $this->getAbsFontMeasure(intval($this->CurrentFont['desc']['MaxWidth']));
  4174. } else {
  4175. $maxw = 0;
  4176. if (isset($this->CurrentFont['desc']['MissingWidth'])) {
  4177. $maxw = max($maxw, $this->CurrentFont['desc']['MissingWidth']);
  4178. }
  4179. if (isset($this->CurrentFont['desc']['AvgWidth'])) {
  4180. $maxw = max($maxw, $this->CurrentFont['desc']['AvgWidth']);
  4181. }
  4182. if (isset($this->CurrentFont['dw'])) {
  4183. $maxw = max($maxw, $this->CurrentFont['dw']);
  4184. }
  4185. foreach ($this->CurrentFont['cw'] as $char => $w) {
  4186. $maxw = max($maxw, $w);
  4187. }
  4188. if ($maxw == 0) {
  4189. $maxw = 600;
  4190. }
  4191. $maxw = $this->getAbsFontMeasure($maxw);
  4192. }
  4193. $fbbox = array(0, (0 - $this->FontDescent), $maxw, $this->FontAscent);
  4194. }
  4195. return $fbbox;
  4196. }
  4197. /**
  4198. * Convert a relative font measure into absolute value.
  4199. * @param $s (int) Font measure.
  4200. * @return float Absolute measure.
  4201. * @since 5.9.186 (2012-09-13)
  4202. */
  4203. public function getAbsFontMeasure($s) {
  4204. return ($s * $this->FontSize / 1000);
  4205. }
  4206. /**
  4207. * Returns the glyph bounding box of the specified character in the current font in user units.
  4208. * @param $char (int) Input character code.
  4209. * @return mixed array(xMin, yMin, xMax, yMax) or FALSE if not defined.
  4210. * @since 5.9.186 (2012-09-13)
  4211. */
  4212. public function getCharBBox($char) {
  4213. $c = intval($char);
  4214. if (isset($this->CurrentFont['cw'][$c])) {
  4215. // glyph is defined ... use zero width & height for glyphs without outlines
  4216. $result = array(0,0,0,0);
  4217. if (isset($this->CurrentFont['cbbox'][$c])) {
  4218. $result = $this->CurrentFont['cbbox'][$c];
  4219. }
  4220. return array_map(array($this,'getAbsFontMeasure'), $result);
  4221. }
  4222. return false;
  4223. }
  4224. /**
  4225. * Return the font descent value
  4226. * @param $font (string) font name
  4227. * @param $style (string) font style
  4228. * @param $size (float) The size (in points)
  4229. * @return int font descent
  4230. * @public
  4231. * @author Nicola Asuni
  4232. * @since 4.9.003 (2010-03-30)
  4233. */
  4234. public function getFontDescent($font, $style='', $size=0) {
  4235. $fontdata = $this->AddFont($font, $style);
  4236. $fontinfo = $this->getFontBuffer($fontdata['fontkey']);
  4237. if (isset($fontinfo['desc']['Descent']) AND ($fontinfo['desc']['Descent'] <= 0)) {
  4238. $descent = (- $fontinfo['desc']['Descent'] * $size / 1000);
  4239. } else {
  4240. $descent = (1.219 * 0.24 * $size);
  4241. }
  4242. return ($descent / $this->k);
  4243. }
  4244. /**
  4245. * Return the font ascent value.
  4246. * @param $font (string) font name
  4247. * @param $style (string) font style
  4248. * @param $size (float) The size (in points)
  4249. * @return int font ascent
  4250. * @public
  4251. * @author Nicola Asuni
  4252. * @since 4.9.003 (2010-03-30)
  4253. */
  4254. public function getFontAscent($font, $style='', $size=0) {
  4255. $fontdata = $this->AddFont($font, $style);
  4256. $fontinfo = $this->getFontBuffer($fontdata['fontkey']);
  4257. if (isset($fontinfo['desc']['Ascent']) AND ($fontinfo['desc']['Ascent'] > 0)) {
  4258. $ascent = ($fontinfo['desc']['Ascent'] * $size / 1000);
  4259. } else {
  4260. $ascent = 1.219 * 0.76 * $size;
  4261. }
  4262. return ($ascent / $this->k);
  4263. }
  4264. /**
  4265. * Return true in the character is present in the specified font.
  4266. * @param $char (mixed) Character to check (integer value or string)
  4267. * @param $font (string) Font name (family name).
  4268. * @param $style (string) Font style.
  4269. * @return (boolean) true if the char is defined, false otherwise.
  4270. * @public
  4271. * @since 5.9.153 (2012-03-28)
  4272. */
  4273. public function isCharDefined($char, $font='', $style='') {
  4274. if (is_string($char)) {
  4275. // get character code
  4276. $char = TCPDF_FONTS::UTF8StringToArray($char, $this->isunicode, $this->CurrentFont);
  4277. $char = $char[0];
  4278. }
  4279. if (TCPDF_STATIC::empty_string($font)) {
  4280. if (TCPDF_STATIC::empty_string($style)) {
  4281. return (isset($this->CurrentFont['cw'][intval($char)]));
  4282. }
  4283. $font = $this->FontFamily;
  4284. }
  4285. $fontdata = $this->AddFont($font, $style);
  4286. $fontinfo = $this->getFontBuffer($fontdata['fontkey']);
  4287. return (isset($fontinfo['cw'][intval($char)]));
  4288. }
  4289. /**
  4290. * Replace missing font characters on selected font with specified substitutions.
  4291. * @param $text (string) Text to process.
  4292. * @param $font (string) Font name (family name).
  4293. * @param $style (string) Font style.
  4294. * @param $subs (array) Array of possible character substitutions. The key is the character to check (integer value) and the value is a single intege value or an array of possible substitutes.
  4295. * @return (string) Processed text.
  4296. * @public
  4297. * @since 5.9.153 (2012-03-28)
  4298. */
  4299. public function replaceMissingChars($text, $font='', $style='', $subs=array()) {
  4300. if (empty($subs)) {
  4301. return $text;
  4302. }
  4303. if (TCPDF_STATIC::empty_string($font)) {
  4304. $font = $this->FontFamily;
  4305. }
  4306. $fontdata = $this->AddFont($font, $style);
  4307. $fontinfo = $this->getFontBuffer($fontdata['fontkey']);
  4308. $uniarr = TCPDF_FONTS::UTF8StringToArray($text, $this->isunicode, $this->CurrentFont);
  4309. foreach ($uniarr as $k => $chr) {
  4310. if (!isset($fontinfo['cw'][$chr])) {
  4311. // this character is missing on the selected font
  4312. if (isset($subs[$chr])) {
  4313. // we have available substitutions
  4314. if (is_array($subs[$chr])) {
  4315. foreach($subs[$chr] as $s) {
  4316. if (isset($fontinfo['cw'][$s])) {
  4317. $uniarr[$k] = $s;
  4318. break;
  4319. }
  4320. }
  4321. } elseif (isset($fontinfo['cw'][$subs[$chr]])) {
  4322. $uniarr[$k] = $subs[$chr];
  4323. }
  4324. }
  4325. }
  4326. }
  4327. return TCPDF_FONTS::UniArrSubString(TCPDF_FONTS::UTF8ArrayToUniArray($uniarr, $this->isunicode));
  4328. }
  4329. /**
  4330. * Defines the default monospaced font.
  4331. * @param $font (string) Font name.
  4332. * @public
  4333. * @since 4.5.025
  4334. */
  4335. public function SetDefaultMonospacedFont($font) {
  4336. $this->default_monospaced_font = $font;
  4337. }
  4338. /**
  4339. * Creates a new internal link and returns its identifier. An internal link is a clickable area which directs to another place within the document.<br />
  4340. * The identifier can then be passed to Cell(), Write(), Image() or Link(). The destination is defined with SetLink().
  4341. * @public
  4342. * @since 1.5
  4343. * @see Cell(), Write(), Image(), Link(), SetLink()
  4344. */
  4345. public function AddLink() {
  4346. // create a new internal link
  4347. $n = count($this->links) + 1;
  4348. $this->links[$n] = array('p' => 0, 'y' => 0, 'f' => false);
  4349. return $n;
  4350. }
  4351. /**
  4352. * Defines the page and position a link points to.
  4353. * @param $link (int) The link identifier returned by AddLink()
  4354. * @param $y (float) Ordinate of target position; -1 indicates the current position. The default value is 0 (top of page)
  4355. * @param $page (int|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.
  4356. * @public
  4357. * @since 1.5
  4358. * @see AddLink()
  4359. */
  4360. public function SetLink($link, $y=0, $page=-1) {
  4361. $fixed = false;
  4362. if (!empty($page) AND (substr($page, 0, 1) == '*')) {
  4363. $page = intval(substr($page, 1));
  4364. // this page number will not be changed when moving/add/deleting pages
  4365. $fixed = true;
  4366. }
  4367. if ($page < 0) {
  4368. $page = $this->page;
  4369. }
  4370. if ($y == -1) {
  4371. $y = $this->y;
  4372. }
  4373. $this->links[$link] = array('p' => $page, 'y' => $y, 'f' => $fixed);
  4374. }
  4375. /**
  4376. * Puts a link on a rectangular area of the page.
  4377. * Text or image links are generally put via Cell(), Write() or Image(), but this method can be useful for instance to define a clickable area inside an image.
  4378. * @param $x (float) Abscissa of the upper-left corner of the rectangle
  4379. * @param $y (float) Ordinate of the upper-left corner of the rectangle
  4380. * @param $w (float) Width of the rectangle
  4381. * @param $h (float) Height of the rectangle
  4382. * @param $link (mixed) URL or identifier returned by AddLink()
  4383. * @param $spaces (int) number of spaces on the text to link
  4384. * @public
  4385. * @since 1.5
  4386. * @see AddLink(), Annotation(), Cell(), Write(), Image()
  4387. */
  4388. public function Link($x, $y, $w, $h, $link, $spaces=0) {
  4389. $this->Annotation($x, $y, $w, $h, $link, array('Subtype'=>'Link'), $spaces);
  4390. }
  4391. /**
  4392. * Puts a markup annotation on a rectangular area of the page.
  4393. * !!!!THE ANNOTATION SUPPORT IS NOT YET FULLY IMPLEMENTED !!!!
  4394. * @param $x (float) Abscissa of the upper-left corner of the rectangle
  4395. * @param $y (float) Ordinate of the upper-left corner of the rectangle
  4396. * @param $w (float) Width of the rectangle
  4397. * @param $h (float) Height of the rectangle
  4398. * @param $text (string) annotation text or alternate content
  4399. * @param $opt (array) array of options (see section 8.4 of PDF reference 1.7).
  4400. * @param $spaces (int) number of spaces on the text to link
  4401. * @public
  4402. * @since 4.0.018 (2008-08-06)
  4403. */
  4404. public function Annotation($x, $y, $w, $h, $text, $opt=array('Subtype'=>'Text'), $spaces=0) {
  4405. if ($this->inxobj) {
  4406. // store parameters for later use on template
  4407. $this->xobjects[$this->xobjid]['annotations'][] = array('x' => $x, 'y' => $y, 'w' => $w, 'h' => $h, 'text' => $text, 'opt' => $opt, 'spaces' => $spaces);
  4408. return;
  4409. }
  4410. if ($x === '') {
  4411. $x = $this->x;
  4412. }
  4413. if ($y === '') {
  4414. $y = $this->y;
  4415. }
  4416. // check page for no-write regions and adapt page margins if necessary
  4417. list($x, $y) = $this->checkPageRegions($h, $x, $y);
  4418. // recalculate coordinates to account for graphic transformations
  4419. if (isset($this->transfmatrix) AND !empty($this->transfmatrix)) {
  4420. for ($i=$this->transfmatrix_key; $i > 0; --$i) {
  4421. $maxid = count($this->transfmatrix[$i]) - 1;
  4422. for ($j=$maxid; $j >= 0; --$j) {
  4423. $ctm = $this->transfmatrix[$i][$j];
  4424. if (isset($ctm['a'])) {
  4425. $x = $x * $this->k;
  4426. $y = ($this->h - $y) * $this->k;
  4427. $w = $w * $this->k;
  4428. $h = $h * $this->k;
  4429. // top left
  4430. $xt = $x;
  4431. $yt = $y;
  4432. $x1 = ($ctm['a'] * $xt) + ($ctm['c'] * $yt) + $ctm['e'];
  4433. $y1 = ($ctm['b'] * $xt) + ($ctm['d'] * $yt) + $ctm['f'];
  4434. // top right
  4435. $xt = $x + $w;
  4436. $yt = $y;
  4437. $x2 = ($ctm['a'] * $xt) + ($ctm['c'] * $yt) + $ctm['e'];
  4438. $y2 = ($ctm['b'] * $xt) + ($ctm['d'] * $yt) + $ctm['f'];
  4439. // bottom left
  4440. $xt = $x;
  4441. $yt = $y - $h;
  4442. $x3 = ($ctm['a'] * $xt) + ($ctm['c'] * $yt) + $ctm['e'];
  4443. $y3 = ($ctm['b'] * $xt) + ($ctm['d'] * $yt) + $ctm['f'];
  4444. // bottom right
  4445. $xt = $x + $w;
  4446. $yt = $y - $h;
  4447. $x4 = ($ctm['a'] * $xt) + ($ctm['c'] * $yt) + $ctm['e'];
  4448. $y4 = ($ctm['b'] * $xt) + ($ctm['d'] * $yt) + $ctm['f'];
  4449. // new coordinates (rectangle area)
  4450. $x = min($x1, $x2, $x3, $x4);
  4451. $y = max($y1, $y2, $y3, $y4);
  4452. $w = (max($x1, $x2, $x3, $x4) - $x) / $this->k;
  4453. $h = ($y - min($y1, $y2, $y3, $y4)) / $this->k;
  4454. $x = $x / $this->k;
  4455. $y = $this->h - ($y / $this->k);
  4456. }
  4457. }
  4458. }
  4459. }
  4460. if ($this->page <= 0) {
  4461. $page = 1;
  4462. } else {
  4463. $page = $this->page;
  4464. }
  4465. if (!isset($this->PageAnnots[$page])) {
  4466. $this->PageAnnots[$page] = array();
  4467. }
  4468. $this->PageAnnots[$page][] = array('n' => ++$this->n, 'x' => $x, 'y' => $y, 'w' => $w, 'h' => $h, 'txt' => $text, 'opt' => $opt, 'numspaces' => $spaces);
  4469. if (!$this->pdfa_mode || ($this->pdfa_mode && $this->pdfa_version == 3)) {
  4470. if ((($opt['Subtype'] == 'FileAttachment') OR ($opt['Subtype'] == 'Sound')) AND (!TCPDF_STATIC::empty_string($opt['FS']))
  4471. AND (@TCPDF_STATIC::file_exists($opt['FS']) OR TCPDF_STATIC::isValidURL($opt['FS']))
  4472. AND (!isset($this->embeddedfiles[basename($opt['FS'])]))) {
  4473. $this->embeddedfiles[basename($opt['FS'])] = array('f' => ++$this->n, 'n' => ++$this->n, 'file' => $opt['FS']);
  4474. }
  4475. }
  4476. // Add widgets annotation's icons
  4477. if (isset($opt['mk']['i']) AND @TCPDF_STATIC::file_exists($opt['mk']['i'])) {
  4478. $this->Image($opt['mk']['i'], '', '', 10, 10, '', '', '', false, 300, '', false, false, 0, false, true);
  4479. }
  4480. if (isset($opt['mk']['ri']) AND @TCPDF_STATIC::file_exists($opt['mk']['ri'])) {
  4481. $this->Image($opt['mk']['ri'], '', '', 0, 0, '', '', '', false, 300, '', false, false, 0, false, true);
  4482. }
  4483. if (isset($opt['mk']['ix']) AND @TCPDF_STATIC::file_exists($opt['mk']['ix'])) {
  4484. $this->Image($opt['mk']['ix'], '', '', 0, 0, '', '', '', false, 300, '', false, false, 0, false, true);
  4485. }
  4486. }
  4487. /**
  4488. * Embedd the attached files.
  4489. * @since 4.4.000 (2008-12-07)
  4490. * @protected
  4491. * @see Annotation()
  4492. */
  4493. protected function _putEmbeddedFiles() {
  4494. if ($this->pdfa_mode && $this->pdfa_version != 3) {
  4495. // embedded files are not allowed in PDF/A mode version 1 and 2
  4496. return;
  4497. }
  4498. reset($this->embeddedfiles);
  4499. foreach ($this->embeddedfiles as $filename => $filedata) {
  4500. $data = TCPDF_STATIC::fileGetContents($filedata['file']);
  4501. if ($data !== FALSE) {
  4502. $rawsize = strlen($data);
  4503. if ($rawsize > 0) {
  4504. // update name tree
  4505. $this->efnames[$filename] = $filedata['f'].' 0 R';
  4506. // embedded file specification object
  4507. $out = $this->_getobj($filedata['f'])."\n";
  4508. $out .= '<</Type /Filespec /F '.$this->_datastring($filename, $filedata['f']);
  4509. $out .= ' /UF '.$this->_datastring($filename, $filedata['f']);
  4510. $out .= ' /AFRelationship /Source';
  4511. $out .= ' /EF <</F '.$filedata['n'].' 0 R>> >>';
  4512. $out .= "\n".'endobj';
  4513. $this->_out($out);
  4514. // embedded file object
  4515. $filter = '';
  4516. if ($this->compress) {
  4517. $data = gzcompress($data);
  4518. $filter = ' /Filter /FlateDecode';
  4519. }
  4520. if ($this->pdfa_version == 3) {
  4521. $filter = ' /Subtype /text#2Fxml';
  4522. }
  4523. $stream = $this->_getrawstream($data, $filedata['n']);
  4524. $out = $this->_getobj($filedata['n'])."\n";
  4525. $out .= '<< /Type /EmbeddedFile'.$filter.' /Length '.strlen($stream).' /Params <</Size '.$rawsize.'>> >>';
  4526. $out .= ' stream'."\n".$stream."\n".'endstream';
  4527. $out .= "\n".'endobj';
  4528. $this->_out($out);
  4529. }
  4530. }
  4531. }
  4532. }
  4533. /**
  4534. * Prints a text cell at the specified position.
  4535. * This method allows to place a string precisely on the page.
  4536. * @param $x (float) Abscissa of the cell origin
  4537. * @param $y (float) Ordinate of the cell origin
  4538. * @param $txt (string) String to print
  4539. * @param $fstroke (int) outline size in user units (false = disable)
  4540. * @param $fclip (boolean) if true activate clipping mode (you must call StartTransform() before this function and StopTransform() to stop the clipping tranformation).
  4541. * @param $ffill (boolean) if true fills the text
  4542. * @param $border (mixed) Indicates if borders must be drawn around the cell. The value can be a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul> or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul> or an array of line styles for each border group - for example: array('LTRB' => array('width' => 2, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0)))
  4543. * @param $ln (int) Indicates where the current position should go after the call. Possible values are:<ul><li>0: to the right (or left for RTL languages)</li><li>1: to the beginning of the next line</li><li>2: below</li></ul>Putting 1 is equivalent to putting 0 and calling Ln() just after. Default value: 0.
  4544. * @param $align (string) Allows to center or align the text. Possible values are:<ul><li>L or empty string: left align (default value)</li><li>C: center</li><li>R: right align</li><li>J: justify</li></ul>
  4545. * @param $fill (boolean) Indicates if the cell background must be painted (true) or transparent (false).
  4546. * @param $link (mixed) URL or identifier returned by AddLink().
  4547. * @param $stretch (int) font stretch mode: <ul><li>0 = disabled</li><li>1 = horizontal scaling only if text is larger than cell width</li><li>2 = forced horizontal scaling to fit cell width</li><li>3 = character spacing only if text is larger than cell width</li><li>4 = forced character spacing to fit cell width</li></ul> General font stretching and scaling values will be preserved when possible.
  4548. * @param $ignore_min_height (boolean) if true ignore automatic minimum height value.
  4549. * @param $calign (string) cell vertical alignment relative to the specified Y value. Possible values are:<ul><li>T : cell top</li><li>A : font top</li><li>L : font baseline</li><li>D : font bottom</li><li>B : cell bottom</li></ul>
  4550. * @param $valign (string) text vertical alignment inside the cell. Possible values are:<ul><li>T : top</li><li>C : center</li><li>B : bottom</li></ul>
  4551. * @param $rtloff (boolean) if true uses the page top-left corner as origin of axis for $x and $y initial position.
  4552. * @public
  4553. * @since 1.0
  4554. * @see Cell(), Write(), MultiCell(), WriteHTML(), WriteHTMLCell()
  4555. */
  4556. public function Text($x, $y, $txt, $fstroke=false, $fclip=false, $ffill=true, $border=0, $ln=0, $align='', $fill=false, $link='', $stretch=0, $ignore_min_height=false, $calign='T', $valign='M', $rtloff=false) {
  4557. $textrendermode = $this->textrendermode;
  4558. $textstrokewidth = $this->textstrokewidth;
  4559. $this->setTextRenderingMode($fstroke, $ffill, $fclip);
  4560. $this->SetXY($x, $y, $rtloff);
  4561. $this->Cell(0, 0, $txt, $border, $ln, $align, $fill, $link, $stretch, $ignore_min_height, $calign, $valign);
  4562. // restore previous rendering mode
  4563. $this->textrendermode = $textrendermode;
  4564. $this->textstrokewidth = $textstrokewidth;
  4565. }
  4566. /**
  4567. * Whenever a page break condition is met, the method is called, and the break is issued or not depending on the returned value.
  4568. * The default implementation returns a value according to the mode selected by SetAutoPageBreak().<br />
  4569. * This method is called automatically and should not be called directly by the application.
  4570. * @return boolean
  4571. * @public
  4572. * @since 1.4
  4573. * @see SetAutoPageBreak()
  4574. */
  4575. public function AcceptPageBreak() {
  4576. if ($this->num_columns > 1) {
  4577. // multi column mode
  4578. if ($this->current_column < ($this->num_columns - 1)) {
  4579. // go to next column
  4580. $this->selectColumn($this->current_column + 1);
  4581. } elseif ($this->AutoPageBreak) {
  4582. // add a new page
  4583. $this->AddPage();
  4584. // set first column
  4585. $this->selectColumn(0);
  4586. }
  4587. // avoid page breaking from checkPageBreak()
  4588. return false;
  4589. }
  4590. return $this->AutoPageBreak;
  4591. }
  4592. /**
  4593. * Add page if needed.
  4594. * @param $h (float) Cell height. Default value: 0.
  4595. * @param $y (mixed) starting y position, leave empty for current position.
  4596. * @param $addpage (boolean) if true add a page, otherwise only return the true/false state
  4597. * @return boolean true in case of page break, false otherwise.
  4598. * @since 3.2.000 (2008-07-01)
  4599. * @protected
  4600. */
  4601. protected function checkPageBreak($h=0, $y='', $addpage=true) {
  4602. if (TCPDF_STATIC::empty_string($y)) {
  4603. $y = $this->y;
  4604. }
  4605. $current_page = $this->page;
  4606. if ((($y + $h) > $this->PageBreakTrigger) AND ($this->inPageBody()) AND ($this->AcceptPageBreak())) {
  4607. if ($addpage) {
  4608. //Automatic page break
  4609. $x = $this->x;
  4610. $this->AddPage($this->CurOrientation);
  4611. $this->y = $this->tMargin;
  4612. $oldpage = $this->page - 1;
  4613. if ($this->rtl) {
  4614. if ($this->pagedim[$this->page]['orm'] != $this->pagedim[$oldpage]['orm']) {
  4615. $this->x = $x - ($this->pagedim[$this->page]['orm'] - $this->pagedim[$oldpage]['orm']);
  4616. } else {
  4617. $this->x = $x;
  4618. }
  4619. } else {
  4620. if ($this->pagedim[$this->page]['olm'] != $this->pagedim[$oldpage]['olm']) {
  4621. $this->x = $x + ($this->pagedim[$this->page]['olm'] - $this->pagedim[$oldpage]['olm']);
  4622. } else {
  4623. $this->x = $x;
  4624. }
  4625. }
  4626. }
  4627. return true;
  4628. }
  4629. if ($current_page != $this->page) {
  4630. // account for columns mode
  4631. return true;
  4632. }
  4633. return false;
  4634. }
  4635. /**
  4636. * Prints a cell (rectangular area) with optional borders, background color and character string. The upper-left corner of the cell corresponds to the current position. The text can be aligned or centered. After the call, the current position moves to the right or to the next line. It is possible to put a link on the text.<br />
  4637. * If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting.
  4638. * @param $w (float) Cell width. If 0, the cell extends up to the right margin.
  4639. * @param $h (float) Cell height. Default value: 0.
  4640. * @param $txt (string) String to print. Default value: empty string.
  4641. * @param $border (mixed) Indicates if borders must be drawn around the cell. The value can be a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul> or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul> or an array of line styles for each border group - for example: array('LTRB' => array('width' => 2, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0)))
  4642. * @param $ln (int) Indicates where the current position should go after the call. Possible values are:<ul><li>0: to the right (or left for RTL languages)</li><li>1: to the beginning of the next line</li><li>2: below</li></ul> Putting 1 is equivalent to putting 0 and calling Ln() just after. Default value: 0.
  4643. * @param $align (string) Allows to center or align the text. Possible values are:<ul><li>L or empty string: left align (default value)</li><li>C: center</li><li>R: right align</li><li>J: justify</li></ul>
  4644. * @param $fill (boolean) Indicates if the cell background must be painted (true) or transparent (false).
  4645. * @param $link (mixed) URL or identifier returned by AddLink().
  4646. * @param $stretch (int) font stretch mode: <ul><li>0 = disabled</li><li>1 = horizontal scaling only if text is larger than cell width</li><li>2 = forced horizontal scaling to fit cell width</li><li>3 = character spacing only if text is larger than cell width</li><li>4 = forced character spacing to fit cell width</li></ul> General font stretching and scaling values will be preserved when possible.
  4647. * @param $ignore_min_height (boolean) if true ignore automatic minimum height value.
  4648. * @param $calign (string) cell vertical alignment relative to the specified Y value. Possible values are:<ul><li>T : cell top</li><li>C : center</li><li>B : cell bottom</li><li>A : font top</li><li>L : font baseline</li><li>D : font bottom</li></ul>
  4649. * @param $valign (string) text vertical alignment inside the cell. Possible values are:<ul><li>T : top</li><li>C : center</li><li>B : bottom</li></ul>
  4650. * @public
  4651. * @since 1.0
  4652. * @see SetFont(), SetDrawColor(), SetFillColor(), SetTextColor(), SetLineWidth(), AddLink(), Ln(), MultiCell(), Write(), SetAutoPageBreak()
  4653. */
  4654. public function Cell($w, $h=0, $txt='', $border=0, $ln=0, $align='', $fill=false, $link='', $stretch=0, $ignore_min_height=false, $calign='T', $valign='M') {
  4655. $prev_cell_margin = $this->cell_margin;
  4656. $prev_cell_padding = $this->cell_padding;
  4657. $this->adjustCellPadding($border);
  4658. if (!$ignore_min_height) {
  4659. $min_cell_height = $this->getCellHeight($this->FontSize);
  4660. if ($h < $min_cell_height) {
  4661. $h = $min_cell_height;
  4662. }
  4663. }
  4664. $this->checkPageBreak($h + $this->cell_margin['T'] + $this->cell_margin['B']);
  4665. // apply text shadow if enabled
  4666. if ($this->txtshadow['enabled']) {
  4667. // save data
  4668. $x = $this->x;
  4669. $y = $this->y;
  4670. $bc = $this->bgcolor;
  4671. $fc = $this->fgcolor;
  4672. $sc = $this->strokecolor;
  4673. $alpha = $this->alpha;
  4674. // print shadow
  4675. $this->x += $this->txtshadow['depth_w'];
  4676. $this->y += $this->txtshadow['depth_h'];
  4677. $this->SetFillColorArray($this->txtshadow['color']);
  4678. $this->SetTextColorArray($this->txtshadow['color']);
  4679. $this->SetDrawColorArray($this->txtshadow['color']);
  4680. if ($this->txtshadow['opacity'] != $alpha['CA']) {
  4681. $this->setAlpha($this->txtshadow['opacity'], $this->txtshadow['blend_mode']);
  4682. }
  4683. if ($this->state == 2) {
  4684. $this->_out($this->getCellCode($w, $h, $txt, $border, $ln, $align, $fill, $link, $stretch, true, $calign, $valign));
  4685. }
  4686. //restore data
  4687. $this->x = $x;
  4688. $this->y = $y;
  4689. $this->SetFillColorArray($bc);
  4690. $this->SetTextColorArray($fc);
  4691. $this->SetDrawColorArray($sc);
  4692. if ($this->txtshadow['opacity'] != $alpha['CA']) {
  4693. $this->setAlpha($alpha['CA'], $alpha['BM'], $alpha['ca'], $alpha['AIS']);
  4694. }
  4695. }
  4696. if ($this->state == 2) {
  4697. $this->_out($this->getCellCode($w, $h, $txt, $border, $ln, $align, $fill, $link, $stretch, true, $calign, $valign));
  4698. }
  4699. $this->cell_padding = $prev_cell_padding;
  4700. $this->cell_margin = $prev_cell_margin;
  4701. }
  4702. /**
  4703. * Returns the PDF string code to print a cell (rectangular area) with optional borders, background color and character string. The upper-left corner of the cell corresponds to the current position. The text can be aligned or centered. After the call, the current position moves to the right or to the next line. It is possible to put a link on the text.<br />
  4704. * If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting.
  4705. * @param $w (float) Cell width. If 0, the cell extends up to the right margin.
  4706. * @param $h (float) Cell height. Default value: 0.
  4707. * @param $txt (string) String to print. Default value: empty string.
  4708. * @param $border (mixed) Indicates if borders must be drawn around the cell. The value can be a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul> or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul> or an array of line styles for each border group - for example: array('LTRB' => array('width' => 2, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0)))
  4709. * @param $ln (int) Indicates where the current position should go after the call. Possible values are:<ul><li>0: to the right (or left for RTL languages)</li><li>1: to the beginning of the next line</li><li>2: below</li></ul>Putting 1 is equivalent to putting 0 and calling Ln() just after. Default value: 0.
  4710. * @param $align (string) Allows to center or align the text. Possible values are:<ul><li>L or empty string: left align (default value)</li><li>C: center</li><li>R: right align</li><li>J: justify</li></ul>
  4711. * @param $fill (boolean) Indicates if the cell background must be painted (true) or transparent (false).
  4712. * @param $link (mixed) URL or identifier returned by AddLink().
  4713. * @param $stretch (int) font stretch mode: <ul><li>0 = disabled</li><li>1 = horizontal scaling only if text is larger than cell width</li><li>2 = forced horizontal scaling to fit cell width</li><li>3 = character spacing only if text is larger than cell width</li><li>4 = forced character spacing to fit cell width</li></ul> General font stretching and scaling values will be preserved when possible.
  4714. * @param $ignore_min_height (boolean) if true ignore automatic minimum height value.
  4715. * @param $calign (string) cell vertical alignment relative to the specified Y value. Possible values are:<ul><li>T : cell top</li><li>C : center</li><li>B : cell bottom</li><li>A : font top</li><li>L : font baseline</li><li>D : font bottom</li></ul>
  4716. * @param $valign (string) text vertical alignment inside the cell. Possible values are:<ul><li>T : top</li><li>M : middle</li><li>B : bottom</li></ul>
  4717. * @return string containing cell code
  4718. * @protected
  4719. * @since 1.0
  4720. * @see Cell()
  4721. */
  4722. protected function getCellCode($w, $h=0, $txt='', $border=0, $ln=0, $align='', $fill=false, $link='', $stretch=0, $ignore_min_height=false, $calign='T', $valign='M') {
  4723. // replace 'NO-BREAK SPACE' (U+00A0) character with a simple space
  4724. $txt = str_replace(TCPDF_FONTS::unichr(160, $this->isunicode), ' ', $txt);
  4725. $prev_cell_margin = $this->cell_margin;
  4726. $prev_cell_padding = $this->cell_padding;
  4727. $txt = TCPDF_STATIC::removeSHY($txt, $this->isunicode);
  4728. $rs = ''; //string to be returned
  4729. $this->adjustCellPadding($border);
  4730. if (!$ignore_min_height) {
  4731. $min_cell_height = $this->getCellHeight($this->FontSize);
  4732. if ($h < $min_cell_height) {
  4733. $h = $min_cell_height;
  4734. }
  4735. }
  4736. $k = $this->k;
  4737. // check page for no-write regions and adapt page margins if necessary
  4738. list($this->x, $this->y) = $this->checkPageRegions($h, $this->x, $this->y);
  4739. if ($this->rtl) {
  4740. $x = $this->x - $this->cell_margin['R'];
  4741. } else {
  4742. $x = $this->x + $this->cell_margin['L'];
  4743. }
  4744. $y = $this->y + $this->cell_margin['T'];
  4745. $prev_font_stretching = $this->font_stretching;
  4746. $prev_font_spacing = $this->font_spacing;
  4747. // cell vertical alignment
  4748. switch ($calign) {
  4749. case 'A': {
  4750. // font top
  4751. switch ($valign) {
  4752. case 'T': {
  4753. // top
  4754. $y -= $this->cell_padding['T'];
  4755. break;
  4756. }
  4757. case 'B': {
  4758. // bottom
  4759. $y -= ($h - $this->cell_padding['B'] - $this->FontAscent - $this->FontDescent);
  4760. break;
  4761. }
  4762. default:
  4763. case 'C':
  4764. case 'M': {
  4765. // center
  4766. $y -= (($h - $this->FontAscent - $this->FontDescent) / 2);
  4767. break;
  4768. }
  4769. }
  4770. break;
  4771. }
  4772. case 'L': {
  4773. // font baseline
  4774. switch ($valign) {
  4775. case 'T': {
  4776. // top
  4777. $y -= ($this->cell_padding['T'] + $this->FontAscent);
  4778. break;
  4779. }
  4780. case 'B': {
  4781. // bottom
  4782. $y -= ($h - $this->cell_padding['B'] - $this->FontDescent);
  4783. break;
  4784. }
  4785. default:
  4786. case 'C':
  4787. case 'M': {
  4788. // center
  4789. $y -= (($h + $this->FontAscent - $this->FontDescent) / 2);
  4790. break;
  4791. }
  4792. }
  4793. break;
  4794. }
  4795. case 'D': {
  4796. // font bottom
  4797. switch ($valign) {
  4798. case 'T': {
  4799. // top
  4800. $y -= ($this->cell_padding['T'] + $this->FontAscent + $this->FontDescent);
  4801. break;
  4802. }
  4803. case 'B': {
  4804. // bottom
  4805. $y -= ($h - $this->cell_padding['B']);
  4806. break;
  4807. }
  4808. default:
  4809. case 'C':
  4810. case 'M': {
  4811. // center
  4812. $y -= (($h + $this->FontAscent + $this->FontDescent) / 2);
  4813. break;
  4814. }
  4815. }
  4816. break;
  4817. }
  4818. case 'B': {
  4819. // cell bottom
  4820. $y -= $h;
  4821. break;
  4822. }
  4823. case 'C':
  4824. case 'M': {
  4825. // cell center
  4826. $y -= ($h / 2);
  4827. break;
  4828. }
  4829. default:
  4830. case 'T': {
  4831. // cell top
  4832. break;
  4833. }
  4834. }
  4835. // text vertical alignment
  4836. switch ($valign) {
  4837. case 'T': {
  4838. // top
  4839. $yt = $y + $this->cell_padding['T'];
  4840. break;
  4841. }
  4842. case 'B': {
  4843. // bottom
  4844. $yt = $y + $h - $this->cell_padding['B'] - $this->FontAscent - $this->FontDescent;
  4845. break;
  4846. }
  4847. default:
  4848. case 'C':
  4849. case 'M': {
  4850. // center
  4851. $yt = $y + (($h - $this->FontAscent - $this->FontDescent) / 2);
  4852. break;
  4853. }
  4854. }
  4855. $basefonty = $yt + $this->FontAscent;
  4856. if (TCPDF_STATIC::empty_string($w) OR ($w <= 0)) {
  4857. if ($this->rtl) {
  4858. $w = $x - $this->lMargin;
  4859. } else {
  4860. $w = $this->w - $this->rMargin - $x;
  4861. }
  4862. }
  4863. $s = '';
  4864. // fill and borders
  4865. if (is_string($border) AND (strlen($border) == 4)) {
  4866. // full border
  4867. $border = 1;
  4868. }
  4869. if ($fill OR ($border == 1)) {
  4870. if ($fill) {
  4871. $op = ($border == 1) ? 'B' : 'f';
  4872. } else {
  4873. $op = 'S';
  4874. }
  4875. if ($this->rtl) {
  4876. $xk = (($x - $w) * $k);
  4877. } else {
  4878. $xk = ($x * $k);
  4879. }
  4880. $s .= sprintf('%F %F %F %F re %s ', $xk, (($this->h - $y) * $k), ($w * $k), (-$h * $k), $op);
  4881. }
  4882. // draw borders
  4883. $s .= $this->getCellBorder($x, $y, $w, $h, $border);
  4884. if ($txt != '') {
  4885. $txt2 = $txt;
  4886. if ($this->isunicode) {
  4887. if (($this->CurrentFont['type'] == 'core') OR ($this->CurrentFont['type'] == 'TrueType') OR ($this->CurrentFont['type'] == 'Type1')) {
  4888. $txt2 = TCPDF_FONTS::UTF8ToLatin1($txt2, $this->isunicode, $this->CurrentFont);
  4889. } else {
  4890. $unicode = TCPDF_FONTS::UTF8StringToArray($txt, $this->isunicode, $this->CurrentFont); // array of UTF-8 unicode values
  4891. $unicode = TCPDF_FONTS::utf8Bidi($unicode, '', $this->tmprtl, $this->isunicode, $this->CurrentFont);
  4892. // replace thai chars (if any)
  4893. if (defined('K_THAI_TOPCHARS') AND (K_THAI_TOPCHARS == true)) {
  4894. // number of chars
  4895. $numchars = count($unicode);
  4896. // po pla, for far, for fan
  4897. $longtail = array(0x0e1b, 0x0e1d, 0x0e1f);
  4898. // do chada, to patak
  4899. $lowtail = array(0x0e0e, 0x0e0f);
  4900. // mai hun arkad, sara i, sara ii, sara ue, sara uee
  4901. $upvowel = array(0x0e31, 0x0e34, 0x0e35, 0x0e36, 0x0e37);
  4902. // mai ek, mai tho, mai tri, mai chattawa, karan
  4903. $tonemark = array(0x0e48, 0x0e49, 0x0e4a, 0x0e4b, 0x0e4c);
  4904. // sara u, sara uu, pinthu
  4905. $lowvowel = array(0x0e38, 0x0e39, 0x0e3a);
  4906. $output = array();
  4907. for ($i = 0; $i < $numchars; $i++) {
  4908. if (($unicode[$i] >= 0x0e00) && ($unicode[$i] <= 0x0e5b)) {
  4909. $ch0 = $unicode[$i];
  4910. $ch1 = ($i > 0) ? $unicode[($i - 1)] : 0;
  4911. $ch2 = ($i > 1) ? $unicode[($i - 2)] : 0;
  4912. $chn = ($i < ($numchars - 1)) ? $unicode[($i + 1)] : 0;
  4913. if (in_array($ch0, $tonemark)) {
  4914. if ($chn == 0x0e33) {
  4915. // sara um
  4916. if (in_array($ch1, $longtail)) {
  4917. // tonemark at upper left
  4918. $output[] = $this->replaceChar($ch0, (0xf713 + $ch0 - 0x0e48));
  4919. } else {
  4920. // tonemark at upper right (normal position)
  4921. $output[] = $ch0;
  4922. }
  4923. } elseif (in_array($ch1, $longtail) OR (in_array($ch2, $longtail) AND in_array($ch1, $lowvowel))) {
  4924. // tonemark at lower left
  4925. $output[] = $this->replaceChar($ch0, (0xf705 + $ch0 - 0x0e48));
  4926. } elseif (in_array($ch1, $upvowel)) {
  4927. if (in_array($ch2, $longtail)) {
  4928. // tonemark at upper left
  4929. $output[] = $this->replaceChar($ch0, (0xf713 + $ch0 - 0x0e48));
  4930. } else {
  4931. // tonemark at upper right (normal position)
  4932. $output[] = $ch0;
  4933. }
  4934. } else {
  4935. // tonemark at lower right
  4936. $output[] = $this->replaceChar($ch0, (0xf70a + $ch0 - 0x0e48));
  4937. }
  4938. } elseif (($ch0 == 0x0e33) AND (in_array($ch1, $longtail) OR (in_array($ch2, $longtail) AND in_array($ch1, $tonemark)))) {
  4939. // add lower left nikhahit and sara aa
  4940. if ($this->isCharDefined(0xf711) AND $this->isCharDefined(0x0e32)) {
  4941. $output[] = 0xf711;
  4942. $this->CurrentFont['subsetchars'][0xf711] = true;
  4943. $output[] = 0x0e32;
  4944. $this->CurrentFont['subsetchars'][0x0e32] = true;
  4945. } else {
  4946. $output[] = $ch0;
  4947. }
  4948. } elseif (in_array($ch1, $longtail)) {
  4949. if ($ch0 == 0x0e31) {
  4950. // lower left mai hun arkad
  4951. $output[] = $this->replaceChar($ch0, 0xf710);
  4952. } elseif (in_array($ch0, $upvowel)) {
  4953. // lower left
  4954. $output[] = $this->replaceChar($ch0, (0xf701 + $ch0 - 0x0e34));
  4955. } elseif ($ch0 == 0x0e47) {
  4956. // lower left mai tai koo
  4957. $output[] = $this->replaceChar($ch0, 0xf712);
  4958. } else {
  4959. // normal character
  4960. $output[] = $ch0;
  4961. }
  4962. } elseif (in_array($ch1, $lowtail) AND in_array($ch0, $lowvowel)) {
  4963. // lower vowel
  4964. $output[] = $this->replaceChar($ch0, (0xf718 + $ch0 - 0x0e38));
  4965. } elseif (($ch0 == 0x0e0d) AND in_array($chn, $lowvowel)) {
  4966. // yo ying without lower part
  4967. $output[] = $this->replaceChar($ch0, 0xf70f);
  4968. } elseif (($ch0 == 0x0e10) AND in_array($chn, $lowvowel)) {
  4969. // tho santan without lower part
  4970. $output[] = $this->replaceChar($ch0, 0xf700);
  4971. } else {
  4972. $output[] = $ch0;
  4973. }
  4974. } else {
  4975. // non-thai character
  4976. $output[] = $unicode[$i];
  4977. }
  4978. }
  4979. $unicode = $output;
  4980. // update font subsetchars
  4981. $this->setFontSubBuffer($this->CurrentFont['fontkey'], 'subsetchars', $this->CurrentFont['subsetchars']);
  4982. } // end of K_THAI_TOPCHARS
  4983. $txt2 = TCPDF_FONTS::arrUTF8ToUTF16BE($unicode, false);
  4984. }
  4985. }
  4986. $txt2 = TCPDF_STATIC::_escape($txt2);
  4987. // get current text width (considering general font stretching and spacing)
  4988. $txwidth = $this->GetStringWidth($txt);
  4989. $width = $txwidth;
  4990. // check for stretch mode
  4991. if ($stretch > 0) {
  4992. // calculate ratio between cell width and text width
  4993. if ($width <= 0) {
  4994. $ratio = 1;
  4995. } else {
  4996. $ratio = (($w - $this->cell_padding['L'] - $this->cell_padding['R']) / $width);
  4997. }
  4998. // check if stretching is required
  4999. if (($ratio < 1) OR (($ratio > 1) AND (($stretch % 2) == 0))) {
  5000. // the text will be stretched to fit cell width
  5001. if ($stretch > 2) {
  5002. // set new character spacing
  5003. $this->font_spacing += ($w - $this->cell_padding['L'] - $this->cell_padding['R'] - $width) / (max(($this->GetNumChars($txt) - 1), 1) * ($this->font_stretching / 100));
  5004. } else {
  5005. // set new horizontal stretching
  5006. $this->font_stretching *= $ratio;
  5007. }
  5008. // recalculate text width (the text fills the entire cell)
  5009. $width = $w - $this->cell_padding['L'] - $this->cell_padding['R'];
  5010. // reset alignment
  5011. $align = '';
  5012. }
  5013. }
  5014. if ($this->font_stretching != 100) {
  5015. // apply font stretching
  5016. $rs .= sprintf('BT %F Tz ET ', $this->font_stretching);
  5017. }
  5018. if ($this->font_spacing != 0) {
  5019. // increase/decrease font spacing
  5020. $rs .= sprintf('BT %F Tc ET ', ($this->font_spacing * $this->k));
  5021. }
  5022. if ($this->ColorFlag AND ($this->textrendermode < 4)) {
  5023. $s .= 'q '.$this->TextColor.' ';
  5024. }
  5025. // rendering mode
  5026. $s .= sprintf('BT %d Tr %F w ET ', $this->textrendermode, ($this->textstrokewidth * $this->k));
  5027. // count number of spaces
  5028. $ns = substr_count($txt, chr(32));
  5029. // Justification
  5030. $spacewidth = 0;
  5031. if (($align == 'J') AND ($ns > 0)) {
  5032. if ($this->isUnicodeFont()) {
  5033. // get string width without spaces
  5034. $width = $this->GetStringWidth(str_replace(' ', '', $txt));
  5035. // calculate average space width
  5036. $spacewidth = -1000 * ($w - $width - $this->cell_padding['L'] - $this->cell_padding['R']) / ($ns?$ns:1) / ($this->FontSize?$this->FontSize:1);
  5037. if ($this->font_stretching != 100) {
  5038. // word spacing is affected by stretching
  5039. $spacewidth /= ($this->font_stretching / 100);
  5040. }
  5041. // set word position to be used with TJ operator
  5042. $txt2 = str_replace(chr(0).chr(32), ') '.sprintf('%F', $spacewidth).' (', $txt2);
  5043. $unicode_justification = true;
  5044. } else {
  5045. // get string width
  5046. $width = $txwidth;
  5047. // new space width
  5048. $spacewidth = (($w - $width - $this->cell_padding['L'] - $this->cell_padding['R']) / ($ns?$ns:1)) * $this->k;
  5049. if ($this->font_stretching != 100) {
  5050. // word spacing (Tw) is affected by stretching
  5051. $spacewidth /= ($this->font_stretching / 100);
  5052. }
  5053. // set word spacing
  5054. $rs .= sprintf('BT %F Tw ET ', $spacewidth);
  5055. }
  5056. $width = $w - $this->cell_padding['L'] - $this->cell_padding['R'];
  5057. }
  5058. // replace carriage return characters
  5059. $txt2 = str_replace("\r", ' ', $txt2);
  5060. switch ($align) {
  5061. case 'C': {
  5062. $dx = ($w - $width) / 2;
  5063. break;
  5064. }
  5065. case 'R': {
  5066. if ($this->rtl) {
  5067. $dx = $this->cell_padding['R'];
  5068. } else {
  5069. $dx = $w - $width - $this->cell_padding['R'];
  5070. }
  5071. break;
  5072. }
  5073. case 'L': {
  5074. if ($this->rtl) {
  5075. $dx = $w - $width - $this->cell_padding['L'];
  5076. } else {
  5077. $dx = $this->cell_padding['L'];
  5078. }
  5079. break;
  5080. }
  5081. case 'J':
  5082. default: {
  5083. if ($this->rtl) {
  5084. $dx = $this->cell_padding['R'];
  5085. } else {
  5086. $dx = $this->cell_padding['L'];
  5087. }
  5088. break;
  5089. }
  5090. }
  5091. if ($this->rtl) {
  5092. $xdx = $x - $dx - $width;
  5093. } else {
  5094. $xdx = $x + $dx;
  5095. }
  5096. $xdk = $xdx * $k;
  5097. // print text
  5098. $s .= sprintf('BT %F %F Td [(%s)] TJ ET', $xdk, (($this->h - $basefonty) * $k), $txt2);
  5099. if (isset($uniblock)) {
  5100. // print overlapping characters as separate string
  5101. $xshift = 0; // horizontal shift
  5102. $ty = (($this->h - $basefonty + (0.2 * $this->FontSize)) * $k);
  5103. $spw = (($w - $txwidth - $this->cell_padding['L'] - $this->cell_padding['R']) / ($ns?$ns:1));
  5104. foreach ($uniblock as $uk => $uniarr) {
  5105. if (($uk % 2) == 0) {
  5106. // x space to skip
  5107. if ($spacewidth != 0) {
  5108. // justification shift
  5109. $xshift += (count(array_keys($uniarr, 32)) * $spw);
  5110. }
  5111. $xshift += $this->GetArrStringWidth($uniarr); // + shift justification
  5112. } else {
  5113. // character to print
  5114. $topchr = TCPDF_FONTS::arrUTF8ToUTF16BE($uniarr, false);
  5115. $topchr = TCPDF_STATIC::_escape($topchr);
  5116. $s .= sprintf(' BT %F %F Td [(%s)] TJ ET', ($xdk + ($xshift * $k)), $ty, $topchr);
  5117. }
  5118. }
  5119. }
  5120. if ($this->underline) {
  5121. $s .= ' '.$this->_dounderlinew($xdx, $basefonty, $width);
  5122. }
  5123. if ($this->linethrough) {
  5124. $s .= ' '.$this->_dolinethroughw($xdx, $basefonty, $width);
  5125. }
  5126. if ($this->overline) {
  5127. $s .= ' '.$this->_dooverlinew($xdx, $basefonty, $width);
  5128. }
  5129. if ($this->ColorFlag AND ($this->textrendermode < 4)) {
  5130. $s .= ' Q';
  5131. }
  5132. if ($link) {
  5133. $this->Link($xdx, $yt, $width, ($this->FontAscent + $this->FontDescent), $link, $ns);
  5134. }
  5135. }
  5136. // output cell
  5137. if ($s) {
  5138. // output cell
  5139. $rs .= $s;
  5140. if ($this->font_spacing != 0) {
  5141. // reset font spacing mode
  5142. $rs .= ' BT 0 Tc ET';
  5143. }
  5144. if ($this->font_stretching != 100) {
  5145. // reset font stretching mode
  5146. $rs .= ' BT 100 Tz ET';
  5147. }
  5148. }
  5149. // reset word spacing
  5150. if (!$this->isUnicodeFont() AND ($align == 'J')) {
  5151. $rs .= ' BT 0 Tw ET';
  5152. }
  5153. // reset stretching and spacing
  5154. $this->font_stretching = $prev_font_stretching;
  5155. $this->font_spacing = $prev_font_spacing;
  5156. $this->lasth = $h;
  5157. if ($ln > 0) {
  5158. //Go to the beginning of the next line
  5159. $this->y = $y + $h + $this->cell_margin['B'];
  5160. if ($ln == 1) {
  5161. if ($this->rtl) {
  5162. $this->x = $this->w - $this->rMargin;
  5163. } else {
  5164. $this->x = $this->lMargin;
  5165. }
  5166. }
  5167. } else {
  5168. // go left or right by case
  5169. if ($this->rtl) {
  5170. $this->x = $x - $w - $this->cell_margin['L'];
  5171. } else {
  5172. $this->x = $x + $w + $this->cell_margin['R'];
  5173. }
  5174. }
  5175. $gstyles = ''.$this->linestyleWidth.' '.$this->linestyleCap.' '.$this->linestyleJoin.' '.$this->linestyleDash.' '.$this->DrawColor.' '.$this->FillColor."\n";
  5176. $rs = $gstyles.$rs;
  5177. $this->cell_padding = $prev_cell_padding;
  5178. $this->cell_margin = $prev_cell_margin;
  5179. return $rs;
  5180. }
  5181. /**
  5182. * Replace a char if is defined on the current font.
  5183. * @param $oldchar (int) Integer code (unicode) of the character to replace.
  5184. * @param $newchar (int) Integer code (unicode) of the new character.
  5185. * @return int the replaced char or the old char in case the new char i not defined
  5186. * @protected
  5187. * @since 5.9.167 (2012-06-22)
  5188. */
  5189. protected function replaceChar($oldchar, $newchar) {
  5190. if ($this->isCharDefined($newchar)) {
  5191. // add the new char on the subset list
  5192. $this->CurrentFont['subsetchars'][$newchar] = true;
  5193. // return the new character
  5194. return $newchar;
  5195. }
  5196. // return the old char
  5197. return $oldchar;
  5198. }
  5199. /**
  5200. * Returns the code to draw the cell border
  5201. * @param $x (float) X coordinate.
  5202. * @param $y (float) Y coordinate.
  5203. * @param $w (float) Cell width.
  5204. * @param $h (float) Cell height.
  5205. * @param $brd (mixed) Indicates if borders must be drawn around the cell. The value can be a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul> or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul> or an array of line styles for each border group - for example: array('LTRB' => array('width' => 2, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0)))
  5206. * @return string containing cell border code
  5207. * @protected
  5208. * @see SetLineStyle()
  5209. * @since 5.7.000 (2010-08-02)
  5210. */
  5211. protected function getCellBorder($x, $y, $w, $h, $brd) {
  5212. $s = ''; // string to be returned
  5213. if (empty($brd)) {
  5214. return $s;
  5215. }
  5216. if ($brd == 1) {
  5217. $brd = array('LRTB' => true);
  5218. }
  5219. // calculate coordinates for border
  5220. $k = $this->k;
  5221. if ($this->rtl) {
  5222. $xeL = ($x - $w) * $k;
  5223. $xeR = $x * $k;
  5224. } else {
  5225. $xeL = $x * $k;
  5226. $xeR = ($x + $w) * $k;
  5227. }
  5228. $yeL = (($this->h - ($y + $h)) * $k);
  5229. $yeT = (($this->h - $y) * $k);
  5230. $xeT = $xeL;
  5231. $xeB = $xeR;
  5232. $yeR = $yeT;
  5233. $yeB = $yeL;
  5234. if (is_string($brd)) {
  5235. // convert string to array
  5236. $slen = strlen($brd);
  5237. $newbrd = array();
  5238. for ($i = 0; $i < $slen; ++$i) {
  5239. $newbrd[$brd[$i]] = array('cap' => 'square', 'join' => 'miter');
  5240. }
  5241. $brd = $newbrd;
  5242. }
  5243. if (isset($brd['mode'])) {
  5244. $mode = $brd['mode'];
  5245. unset($brd['mode']);
  5246. } else {
  5247. $mode = 'normal';
  5248. }
  5249. foreach ($brd as $border => $style) {
  5250. if (is_array($style) AND !empty($style)) {
  5251. // apply border style
  5252. $prev_style = $this->linestyleWidth.' '.$this->linestyleCap.' '.$this->linestyleJoin.' '.$this->linestyleDash.' '.$this->DrawColor.' ';
  5253. $s .= $this->SetLineStyle($style, true)."\n";
  5254. }
  5255. switch ($mode) {
  5256. case 'ext': {
  5257. $off = (($this->LineWidth / 2) * $k);
  5258. $xL = $xeL - $off;
  5259. $xR = $xeR + $off;
  5260. $yT = $yeT + $off;
  5261. $yL = $yeL - $off;
  5262. $xT = $xL;
  5263. $xB = $xR;
  5264. $yR = $yT;
  5265. $yB = $yL;
  5266. $w += $this->LineWidth;
  5267. $h += $this->LineWidth;
  5268. break;
  5269. }
  5270. case 'int': {
  5271. $off = ($this->LineWidth / 2) * $k;
  5272. $xL = $xeL + $off;
  5273. $xR = $xeR - $off;
  5274. $yT = $yeT - $off;
  5275. $yL = $yeL + $off;
  5276. $xT = $xL;
  5277. $xB = $xR;
  5278. $yR = $yT;
  5279. $yB = $yL;
  5280. $w -= $this->LineWidth;
  5281. $h -= $this->LineWidth;
  5282. break;
  5283. }
  5284. case 'normal':
  5285. default: {
  5286. $xL = $xeL;
  5287. $xT = $xeT;
  5288. $xB = $xeB;
  5289. $xR = $xeR;
  5290. $yL = $yeL;
  5291. $yT = $yeT;
  5292. $yB = $yeB;
  5293. $yR = $yeR;
  5294. break;
  5295. }
  5296. }
  5297. // draw borders by case
  5298. if (strlen($border) == 4) {
  5299. $s .= sprintf('%F %F %F %F re S ', $xT, $yT, ($w * $k), (-$h * $k));
  5300. } elseif (strlen($border) == 3) {
  5301. if (strpos($border,'B') === false) { // LTR
  5302. $s .= sprintf('%F %F m ', $xL, $yL);
  5303. $s .= sprintf('%F %F l ', $xT, $yT);
  5304. $s .= sprintf('%F %F l ', $xR, $yR);
  5305. $s .= sprintf('%F %F l ', $xB, $yB);
  5306. $s .= 'S ';
  5307. } elseif (strpos($border,'L') === false) { // TRB
  5308. $s .= sprintf('%F %F m ', $xT, $yT);
  5309. $s .= sprintf('%F %F l ', $xR, $yR);
  5310. $s .= sprintf('%F %F l ', $xB, $yB);
  5311. $s .= sprintf('%F %F l ', $xL, $yL);
  5312. $s .= 'S ';
  5313. } elseif (strpos($border,'T') === false) { // RBL
  5314. $s .= sprintf('%F %F m ', $xR, $yR);
  5315. $s .= sprintf('%F %F l ', $xB, $yB);
  5316. $s .= sprintf('%F %F l ', $xL, $yL);
  5317. $s .= sprintf('%F %F l ', $xT, $yT);
  5318. $s .= 'S ';
  5319. } elseif (strpos($border,'R') === false) { // BLT
  5320. $s .= sprintf('%F %F m ', $xB, $yB);
  5321. $s .= sprintf('%F %F l ', $xL, $yL);
  5322. $s .= sprintf('%F %F l ', $xT, $yT);
  5323. $s .= sprintf('%F %F l ', $xR, $yR);
  5324. $s .= 'S ';
  5325. }
  5326. } elseif (strlen($border) == 2) {
  5327. if ((strpos($border,'L') !== false) AND (strpos($border,'T') !== false)) { // LT
  5328. $s .= sprintf('%F %F m ', $xL, $yL);
  5329. $s .= sprintf('%F %F l ', $xT, $yT);
  5330. $s .= sprintf('%F %F l ', $xR, $yR);
  5331. $s .= 'S ';
  5332. } elseif ((strpos($border,'T') !== false) AND (strpos($border,'R') !== false)) { // TR
  5333. $s .= sprintf('%F %F m ', $xT, $yT);
  5334. $s .= sprintf('%F %F l ', $xR, $yR);
  5335. $s .= sprintf('%F %F l ', $xB, $yB);
  5336. $s .= 'S ';
  5337. } elseif ((strpos($border,'R') !== false) AND (strpos($border,'B') !== false)) { // RB
  5338. $s .= sprintf('%F %F m ', $xR, $yR);
  5339. $s .= sprintf('%F %F l ', $xB, $yB);
  5340. $s .= sprintf('%F %F l ', $xL, $yL);
  5341. $s .= 'S ';
  5342. } elseif ((strpos($border,'B') !== false) AND (strpos($border,'L') !== false)) { // BL
  5343. $s .= sprintf('%F %F m ', $xB, $yB);
  5344. $s .= sprintf('%F %F l ', $xL, $yL);
  5345. $s .= sprintf('%F %F l ', $xT, $yT);
  5346. $s .= 'S ';
  5347. } elseif ((strpos($border,'L') !== false) AND (strpos($border,'R') !== false)) { // LR
  5348. $s .= sprintf('%F %F m ', $xL, $yL);
  5349. $s .= sprintf('%F %F l ', $xT, $yT);
  5350. $s .= 'S ';
  5351. $s .= sprintf('%F %F m ', $xR, $yR);
  5352. $s .= sprintf('%F %F l ', $xB, $yB);
  5353. $s .= 'S ';
  5354. } elseif ((strpos($border,'T') !== false) AND (strpos($border,'B') !== false)) { // TB
  5355. $s .= sprintf('%F %F m ', $xT, $yT);
  5356. $s .= sprintf('%F %F l ', $xR, $yR);
  5357. $s .= 'S ';
  5358. $s .= sprintf('%F %F m ', $xB, $yB);
  5359. $s .= sprintf('%F %F l ', $xL, $yL);
  5360. $s .= 'S ';
  5361. }
  5362. } else { // strlen($border) == 1
  5363. if (strpos($border,'L') !== false) { // L
  5364. $s .= sprintf('%F %F m ', $xL, $yL);
  5365. $s .= sprintf('%F %F l ', $xT, $yT);
  5366. $s .= 'S ';
  5367. } elseif (strpos($border,'T') !== false) { // T
  5368. $s .= sprintf('%F %F m ', $xT, $yT);
  5369. $s .= sprintf('%F %F l ', $xR, $yR);
  5370. $s .= 'S ';
  5371. } elseif (strpos($border,'R') !== false) { // R
  5372. $s .= sprintf('%F %F m ', $xR, $yR);
  5373. $s .= sprintf('%F %F l ', $xB, $yB);
  5374. $s .= 'S ';
  5375. } elseif (strpos($border,'B') !== false) { // B
  5376. $s .= sprintf('%F %F m ', $xB, $yB);
  5377. $s .= sprintf('%F %F l ', $xL, $yL);
  5378. $s .= 'S ';
  5379. }
  5380. }
  5381. if (is_array($style) AND !empty($style)) {
  5382. // reset border style to previous value
  5383. $s .= "\n".$this->linestyleWidth.' '.$this->linestyleCap.' '.$this->linestyleJoin.' '.$this->linestyleDash.' '.$this->DrawColor."\n";
  5384. }
  5385. }
  5386. return $s;
  5387. }
  5388. /**
  5389. * This method allows printing text with line breaks.
  5390. * They can be automatic (as soon as the text reaches the right border of the cell) or explicit (via the \n character). As many cells as necessary are output, one below the other.<br />
  5391. * Text can be aligned, centered or justified. The cell block can be framed and the background painted.
  5392. * @param $w (float) Width of cells. If 0, they extend up to the right margin of the page.
  5393. * @param $h (float) Cell minimum height. The cell extends automatically if needed.
  5394. * @param $txt (string) String to print
  5395. * @param $border (mixed) Indicates if borders must be drawn around the cell. The value can be a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul> or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul> or an array of line styles for each border group - for example: array('LTRB' => array('width' => 2, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0)))
  5396. * @param $align (string) Allows to center or align the text. Possible values are:<ul><li>L or empty string: left align</li><li>C: center</li><li>R: right align</li><li>J: justification (default value when $ishtml=false)</li></ul>
  5397. * @param $fill (boolean) Indicates if the cell background must be painted (true) or transparent (false).
  5398. * @param $ln (int) Indicates where the current position should go after the call. Possible values are:<ul><li>0: to the right</li><li>1: to the beginning of the next line [DEFAULT]</li><li>2: below</li></ul>
  5399. * @param $x (float) x position in user units
  5400. * @param $y (float) y position in user units
  5401. * @param $reseth (boolean) if true reset the last cell height (default true).
  5402. * @param $stretch (int) font stretch mode: <ul><li>0 = disabled</li><li>1 = horizontal scaling only if text is larger than cell width</li><li>2 = forced horizontal scaling to fit cell width</li><li>3 = character spacing only if text is larger than cell width</li><li>4 = forced character spacing to fit cell width</li></ul> General font stretching and scaling values will be preserved when possible.
  5403. * @param $ishtml (boolean) INTERNAL USE ONLY -- set to true if $txt is HTML content (default = false). Never set this parameter to true, use instead writeHTMLCell() or writeHTML() methods.
  5404. * @param $autopadding (boolean) if true, uses internal padding and automatically adjust it to account for line width.
  5405. * @param $maxh (float) maximum height. It should be >= $h and less then remaining space to the bottom of the page, or 0 for disable this feature. This feature works only when $ishtml=false.
  5406. * @param $valign (string) Vertical alignment of text (requires $maxh = $h > 0). Possible values are:<ul><li>T: TOP</li><li>M: middle</li><li>B: bottom</li></ul>. This feature works only when $ishtml=false and the cell must fit in a single page.
  5407. * @param $fitcell (boolean) if true attempt to fit all the text within the cell by reducing the font size (do not work in HTML mode). $maxh must be greater than 0 and equal to $h.
  5408. * @return int Return the number of cells or 1 for html mode.
  5409. * @public
  5410. * @since 1.3
  5411. * @see SetFont(), SetDrawColor(), SetFillColor(), SetTextColor(), SetLineWidth(), Cell(), Write(), SetAutoPageBreak()
  5412. */
  5413. public function MultiCell($w, $h, $txt, $border=0, $align='J', $fill=false, $ln=1, $x='', $y='', $reseth=true, $stretch=0, $ishtml=false, $autopadding=true, $maxh=0, $valign='T', $fitcell=false) {
  5414. $prev_cell_margin = $this->cell_margin;
  5415. $prev_cell_padding = $this->cell_padding;
  5416. // adjust internal padding
  5417. $this->adjustCellPadding($border);
  5418. $mc_padding = $this->cell_padding;
  5419. $mc_margin = $this->cell_margin;
  5420. $this->cell_padding['T'] = 0;
  5421. $this->cell_padding['B'] = 0;
  5422. $this->setCellMargins(0, 0, 0, 0);
  5423. if (TCPDF_STATIC::empty_string($this->lasth) OR $reseth) {
  5424. // reset row height
  5425. $this->resetLastH();
  5426. }
  5427. if (!TCPDF_STATIC::empty_string($y)) {
  5428. $this->SetY($y); // set y in order to convert negative y values to positive ones
  5429. }
  5430. $y = $this->GetY();
  5431. $resth = 0;
  5432. if (($h > 0) AND $this->inPageBody() AND (($y + $h + $mc_margin['T'] + $mc_margin['B']) > $this->PageBreakTrigger)) {
  5433. // spit cell in more pages/columns
  5434. $newh = ($this->PageBreakTrigger - $y);
  5435. $resth = ($h - $newh); // cell to be printed on the next page/column
  5436. $h = $newh;
  5437. }
  5438. // get current page number
  5439. $startpage = $this->page;
  5440. // get current column
  5441. $startcolumn = $this->current_column;
  5442. if (!TCPDF_STATIC::empty_string($x)) {
  5443. $this->SetX($x);
  5444. } else {
  5445. $x = $this->GetX();
  5446. }
  5447. // check page for no-write regions and adapt page margins if necessary
  5448. list($x, $y) = $this->checkPageRegions(0, $x, $y);
  5449. // apply margins
  5450. $oy = $y + $mc_margin['T'];
  5451. if ($this->rtl) {
  5452. $ox = ($this->w - $x - $mc_margin['R']);
  5453. } else {
  5454. $ox = ($x + $mc_margin['L']);
  5455. }
  5456. $this->x = $ox;
  5457. $this->y = $oy;
  5458. // set width
  5459. if (TCPDF_STATIC::empty_string($w) OR ($w <= 0)) {
  5460. if ($this->rtl) {
  5461. $w = ($this->x - $this->lMargin - $mc_margin['L']);
  5462. } else {
  5463. $w = ($this->w - $this->x - $this->rMargin - $mc_margin['R']);
  5464. }
  5465. }
  5466. // store original margin values
  5467. $lMargin = $this->lMargin;
  5468. $rMargin = $this->rMargin;
  5469. if ($this->rtl) {
  5470. $this->rMargin = ($this->w - $this->x);
  5471. $this->lMargin = ($this->x - $w);
  5472. } else {
  5473. $this->lMargin = ($this->x);
  5474. $this->rMargin = ($this->w - $this->x - $w);
  5475. }
  5476. $this->clMargin = $this->lMargin;
  5477. $this->crMargin = $this->rMargin;
  5478. if ($autopadding) {
  5479. // add top padding
  5480. $this->y += $mc_padding['T'];
  5481. }
  5482. if ($ishtml) { // ******* Write HTML text
  5483. $this->writeHTML($txt, true, false, $reseth, true, $align);
  5484. $nl = 1;
  5485. } else { // ******* Write simple text
  5486. $prev_FontSizePt = $this->FontSizePt;
  5487. if ($fitcell) {
  5488. // ajust height values
  5489. $tobottom = ($this->h - $this->y - $this->bMargin - $this->cell_padding['T'] - $this->cell_padding['B']);
  5490. $h = $maxh = max(min($h, $tobottom), min($maxh, $tobottom));
  5491. }
  5492. // vertical alignment
  5493. if ($maxh > 0) {
  5494. // get text height
  5495. $text_height = $this->getStringHeight($w, $txt, $reseth, $autopadding, $mc_padding, $border);
  5496. if ($fitcell AND ($text_height > $maxh) AND ($this->FontSizePt > 1)) {
  5497. // try to reduce font size to fit text on cell (use a quick search algorithm)
  5498. $fmin = 1;
  5499. $fmax = $this->FontSizePt;
  5500. $diff_epsilon = (1 / $this->k); // one point (min resolution)
  5501. $maxit = (2 * min(100, max(10, intval($fmax)))); // max number of iterations
  5502. while ($maxit >= 0) {
  5503. $fmid = (($fmax + $fmin) / 2);
  5504. $this->SetFontSize($fmid, false);
  5505. $this->resetLastH();
  5506. $text_height = $this->getStringHeight($w, $txt, $reseth, $autopadding, $mc_padding, $border);
  5507. $diff = ($maxh - $text_height);
  5508. if ($diff >= 0) {
  5509. if ($diff <= $diff_epsilon) {
  5510. break;
  5511. }
  5512. $fmin = $fmid;
  5513. } else {
  5514. $fmax = $fmid;
  5515. }
  5516. --$maxit;
  5517. }
  5518. if ($maxit < 0) {
  5519. // premature exit, we get the minimum font value to fit the cell
  5520. $this->SetFontSize($fmin);
  5521. $this->resetLastH();
  5522. $text_height = $this->getStringHeight($w, $txt, $reseth, $autopadding, $mc_padding, $border);
  5523. } else {
  5524. $this->SetFontSize($fmid);
  5525. $this->resetLastH();
  5526. }
  5527. }
  5528. if ($text_height < $maxh) {
  5529. if ($valign == 'M') {
  5530. // text vertically centered
  5531. $this->y += (($maxh - $text_height) / 2);
  5532. } elseif ($valign == 'B') {
  5533. // text vertically aligned on bottom
  5534. $this->y += ($maxh - $text_height);
  5535. }
  5536. }
  5537. }
  5538. $nl = $this->Write($this->lasth, $txt, '', 0, $align, true, $stretch, false, true, $maxh, 0, $mc_margin);
  5539. if ($fitcell) {
  5540. // restore font size
  5541. $this->SetFontSize($prev_FontSizePt);
  5542. }
  5543. }
  5544. if ($autopadding) {
  5545. // add bottom padding
  5546. $this->y += $mc_padding['B'];
  5547. }
  5548. // Get end-of-text Y position
  5549. $currentY = $this->y;
  5550. // get latest page number
  5551. $endpage = $this->page;
  5552. if ($resth > 0) {
  5553. $skip = ($endpage - $startpage);
  5554. $tmpresth = $resth;
  5555. while ($tmpresth > 0) {
  5556. if ($skip <= 0) {
  5557. // add a page (or trig AcceptPageBreak() for multicolumn mode)
  5558. $this->checkPageBreak($this->PageBreakTrigger + 1);
  5559. }
  5560. if ($this->num_columns > 1) {
  5561. $tmpresth -= ($this->h - $this->y - $this->bMargin);
  5562. } else {
  5563. $tmpresth -= ($this->h - $this->tMargin - $this->bMargin);
  5564. }
  5565. --$skip;
  5566. }
  5567. $currentY = $this->y;
  5568. $endpage = $this->page;
  5569. }
  5570. // get latest column
  5571. $endcolumn = $this->current_column;
  5572. if ($this->num_columns == 0) {
  5573. $this->num_columns = 1;
  5574. }
  5575. // disable page regions check
  5576. $check_page_regions = $this->check_page_regions;
  5577. $this->check_page_regions = false;
  5578. // get border modes
  5579. $border_start = TCPDF_STATIC::getBorderMode($border, $position='start', $this->opencell);
  5580. $border_end = TCPDF_STATIC::getBorderMode($border, $position='end', $this->opencell);
  5581. $border_middle = TCPDF_STATIC::getBorderMode($border, $position='middle', $this->opencell);
  5582. // design borders around HTML cells.
  5583. for ($page = $startpage; $page <= $endpage; ++$page) { // for each page
  5584. $ccode = '';
  5585. $this->setPage($page);
  5586. if ($this->num_columns < 2) {
  5587. // single-column mode
  5588. $this->SetX($x);
  5589. $this->y = $this->tMargin;
  5590. }
  5591. // account for margin changes
  5592. if ($page > $startpage) {
  5593. if (($this->rtl) AND ($this->pagedim[$page]['orm'] != $this->pagedim[$startpage]['orm'])) {
  5594. $this->x -= ($this->pagedim[$page]['orm'] - $this->pagedim[$startpage]['orm']);
  5595. } elseif ((!$this->rtl) AND ($this->pagedim[$page]['olm'] != $this->pagedim[$startpage]['olm'])) {
  5596. $this->x += ($this->pagedim[$page]['olm'] - $this->pagedim[$startpage]['olm']);
  5597. }
  5598. }
  5599. if ($startpage == $endpage) {
  5600. // single page
  5601. for ($column = $startcolumn; $column <= $endcolumn; ++$column) { // for each column
  5602. if ($column != $this->current_column) {
  5603. $this->selectColumn($column);
  5604. }
  5605. if ($this->rtl) {
  5606. $this->x -= $mc_margin['R'];
  5607. } else {
  5608. $this->x += $mc_margin['L'];
  5609. }
  5610. if ($startcolumn == $endcolumn) { // single column
  5611. $cborder = $border;
  5612. $h = max($h, ($currentY - $oy));
  5613. $this->y = $oy;
  5614. } elseif ($column == $startcolumn) { // first column
  5615. $cborder = $border_start;
  5616. $this->y = $oy;
  5617. $h = $this->h - $this->y - $this->bMargin;
  5618. } elseif ($column == $endcolumn) { // end column
  5619. $cborder = $border_end;
  5620. $h = $currentY - $this->y;
  5621. if ($resth > $h) {
  5622. $h = $resth;
  5623. }
  5624. } else { // middle column
  5625. $cborder = $border_middle;
  5626. $h = $this->h - $this->y - $this->bMargin;
  5627. $resth -= $h;
  5628. }
  5629. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  5630. } // end for each column
  5631. } elseif ($page == $startpage) { // first page
  5632. for ($column = $startcolumn; $column < $this->num_columns; ++$column) { // for each column
  5633. if ($column != $this->current_column) {
  5634. $this->selectColumn($column);
  5635. }
  5636. if ($this->rtl) {
  5637. $this->x -= $mc_margin['R'];
  5638. } else {
  5639. $this->x += $mc_margin['L'];
  5640. }
  5641. if ($column == $startcolumn) { // first column
  5642. $cborder = $border_start;
  5643. $this->y = $oy;
  5644. $h = $this->h - $this->y - $this->bMargin;
  5645. } else { // middle column
  5646. $cborder = $border_middle;
  5647. $h = $this->h - $this->y - $this->bMargin;
  5648. $resth -= $h;
  5649. }
  5650. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  5651. } // end for each column
  5652. } elseif ($page == $endpage) { // last page
  5653. for ($column = 0; $column <= $endcolumn; ++$column) { // for each column
  5654. if ($column != $this->current_column) {
  5655. $this->selectColumn($column);
  5656. }
  5657. if ($this->rtl) {
  5658. $this->x -= $mc_margin['R'];
  5659. } else {
  5660. $this->x += $mc_margin['L'];
  5661. }
  5662. if ($column == $endcolumn) {
  5663. // end column
  5664. $cborder = $border_end;
  5665. $h = $currentY - $this->y;
  5666. if ($resth > $h) {
  5667. $h = $resth;
  5668. }
  5669. } else {
  5670. // middle column
  5671. $cborder = $border_middle;
  5672. $h = $this->h - $this->y - $this->bMargin;
  5673. $resth -= $h;
  5674. }
  5675. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  5676. } // end for each column
  5677. } else { // middle page
  5678. for ($column = 0; $column < $this->num_columns; ++$column) { // for each column
  5679. $this->selectColumn($column);
  5680. if ($this->rtl) {
  5681. $this->x -= $mc_margin['R'];
  5682. } else {
  5683. $this->x += $mc_margin['L'];
  5684. }
  5685. $cborder = $border_middle;
  5686. $h = $this->h - $this->y - $this->bMargin;
  5687. $resth -= $h;
  5688. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  5689. } // end for each column
  5690. }
  5691. if ($cborder OR $fill) {
  5692. $offsetlen = strlen($ccode);
  5693. // draw border and fill
  5694. if ($this->inxobj) {
  5695. // we are inside an XObject template
  5696. if (end($this->xobjects[$this->xobjid]['transfmrk']) !== false) {
  5697. $pagemarkkey = key($this->xobjects[$this->xobjid]['transfmrk']);
  5698. $pagemark = $this->xobjects[$this->xobjid]['transfmrk'][$pagemarkkey];
  5699. $this->xobjects[$this->xobjid]['transfmrk'][$pagemarkkey] += $offsetlen;
  5700. } else {
  5701. $pagemark = $this->xobjects[$this->xobjid]['intmrk'];
  5702. $this->xobjects[$this->xobjid]['intmrk'] += $offsetlen;
  5703. }
  5704. $pagebuff = $this->xobjects[$this->xobjid]['outdata'];
  5705. $pstart = substr($pagebuff, 0, $pagemark);
  5706. $pend = substr($pagebuff, $pagemark);
  5707. $this->xobjects[$this->xobjid]['outdata'] = $pstart.$ccode.$pend;
  5708. } else {
  5709. if (end($this->transfmrk[$this->page]) !== false) {
  5710. $pagemarkkey = key($this->transfmrk[$this->page]);
  5711. $pagemark = $this->transfmrk[$this->page][$pagemarkkey];
  5712. $this->transfmrk[$this->page][$pagemarkkey] += $offsetlen;
  5713. } elseif ($this->InFooter) {
  5714. $pagemark = $this->footerpos[$this->page];
  5715. $this->footerpos[$this->page] += $offsetlen;
  5716. } else {
  5717. $pagemark = $this->intmrk[$this->page];
  5718. $this->intmrk[$this->page] += $offsetlen;
  5719. }
  5720. $pagebuff = $this->getPageBuffer($this->page);
  5721. $pstart = substr($pagebuff, 0, $pagemark);
  5722. $pend = substr($pagebuff, $pagemark);
  5723. $this->setPageBuffer($this->page, $pstart.$ccode.$pend);
  5724. }
  5725. }
  5726. } // end for each page
  5727. // restore page regions check
  5728. $this->check_page_regions = $check_page_regions;
  5729. // Get end-of-cell Y position
  5730. $currentY = $this->GetY();
  5731. // restore previous values
  5732. if ($this->num_columns > 1) {
  5733. $this->selectColumn();
  5734. } else {
  5735. // restore original margins
  5736. $this->lMargin = $lMargin;
  5737. $this->rMargin = $rMargin;
  5738. if ($this->page > $startpage) {
  5739. // check for margin variations between pages (i.e. booklet mode)
  5740. $dl = ($this->pagedim[$this->page]['olm'] - $this->pagedim[$startpage]['olm']);
  5741. $dr = ($this->pagedim[$this->page]['orm'] - $this->pagedim[$startpage]['orm']);
  5742. if (($dl != 0) OR ($dr != 0)) {
  5743. $this->lMargin += $dl;
  5744. $this->rMargin += $dr;
  5745. }
  5746. }
  5747. }
  5748. if ($ln > 0) {
  5749. //Go to the beginning of the next line
  5750. $this->SetY($currentY + $mc_margin['B']);
  5751. if ($ln == 2) {
  5752. $this->SetX($x + $w + $mc_margin['L'] + $mc_margin['R']);
  5753. }
  5754. } else {
  5755. // go left or right by case
  5756. $this->setPage($startpage);
  5757. $this->y = $y;
  5758. $this->SetX($x + $w + $mc_margin['L'] + $mc_margin['R']);
  5759. }
  5760. $this->setContentMark();
  5761. $this->cell_padding = $prev_cell_padding;
  5762. $this->cell_margin = $prev_cell_margin;
  5763. $this->clMargin = $this->lMargin;
  5764. $this->crMargin = $this->rMargin;
  5765. return $nl;
  5766. }
  5767. /**
  5768. * This method return the estimated number of lines for print a simple text string using Multicell() method.
  5769. * @param $txt (string) String for calculating his height
  5770. * @param $w (float) Width of cells. If 0, they extend up to the right margin of the page.
  5771. * @param $reseth (boolean) if true reset the last cell height (default false).
  5772. * @param $autopadding (boolean) if true, uses internal padding and automatically adjust it to account for line width (default true).
  5773. * @param $cellpadding (float) Internal cell padding, if empty uses default cell padding.
  5774. * @param $border (mixed) Indicates if borders must be drawn around the cell. The value can be a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul> or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul> or an array of line styles for each border group - for example: array('LTRB' => array('width' => 2, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0)))
  5775. * @return float Return the minimal height needed for multicell method for printing the $txt param.
  5776. * @author Alexander Escalona Fern\E1ndez, Nicola Asuni
  5777. * @public
  5778. * @since 4.5.011
  5779. */
  5780. public function getNumLines($txt, $w=0, $reseth=false, $autopadding=true, $cellpadding='', $border=0) {
  5781. if ($txt === NULL) {
  5782. return 0;
  5783. }
  5784. if ($txt === '') {
  5785. // empty string
  5786. return 1;
  5787. }
  5788. // adjust internal padding
  5789. $prev_cell_padding = $this->cell_padding;
  5790. $prev_lasth = $this->lasth;
  5791. if (is_array($cellpadding)) {
  5792. $this->cell_padding = $cellpadding;
  5793. }
  5794. $this->adjustCellPadding($border);
  5795. if (TCPDF_STATIC::empty_string($w) OR ($w <= 0)) {
  5796. if ($this->rtl) {
  5797. $w = $this->x - $this->lMargin;
  5798. } else {
  5799. $w = $this->w - $this->rMargin - $this->x;
  5800. }
  5801. }
  5802. $wmax = $w - $this->cell_padding['L'] - $this->cell_padding['R'];
  5803. if ($reseth) {
  5804. // reset row height
  5805. $this->resetLastH();
  5806. }
  5807. $lines = 1;
  5808. $sum = 0;
  5809. $chars = TCPDF_FONTS::utf8Bidi(TCPDF_FONTS::UTF8StringToArray($txt, $this->isunicode, $this->CurrentFont), $txt, $this->tmprtl, $this->isunicode, $this->CurrentFont);
  5810. $charsWidth = $this->GetArrStringWidth($chars, '', '', 0, true);
  5811. $length = count($chars);
  5812. $lastSeparator = -1;
  5813. for ($i = 0; $i < $length; ++$i) {
  5814. $c = $chars[$i];
  5815. $charWidth = $charsWidth[$i];
  5816. if (($c != 160)
  5817. AND (($c == 173)
  5818. OR preg_match($this->re_spaces, TCPDF_FONTS::unichr($c, $this->isunicode))
  5819. OR (($c == 45)
  5820. AND ($i > 0) AND ($i < ($length - 1))
  5821. AND @preg_match('/[\p{L}]/'.$this->re_space['m'], TCPDF_FONTS::unichr($chars[($i - 1)], $this->isunicode))
  5822. AND @preg_match('/[\p{L}]/'.$this->re_space['m'], TCPDF_FONTS::unichr($chars[($i + 1)], $this->isunicode))
  5823. )
  5824. )
  5825. ) {
  5826. $lastSeparator = $i;
  5827. }
  5828. if ((($sum + $charWidth) > $wmax) OR ($c == 10)) {
  5829. ++$lines;
  5830. if ($c == 10) {
  5831. $lastSeparator = -1;
  5832. $sum = 0;
  5833. } elseif ($lastSeparator != -1) {
  5834. $i = $lastSeparator;
  5835. $lastSeparator = -1;
  5836. $sum = 0;
  5837. } else {
  5838. $sum = $charWidth;
  5839. }
  5840. } else {
  5841. $sum += $charWidth;
  5842. }
  5843. }
  5844. if ($chars[($length - 1)] == 10) {
  5845. --$lines;
  5846. }
  5847. $this->cell_padding = $prev_cell_padding;
  5848. $this->lasth = $prev_lasth;
  5849. return $lines;
  5850. }
  5851. /**
  5852. * This method return the estimated height needed for printing a simple text string using the Multicell() method.
  5853. * Generally, if you want to know the exact height for a block of content you can use the following alternative technique:
  5854. * @pre
  5855. * // store current object
  5856. * $pdf->startTransaction();
  5857. * // store starting values
  5858. * $start_y = $pdf->GetY();
  5859. * $start_page = $pdf->getPage();
  5860. * // call your printing functions with your parameters
  5861. * // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  5862. * $pdf->MultiCell($w=0, $h=0, $txt, $border=1, $align='L', $fill=false, $ln=1, $x='', $y='', $reseth=true, $stretch=0, $ishtml=false, $autopadding=true, $maxh=0);
  5863. * // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  5864. * // get the new Y
  5865. * $end_y = $pdf->GetY();
  5866. * $end_page = $pdf->getPage();
  5867. * // calculate height
  5868. * $height = 0;
  5869. * if ($end_page == $start_page) {
  5870. * $height = $end_y - $start_y;
  5871. * } else {
  5872. * for ($page=$start_page; $page <= $end_page; ++$page) {
  5873. * $this->setPage($page);
  5874. * if ($page == $start_page) {
  5875. * // first page
  5876. * $height += $this->h - $start_y - $this->bMargin;
  5877. * } elseif ($page == $end_page) {
  5878. * // last page
  5879. * $height += $end_y - $this->tMargin;
  5880. * } else {
  5881. * $height += $this->h - $this->tMargin - $this->bMargin;
  5882. * }
  5883. * }
  5884. * }
  5885. * // restore previous object
  5886. * $pdf = $pdf->rollbackTransaction();
  5887. *
  5888. * @param $w (float) Width of cells. If 0, they extend up to the right margin of the page.
  5889. * @param $txt (string) String for calculating his height
  5890. * @param $reseth (boolean) if true reset the last cell height (default false).
  5891. * @param $autopadding (boolean) if true, uses internal padding and automatically adjust it to account for line width (default true).
  5892. * @param $cellpadding (float) Internal cell padding, if empty uses default cell padding.
  5893. * @param $border (mixed) Indicates if borders must be drawn around the cell. The value can be a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul> or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul> or an array of line styles for each border group - for example: array('LTRB' => array('width' => 2, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0)))
  5894. * @return float Return the minimal height needed for multicell method for printing the $txt param.
  5895. * @author Nicola Asuni, Alexander Escalona Fern\E1ndez
  5896. * @public
  5897. */
  5898. public function getStringHeight($w, $txt, $reseth=false, $autopadding=true, $cellpadding='', $border=0) {
  5899. // adjust internal padding
  5900. $prev_cell_padding = $this->cell_padding;
  5901. $prev_lasth = $this->lasth;
  5902. if (is_array($cellpadding)) {
  5903. $this->cell_padding = $cellpadding;
  5904. }
  5905. $this->adjustCellPadding($border);
  5906. $lines = $this->getNumLines($txt, $w, $reseth, $autopadding, $cellpadding, $border);
  5907. $height = $this->getCellHeight(($lines * $this->FontSize), $autopadding);
  5908. $this->cell_padding = $prev_cell_padding;
  5909. $this->lasth = $prev_lasth;
  5910. return $height;
  5911. }
  5912. /**
  5913. * This method prints text from the current position.<br />
  5914. * @param $h (float) Line height
  5915. * @param $txt (string) String to print
  5916. * @param $link (mixed) URL or identifier returned by AddLink()
  5917. * @param $fill (boolean) Indicates if the cell background must be painted (true) or transparent (false).
  5918. * @param $align (string) Allows to center or align the text. Possible values are:<ul><li>L or empty string: left align (default value)</li><li>C: center</li><li>R: right align</li><li>J: justify</li></ul>
  5919. * @param $ln (boolean) if true set cursor at the bottom of the line, otherwise set cursor at the top of the line.
  5920. * @param $stretch (int) font stretch mode: <ul><li>0 = disabled</li><li>1 = horizontal scaling only if text is larger than cell width</li><li>2 = forced horizontal scaling to fit cell width</li><li>3 = character spacing only if text is larger than cell width</li><li>4 = forced character spacing to fit cell width</li></ul> General font stretching and scaling values will be preserved when possible.
  5921. * @param $firstline (boolean) if true prints only the first line and return the remaining string.
  5922. * @param $firstblock (boolean) if true the string is the starting of a line.
  5923. * @param $maxh (float) maximum height. It should be >= $h and less then remaining space to the bottom of the page, or 0 for disable this feature.
  5924. * @param $wadj (float) first line width will be reduced by this amount (used in HTML mode).
  5925. * @param $margin (array) margin array of the parent container
  5926. * @return mixed Return the number of cells or the remaining string if $firstline = true.
  5927. * @public
  5928. * @since 1.5
  5929. */
  5930. public function Write($h, $txt, $link='', $fill=false, $align='', $ln=false, $stretch=0, $firstline=false, $firstblock=false, $maxh=0, $wadj=0, $margin='') {
  5931. // check page for no-write regions and adapt page margins if necessary
  5932. list($this->x, $this->y) = $this->checkPageRegions($h, $this->x, $this->y);
  5933. if (strlen($txt) == 0) {
  5934. // fix empty text
  5935. $txt = ' ';
  5936. }
  5937. if ($margin === '') {
  5938. // set default margins
  5939. $margin = $this->cell_margin;
  5940. }
  5941. // remove carriage returns
  5942. $s = str_replace("\r", '', $txt);
  5943. // check if string contains arabic text
  5944. if (preg_match(TCPDF_FONT_DATA::$uni_RE_PATTERN_ARABIC, $s)) {
  5945. $arabic = true;
  5946. } else {
  5947. $arabic = false;
  5948. }
  5949. // check if string contains RTL text
  5950. if ($arabic OR ($this->tmprtl == 'R') OR preg_match(TCPDF_FONT_DATA::$uni_RE_PATTERN_RTL, $s)) {
  5951. $rtlmode = true;
  5952. } else {
  5953. $rtlmode = false;
  5954. }
  5955. // get a char width
  5956. $chrwidth = $this->GetCharWidth(46); // dot character
  5957. // get array of unicode values
  5958. $chars = TCPDF_FONTS::UTF8StringToArray($s, $this->isunicode, $this->CurrentFont);
  5959. // calculate maximum width for a single character on string
  5960. $chrw = $this->GetArrStringWidth($chars, '', '', 0, true);
  5961. array_walk($chrw, array($this, 'getRawCharWidth'));
  5962. $maxchwidth = max($chrw);
  5963. // get array of chars
  5964. $uchars = TCPDF_FONTS::UTF8ArrayToUniArray($chars, $this->isunicode);
  5965. // get the number of characters
  5966. $nb = count($chars);
  5967. // replacement for SHY character (minus symbol)
  5968. $shy_replacement = 45;
  5969. $shy_replacement_char = TCPDF_FONTS::unichr($shy_replacement, $this->isunicode);
  5970. // widht for SHY replacement
  5971. $shy_replacement_width = $this->GetCharWidth($shy_replacement);
  5972. // page width
  5973. $pw = $w = $this->w - $this->lMargin - $this->rMargin;
  5974. // calculate remaining line width ($w)
  5975. if ($this->rtl) {
  5976. $w = $this->x - $this->lMargin;
  5977. } else {
  5978. $w = $this->w - $this->rMargin - $this->x;
  5979. }
  5980. // max column width
  5981. $wmax = ($w - $wadj);
  5982. if (!$firstline) {
  5983. $wmax -= ($this->cell_padding['L'] + $this->cell_padding['R']);
  5984. }
  5985. if ((!$firstline) AND (($chrwidth > $wmax) OR ($maxchwidth > $wmax))) {
  5986. // the maximum width character do not fit on column
  5987. return '';
  5988. }
  5989. // minimum row height
  5990. $row_height = max($h, $this->getCellHeight($this->FontSize));
  5991. // max Y
  5992. $maxy = $this->y + $maxh - max($row_height, $h);
  5993. $start_page = $this->page;
  5994. $i = 0; // character position
  5995. $j = 0; // current starting position
  5996. $sep = -1; // position of the last blank space
  5997. $prevsep = $sep; // previous separator
  5998. $shy = false; // true if the last blank is a soft hypen (SHY)
  5999. $prevshy = $shy; // previous shy mode
  6000. $l = 0; // current string length
  6001. $nl = 0; //number of lines
  6002. $linebreak = false;
  6003. $pc = 0; // previous character
  6004. // for each character
  6005. while ($i < $nb) {
  6006. if (($maxh > 0) AND ($this->y > $maxy) ) {
  6007. break;
  6008. }
  6009. //Get the current character
  6010. $c = $chars[$i];
  6011. if ($c == 10) { // 10 = "\n" = new line
  6012. //Explicit line break
  6013. if ($align == 'J') {
  6014. if ($this->rtl) {
  6015. $talign = 'R';
  6016. } else {
  6017. $talign = 'L';
  6018. }
  6019. } else {
  6020. $talign = $align;
  6021. }
  6022. $tmpstr = TCPDF_FONTS::UniArrSubString($uchars, $j, $i);
  6023. if ($firstline) {
  6024. $startx = $this->x;
  6025. $tmparr = array_slice($chars, $j, ($i - $j));
  6026. if ($rtlmode) {
  6027. $tmparr = TCPDF_FONTS::utf8Bidi($tmparr, $tmpstr, $this->tmprtl, $this->isunicode, $this->CurrentFont);
  6028. }
  6029. $linew = $this->GetArrStringWidth($tmparr);
  6030. unset($tmparr);
  6031. if ($this->rtl) {
  6032. $this->endlinex = $startx - $linew;
  6033. } else {
  6034. $this->endlinex = $startx + $linew;
  6035. }
  6036. $w = $linew;
  6037. $tmpcellpadding = $this->cell_padding;
  6038. if ($maxh == 0) {
  6039. $this->SetCellPadding(0);
  6040. }
  6041. }
  6042. if ($firstblock AND $this->isRTLTextDir()) {
  6043. $tmpstr = $this->stringRightTrim($tmpstr);
  6044. }
  6045. // Skip newlines at the beginning of a page or column
  6046. if (!empty($tmpstr) OR ($this->y < ($this->PageBreakTrigger - $row_height))) {
  6047. $this->Cell($w, $h, $tmpstr, 0, 1, $talign, $fill, $link, $stretch);
  6048. }
  6049. unset($tmpstr);
  6050. if ($firstline) {
  6051. $this->cell_padding = $tmpcellpadding;
  6052. return (TCPDF_FONTS::UniArrSubString($uchars, $i));
  6053. }
  6054. ++$nl;
  6055. $j = $i + 1;
  6056. $l = 0;
  6057. $sep = -1;
  6058. $prevsep = $sep;
  6059. $shy = false;
  6060. // account for margin changes
  6061. if ((($this->y + $this->lasth) > $this->PageBreakTrigger) AND ($this->inPageBody())) {
  6062. $this->AcceptPageBreak();
  6063. if ($this->rtl) {
  6064. $this->x -= $margin['R'];
  6065. } else {
  6066. $this->x += $margin['L'];
  6067. }
  6068. $this->lMargin += $margin['L'];
  6069. $this->rMargin += $margin['R'];
  6070. }
  6071. $w = $this->getRemainingWidth();
  6072. $wmax = ($w - $this->cell_padding['L'] - $this->cell_padding['R']);
  6073. } else {
  6074. // 160 is the non-breaking space.
  6075. // 173 is SHY (Soft Hypen).
  6076. // \p{Z} or \p{Separator}: any kind of Unicode whitespace or invisible separator.
  6077. // \p{Lo} or \p{Other_Letter}: a Unicode letter or ideograph that does not have lowercase and uppercase variants.
  6078. // \p{Lo} is needed because Chinese characters are packed next to each other without spaces in between.
  6079. if (($c != 160)
  6080. AND (($c == 173)
  6081. OR preg_match($this->re_spaces, TCPDF_FONTS::unichr($c, $this->isunicode))
  6082. OR (($c == 45)
  6083. AND ($i < ($nb - 1))
  6084. AND @preg_match('/[\p{L}]/'.$this->re_space['m'], TCPDF_FONTS::unichr($pc, $this->isunicode))
  6085. AND @preg_match('/[\p{L}]/'.$this->re_space['m'], TCPDF_FONTS::unichr($chars[($i + 1)], $this->isunicode))
  6086. )
  6087. )
  6088. ) {
  6089. // update last blank space position
  6090. $prevsep = $sep;
  6091. $sep = $i;
  6092. // check if is a SHY
  6093. if (($c == 173) OR ($c == 45)) {
  6094. $prevshy = $shy;
  6095. $shy = true;
  6096. if ($pc == 45) {
  6097. $tmp_shy_replacement_width = 0;
  6098. $tmp_shy_replacement_char = '';
  6099. } else {
  6100. $tmp_shy_replacement_width = $shy_replacement_width;
  6101. $tmp_shy_replacement_char = $shy_replacement_char;
  6102. }
  6103. } else {
  6104. $shy = false;
  6105. }
  6106. }
  6107. // update string length
  6108. if ($this->isUnicodeFont() AND ($arabic)) {
  6109. // with bidirectional algorithm some chars may be changed affecting the line length
  6110. // *** very slow ***
  6111. $l = $this->GetArrStringWidth(TCPDF_FONTS::utf8Bidi(array_slice($chars, $j, ($i - $j)), '', $this->tmprtl, $this->isunicode, $this->CurrentFont));
  6112. } else {
  6113. $l += $this->GetCharWidth($c);
  6114. }
  6115. if (($l > $wmax) OR (($c == 173) AND (($l + $tmp_shy_replacement_width) >= $wmax))) {
  6116. if (($c == 173) AND (($l + $tmp_shy_replacement_width) > $wmax)) {
  6117. $sep = $prevsep;
  6118. $shy = $prevshy;
  6119. }
  6120. // we have reached the end of column
  6121. if ($sep == -1) {
  6122. // check if the line was already started
  6123. if (($this->rtl AND ($this->x <= ($this->w - $this->rMargin - $this->cell_padding['R'] - $margin['R'] - $chrwidth)))
  6124. OR ((!$this->rtl) AND ($this->x >= ($this->lMargin + $this->cell_padding['L'] + $margin['L'] + $chrwidth)))) {
  6125. // print a void cell and go to next line
  6126. $this->Cell($w, $h, '', 0, 1);
  6127. $linebreak = true;
  6128. if ($firstline) {
  6129. return (TCPDF_FONTS::UniArrSubString($uchars, $j));
  6130. }
  6131. } else {
  6132. // truncate the word because do not fit on column
  6133. $tmpstr = TCPDF_FONTS::UniArrSubString($uchars, $j, $i);
  6134. if ($firstline) {
  6135. $startx = $this->x;
  6136. $tmparr = array_slice($chars, $j, ($i - $j));
  6137. if ($rtlmode) {
  6138. $tmparr = TCPDF_FONTS::utf8Bidi($tmparr, $tmpstr, $this->tmprtl, $this->isunicode, $this->CurrentFont);
  6139. }
  6140. $linew = $this->GetArrStringWidth($tmparr);
  6141. unset($tmparr);
  6142. if ($this->rtl) {
  6143. $this->endlinex = $startx - $linew;
  6144. } else {
  6145. $this->endlinex = $startx + $linew;
  6146. }
  6147. $w = $linew;
  6148. $tmpcellpadding = $this->cell_padding;
  6149. if ($maxh == 0) {
  6150. $this->SetCellPadding(0);
  6151. }
  6152. }
  6153. if ($firstblock AND $this->isRTLTextDir()) {
  6154. $tmpstr = $this->stringRightTrim($tmpstr);
  6155. }
  6156. $this->Cell($w, $h, $tmpstr, 0, 1, $align, $fill, $link, $stretch);
  6157. unset($tmpstr);
  6158. if ($firstline) {
  6159. $this->cell_padding = $tmpcellpadding;
  6160. return (TCPDF_FONTS::UniArrSubString($uchars, $i));
  6161. }
  6162. $j = $i;
  6163. --$i;
  6164. }
  6165. } else {
  6166. // word wrapping
  6167. if ($this->rtl AND (!$firstblock) AND ($sep < $i)) {
  6168. $endspace = 1;
  6169. } else {
  6170. $endspace = 0;
  6171. }
  6172. // check the length of the next string
  6173. $strrest = TCPDF_FONTS::UniArrSubString($uchars, ($sep + $endspace));
  6174. $nextstr = TCPDF_STATIC::pregSplit('/'.$this->re_space['p'].'/', $this->re_space['m'], $this->stringTrim($strrest));
  6175. if (isset($nextstr[0]) AND ($this->GetStringWidth($nextstr[0]) > $pw)) {
  6176. // truncate the word because do not fit on a full page width
  6177. $tmpstr = TCPDF_FONTS::UniArrSubString($uchars, $j, $i);
  6178. if ($firstline) {
  6179. $startx = $this->x;
  6180. $tmparr = array_slice($chars, $j, ($i - $j));
  6181. if ($rtlmode) {
  6182. $tmparr = TCPDF_FONTS::utf8Bidi($tmparr, $tmpstr, $this->tmprtl, $this->isunicode, $this->CurrentFont);
  6183. }
  6184. $linew = $this->GetArrStringWidth($tmparr);
  6185. unset($tmparr);
  6186. if ($this->rtl) {
  6187. $this->endlinex = ($startx - $linew);
  6188. } else {
  6189. $this->endlinex = ($startx + $linew);
  6190. }
  6191. $w = $linew;
  6192. $tmpcellpadding = $this->cell_padding;
  6193. if ($maxh == 0) {
  6194. $this->SetCellPadding(0);
  6195. }
  6196. }
  6197. if ($firstblock AND $this->isRTLTextDir()) {
  6198. $tmpstr = $this->stringRightTrim($tmpstr);
  6199. }
  6200. $this->Cell($w, $h, $tmpstr, 0, 1, $align, $fill, $link, $stretch);
  6201. unset($tmpstr);
  6202. if ($firstline) {
  6203. $this->cell_padding = $tmpcellpadding;
  6204. return (TCPDF_FONTS::UniArrSubString($uchars, $i));
  6205. }
  6206. $j = $i;
  6207. --$i;
  6208. } else {
  6209. // word wrapping
  6210. if ($shy) {
  6211. // add hypen (minus symbol) at the end of the line
  6212. $shy_width = $tmp_shy_replacement_width;
  6213. if ($this->rtl) {
  6214. $shy_char_left = $tmp_shy_replacement_char;
  6215. $shy_char_right = '';
  6216. } else {
  6217. $shy_char_left = '';
  6218. $shy_char_right = $tmp_shy_replacement_char;
  6219. }
  6220. } else {
  6221. $shy_width = 0;
  6222. $shy_char_left = '';
  6223. $shy_char_right = '';
  6224. }
  6225. $tmpstr = TCPDF_FONTS::UniArrSubString($uchars, $j, ($sep + $endspace));
  6226. if ($firstline) {
  6227. $startx = $this->x;
  6228. $tmparr = array_slice($chars, $j, (($sep + $endspace) - $j));
  6229. if ($rtlmode) {
  6230. $tmparr = TCPDF_FONTS::utf8Bidi($tmparr, $tmpstr, $this->tmprtl, $this->isunicode, $this->CurrentFont);
  6231. }
  6232. $linew = $this->GetArrStringWidth($tmparr);
  6233. unset($tmparr);
  6234. if ($this->rtl) {
  6235. $this->endlinex = $startx - $linew - $shy_width;
  6236. } else {
  6237. $this->endlinex = $startx + $linew + $shy_width;
  6238. }
  6239. $w = $linew;
  6240. $tmpcellpadding = $this->cell_padding;
  6241. if ($maxh == 0) {
  6242. $this->SetCellPadding(0);
  6243. }
  6244. }
  6245. // print the line
  6246. if ($firstblock AND $this->isRTLTextDir()) {
  6247. $tmpstr = $this->stringRightTrim($tmpstr);
  6248. }
  6249. $this->Cell($w, $h, $shy_char_left.$tmpstr.$shy_char_right, 0, 1, $align, $fill, $link, $stretch);
  6250. unset($tmpstr);
  6251. if ($firstline) {
  6252. if ($chars[$sep] == 45) {
  6253. $endspace += 1;
  6254. }
  6255. // return the remaining text
  6256. $this->cell_padding = $tmpcellpadding;
  6257. return (TCPDF_FONTS::UniArrSubString($uchars, ($sep + $endspace)));
  6258. }
  6259. $i = $sep;
  6260. $sep = -1;
  6261. $shy = false;
  6262. $j = ($i + 1);
  6263. }
  6264. }
  6265. // account for margin changes
  6266. if ((($this->y + $this->lasth) > $this->PageBreakTrigger) AND ($this->inPageBody())) {
  6267. $this->AcceptPageBreak();
  6268. if ($this->rtl) {
  6269. $this->x -= $margin['R'];
  6270. } else {
  6271. $this->x += $margin['L'];
  6272. }
  6273. $this->lMargin += $margin['L'];
  6274. $this->rMargin += $margin['R'];
  6275. }
  6276. $w = $this->getRemainingWidth();
  6277. $wmax = $w - $this->cell_padding['L'] - $this->cell_padding['R'];
  6278. if ($linebreak) {
  6279. $linebreak = false;
  6280. } else {
  6281. ++$nl;
  6282. $l = 0;
  6283. }
  6284. }
  6285. }
  6286. // save last character
  6287. $pc = $c;
  6288. ++$i;
  6289. } // end while i < nb
  6290. // print last substring (if any)
  6291. if ($l > 0) {
  6292. switch ($align) {
  6293. case 'J':
  6294. case 'C': {
  6295. $w = $w;
  6296. break;
  6297. }
  6298. case 'L': {
  6299. if ($this->rtl) {
  6300. $w = $w;
  6301. } else {
  6302. $w = $l;
  6303. }
  6304. break;
  6305. }
  6306. case 'R': {
  6307. if ($this->rtl) {
  6308. $w = $l;
  6309. } else {
  6310. $w = $w;
  6311. }
  6312. break;
  6313. }
  6314. default: {
  6315. $w = $l;
  6316. break;
  6317. }
  6318. }
  6319. $tmpstr = TCPDF_FONTS::UniArrSubString($uchars, $j, $nb);
  6320. if ($firstline) {
  6321. $startx = $this->x;
  6322. $tmparr = array_slice($chars, $j, ($nb - $j));
  6323. if ($rtlmode) {
  6324. $tmparr = TCPDF_FONTS::utf8Bidi($tmparr, $tmpstr, $this->tmprtl, $this->isunicode, $this->CurrentFont);
  6325. }
  6326. $linew = $this->GetArrStringWidth($tmparr);
  6327. unset($tmparr);
  6328. if ($this->rtl) {
  6329. $this->endlinex = $startx - $linew;
  6330. } else {
  6331. $this->endlinex = $startx + $linew;
  6332. }
  6333. $w = $linew;
  6334. $tmpcellpadding = $this->cell_padding;
  6335. if ($maxh == 0) {
  6336. $this->SetCellPadding(0);
  6337. }
  6338. }
  6339. if ($firstblock AND $this->isRTLTextDir()) {
  6340. $tmpstr = $this->stringRightTrim($tmpstr);
  6341. }
  6342. $this->Cell($w, $h, $tmpstr, 0, $ln, $align, $fill, $link, $stretch);
  6343. unset($tmpstr);
  6344. if ($firstline) {
  6345. $this->cell_padding = $tmpcellpadding;
  6346. return (TCPDF_FONTS::UniArrSubString($uchars, $nb));
  6347. }
  6348. ++$nl;
  6349. }
  6350. if ($firstline) {
  6351. return '';
  6352. }
  6353. return $nl;
  6354. }
  6355. /**
  6356. * Returns the remaining width between the current position and margins.
  6357. * @return int Return the remaining width
  6358. * @protected
  6359. */
  6360. protected function getRemainingWidth() {
  6361. list($this->x, $this->y) = $this->checkPageRegions(0, $this->x, $this->y);
  6362. if ($this->rtl) {
  6363. return ($this->x - $this->lMargin);
  6364. } else {
  6365. return ($this->w - $this->rMargin - $this->x);
  6366. }
  6367. }
  6368. /**
  6369. * Set the block dimensions accounting for page breaks and page/column fitting
  6370. * @param $w (float) width
  6371. * @param $h (float) height
  6372. * @param $x (float) X coordinate
  6373. * @param $y (float) Y coodiante
  6374. * @param $fitonpage (boolean) if true the block is resized to not exceed page dimensions.
  6375. * @return array($w, $h, $x, $y)
  6376. * @protected
  6377. * @since 5.5.009 (2010-07-05)
  6378. */
  6379. protected function fitBlock($w, $h, $x, $y, $fitonpage=false) {
  6380. if ($w <= 0) {
  6381. // set maximum width
  6382. $w = ($this->w - $this->lMargin - $this->rMargin);
  6383. if ($w <= 0) {
  6384. $w = 1;
  6385. }
  6386. }
  6387. if ($h <= 0) {
  6388. // set maximum height
  6389. $h = ($this->PageBreakTrigger - $this->tMargin);
  6390. if ($h <= 0) {
  6391. $h = 1;
  6392. }
  6393. }
  6394. // resize the block to be vertically contained on a single page or single column
  6395. if ($fitonpage OR $this->AutoPageBreak) {
  6396. $ratio_wh = ($w / $h);
  6397. if ($h > ($this->PageBreakTrigger - $this->tMargin)) {
  6398. $h = $this->PageBreakTrigger - $this->tMargin;
  6399. $w = ($h * $ratio_wh);
  6400. }
  6401. // resize the block to be horizontally contained on a single page or single column
  6402. if ($fitonpage) {
  6403. $maxw = ($this->w - $this->lMargin - $this->rMargin);
  6404. if ($w > $maxw) {
  6405. $w = $maxw;
  6406. $h = ($w / $ratio_wh);
  6407. }
  6408. }
  6409. }
  6410. // Check whether we need a new page or new column first as this does not fit
  6411. $prev_x = $this->x;
  6412. $prev_y = $this->y;
  6413. if ($this->checkPageBreak($h, $y) OR ($this->y < $prev_y)) {
  6414. $y = $this->y;
  6415. if ($this->rtl) {
  6416. $x += ($prev_x - $this->x);
  6417. } else {
  6418. $x += ($this->x - $prev_x);
  6419. }
  6420. $this->newline = true;
  6421. }
  6422. // resize the block to be contained on the remaining available page or column space
  6423. if ($fitonpage) {
  6424. $ratio_wh = ($w / $h);
  6425. if (($y + $h) > $this->PageBreakTrigger) {
  6426. $h = $this->PageBreakTrigger - $y;
  6427. $w = ($h * $ratio_wh);
  6428. }
  6429. if ((!$this->rtl) AND (($x + $w) > ($this->w - $this->rMargin))) {
  6430. $w = $this->w - $this->rMargin - $x;
  6431. $h = ($w / $ratio_wh);
  6432. } elseif (($this->rtl) AND (($x - $w) < ($this->lMargin))) {
  6433. $w = $x - $this->lMargin;
  6434. $h = ($w / $ratio_wh);
  6435. }
  6436. }
  6437. return array($w, $h, $x, $y);
  6438. }
  6439. /**
  6440. * Puts an image in the page.
  6441. * The upper-left corner must be given.
  6442. * The dimensions can be specified in different ways:<ul>
  6443. * <li>explicit width and height (expressed in user unit)</li>
  6444. * <li>one explicit dimension, the other being calculated automatically in order to keep the original proportions</li>
  6445. * <li>no explicit dimension, in which case the image is put at 72 dpi</li></ul>
  6446. * Supported formats are JPEG and PNG images whitout GD library and all images supported by GD: GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM;
  6447. * The format can be specified explicitly or inferred from the file extension.<br />
  6448. * It is possible to put a link on the image.<br />
  6449. * Remark: if an image is used several times, only one copy will be embedded in the file.<br />
  6450. * @param $file (string) Name of the file containing the image or a '@' character followed by the image data string. To link an image without embedding it on the document, set an asterisk character before the URL (i.e.: '*http://www.example.com/image.jpg').
  6451. * @param $x (float) Abscissa of the upper-left corner (LTR) or upper-right corner (RTL).
  6452. * @param $y (float) Ordinate of the upper-left corner (LTR) or upper-right corner (RTL).
  6453. * @param $w (float) Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
  6454. * @param $h (float) Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
  6455. * @param $type (string) Image format. Possible values are (case insensitive): JPEG and PNG (whitout GD library) and all images supported by GD: GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM;. If not specified, the type is inferred from the file extension.
  6456. * @param $link (mixed) URL or identifier returned by AddLink().
  6457. * @param $align (string) Indicates the alignment of the pointer next to image insertion relative to image height. The value can be:<ul><li>T: top-right for LTR or top-left for RTL</li><li>M: middle-right for LTR or middle-left for RTL</li><li>B: bottom-right for LTR or bottom-left for RTL</li><li>N: next line</li></ul>
  6458. * @param $resize (mixed) If true resize (reduce) the image to fit $w and $h (requires GD or ImageMagick library); if false do not resize; if 2 force resize in all cases (upscaling and downscaling).
  6459. * @param $dpi (int) dot-per-inch resolution used on resize
  6460. * @param $palign (string) Allows to center or align the image on the current line. Possible values are:<ul><li>L : left align</li><li>C : center</li><li>R : right align</li><li>'' : empty string : left for LTR or right for RTL</li></ul>
  6461. * @param $ismask (boolean) true if this image is a mask, false otherwise
  6462. * @param $imgmask (mixed) image object returned by this function or false
  6463. * @param $border (mixed) Indicates if borders must be drawn around the cell. The value can be a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul> or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul> or an array of line styles for each border group - for example: array('LTRB' => array('width' => 2, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0)))
  6464. * @param $fitbox (mixed) If not false scale image dimensions proportionally to fit within the ($w, $h) box. $fitbox can be true or a 2 characters string indicating the image alignment inside the box. The first character indicate the horizontal alignment (L = left, C = center, R = right) the second character indicate the vertical algnment (T = top, M = middle, B = bottom).
  6465. * @param $hidden (boolean) If true do not display the image.
  6466. * @param $fitonpage (boolean) If true the image is resized to not exceed page dimensions.
  6467. * @param $alt (boolean) If true the image will be added as alternative and not directly printed (the ID of the image will be returned).
  6468. * @param $altimgs (array) Array of alternate images IDs. Each alternative image must be an array with two values: an integer representing the image ID (the value returned by the Image method) and a boolean value to indicate if the image is the default for printing.
  6469. * @return image information
  6470. * @public
  6471. * @since 1.1
  6472. */
  6473. public function Image($file, $x='', $y='', $w=0, $h=0, $type='', $link='', $align='', $resize=false, $dpi=300, $palign='', $ismask=false, $imgmask=false, $border=0, $fitbox=false, $hidden=false, $fitonpage=false, $alt=false, $altimgs=array()) {
  6474. if ($this->state != 2) {
  6475. return;
  6476. }
  6477. if (strcmp($x, '') === 0) {
  6478. $x = $this->x;
  6479. }
  6480. if (strcmp($y, '') === 0) {
  6481. $y = $this->y;
  6482. }
  6483. // check page for no-write regions and adapt page margins if necessary
  6484. list($x, $y) = $this->checkPageRegions($h, $x, $y);
  6485. $exurl = ''; // external streams
  6486. $imsize = FALSE;
  6487. // check if we are passing an image as file or string
  6488. if ($file[0] === '@') {
  6489. // image from string
  6490. $imgdata = substr($file, 1);
  6491. } else { // image file
  6492. if ($file[0] === '*') {
  6493. // image as external stream
  6494. $file = substr($file, 1);
  6495. $exurl = $file;
  6496. }
  6497. // check if file exist and it is valid
  6498. if (!@TCPDF_STATIC::file_exists($file)) {
  6499. return false;
  6500. }
  6501. if (($imsize = @getimagesize($file)) === FALSE) {
  6502. if (in_array($file, $this->imagekeys)) {
  6503. // get existing image data
  6504. $info = $this->getImageBuffer($file);
  6505. $imsize = array($info['w'], $info['h']);
  6506. } elseif (strpos($file, '__tcpdf_'.$this->file_id.'_img') === FALSE) {
  6507. $imgdata = TCPDF_STATIC::fileGetContents($file);
  6508. }
  6509. }
  6510. }
  6511. if (!empty($imgdata)) {
  6512. // copy image to cache
  6513. $original_file = $file;
  6514. $file = TCPDF_STATIC::getObjFilename('img', $this->file_id);
  6515. $fp = TCPDF_STATIC::fopenLocal($file, 'w');
  6516. if (!$fp) {
  6517. $this->Error('Unable to write file: '.$file);
  6518. }
  6519. fwrite($fp, $imgdata);
  6520. fclose($fp);
  6521. unset($imgdata);
  6522. $imsize = @getimagesize($file);
  6523. if ($imsize === FALSE) {
  6524. unlink($file);
  6525. $file = $original_file;
  6526. }
  6527. }
  6528. if ($imsize === FALSE) {
  6529. if (($w > 0) AND ($h > 0)) {
  6530. // get measures from specified data
  6531. $pw = $this->getHTMLUnitToUnits($w, 0, $this->pdfunit, true) * $this->imgscale * $this->k;
  6532. $ph = $this->getHTMLUnitToUnits($h, 0, $this->pdfunit, true) * $this->imgscale * $this->k;
  6533. $imsize = array($pw, $ph);
  6534. } else {
  6535. $this->Error('[Image] Unable to get the size of the image: '.$file);
  6536. }
  6537. }
  6538. // file hash
  6539. $filehash = md5($file);
  6540. // get original image width and height in pixels
  6541. list($pixw, $pixh) = $imsize;
  6542. // calculate image width and height on document
  6543. if (($w <= 0) AND ($h <= 0)) {
  6544. // convert image size to document unit
  6545. $w = $this->pixelsToUnits($pixw);
  6546. $h = $this->pixelsToUnits($pixh);
  6547. } elseif ($w <= 0) {
  6548. $w = $h * $pixw / $pixh;
  6549. } elseif ($h <= 0) {
  6550. $h = $w * $pixh / $pixw;
  6551. } elseif (($fitbox !== false) AND ($w > 0) AND ($h > 0)) {
  6552. if (strlen($fitbox) !== 2) {
  6553. // set default alignment
  6554. $fitbox = '--';
  6555. }
  6556. // scale image dimensions proportionally to fit within the ($w, $h) box
  6557. if ((($w * $pixh) / ($h * $pixw)) < 1) {
  6558. // store current height
  6559. $oldh = $h;
  6560. // calculate new height
  6561. $h = $w * $pixh / $pixw;
  6562. // height difference
  6563. $hdiff = ($oldh - $h);
  6564. // vertical alignment
  6565. switch (strtoupper($fitbox[1])) {
  6566. case 'T': {
  6567. break;
  6568. }
  6569. case 'M': {
  6570. $y += ($hdiff / 2);
  6571. break;
  6572. }
  6573. case 'B': {
  6574. $y += $hdiff;
  6575. break;
  6576. }
  6577. }
  6578. } else {
  6579. // store current width
  6580. $oldw = $w;
  6581. // calculate new width
  6582. $w = $h * $pixw / $pixh;
  6583. // width difference
  6584. $wdiff = ($oldw - $w);
  6585. // horizontal alignment
  6586. switch (strtoupper($fitbox[0])) {
  6587. case 'L': {
  6588. if ($this->rtl) {
  6589. $x -= $wdiff;
  6590. }
  6591. break;
  6592. }
  6593. case 'C': {
  6594. if ($this->rtl) {
  6595. $x -= ($wdiff / 2);
  6596. } else {
  6597. $x += ($wdiff / 2);
  6598. }
  6599. break;
  6600. }
  6601. case 'R': {
  6602. if (!$this->rtl) {
  6603. $x += $wdiff;
  6604. }
  6605. break;
  6606. }
  6607. }
  6608. }
  6609. }
  6610. // fit the image on available space
  6611. list($w, $h, $x, $y) = $this->fitBlock($w, $h, $x, $y, $fitonpage);
  6612. // calculate new minimum dimensions in pixels
  6613. $neww = round($w * $this->k * $dpi / $this->dpi);
  6614. $newh = round($h * $this->k * $dpi / $this->dpi);
  6615. // check if resize is necessary (resize is used only to reduce the image)
  6616. $newsize = ($neww * $newh);
  6617. $pixsize = ($pixw * $pixh);
  6618. if (intval($resize) == 2) {
  6619. $resize = true;
  6620. } elseif ($newsize >= $pixsize) {
  6621. $resize = false;
  6622. }
  6623. // check if image has been already added on document
  6624. $newimage = true;
  6625. if (in_array($file, $this->imagekeys)) {
  6626. $newimage = false;
  6627. // get existing image data
  6628. $info = $this->getImageBuffer($file);
  6629. if (strpos($file, '__tcpdf_'.$this->file_id.'_imgmask_') === FALSE) {
  6630. // check if the newer image is larger
  6631. $oldsize = ($info['w'] * $info['h']);
  6632. if ((($oldsize < $newsize) AND ($resize)) OR (($oldsize < $pixsize) AND (!$resize))) {
  6633. $newimage = true;
  6634. }
  6635. }
  6636. } elseif (($ismask === false) AND ($imgmask === false) AND (strpos($file, '__tcpdf_'.$this->file_id.'_imgmask_') === FALSE)) {
  6637. // create temp image file (without alpha channel)
  6638. $tempfile_plain = K_PATH_CACHE.'__tcpdf_'.$this->file_id.'_imgmask_plain_'.$filehash;
  6639. // create temp alpha file
  6640. $tempfile_alpha = K_PATH_CACHE.'__tcpdf_'.$this->file_id.'_imgmask_alpha_'.$filehash;
  6641. // check for cached images
  6642. if (in_array($tempfile_plain, $this->imagekeys)) {
  6643. // get existing image data
  6644. $info = $this->getImageBuffer($tempfile_plain);
  6645. // check if the newer image is larger
  6646. $oldsize = ($info['w'] * $info['h']);
  6647. if ((($oldsize < $newsize) AND ($resize)) OR (($oldsize < $pixsize) AND (!$resize))) {
  6648. $newimage = true;
  6649. } else {
  6650. $newimage = false;
  6651. // embed mask image
  6652. $imgmask = $this->Image($tempfile_alpha, $x, $y, $w, $h, 'PNG', '', '', $resize, $dpi, '', true, false);
  6653. // embed image, masked with previously embedded mask
  6654. return $this->Image($tempfile_plain, $x, $y, $w, $h, $type, $link, $align, $resize, $dpi, $palign, false, $imgmask);
  6655. }
  6656. }
  6657. }
  6658. if ($newimage) {
  6659. //First use of image, get info
  6660. $type = strtolower($type);
  6661. if ($type == '') {
  6662. $type = TCPDF_IMAGES::getImageFileType($file, $imsize);
  6663. } elseif ($type == 'jpg') {
  6664. $type = 'jpeg';
  6665. }
  6666. $mqr = TCPDF_STATIC::get_mqr();
  6667. TCPDF_STATIC::set_mqr(false);
  6668. // Specific image handlers (defined on TCPDF_IMAGES CLASS)
  6669. $mtd = '_parse'.$type;
  6670. // GD image handler function
  6671. $gdfunction = 'imagecreatefrom'.$type;
  6672. $info = false;
  6673. if ((method_exists('TCPDF_IMAGES', $mtd)) AND (!($resize AND (function_exists($gdfunction) OR extension_loaded('imagick'))))) {
  6674. // TCPDF image functions
  6675. $info = TCPDF_IMAGES::$mtd($file);
  6676. if (($ismask === false) AND ($imgmask === false) AND (strpos($file, '__tcpdf_'.$this->file_id.'_imgmask_') === FALSE)
  6677. AND (($info === 'pngalpha') OR (isset($info['trns']) AND !empty($info['trns'])))) {
  6678. return $this->ImagePngAlpha($file, $x, $y, $pixw, $pixh, $w, $h, 'PNG', $link, $align, $resize, $dpi, $palign, $filehash);
  6679. }
  6680. }
  6681. if (($info === false) AND function_exists($gdfunction)) {
  6682. try {
  6683. // GD library
  6684. $img = $gdfunction($file);
  6685. if ($img !== false) {
  6686. if ($resize) {
  6687. $imgr = imagecreatetruecolor($neww, $newh);
  6688. if (($type == 'gif') OR ($type == 'png')) {
  6689. $imgr = TCPDF_IMAGES::setGDImageTransparency($imgr, $img);
  6690. }
  6691. imagecopyresampled($imgr, $img, 0, 0, 0, 0, $neww, $newh, $pixw, $pixh);
  6692. $img = $imgr;
  6693. }
  6694. if (($type == 'gif') OR ($type == 'png')) {
  6695. $info = TCPDF_IMAGES::_toPNG($img, TCPDF_STATIC::getObjFilename('img', $this->file_id));
  6696. } else {
  6697. $info = TCPDF_IMAGES::_toJPEG($img, $this->jpeg_quality, TCPDF_STATIC::getObjFilename('img', $this->file_id));
  6698. }
  6699. }
  6700. } catch(Exception $e) {
  6701. $info = false;
  6702. }
  6703. }
  6704. if (($info === false) AND extension_loaded('imagick')) {
  6705. try {
  6706. // ImageMagick library
  6707. $img = new Imagick();
  6708. if ($type == 'svg') {
  6709. if ($file[0] === '@') {
  6710. // image from string
  6711. $svgimg = substr($file, 1);
  6712. } else {
  6713. // get SVG file content
  6714. $svgimg = TCPDF_STATIC::fileGetContents($file);
  6715. }
  6716. if ($svgimg !== FALSE) {
  6717. // get width and height
  6718. $regs = array();
  6719. if (preg_match('/<svg([^\>]*)>/si', $svgimg, $regs)) {
  6720. $svgtag = $regs[1];
  6721. $tmp = array();
  6722. if (preg_match('/[\s]+width[\s]*=[\s]*"([^"]*)"/si', $svgtag, $tmp)) {
  6723. $ow = $this->getHTMLUnitToUnits($tmp[1], 1, $this->svgunit, false);
  6724. $owu = sprintf('%F', ($ow * $dpi / 72)).$this->pdfunit;
  6725. $svgtag = preg_replace('/[\s]+width[\s]*=[\s]*"[^"]*"/si', ' width="'.$owu.'"', $svgtag, 1);
  6726. } else {
  6727. $ow = $w;
  6728. }
  6729. $tmp = array();
  6730. if (preg_match('/[\s]+height[\s]*=[\s]*"([^"]*)"/si', $svgtag, $tmp)) {
  6731. $oh = $this->getHTMLUnitToUnits($tmp[1], 1, $this->svgunit, false);
  6732. $ohu = sprintf('%F', ($oh * $dpi / 72)).$this->pdfunit;
  6733. $svgtag = preg_replace('/[\s]+height[\s]*=[\s]*"[^"]*"/si', ' height="'.$ohu.'"', $svgtag, 1);
  6734. } else {
  6735. $oh = $h;
  6736. }
  6737. $tmp = array();
  6738. if (!preg_match('/[\s]+viewBox[\s]*=[\s]*"[\s]*([0-9\.]+)[\s]+([0-9\.]+)[\s]+([0-9\.]+)[\s]+([0-9\.]+)[\s]*"/si', $svgtag, $tmp)) {
  6739. $vbw = ($ow * $this->imgscale * $this->k);
  6740. $vbh = ($oh * $this->imgscale * $this->k);
  6741. $vbox = sprintf(' viewBox="0 0 %F %F" ', $vbw, $vbh);
  6742. $svgtag = $vbox.$svgtag;
  6743. }
  6744. $svgimg = preg_replace('/<svg([^\>]*)>/si', '<svg'.$svgtag.'>', $svgimg, 1);
  6745. }
  6746. $img->readImageBlob($svgimg);
  6747. }
  6748. } else {
  6749. $img->readImage($file);
  6750. }
  6751. if ($resize) {
  6752. $img->resizeImage($neww, $newh, 10, 1, false);
  6753. }
  6754. $img->setCompressionQuality($this->jpeg_quality);
  6755. $img->setImageFormat('jpeg');
  6756. $tempname = TCPDF_STATIC::getObjFilename('img', $this->file_id);
  6757. $img->writeImage($tempname);
  6758. $info = TCPDF_IMAGES::_parsejpeg($tempname);
  6759. unlink($tempname);
  6760. $img->destroy();
  6761. } catch(Exception $e) {
  6762. $info = false;
  6763. }
  6764. }
  6765. if ($info === false) {
  6766. // unable to process image
  6767. return;
  6768. }
  6769. TCPDF_STATIC::set_mqr($mqr);
  6770. if ($ismask) {
  6771. // force grayscale
  6772. $info['cs'] = 'DeviceGray';
  6773. }
  6774. if ($imgmask !== false) {
  6775. $info['masked'] = $imgmask;
  6776. }
  6777. if (!empty($exurl)) {
  6778. $info['exurl'] = $exurl;
  6779. }
  6780. // array of alternative images
  6781. $info['altimgs'] = $altimgs;
  6782. // add image to document
  6783. $info['i'] = $this->setImageBuffer($file, $info);
  6784. }
  6785. // set alignment
  6786. $this->img_rb_x = $x + $w;
  6787. $this->img_rb_y = $y + $h;
  6788. // set alignment
  6789. if ($palign == 'L') {
  6790. $ximg = $this->lMargin;
  6791. } elseif ($palign == 'C') {
  6792. $ximg = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
  6793. } elseif ($palign == 'R') {
  6794. $ximg = $this->w - $this->rMargin - $w;
  6795. } else {
  6796. $ximg = $x;
  6797. }
  6798. if ($ismask OR $hidden) {
  6799. // image is not displayed
  6800. return $info['i'];
  6801. }
  6802. $xkimg = $ximg * $this->k;
  6803. if (!$alt) {
  6804. // only non-alternative immages will be set
  6805. $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']));
  6806. }
  6807. if (!empty($border)) {
  6808. $bx = $this->x;
  6809. $by = $this->y;
  6810. $this->x = $ximg;
  6811. if ($this->rtl) {
  6812. $this->x += $w;
  6813. }
  6814. $this->y = $y;
  6815. $this->Cell($w, $h, '', $border, 0, '', 0, '', 0, true);
  6816. $this->x = $bx;
  6817. $this->y = $by;
  6818. }
  6819. if ($link) {
  6820. $this->Link($ximg, $y, $w, $h, $link, 0);
  6821. }
  6822. // set pointer to align the next text/objects
  6823. switch($align) {
  6824. case 'T': {
  6825. $this->y = $y;
  6826. $this->x = $this->img_rb_x;
  6827. break;
  6828. }
  6829. case 'M': {
  6830. $this->y = $y + round($h/2);
  6831. $this->x = $this->img_rb_x;
  6832. break;
  6833. }
  6834. case 'B': {
  6835. $this->y = $this->img_rb_y;
  6836. $this->x = $this->img_rb_x;
  6837. break;
  6838. }
  6839. case 'N': {
  6840. $this->SetY($this->img_rb_y);
  6841. break;
  6842. }
  6843. default:{
  6844. break;
  6845. }
  6846. }
  6847. $this->endlinex = $this->img_rb_x;
  6848. if ($this->inxobj) {
  6849. // we are inside an XObject template
  6850. $this->xobjects[$this->xobjid]['images'][] = $info['i'];
  6851. }
  6852. return $info['i'];
  6853. }
  6854. /**
  6855. * Extract info from a PNG image with alpha channel using the Imagick or GD library.
  6856. * @param $file (string) Name of the file containing the image.
  6857. * @param $x (float) Abscissa of the upper-left corner.
  6858. * @param $y (float) Ordinate of the upper-left corner.
  6859. * @param $wpx (float) Original width of the image in pixels.
  6860. * @param $hpx (float) original height of the image in pixels.
  6861. * @param $w (float) Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
  6862. * @param $h (float) Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
  6863. * @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.
  6864. * @param $link (mixed) URL or identifier returned by AddLink().
  6865. * @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>
  6866. * @param $resize (boolean) If true resize (reduce) the image to fit $w and $h (requires GD library).
  6867. * @param $dpi (int) dot-per-inch resolution used on resize
  6868. * @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>
  6869. * @param $filehash (string) File hash used to build unique file names.
  6870. * @author Nicola Asuni
  6871. * @protected
  6872. * @since 4.3.007 (2008-12-04)
  6873. * @see Image()
  6874. */
  6875. protected function ImagePngAlpha($file, $x, $y, $wpx, $hpx, $w, $h, $type, $link, $align, $resize, $dpi, $palign, $filehash='') {
  6876. // create temp images
  6877. if (empty($filehash)) {
  6878. $filehash = md5($file);
  6879. }
  6880. // create temp image file (without alpha channel)
  6881. $tempfile_plain = K_PATH_CACHE.'__tcpdf_'.$this->file_id.'_imgmask_plain_'.$filehash;
  6882. // create temp alpha file
  6883. $tempfile_alpha = K_PATH_CACHE.'__tcpdf_'.$this->file_id.'_imgmask_alpha_'.$filehash;
  6884. $parsed = false;
  6885. $parse_error = '';
  6886. // ImageMagick extension
  6887. if (($parsed === false) AND extension_loaded('imagick')) {
  6888. try {
  6889. // ImageMagick library
  6890. $img = new Imagick();
  6891. $img->readImage($file);
  6892. // clone image object
  6893. $imga = TCPDF_STATIC::objclone($img);
  6894. // extract alpha channel
  6895. if (method_exists($img, 'setImageAlphaChannel') AND defined('Imagick::ALPHACHANNEL_EXTRACT')) {
  6896. $img->setImageAlphaChannel(Imagick::ALPHACHANNEL_EXTRACT);
  6897. } else {
  6898. $img->separateImageChannel(8); // 8 = (imagick::CHANNEL_ALPHA | imagick::CHANNEL_OPACITY | imagick::CHANNEL_MATTE);
  6899. $img->negateImage(true);
  6900. }
  6901. $img->setImageFormat('png');
  6902. $img->writeImage($tempfile_alpha);
  6903. // remove alpha channel
  6904. if (method_exists($imga, 'setImageMatte')) {
  6905. $imga->setImageMatte(false);
  6906. } else {
  6907. $imga->separateImageChannel(39); // 39 = (imagick::CHANNEL_ALL & ~(imagick::CHANNEL_ALPHA | imagick::CHANNEL_OPACITY | imagick::CHANNEL_MATTE));
  6908. }
  6909. $imga->setImageFormat('png');
  6910. $imga->writeImage($tempfile_plain);
  6911. $parsed = true;
  6912. } catch (Exception $e) {
  6913. // Imagemagick fails, try with GD
  6914. $parse_error = 'Imagick library error: '.$e->getMessage();
  6915. }
  6916. }
  6917. // GD extension
  6918. if (($parsed === false) AND function_exists('imagecreatefrompng')) {
  6919. try {
  6920. // generate images
  6921. $img = imagecreatefrompng($file);
  6922. $imgalpha = imagecreate($wpx, $hpx);
  6923. // generate gray scale palette (0 -> 255)
  6924. for ($c = 0; $c < 256; ++$c) {
  6925. ImageColorAllocate($imgalpha, $c, $c, $c);
  6926. }
  6927. // extract alpha channel
  6928. for ($xpx = 0; $xpx < $wpx; ++$xpx) {
  6929. for ($ypx = 0; $ypx < $hpx; ++$ypx) {
  6930. $color = imagecolorat($img, $xpx, $ypx);
  6931. // get and correct gamma color
  6932. $alpha = $this->getGDgamma($img, $color);
  6933. imagesetpixel($imgalpha, $xpx, $ypx, $alpha);
  6934. }
  6935. }
  6936. imagepng($imgalpha, $tempfile_alpha);
  6937. imagedestroy($imgalpha);
  6938. // extract image without alpha channel
  6939. $imgplain = imagecreatetruecolor($wpx, $hpx);
  6940. imagecopy($imgplain, $img, 0, 0, 0, 0, $wpx, $hpx);
  6941. imagepng($imgplain, $tempfile_plain);
  6942. imagedestroy($imgplain);
  6943. $parsed = true;
  6944. } catch (Exception $e) {
  6945. // GD fails
  6946. $parse_error = 'GD library error: '.$e->getMessage();
  6947. }
  6948. }
  6949. if ($parsed === false) {
  6950. if (empty($parse_error)) {
  6951. $this->Error('TCPDF requires the Imagick or GD extension to handle PNG images with alpha channel.');
  6952. } else {
  6953. $this->Error($parse_error);
  6954. }
  6955. }
  6956. // embed mask image
  6957. $imgmask = $this->Image($tempfile_alpha, $x, $y, $w, $h, 'PNG', '', '', $resize, $dpi, '', true, false);
  6958. // embed image, masked with previously embedded mask
  6959. $this->Image($tempfile_plain, $x, $y, $w, $h, $type, $link, $align, $resize, $dpi, $palign, false, $imgmask);
  6960. }
  6961. /**
  6962. * Get the GD-corrected PNG gamma value from alpha color
  6963. * @param $img (int) GD image Resource ID.
  6964. * @param $c (int) alpha color
  6965. * @protected
  6966. * @since 4.3.007 (2008-12-04)
  6967. */
  6968. protected function getGDgamma($img, $c) {
  6969. if (!isset($this->gdgammacache['#'.$c])) {
  6970. $colors = imagecolorsforindex($img, $c);
  6971. // GD alpha is only 7 bit (0 -> 127)
  6972. $this->gdgammacache['#'.$c] = (((127 - $colors['alpha']) / 127) * 255);
  6973. // correct gamma
  6974. $this->gdgammacache['#'.$c] = (pow(($this->gdgammacache['#'.$c] / 255), 2.2) * 255);
  6975. // store the latest values on cache to improve performances
  6976. if (count($this->gdgammacache) > 8) {
  6977. // remove one element from the cache array
  6978. array_shift($this->gdgammacache);
  6979. }
  6980. }
  6981. return $this->gdgammacache['#'.$c];
  6982. }
  6983. /**
  6984. * Performs a line break.
  6985. * The current abscissa goes back to the left margin and the ordinate increases by the amount passed in parameter.
  6986. * @param $h (float) The height of the break. By default, the value equals the height of the last printed cell.
  6987. * @param $cell (boolean) if true add the current left (or right o for RTL) padding to the X coordinate
  6988. * @public
  6989. * @since 1.0
  6990. * @see Cell()
  6991. */
  6992. public function Ln($h='', $cell=false) {
  6993. 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'])) {
  6994. // revove vertical space from the top of the column
  6995. return;
  6996. }
  6997. if ($cell) {
  6998. if ($this->rtl) {
  6999. $cellpadding = $this->cell_padding['R'];
  7000. } else {
  7001. $cellpadding = $this->cell_padding['L'];
  7002. }
  7003. } else {
  7004. $cellpadding = 0;
  7005. }
  7006. if ($this->rtl) {
  7007. $this->x = $this->w - $this->rMargin - $cellpadding;
  7008. } else {
  7009. $this->x = $this->lMargin + $cellpadding;
  7010. }
  7011. if (is_string($h)) {
  7012. $h = $this->lasth;
  7013. }
  7014. $this->y += $h;
  7015. $this->newline = true;
  7016. }
  7017. /**
  7018. * Returns the relative X value of current position.
  7019. * The value is relative to the left border for LTR languages and to the right border for RTL languages.
  7020. * @return float
  7021. * @public
  7022. * @since 1.2
  7023. * @see SetX(), GetY(), SetY()
  7024. */
  7025. public function GetX() {
  7026. //Get x position
  7027. if ($this->rtl) {
  7028. return ($this->w - $this->x);
  7029. } else {
  7030. return $this->x;
  7031. }
  7032. }
  7033. /**
  7034. * Returns the absolute X value of current position.
  7035. * @return float
  7036. * @public
  7037. * @since 1.2
  7038. * @see SetX(), GetY(), SetY()
  7039. */
  7040. public function GetAbsX() {
  7041. return $this->x;
  7042. }
  7043. /**
  7044. * Returns the ordinate of the current position.
  7045. * @return float
  7046. * @public
  7047. * @since 1.0
  7048. * @see SetY(), GetX(), SetX()
  7049. */
  7050. public function GetY() {
  7051. return $this->y;
  7052. }
  7053. /**
  7054. * Defines the abscissa of the current position.
  7055. * If the passed value is negative, it is relative to the right of the page (or left if language is RTL).
  7056. * @param $x (float) The value of the abscissa in user units.
  7057. * @param $rtloff (boolean) if true always uses the page top-left corner as origin of axis.
  7058. * @public
  7059. * @since 1.2
  7060. * @see GetX(), GetY(), SetY(), SetXY()
  7061. */
  7062. public function SetX($x, $rtloff=false) {
  7063. $x = floatval($x);
  7064. if (!$rtloff AND $this->rtl) {
  7065. if ($x >= 0) {
  7066. $this->x = $this->w - $x;
  7067. } else {
  7068. $this->x = abs($x);
  7069. }
  7070. } else {
  7071. if ($x >= 0) {
  7072. $this->x = $x;
  7073. } else {
  7074. $this->x = $this->w + $x;
  7075. }
  7076. }
  7077. if ($this->x < 0) {
  7078. $this->x = 0;
  7079. }
  7080. if ($this->x > $this->w) {
  7081. $this->x = $this->w;
  7082. }
  7083. }
  7084. /**
  7085. * Moves the current abscissa back to the left margin and sets the ordinate.
  7086. * If the passed value is negative, it is relative to the bottom of the page.
  7087. * @param $y (float) The value of the ordinate in user units.
  7088. * @param $resetx (bool) if true (default) reset the X position.
  7089. * @param $rtloff (boolean) if true always uses the page top-left corner as origin of axis.
  7090. * @public
  7091. * @since 1.0
  7092. * @see GetX(), GetY(), SetY(), SetXY()
  7093. */
  7094. public function SetY($y, $resetx=true, $rtloff=false) {
  7095. $y = floatval($y);
  7096. if ($resetx) {
  7097. //reset x
  7098. if (!$rtloff AND $this->rtl) {
  7099. $this->x = $this->w - $this->rMargin;
  7100. } else {
  7101. $this->x = $this->lMargin;
  7102. }
  7103. }
  7104. if ($y >= 0) {
  7105. $this->y = $y;
  7106. } else {
  7107. $this->y = $this->h + $y;
  7108. }
  7109. if ($this->y < 0) {
  7110. $this->y = 0;
  7111. }
  7112. if ($this->y > $this->h) {
  7113. $this->y = $this->h;
  7114. }
  7115. }
  7116. /**
  7117. * Defines the abscissa and ordinate of the current position.
  7118. * If the passed values are negative, they are relative respectively to the right and bottom of the page.
  7119. * @param $x (float) The value of the abscissa.
  7120. * @param $y (float) The value of the ordinate.
  7121. * @param $rtloff (boolean) if true always uses the page top-left corner as origin of axis.
  7122. * @public
  7123. * @since 1.2
  7124. * @see SetX(), SetY()
  7125. */
  7126. public function SetXY($x, $y, $rtloff=false) {
  7127. $this->SetY($y, false, $rtloff);
  7128. $this->SetX($x, $rtloff);
  7129. }
  7130. /**
  7131. * Set the absolute X coordinate of the current pointer.
  7132. * @param $x (float) The value of the abscissa in user units.
  7133. * @public
  7134. * @since 5.9.186 (2012-09-13)
  7135. * @see setAbsX(), setAbsY(), SetAbsXY()
  7136. */
  7137. public function SetAbsX($x) {
  7138. $this->x = floatval($x);
  7139. }
  7140. /**
  7141. * Set the absolute Y coordinate of the current pointer.
  7142. * @param $y (float) (float) The value of the ordinate in user units.
  7143. * @public
  7144. * @since 5.9.186 (2012-09-13)
  7145. * @see setAbsX(), setAbsY(), SetAbsXY()
  7146. */
  7147. public function SetAbsY($y) {
  7148. $this->y = floatval($y);
  7149. }
  7150. /**
  7151. * Set the absolute X and Y coordinates of the current pointer.
  7152. * @param $x (float) The value of the abscissa in user units.
  7153. * @param $y (float) (float) The value of the ordinate in user units.
  7154. * @public
  7155. * @since 5.9.186 (2012-09-13)
  7156. * @see setAbsX(), setAbsY(), SetAbsXY()
  7157. */
  7158. public function SetAbsXY($x, $y) {
  7159. $this->SetAbsX($x);
  7160. $this->SetAbsY($y);
  7161. }
  7162. /**
  7163. * Send the document to a given destination: string, local file or browser.
  7164. * In the last case, the plug-in may be used (if present) or a download ("Save as" dialog box) may be forced.<br />
  7165. * The method first calls Close() if necessary to terminate the document.
  7166. * @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.
  7167. * @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>
  7168. * @return string
  7169. * @public
  7170. * @since 1.0
  7171. * @see Close()
  7172. */
  7173. public function Output($name='doc.pdf', $dest='I') {
  7174. //Output PDF to some destination
  7175. //Finish document if necessary
  7176. if ($this->state < 3) {
  7177. $this->Close();
  7178. }
  7179. //Normalize parameters
  7180. if (is_bool($dest)) {
  7181. $dest = $dest ? 'D' : 'F';
  7182. }
  7183. $dest = strtoupper($dest);
  7184. if ($dest[0] != 'F') {
  7185. $name = preg_replace('/[\s]+/', '_', $name);
  7186. $name = preg_replace('/[^a-zA-Z0-9_\.-]/', '', $name);
  7187. }
  7188. if ($this->sign) {
  7189. // *** apply digital signature to the document ***
  7190. // get the document content
  7191. $pdfdoc = $this->getBuffer();
  7192. // remove last newline
  7193. $pdfdoc = substr($pdfdoc, 0, -1);
  7194. // remove filler space
  7195. $byterange_string_len = strlen(TCPDF_STATIC::$byterange_string);
  7196. // define the ByteRange
  7197. $byte_range = array();
  7198. $byte_range[0] = 0;
  7199. $byte_range[1] = strpos($pdfdoc, TCPDF_STATIC::$byterange_string) + $byterange_string_len + 10;
  7200. $byte_range[2] = $byte_range[1] + $this->signature_max_length + 2;
  7201. $byte_range[3] = strlen($pdfdoc) - $byte_range[2];
  7202. $pdfdoc = substr($pdfdoc, 0, $byte_range[1]).substr($pdfdoc, $byte_range[2]);
  7203. // replace the ByteRange
  7204. $byterange = sprintf('/ByteRange[0 %u %u %u]', $byte_range[1], $byte_range[2], $byte_range[3]);
  7205. $byterange .= str_repeat(' ', ($byterange_string_len - strlen($byterange)));
  7206. $pdfdoc = str_replace(TCPDF_STATIC::$byterange_string, $byterange, $pdfdoc);
  7207. // write the document to a temporary folder
  7208. $tempdoc = TCPDF_STATIC::getObjFilename('doc', $this->file_id);
  7209. $f = TCPDF_STATIC::fopenLocal($tempdoc, 'wb');
  7210. if (!$f) {
  7211. $this->Error('Unable to create temporary file: '.$tempdoc);
  7212. }
  7213. $pdfdoc_length = strlen($pdfdoc);
  7214. fwrite($f, $pdfdoc, $pdfdoc_length);
  7215. fclose($f);
  7216. // get digital signature via openssl library
  7217. $tempsign = TCPDF_STATIC::getObjFilename('sig', $this->file_id);
  7218. if (empty($this->signature_data['extracerts'])) {
  7219. openssl_pkcs7_sign($tempdoc, $tempsign, $this->signature_data['signcert'], array($this->signature_data['privkey'], $this->signature_data['password']), array(), PKCS7_BINARY | PKCS7_DETACHED);
  7220. } else {
  7221. 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']);
  7222. }
  7223. // read signature
  7224. $signature = file_get_contents($tempsign);
  7225. // extract signature
  7226. $signature = substr($signature, $pdfdoc_length);
  7227. $signature = substr($signature, (strpos($signature, "%%EOF\n\n------") + 13));
  7228. $tmparr = explode("\n\n", $signature);
  7229. $signature = $tmparr[1];
  7230. // decode signature
  7231. $signature = base64_decode(trim($signature));
  7232. // add TSA timestamp to signature
  7233. $signature = $this->applyTSA($signature);
  7234. // convert signature to hex
  7235. $signature = current(unpack('H*', $signature));
  7236. $signature = str_pad($signature, $this->signature_max_length, '0');
  7237. // Add signature to the document
  7238. $this->buffer = substr($pdfdoc, 0, $byte_range[1]).'<'.$signature.'>'.substr($pdfdoc, $byte_range[1]);
  7239. $this->bufferlen = strlen($this->buffer);
  7240. }
  7241. switch($dest) {
  7242. case 'I': {
  7243. // Send PDF to the standard output
  7244. if (ob_get_contents()) {
  7245. $this->Error('Some data has already been output, can\'t send PDF file');
  7246. }
  7247. if (php_sapi_name() != 'cli') {
  7248. // send output to a browser
  7249. header('Content-Type: application/pdf');
  7250. if (headers_sent()) {
  7251. $this->Error('Some data has already been output to browser, can\'t send PDF file');
  7252. }
  7253. header('Cache-Control: private, must-revalidate, post-check=0, pre-check=0, max-age=1');
  7254. //header('Cache-Control: public, must-revalidate, max-age=0'); // HTTP/1.1
  7255. header('Pragma: public');
  7256. header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
  7257. header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
  7258. header('Content-Disposition: inline; filename="'.basename($name).'"');
  7259. TCPDF_STATIC::sendOutputData($this->getBuffer(), $this->bufferlen);
  7260. } else {
  7261. echo $this->getBuffer();
  7262. }
  7263. break;
  7264. }
  7265. case 'D': {
  7266. // download PDF as file
  7267. if (ob_get_contents()) {
  7268. $this->Error('Some data has already been output, can\'t send PDF file');
  7269. }
  7270. header('Content-Description: File Transfer');
  7271. if (headers_sent()) {
  7272. $this->Error('Some data has already been output to browser, can\'t send PDF file');
  7273. }
  7274. header('Cache-Control: private, must-revalidate, post-check=0, pre-check=0, max-age=1');
  7275. //header('Cache-Control: public, must-revalidate, max-age=0'); // HTTP/1.1
  7276. header('Pragma: public');
  7277. header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
  7278. header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
  7279. // force download dialog
  7280. if (strpos(php_sapi_name(), 'cgi') === false) {
  7281. header('Content-Type: application/force-download');
  7282. header('Content-Type: application/octet-stream', false);
  7283. header('Content-Type: application/download', false);
  7284. header('Content-Type: application/pdf', false);
  7285. } else {
  7286. header('Content-Type: application/pdf');
  7287. }
  7288. // use the Content-Disposition header to supply a recommended filename
  7289. header('Content-Disposition: attachment; filename="'.basename($name).'"');
  7290. header('Content-Transfer-Encoding: binary');
  7291. TCPDF_STATIC::sendOutputData($this->getBuffer(), $this->bufferlen);
  7292. break;
  7293. }
  7294. case 'F':
  7295. case 'FI':
  7296. case 'FD': {
  7297. // save PDF to a local file
  7298. $f = TCPDF_STATIC::fopenLocal($name, 'wb');
  7299. if (!$f) {
  7300. $this->Error('Unable to create output file: '.$name);
  7301. }
  7302. fwrite($f, $this->getBuffer(), $this->bufferlen);
  7303. fclose($f);
  7304. if ($dest == 'FI') {
  7305. // send headers to browser
  7306. header('Content-Type: application/pdf');
  7307. header('Cache-Control: private, must-revalidate, post-check=0, pre-check=0, max-age=1');
  7308. //header('Cache-Control: public, must-revalidate, max-age=0'); // HTTP/1.1
  7309. header('Pragma: public');
  7310. header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
  7311. header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
  7312. header('Content-Disposition: inline; filename="'.basename($name).'"');
  7313. TCPDF_STATIC::sendOutputData(file_get_contents($name), filesize($name));
  7314. } elseif ($dest == 'FD') {
  7315. // send headers to browser
  7316. if (ob_get_contents()) {
  7317. $this->Error('Some data has already been output, can\'t send PDF file');
  7318. }
  7319. header('Content-Description: File Transfer');
  7320. if (headers_sent()) {
  7321. $this->Error('Some data has already been output to browser, can\'t send PDF file');
  7322. }
  7323. header('Cache-Control: private, must-revalidate, post-check=0, pre-check=0, max-age=1');
  7324. header('Pragma: public');
  7325. header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
  7326. header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
  7327. // force download dialog
  7328. if (strpos(php_sapi_name(), 'cgi') === false) {
  7329. header('Content-Type: application/force-download');
  7330. header('Content-Type: application/octet-stream', false);
  7331. header('Content-Type: application/download', false);
  7332. header('Content-Type: application/pdf', false);
  7333. } else {
  7334. header('Content-Type: application/pdf');
  7335. }
  7336. // use the Content-Disposition header to supply a recommended filename
  7337. header('Content-Disposition: attachment; filename="'.basename($name).'"');
  7338. header('Content-Transfer-Encoding: binary');
  7339. TCPDF_STATIC::sendOutputData(file_get_contents($name), filesize($name));
  7340. }
  7341. break;
  7342. }
  7343. case 'E': {
  7344. // return PDF as base64 mime multi-part email attachment (RFC 2045)
  7345. $retval = 'Content-Type: application/pdf;'."\r\n";
  7346. $retval .= ' name="'.$name.'"'."\r\n";
  7347. $retval .= 'Content-Transfer-Encoding: base64'."\r\n";
  7348. $retval .= 'Content-Disposition: attachment;'."\r\n";
  7349. $retval .= ' filename="'.$name.'"'."\r\n\r\n";
  7350. $retval .= chunk_split(base64_encode($this->getBuffer()), 76, "\r\n");
  7351. return $retval;
  7352. }
  7353. case 'S': {
  7354. // returns PDF as a string
  7355. return $this->getBuffer();
  7356. }
  7357. default: {
  7358. $this->Error('Incorrect output destination: '.$dest);
  7359. }
  7360. }
  7361. return '';
  7362. }
  7363. protected static $cleaned_ids = array();
  7364. /**
  7365. * Unset all class variables except the following critical variables.
  7366. * @param $destroyall (boolean) if true destroys all class variables, otherwise preserves critical variables.
  7367. * @param $preserve_objcopy (boolean) if true preserves the objcopy variable
  7368. * @public
  7369. * @since 4.5.016 (2009-02-24)
  7370. */
  7371. public function _destroy($destroyall=false, $preserve_objcopy=false) {
  7372. // restore internal encoding
  7373. if (isset($this->internal_encoding) AND !empty($this->internal_encoding)) {
  7374. mb_internal_encoding($this->internal_encoding);
  7375. }
  7376. if (isset(self::$cleaned_ids[$this->file_id])) {
  7377. $destroyall = false;
  7378. }
  7379. if ($destroyall AND !$preserve_objcopy) {
  7380. self::$cleaned_ids[$this->file_id] = true;
  7381. // remove all temporary files
  7382. if ($handle = @opendir(K_PATH_CACHE)) {
  7383. while ( false !== ( $file_name = readdir( $handle ) ) ) {
  7384. if (strpos($file_name, '__tcpdf_'.$this->file_id.'_') === 0) {
  7385. unlink(K_PATH_CACHE.$file_name);
  7386. }
  7387. }
  7388. closedir($handle);
  7389. }
  7390. if (isset($this->imagekeys)) {
  7391. foreach($this->imagekeys as $file) {
  7392. if (strpos($file, K_PATH_CACHE) === 0) {
  7393. @unlink($file);
  7394. }
  7395. }
  7396. }
  7397. }
  7398. $preserve = array(
  7399. 'file_id',
  7400. 'internal_encoding',
  7401. 'state',
  7402. 'bufferlen',
  7403. 'buffer',
  7404. 'cached_files',
  7405. 'imagekeys',
  7406. 'sign',
  7407. 'signature_data',
  7408. 'signature_max_length',
  7409. 'byterange_string',
  7410. 'tsa_timestamp',
  7411. 'tsa_data'
  7412. );
  7413. foreach (array_keys(get_object_vars($this)) as $val) {
  7414. if ($destroyall OR !in_array($val, $preserve)) {
  7415. if ((!$preserve_objcopy OR ($val != 'objcopy')) AND ($val != 'file_id') AND isset($this->$val)) {
  7416. unset($this->$val);
  7417. }
  7418. }
  7419. }
  7420. }
  7421. /**
  7422. * Check for locale-related bug
  7423. * @protected
  7424. */
  7425. protected function _dochecks() {
  7426. //Check for locale-related bug
  7427. if (1.1 == 1) {
  7428. $this->Error('Don\'t alter the locale before including class file');
  7429. }
  7430. //Check for decimal separator
  7431. if (sprintf('%.1F', 1.0) != '1.0') {
  7432. setlocale(LC_NUMERIC, 'C');
  7433. }
  7434. }
  7435. /**
  7436. * Return an array containing variations for the basic page number alias.
  7437. * @param $a (string) Base alias.
  7438. * @return array of page number aliases
  7439. * @protected
  7440. */
  7441. protected function getInternalPageNumberAliases($a= '') {
  7442. $alias = array();
  7443. // build array of Unicode + ASCII variants (the order is important)
  7444. $alias = array('u' => array(), 'a' => array());
  7445. $u = '{'.$a.'}';
  7446. $alias['u'][] = TCPDF_STATIC::_escape($u);
  7447. if ($this->isunicode) {
  7448. $alias['u'][] = TCPDF_STATIC::_escape(TCPDF_FONTS::UTF8ToLatin1($u, $this->isunicode, $this->CurrentFont));
  7449. $alias['u'][] = TCPDF_STATIC::_escape(TCPDF_FONTS::utf8StrRev($u, false, $this->tmprtl, $this->isunicode, $this->CurrentFont));
  7450. $alias['a'][] = TCPDF_STATIC::_escape(TCPDF_FONTS::UTF8ToLatin1($a, $this->isunicode, $this->CurrentFont));
  7451. $alias['a'][] = TCPDF_STATIC::_escape(TCPDF_FONTS::utf8StrRev($a, false, $this->tmprtl, $this->isunicode, $this->CurrentFont));
  7452. }
  7453. $alias['a'][] = TCPDF_STATIC::_escape($a);
  7454. return $alias;
  7455. }
  7456. /**
  7457. * Return an array containing all internal page aliases.
  7458. * @return array of page number aliases
  7459. * @protected
  7460. */
  7461. protected function getAllInternalPageNumberAliases() {
  7462. $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);
  7463. $pnalias = array();
  7464. foreach($basic_alias as $k => $a) {
  7465. $pnalias[$k] = $this->getInternalPageNumberAliases($a);
  7466. }
  7467. return $pnalias;
  7468. }
  7469. /**
  7470. * Replace right shift page number aliases with spaces to correct right alignment.
  7471. * This works perfectly only when using monospaced fonts.
  7472. * @param $page (string) Page content.
  7473. * @param $aliases (array) Array of page aliases.
  7474. * @param $diff (int) initial difference to add.
  7475. * @return replaced page content.
  7476. * @protected
  7477. */
  7478. protected function replaceRightShiftPageNumAliases($page, $aliases, $diff) {
  7479. foreach ($aliases as $type => $alias) {
  7480. foreach ($alias as $a) {
  7481. // find position of compensation factor
  7482. $startnum = (strpos($a, ':') + 1);
  7483. $a = substr($a, 0, $startnum);
  7484. if (($pos = strpos($page, $a)) !== false) {
  7485. // end of alias
  7486. $endnum = strpos($page, '}', $pos);
  7487. // string to be replaced
  7488. $aa = substr($page, $pos, ($endnum - $pos + 1));
  7489. // get compensation factor
  7490. $ratio = substr($page, ($pos + $startnum), ($endnum - $pos - $startnum));
  7491. $ratio = preg_replace('/[^0-9\.]/', '', $ratio);
  7492. $ratio = floatval($ratio);
  7493. if ($type == 'u') {
  7494. $chrdiff = floor(($diff + 12) * $ratio);
  7495. $shift = str_repeat(' ', $chrdiff);
  7496. $shift = TCPDF_FONTS::UTF8ToUTF16BE($shift, false, $this->isunicode, $this->CurrentFont);
  7497. } else {
  7498. $chrdiff = floor(($diff + 11) * $ratio);
  7499. $shift = str_repeat(' ', $chrdiff);
  7500. }
  7501. $page = str_replace($aa, $shift, $page);
  7502. }
  7503. }
  7504. }
  7505. return $page;
  7506. }
  7507. /**
  7508. * Set page boxes to be included on page descriptions.
  7509. * @param $boxes (array) Array of page boxes to set on document: ('MediaBox', 'CropBox', 'BleedBox', 'TrimBox', 'ArtBox').
  7510. * @protected
  7511. */
  7512. protected function setPageBoxTypes($boxes) {
  7513. $this->page_boxes = array();
  7514. foreach ($boxes as $box) {
  7515. if (in_array($box, TCPDF_STATIC::$pageboxes)) {
  7516. $this->page_boxes[] = $box;
  7517. }
  7518. }
  7519. }
  7520. /**
  7521. * Output pages (and replace page number aliases).
  7522. * @protected
  7523. */
  7524. protected function _putpages() {
  7525. $filter = ($this->compress) ? '/Filter /FlateDecode ' : '';
  7526. // get internal aliases for page numbers
  7527. $pnalias = $this->getAllInternalPageNumberAliases();
  7528. $num_pages = $this->numpages;
  7529. $ptpa = TCPDF_STATIC::formatPageNumber(($this->starting_page_number + $num_pages - 1));
  7530. $ptpu = TCPDF_FONTS::UTF8ToUTF16BE($ptpa, false, $this->isunicode, $this->CurrentFont);
  7531. $ptp_num_chars = $this->GetNumChars($ptpa);
  7532. $pagegroupnum = 0;
  7533. $groupnum = 0;
  7534. $ptgu = 1;
  7535. $ptga = 1;
  7536. $ptg_num_chars = 1;
  7537. for ($n = 1; $n <= $num_pages; ++$n) {
  7538. // get current page
  7539. $temppage = $this->getPageBuffer($n);
  7540. $pagelen = strlen($temppage);
  7541. // set replacements for total pages number
  7542. $pnpa = TCPDF_STATIC::formatPageNumber(($this->starting_page_number + $n - 1));
  7543. $pnpu = TCPDF_FONTS::UTF8ToUTF16BE($pnpa, false, $this->isunicode, $this->CurrentFont);
  7544. $pnp_num_chars = $this->GetNumChars($pnpa);
  7545. $pdiff = 0; // difference used for right shift alignment of page numbers
  7546. $gdiff = 0; // difference used for right shift alignment of page group numbers
  7547. if (!empty($this->pagegroups)) {
  7548. if (isset($this->newpagegroup[$n])) {
  7549. $pagegroupnum = 0;
  7550. ++$groupnum;
  7551. $ptga = TCPDF_STATIC::formatPageNumber($this->pagegroups[$groupnum]);
  7552. $ptgu = TCPDF_FONTS::UTF8ToUTF16BE($ptga, false, $this->isunicode, $this->CurrentFont);
  7553. $ptg_num_chars = $this->GetNumChars($ptga);
  7554. }
  7555. ++$pagegroupnum;
  7556. $pnga = TCPDF_STATIC::formatPageNumber($pagegroupnum);
  7557. $pngu = TCPDF_FONTS::UTF8ToUTF16BE($pnga, false, $this->isunicode, $this->CurrentFont);
  7558. $png_num_chars = $this->GetNumChars($pnga);
  7559. // replace page numbers
  7560. $replace = array();
  7561. $replace[] = array($ptgu, $ptg_num_chars, 9, $pnalias[2]['u']);
  7562. $replace[] = array($ptga, $ptg_num_chars, 7, $pnalias[2]['a']);
  7563. $replace[] = array($pngu, $png_num_chars, 9, $pnalias[3]['u']);
  7564. $replace[] = array($pnga, $png_num_chars, 7, $pnalias[3]['a']);
  7565. list($temppage, $gdiff) = TCPDF_STATIC::replacePageNumAliases($temppage, $replace, $gdiff);
  7566. }
  7567. // replace page numbers
  7568. $replace = array();
  7569. $replace[] = array($ptpu, $ptp_num_chars, 9, $pnalias[0]['u']);
  7570. $replace[] = array($ptpa, $ptp_num_chars, 7, $pnalias[0]['a']);
  7571. $replace[] = array($pnpu, $pnp_num_chars, 9, $pnalias[1]['u']);
  7572. $replace[] = array($pnpa, $pnp_num_chars, 7, $pnalias[1]['a']);
  7573. list($temppage, $pdiff) = TCPDF_STATIC::replacePageNumAliases($temppage, $replace, $pdiff);
  7574. // replace right shift alias
  7575. $temppage = $this->replaceRightShiftPageNumAliases($temppage, $pnalias[4], max($pdiff, $gdiff));
  7576. // replace EPS marker
  7577. $temppage = str_replace($this->epsmarker, '', $temppage);
  7578. //Page
  7579. $this->page_obj_id[$n] = $this->_newobj();
  7580. $out = '<<';
  7581. $out .= ' /Type /Page';
  7582. $out .= ' /Parent 1 0 R';
  7583. if (empty($this->signature_data['approval']) OR ($this->signature_data['approval'] != 'A')) {
  7584. $out .= ' /LastModified '.$this->_datestring(0, $this->doc_modification_timestamp);
  7585. }
  7586. $out .= ' /Resources 2 0 R';
  7587. foreach ($this->page_boxes as $box) {
  7588. $out .= ' /'.$box;
  7589. $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']);
  7590. }
  7591. if (isset($this->pagedim[$n]['BoxColorInfo']) AND !empty($this->pagedim[$n]['BoxColorInfo'])) {
  7592. $out .= ' /BoxColorInfo <<';
  7593. foreach ($this->page_boxes as $box) {
  7594. if (isset($this->pagedim[$n]['BoxColorInfo'][$box])) {
  7595. $out .= ' /'.$box.' <<';
  7596. if (isset($this->pagedim[$n]['BoxColorInfo'][$box]['C'])) {
  7597. $color = $this->pagedim[$n]['BoxColorInfo'][$box]['C'];
  7598. $out .= ' /C [';
  7599. $out .= sprintf(' %F %F %F', ($color[0] / 255), ($color[1] / 255), ($color[2] / 255));
  7600. $out .= ' ]';
  7601. }
  7602. if (isset($this->pagedim[$n]['BoxColorInfo'][$box]['W'])) {
  7603. $out .= ' /W '.($this->pagedim[$n]['BoxColorInfo'][$box]['W'] * $this->k);
  7604. }
  7605. if (isset($this->pagedim[$n]['BoxColorInfo'][$box]['S'])) {
  7606. $out .= ' /S /'.$this->pagedim[$n]['BoxColorInfo'][$box]['S'];
  7607. }
  7608. if (isset($this->pagedim[$n]['BoxColorInfo'][$box]['D'])) {
  7609. $dashes = $this->pagedim[$n]['BoxColorInfo'][$box]['D'];
  7610. $out .= ' /D [';
  7611. foreach ($dashes as $dash) {
  7612. $out .= sprintf(' %F', ($dash * $this->k));
  7613. }
  7614. $out .= ' ]';
  7615. }
  7616. $out .= ' >>';
  7617. }
  7618. }
  7619. $out .= ' >>';
  7620. }
  7621. $out .= ' /Contents '.($this->n + 1).' 0 R';
  7622. $out .= ' /Rotate '.$this->pagedim[$n]['Rotate'];
  7623. if (!$this->pdfa_mode) {
  7624. $out .= ' /Group << /Type /Group /S /Transparency /CS /DeviceRGB >>';
  7625. }
  7626. if (isset($this->pagedim[$n]['trans']) AND !empty($this->pagedim[$n]['trans'])) {
  7627. // page transitions
  7628. if (isset($this->pagedim[$n]['trans']['Dur'])) {
  7629. $out .= ' /Dur '.$this->pagedim[$n]['trans']['Dur'];
  7630. }
  7631. $out .= ' /Trans <<';
  7632. $out .= ' /Type /Trans';
  7633. if (isset($this->pagedim[$n]['trans']['S'])) {
  7634. $out .= ' /S /'.$this->pagedim[$n]['trans']['S'];
  7635. }
  7636. if (isset($this->pagedim[$n]['trans']['D'])) {
  7637. $out .= ' /D '.$this->pagedim[$n]['trans']['D'];
  7638. }
  7639. if (isset($this->pagedim[$n]['trans']['Dm'])) {
  7640. $out .= ' /Dm /'.$this->pagedim[$n]['trans']['Dm'];
  7641. }
  7642. if (isset($this->pagedim[$n]['trans']['M'])) {
  7643. $out .= ' /M /'.$this->pagedim[$n]['trans']['M'];
  7644. }
  7645. if (isset($this->pagedim[$n]['trans']['Di'])) {
  7646. $out .= ' /Di '.$this->pagedim[$n]['trans']['Di'];
  7647. }
  7648. if (isset($this->pagedim[$n]['trans']['SS'])) {
  7649. $out .= ' /SS '.$this->pagedim[$n]['trans']['SS'];
  7650. }
  7651. if (isset($this->pagedim[$n]['trans']['B'])) {
  7652. $out .= ' /B '.$this->pagedim[$n]['trans']['B'];
  7653. }
  7654. $out .= ' >>';
  7655. }
  7656. $out .= $this->_getannotsrefs($n);
  7657. $out .= ' /PZ '.$this->pagedim[$n]['PZ'];
  7658. $out .= ' >>';
  7659. $out .= "\n".'endobj';
  7660. $this->_out($out);
  7661. //Page content
  7662. $p = ($this->compress) ? gzcompress($temppage) : $temppage;
  7663. $this->_newobj();
  7664. $p = $this->_getrawstream($p);
  7665. $this->_out('<<'.$filter.'/Length '.strlen($p).'>> stream'."\n".$p."\n".'endstream'."\n".'endobj');
  7666. }
  7667. //Pages root
  7668. $out = $this->_getobj(1)."\n";
  7669. $out .= '<< /Type /Pages /Kids [';
  7670. foreach($this->page_obj_id as $page_obj) {
  7671. $out .= ' '.$page_obj.' 0 R';
  7672. }
  7673. $out .= ' ] /Count '.$num_pages.' >>';
  7674. $out .= "\n".'endobj';
  7675. $this->_out($out);
  7676. }
  7677. /**
  7678. * Get references to page annotations.
  7679. * @param $n (int) page number
  7680. * @return string
  7681. * @protected
  7682. * @author Nicola Asuni
  7683. * @since 5.0.010 (2010-05-17)
  7684. */
  7685. protected function _getannotsrefs($n) {
  7686. if (!(isset($this->PageAnnots[$n]) OR ($this->sign AND isset($this->signature_data['cert_type'])))) {
  7687. return '';
  7688. }
  7689. $out = ' /Annots [';
  7690. if (isset($this->PageAnnots[$n])) {
  7691. foreach ($this->PageAnnots[$n] as $key => $val) {
  7692. if (!in_array($val['n'], $this->radio_groups)) {
  7693. $out .= ' '.$val['n'].' 0 R';
  7694. }
  7695. }
  7696. // add radiobutton groups
  7697. if (isset($this->radiobutton_groups[$n])) {
  7698. foreach ($this->radiobutton_groups[$n] as $key => $data) {
  7699. if (isset($data['n'])) {
  7700. $out .= ' '.$data['n'].' 0 R';
  7701. }
  7702. }
  7703. }
  7704. }
  7705. if ($this->sign AND ($n == $this->signature_appearance['page']) AND isset($this->signature_data['cert_type'])) {
  7706. // set reference for signature object
  7707. $out .= ' '.$this->sig_obj_id.' 0 R';
  7708. }
  7709. if (!empty($this->empty_signature_appearance)) {
  7710. foreach ($this->empty_signature_appearance as $esa) {
  7711. if ($esa['page'] == $n) {
  7712. // set reference for empty signature objects
  7713. $out .= ' '.$esa['objid'].' 0 R';
  7714. }
  7715. }
  7716. }
  7717. $out .= ' ]';
  7718. return $out;
  7719. }
  7720. /**
  7721. * Output annotations objects for all pages.
  7722. * !!! THIS METHOD IS NOT YET COMPLETED !!!
  7723. * See section 12.5 of PDF 32000_2008 reference.
  7724. * @protected
  7725. * @author Nicola Asuni
  7726. * @since 4.0.018 (2008-08-06)
  7727. */
  7728. protected function _putannotsobjs() {
  7729. // reset object counter
  7730. for ($n=1; $n <= $this->numpages; ++$n) {
  7731. if (isset($this->PageAnnots[$n])) {
  7732. // set page annotations
  7733. foreach ($this->PageAnnots[$n] as $key => $pl) {
  7734. $annot_obj_id = $this->PageAnnots[$n][$key]['n'];
  7735. // create annotation object for grouping radiobuttons
  7736. if (isset($this->radiobutton_groups[$n][$pl['txt']]) AND is_array($this->radiobutton_groups[$n][$pl['txt']])) {
  7737. $radio_button_obj_id = $this->radiobutton_groups[$n][$pl['txt']]['n'];
  7738. $annots = '<<';
  7739. $annots .= ' /Type /Annot';
  7740. $annots .= ' /Subtype /Widget';
  7741. $annots .= ' /Rect [0 0 0 0]';
  7742. if ($this->radiobutton_groups[$n][$pl['txt']]['#readonly#']) {
  7743. // read only
  7744. $annots .= ' /F 68';
  7745. $annots .= ' /Ff 49153';
  7746. } else {
  7747. $annots .= ' /F 4'; // default print for PDF/A
  7748. $annots .= ' /Ff 49152';
  7749. }
  7750. $annots .= ' /T '.$this->_datastring($pl['txt'], $radio_button_obj_id);
  7751. if (isset($pl['opt']['tu']) AND is_string($pl['opt']['tu'])) {
  7752. $annots .= ' /TU '.$this->_datastring($pl['opt']['tu'], $radio_button_obj_id);
  7753. }
  7754. $annots .= ' /FT /Btn';
  7755. $annots .= ' /Kids [';
  7756. $defval = '';
  7757. foreach ($this->radiobutton_groups[$n][$pl['txt']] as $key => $data) {
  7758. if (isset($data['kid'])) {
  7759. $annots .= ' '.$data['kid'].' 0 R';
  7760. if ($data['def'] !== 'Off') {
  7761. $defval = $data['def'];
  7762. }
  7763. }
  7764. }
  7765. $annots .= ' ]';
  7766. if (!empty($defval)) {
  7767. $annots .= ' /V /'.$defval;
  7768. }
  7769. $annots .= ' >>';
  7770. $this->_out($this->_getobj($radio_button_obj_id)."\n".$annots."\n".'endobj');
  7771. $this->form_obj_id[] = $radio_button_obj_id;
  7772. // store object id to be used on Parent entry of Kids
  7773. $this->radiobutton_groups[$n][$pl['txt']] = $radio_button_obj_id;
  7774. }
  7775. $formfield = false;
  7776. $pl['opt'] = array_change_key_case($pl['opt'], CASE_LOWER);
  7777. $a = $pl['x'] * $this->k;
  7778. $b = $this->pagedim[$n]['h'] - (($pl['y'] + $pl['h']) * $this->k);
  7779. $c = $pl['w'] * $this->k;
  7780. $d = $pl['h'] * $this->k;
  7781. $rect = sprintf('%F %F %F %F', $a, $b, $a+$c, $b+$d);
  7782. // create new annotation object
  7783. $annots = '<</Type /Annot';
  7784. $annots .= ' /Subtype /'.$pl['opt']['subtype'];
  7785. $annots .= ' /Rect ['.$rect.']';
  7786. $ft = array('Btn', 'Tx', 'Ch', 'Sig');
  7787. if (isset($pl['opt']['ft']) AND in_array($pl['opt']['ft'], $ft)) {
  7788. $annots .= ' /FT /'.$pl['opt']['ft'];
  7789. $formfield = true;
  7790. }
  7791. if ($pl['opt']['subtype'] !== 'Link') {
  7792. $annots .= ' /Contents '.$this->_textstring($pl['txt'], $annot_obj_id);
  7793. }
  7794. $annots .= ' /P '.$this->page_obj_id[$n].' 0 R';
  7795. $annots .= ' /NM '.$this->_datastring(sprintf('%04u-%04u', $n, $key), $annot_obj_id);
  7796. $annots .= ' /M '.$this->_datestring($annot_obj_id, $this->doc_modification_timestamp);
  7797. if (isset($pl['opt']['f'])) {
  7798. $fval = 0;
  7799. if (is_array($pl['opt']['f'])) {
  7800. foreach ($pl['opt']['f'] as $f) {
  7801. switch (strtolower($f)) {
  7802. case 'invisible': {
  7803. $fval += 1 << 0;
  7804. break;
  7805. }
  7806. case 'hidden': {
  7807. $fval += 1 << 1;
  7808. break;
  7809. }
  7810. case 'print': {
  7811. $fval += 1 << 2;
  7812. break;
  7813. }
  7814. case 'nozoom': {
  7815. $fval += 1 << 3;
  7816. break;
  7817. }
  7818. case 'norotate': {
  7819. $fval += 1 << 4;
  7820. break;
  7821. }
  7822. case 'noview': {
  7823. $fval += 1 << 5;
  7824. break;
  7825. }
  7826. case 'readonly': {
  7827. $fval += 1 << 6;
  7828. break;
  7829. }
  7830. case 'locked': {
  7831. $fval += 1 << 8;
  7832. break;
  7833. }
  7834. case 'togglenoview': {
  7835. $fval += 1 << 9;
  7836. break;
  7837. }
  7838. case 'lockedcontents': {
  7839. $fval += 1 << 10;
  7840. break;
  7841. }
  7842. default: {
  7843. break;
  7844. }
  7845. }
  7846. }
  7847. } else {
  7848. $fval = intval($pl['opt']['f']);
  7849. }
  7850. } else {
  7851. $fval = 4;
  7852. }
  7853. if ($this->pdfa_mode) {
  7854. // force print flag for PDF/A mode
  7855. $fval |= 4;
  7856. }
  7857. $annots .= ' /F '.intval($fval);
  7858. if (isset($pl['opt']['as']) AND is_string($pl['opt']['as'])) {
  7859. $annots .= ' /AS /'.$pl['opt']['as'];
  7860. }
  7861. if (isset($pl['opt']['ap'])) {
  7862. // appearance stream
  7863. $annots .= ' /AP <<';
  7864. if (is_array($pl['opt']['ap'])) {
  7865. foreach ($pl['opt']['ap'] as $apmode => $apdef) {
  7866. // $apmode can be: n = normal; r = rollover; d = down;
  7867. $annots .= ' /'.strtoupper($apmode);
  7868. if (is_array($apdef)) {
  7869. $annots .= ' <<';
  7870. foreach ($apdef as $apstate => $stream) {
  7871. // reference to XObject that define the appearance for this mode-state
  7872. $apsobjid = $this->_putAPXObject($c, $d, $stream);
  7873. $annots .= ' /'.$apstate.' '.$apsobjid.' 0 R';
  7874. }
  7875. $annots .= ' >>';
  7876. } else {
  7877. // reference to XObject that define the appearance for this mode
  7878. $apsobjid = $this->_putAPXObject($c, $d, $apdef);
  7879. $annots .= ' '.$apsobjid.' 0 R';
  7880. }
  7881. }
  7882. } else {
  7883. $annots .= $pl['opt']['ap'];
  7884. }
  7885. $annots .= ' >>';
  7886. }
  7887. if (isset($pl['opt']['bs']) AND (is_array($pl['opt']['bs']))) {
  7888. $annots .= ' /BS <<';
  7889. $annots .= ' /Type /Border';
  7890. if (isset($pl['opt']['bs']['w'])) {
  7891. $annots .= ' /W '.intval($pl['opt']['bs']['w']);
  7892. }
  7893. $bstyles = array('S', 'D', 'B', 'I', 'U');
  7894. if (isset($pl['opt']['bs']['s']) AND in_array($pl['opt']['bs']['s'], $bstyles)) {
  7895. $annots .= ' /S /'.$pl['opt']['bs']['s'];
  7896. }
  7897. if (isset($pl['opt']['bs']['d']) AND (is_array($pl['opt']['bs']['d']))) {
  7898. $annots .= ' /D [';
  7899. foreach ($pl['opt']['bs']['d'] as $cord) {
  7900. $annots .= ' '.intval($cord);
  7901. }
  7902. $annots .= ']';
  7903. }
  7904. $annots .= ' >>';
  7905. } else {
  7906. $annots .= ' /Border [';
  7907. if (isset($pl['opt']['border']) AND (count($pl['opt']['border']) >= 3)) {
  7908. $annots .= intval($pl['opt']['border'][0]).' ';
  7909. $annots .= intval($pl['opt']['border'][1]).' ';
  7910. $annots .= intval($pl['opt']['border'][2]);
  7911. if (isset($pl['opt']['border'][3]) AND is_array($pl['opt']['border'][3])) {
  7912. $annots .= ' [';
  7913. foreach ($pl['opt']['border'][3] as $dash) {
  7914. $annots .= intval($dash).' ';
  7915. }
  7916. $annots .= ']';
  7917. }
  7918. } else {
  7919. $annots .= '0 0 0';
  7920. }
  7921. $annots .= ']';
  7922. }
  7923. if (isset($pl['opt']['be']) AND (is_array($pl['opt']['be']))) {
  7924. $annots .= ' /BE <<';
  7925. $bstyles = array('S', 'C');
  7926. if (isset($pl['opt']['be']['s']) AND in_array($pl['opt']['be']['s'], $bstyles)) {
  7927. $annots .= ' /S /'.$pl['opt']['bs']['s'];
  7928. } else {
  7929. $annots .= ' /S /S';
  7930. }
  7931. if (isset($pl['opt']['be']['i']) AND ($pl['opt']['be']['i'] >= 0) AND ($pl['opt']['be']['i'] <= 2)) {
  7932. $annots .= ' /I '.sprintf(' %F', $pl['opt']['be']['i']);
  7933. }
  7934. $annots .= '>>';
  7935. }
  7936. if (isset($pl['opt']['c']) AND (is_array($pl['opt']['c'])) AND !empty($pl['opt']['c'])) {
  7937. $annots .= ' /C '.TCPDF_COLORS::getColorStringFromArray($pl['opt']['c']);
  7938. }
  7939. //$annots .= ' /StructParent ';
  7940. //$annots .= ' /OC ';
  7941. $markups = array('text', 'freetext', 'line', 'square', 'circle', 'polygon', 'polyline', 'highlight', 'underline', 'squiggly', 'strikeout', 'stamp', 'caret', 'ink', 'fileattachment', 'sound');
  7942. if (in_array(strtolower($pl['opt']['subtype']), $markups)) {
  7943. // this is a markup type
  7944. if (isset($pl['opt']['t']) AND is_string($pl['opt']['t'])) {
  7945. $annots .= ' /T '.$this->_textstring($pl['opt']['t'], $annot_obj_id);
  7946. }
  7947. //$annots .= ' /Popup ';
  7948. if (isset($pl['opt']['ca'])) {
  7949. $annots .= ' /CA '.sprintf('%F', floatval($pl['opt']['ca']));
  7950. }
  7951. if (isset($pl['opt']['rc'])) {
  7952. $annots .= ' /RC '.$this->_textstring($pl['opt']['rc'], $annot_obj_id);
  7953. }
  7954. $annots .= ' /CreationDate '.$this->_datestring($annot_obj_id, $this->doc_creation_timestamp);
  7955. //$annots .= ' /IRT ';
  7956. if (isset($pl['opt']['subj'])) {
  7957. $annots .= ' /Subj '.$this->_textstring($pl['opt']['subj'], $annot_obj_id);
  7958. }
  7959. //$annots .= ' /RT ';
  7960. //$annots .= ' /IT ';
  7961. //$annots .= ' /ExData ';
  7962. }
  7963. $lineendings = array('Square', 'Circle', 'Diamond', 'OpenArrow', 'ClosedArrow', 'None', 'Butt', 'ROpenArrow', 'RClosedArrow', 'Slash');
  7964. // Annotation types
  7965. switch (strtolower($pl['opt']['subtype'])) {
  7966. case 'text': {
  7967. if (isset($pl['opt']['open'])) {
  7968. $annots .= ' /Open '. (strtolower($pl['opt']['open']) == 'true' ? 'true' : 'false');
  7969. }
  7970. $iconsapp = array('Comment', 'Help', 'Insert', 'Key', 'NewParagraph', 'Note', 'Paragraph');
  7971. if (isset($pl['opt']['name']) AND in_array($pl['opt']['name'], $iconsapp)) {
  7972. $annots .= ' /Name /'.$pl['opt']['name'];
  7973. } else {
  7974. $annots .= ' /Name /Note';
  7975. }
  7976. $statemodels = array('Marked', 'Review');
  7977. if (isset($pl['opt']['statemodel']) AND in_array($pl['opt']['statemodel'], $statemodels)) {
  7978. $annots .= ' /StateModel /'.$pl['opt']['statemodel'];
  7979. } else {
  7980. $pl['opt']['statemodel'] = 'Marked';
  7981. $annots .= ' /StateModel /'.$pl['opt']['statemodel'];
  7982. }
  7983. if ($pl['opt']['statemodel'] == 'Marked') {
  7984. $states = array('Accepted', 'Unmarked');
  7985. } else {
  7986. $states = array('Accepted', 'Rejected', 'Cancelled', 'Completed', 'None');
  7987. }
  7988. if (isset($pl['opt']['state']) AND in_array($pl['opt']['state'], $states)) {
  7989. $annots .= ' /State /'.$pl['opt']['state'];
  7990. } else {
  7991. if ($pl['opt']['statemodel'] == 'Marked') {
  7992. $annots .= ' /State /Unmarked';
  7993. } else {
  7994. $annots .= ' /State /None';
  7995. }
  7996. }
  7997. break;
  7998. }
  7999. case 'link': {
  8000. if (is_string($pl['txt']) && !empty($pl['txt'])) {
  8001. if ($pl['txt'][0] == '#') {
  8002. // internal destination
  8003. $annots .= ' /A <</S /GoTo /D '.TCPDF_STATIC::encodeNameObject(substr($pl['txt'], 1)).'>>';
  8004. } elseif ($pl['txt'][0] == '%') {
  8005. // embedded PDF file
  8006. $filename = basename(substr($pl['txt'], 1));
  8007. $annots .= ' /A << /S /GoToE /D [0 /Fit] /NewWindow true /T << /R /C /P '.($n - 1).' /A '.$this->embeddedfiles[$filename]['a'].' >> >>';
  8008. } elseif ($pl['txt'][0] == '*') {
  8009. // embedded generic file
  8010. $filename = basename(substr($pl['txt'], 1));
  8011. $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});';
  8012. $annots .= ' /A << /S /JavaScript /JS '.$this->_textstring($jsa, $annot_obj_id).'>>';
  8013. } else {
  8014. $parsedUrl = parse_url($pl['txt']);
  8015. if (empty($parsedUrl['scheme']) AND (!empty($parsedUrl['path']) && strtolower(substr($parsedUrl['path'], -4)) == '.pdf')) {
  8016. // relative link to a PDF file
  8017. $dest = '[0 /Fit]'; // default page 0
  8018. if (!empty($parsedUrl['fragment'])) {
  8019. // check for named destination
  8020. $tmp = explode('=', $parsedUrl['fragment']);
  8021. $dest = '('.((count($tmp) == 2) ? $tmp[1] : $tmp[0]).')';
  8022. }
  8023. $annots .= ' /A <</S /GoToR /D '.$dest.' /F '.$this->_datastring($this->unhtmlentities($parsedUrl['path']), $annot_obj_id).' /NewWindow true>>';
  8024. } else {
  8025. // external URI link
  8026. $annots .= ' /A <</S /URI /URI '.$this->_datastring($this->unhtmlentities($pl['txt']), $annot_obj_id).'>>';
  8027. }
  8028. }
  8029. } elseif (isset($this->links[$pl['txt']])) {
  8030. // internal link ID
  8031. $l = $this->links[$pl['txt']];
  8032. if (isset($this->page_obj_id[($l['p'])])) {
  8033. $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)));
  8034. }
  8035. }
  8036. $hmodes = array('N', 'I', 'O', 'P');
  8037. if (isset($pl['opt']['h']) AND in_array($pl['opt']['h'], $hmodes)) {
  8038. $annots .= ' /H /'.$pl['opt']['h'];
  8039. } else {
  8040. $annots .= ' /H /I';
  8041. }
  8042. //$annots .= ' /PA ';
  8043. //$annots .= ' /Quadpoints ';
  8044. break;
  8045. }
  8046. case 'freetext': {
  8047. if (isset($pl['opt']['da']) AND !empty($pl['opt']['da'])) {
  8048. $annots .= ' /DA ('.$pl['opt']['da'].')';
  8049. }
  8050. if (isset($pl['opt']['q']) AND ($pl['opt']['q'] >= 0) AND ($pl['opt']['q'] <= 2)) {
  8051. $annots .= ' /Q '.intval($pl['opt']['q']);
  8052. }
  8053. if (isset($pl['opt']['rc'])) {
  8054. $annots .= ' /RC '.$this->_textstring($pl['opt']['rc'], $annot_obj_id);
  8055. }
  8056. if (isset($pl['opt']['ds'])) {
  8057. $annots .= ' /DS '.$this->_textstring($pl['opt']['ds'], $annot_obj_id);
  8058. }
  8059. if (isset($pl['opt']['cl']) AND is_array($pl['opt']['cl'])) {
  8060. $annots .= ' /CL [';
  8061. foreach ($pl['opt']['cl'] as $cl) {
  8062. $annots .= sprintf('%F ', $cl * $this->k);
  8063. }
  8064. $annots .= ']';
  8065. }
  8066. $tfit = array('FreeText', 'FreeTextCallout', 'FreeTextTypeWriter');
  8067. if (isset($pl['opt']['it']) AND in_array($pl['opt']['it'], $tfit)) {
  8068. $annots .= ' /IT /'.$pl['opt']['it'];
  8069. }
  8070. if (isset($pl['opt']['rd']) AND is_array($pl['opt']['rd'])) {
  8071. $l = $pl['opt']['rd'][0] * $this->k;
  8072. $r = $pl['opt']['rd'][1] * $this->k;
  8073. $t = $pl['opt']['rd'][2] * $this->k;
  8074. $b = $pl['opt']['rd'][3] * $this->k;
  8075. $annots .= ' /RD ['.sprintf('%F %F %F %F', $l, $r, $t, $b).']';
  8076. }
  8077. if (isset($pl['opt']['le']) AND in_array($pl['opt']['le'], $lineendings)) {
  8078. $annots .= ' /LE /'.$pl['opt']['le'];
  8079. }
  8080. break;
  8081. }
  8082. case 'line': {
  8083. break;
  8084. }
  8085. case 'square': {
  8086. break;
  8087. }
  8088. case 'circle': {
  8089. break;
  8090. }
  8091. case 'polygon': {
  8092. break;
  8093. }
  8094. case 'polyline': {
  8095. break;
  8096. }
  8097. case 'highlight': {
  8098. break;
  8099. }
  8100. case 'underline': {
  8101. break;
  8102. }
  8103. case 'squiggly': {
  8104. break;
  8105. }
  8106. case 'strikeout': {
  8107. break;
  8108. }
  8109. case 'stamp': {
  8110. break;
  8111. }
  8112. case 'caret': {
  8113. break;
  8114. }
  8115. case 'ink': {
  8116. break;
  8117. }
  8118. case 'popup': {
  8119. break;
  8120. }
  8121. case 'fileattachment': {
  8122. if ($this->pdfa_mode && $this->pdfa_version != 3) {
  8123. // embedded files are not allowed in PDF/A mode version 1 and 2
  8124. break;
  8125. }
  8126. if (!isset($pl['opt']['fs'])) {
  8127. break;
  8128. }
  8129. $filename = basename($pl['opt']['fs']);
  8130. if (isset($this->embeddedfiles[$filename]['f'])) {
  8131. $annots .= ' /FS '.$this->embeddedfiles[$filename]['f'].' 0 R';
  8132. $iconsapp = array('Graph', 'Paperclip', 'PushPin', 'Tag');
  8133. if (isset($pl['opt']['name']) AND in_array($pl['opt']['name'], $iconsapp)) {
  8134. $annots .= ' /Name /'.$pl['opt']['name'];
  8135. } else {
  8136. $annots .= ' /Name /PushPin';
  8137. }
  8138. // index (zero-based) of the annotation in the Annots array of this page
  8139. $this->embeddedfiles[$filename]['a'] = $key;
  8140. }
  8141. break;
  8142. }
  8143. case 'sound': {
  8144. if (!isset($pl['opt']['fs'])) {
  8145. break;
  8146. }
  8147. $filename = basename($pl['opt']['fs']);
  8148. if (isset($this->embeddedfiles[$filename]['f'])) {
  8149. // ... TO BE COMPLETED ...
  8150. // /R /C /B /E /CO /CP
  8151. $annots .= ' /Sound '.$this->embeddedfiles[$filename]['f'].' 0 R';
  8152. $iconsapp = array('Speaker', 'Mic');
  8153. if (isset($pl['opt']['name']) AND in_array($pl['opt']['name'], $iconsapp)) {
  8154. $annots .= ' /Name /'.$pl['opt']['name'];
  8155. } else {
  8156. $annots .= ' /Name /Speaker';
  8157. }
  8158. }
  8159. break;
  8160. }
  8161. case 'movie': {
  8162. break;
  8163. }
  8164. case 'widget': {
  8165. $hmode = array('N', 'I', 'O', 'P', 'T');
  8166. if (isset($pl['opt']['h']) AND in_array($pl['opt']['h'], $hmode)) {
  8167. $annots .= ' /H /'.$pl['opt']['h'];
  8168. }
  8169. if (isset($pl['opt']['mk']) AND (is_array($pl['opt']['mk'])) AND !empty($pl['opt']['mk'])) {
  8170. $annots .= ' /MK <<';
  8171. if (isset($pl['opt']['mk']['r'])) {
  8172. $annots .= ' /R '.$pl['opt']['mk']['r'];
  8173. }
  8174. if (isset($pl['opt']['mk']['bc']) AND (is_array($pl['opt']['mk']['bc']))) {
  8175. $annots .= ' /BC '.TCPDF_COLORS::getColorStringFromArray($pl['opt']['mk']['bc']);
  8176. }
  8177. if (isset($pl['opt']['mk']['bg']) AND (is_array($pl['opt']['mk']['bg']))) {
  8178. $annots .= ' /BG '.TCPDF_COLORS::getColorStringFromArray($pl['opt']['mk']['bg']);
  8179. }
  8180. if (isset($pl['opt']['mk']['ca'])) {
  8181. $annots .= ' /CA '.$pl['opt']['mk']['ca'];
  8182. }
  8183. if (isset($pl['opt']['mk']['rc'])) {
  8184. $annots .= ' /RC '.$pl['opt']['mk']['rc'];
  8185. }
  8186. if (isset($pl['opt']['mk']['ac'])) {
  8187. $annots .= ' /AC '.$pl['opt']['mk']['ac'];
  8188. }
  8189. if (isset($pl['opt']['mk']['i'])) {
  8190. $info = $this->getImageBuffer($pl['opt']['mk']['i']);
  8191. if ($info !== false) {
  8192. $annots .= ' /I '.$info['n'].' 0 R';
  8193. }
  8194. }
  8195. if (isset($pl['opt']['mk']['ri'])) {
  8196. $info = $this->getImageBuffer($pl['opt']['mk']['ri']);
  8197. if ($info !== false) {
  8198. $annots .= ' /RI '.$info['n'].' 0 R';
  8199. }
  8200. }
  8201. if (isset($pl['opt']['mk']['ix'])) {
  8202. $info = $this->getImageBuffer($pl['opt']['mk']['ix']);
  8203. if ($info !== false) {
  8204. $annots .= ' /IX '.$info['n'].' 0 R';
  8205. }
  8206. }
  8207. if (isset($pl['opt']['mk']['if']) AND (is_array($pl['opt']['mk']['if'])) AND !empty($pl['opt']['mk']['if'])) {
  8208. $annots .= ' /IF <<';
  8209. $if_sw = array('A', 'B', 'S', 'N');
  8210. if (isset($pl['opt']['mk']['if']['sw']) AND in_array($pl['opt']['mk']['if']['sw'], $if_sw)) {
  8211. $annots .= ' /SW /'.$pl['opt']['mk']['if']['sw'];
  8212. }
  8213. $if_s = array('A', 'P');
  8214. if (isset($pl['opt']['mk']['if']['s']) AND in_array($pl['opt']['mk']['if']['s'], $if_s)) {
  8215. $annots .= ' /S /'.$pl['opt']['mk']['if']['s'];
  8216. }
  8217. if (isset($pl['opt']['mk']['if']['a']) AND (is_array($pl['opt']['mk']['if']['a'])) AND !empty($pl['opt']['mk']['if']['a'])) {
  8218. $annots .= sprintf(' /A [%F %F]', $pl['opt']['mk']['if']['a'][0], $pl['opt']['mk']['if']['a'][1]);
  8219. }
  8220. if (isset($pl['opt']['mk']['if']['fb']) AND ($pl['opt']['mk']['if']['fb'])) {
  8221. $annots .= ' /FB true';
  8222. }
  8223. $annots .= '>>';
  8224. }
  8225. if (isset($pl['opt']['mk']['tp']) AND ($pl['opt']['mk']['tp'] >= 0) AND ($pl['opt']['mk']['tp'] <= 6)) {
  8226. $annots .= ' /TP '.intval($pl['opt']['mk']['tp']);
  8227. }
  8228. $annots .= '>>';
  8229. } // end MK
  8230. // --- Entries for field dictionaries ---
  8231. if (isset($this->radiobutton_groups[$n][$pl['txt']])) {
  8232. // set parent
  8233. $annots .= ' /Parent '.$this->radiobutton_groups[$n][$pl['txt']].' 0 R';
  8234. }
  8235. if (isset($pl['opt']['t']) AND is_string($pl['opt']['t'])) {
  8236. $annots .= ' /T '.$this->_datastring($pl['opt']['t'], $annot_obj_id);
  8237. }
  8238. if (isset($pl['opt']['tu']) AND is_string($pl['opt']['tu'])) {
  8239. $annots .= ' /TU '.$this->_datastring($pl['opt']['tu'], $annot_obj_id);
  8240. }
  8241. if (isset($pl['opt']['tm']) AND is_string($pl['opt']['tm'])) {
  8242. $annots .= ' /TM '.$this->_datastring($pl['opt']['tm'], $annot_obj_id);
  8243. }
  8244. if (isset($pl['opt']['ff'])) {
  8245. if (is_array($pl['opt']['ff'])) {
  8246. // array of bit settings
  8247. $flag = 0;
  8248. foreach($pl['opt']['ff'] as $val) {
  8249. $flag += 1 << ($val - 1);
  8250. }
  8251. } else {
  8252. $flag = intval($pl['opt']['ff']);
  8253. }
  8254. $annots .= ' /Ff '.$flag;
  8255. }
  8256. if (isset($pl['opt']['maxlen'])) {
  8257. $annots .= ' /MaxLen '.intval($pl['opt']['maxlen']);
  8258. }
  8259. if (isset($pl['opt']['v'])) {
  8260. $annots .= ' /V';
  8261. if (is_array($pl['opt']['v'])) {
  8262. foreach ($pl['opt']['v'] AS $optval) {
  8263. if (is_float($optval)) {
  8264. $optval = sprintf('%F', $optval);
  8265. }
  8266. $annots .= ' '.$optval;
  8267. }
  8268. } else {
  8269. $annots .= ' '.$this->_textstring($pl['opt']['v'], $annot_obj_id);
  8270. }
  8271. }
  8272. if (isset($pl['opt']['dv'])) {
  8273. $annots .= ' /DV';
  8274. if (is_array($pl['opt']['dv'])) {
  8275. foreach ($pl['opt']['dv'] AS $optval) {
  8276. if (is_float($optval)) {
  8277. $optval = sprintf('%F', $optval);
  8278. }
  8279. $annots .= ' '.$optval;
  8280. }
  8281. } else {
  8282. $annots .= ' '.$this->_textstring($pl['opt']['dv'], $annot_obj_id);
  8283. }
  8284. }
  8285. if (isset($pl['opt']['rv'])) {
  8286. $annots .= ' /RV';
  8287. if (is_array($pl['opt']['rv'])) {
  8288. foreach ($pl['opt']['rv'] AS $optval) {
  8289. if (is_float($optval)) {
  8290. $optval = sprintf('%F', $optval);
  8291. }
  8292. $annots .= ' '.$optval;
  8293. }
  8294. } else {
  8295. $annots .= ' '.$this->_textstring($pl['opt']['rv'], $annot_obj_id);
  8296. }
  8297. }
  8298. if (isset($pl['opt']['a']) AND !empty($pl['opt']['a'])) {
  8299. $annots .= ' /A << '.$pl['opt']['a'].' >>';
  8300. }
  8301. if (isset($pl['opt']['aa']) AND !empty($pl['opt']['aa'])) {
  8302. $annots .= ' /AA << '.$pl['opt']['aa'].' >>';
  8303. }
  8304. if (isset($pl['opt']['da']) AND !empty($pl['opt']['da'])) {
  8305. $annots .= ' /DA ('.$pl['opt']['da'].')';
  8306. }
  8307. if (isset($pl['opt']['q']) AND ($pl['opt']['q'] >= 0) AND ($pl['opt']['q'] <= 2)) {
  8308. $annots .= ' /Q '.intval($pl['opt']['q']);
  8309. }
  8310. if (isset($pl['opt']['opt']) AND (is_array($pl['opt']['opt'])) AND !empty($pl['opt']['opt'])) {
  8311. $annots .= ' /Opt [';
  8312. foreach($pl['opt']['opt'] AS $copt) {
  8313. if (is_array($copt)) {
  8314. $annots .= ' ['.$this->_textstring($copt[0], $annot_obj_id).' '.$this->_textstring($copt[1], $annot_obj_id).']';
  8315. } else {
  8316. $annots .= ' '.$this->_textstring($copt, $annot_obj_id);
  8317. }
  8318. }
  8319. $annots .= ']';
  8320. }
  8321. if (isset($pl['opt']['ti'])) {
  8322. $annots .= ' /TI '.intval($pl['opt']['ti']);
  8323. }
  8324. if (isset($pl['opt']['i']) AND (is_array($pl['opt']['i'])) AND !empty($pl['opt']['i'])) {
  8325. $annots .= ' /I [';
  8326. foreach($pl['opt']['i'] AS $copt) {
  8327. $annots .= intval($copt).' ';
  8328. }
  8329. $annots .= ']';
  8330. }
  8331. break;
  8332. }
  8333. case 'screen': {
  8334. break;
  8335. }
  8336. case 'printermark': {
  8337. break;
  8338. }
  8339. case 'trapnet': {
  8340. break;
  8341. }
  8342. case 'watermark': {
  8343. break;
  8344. }
  8345. case '3d': {
  8346. break;
  8347. }
  8348. default: {
  8349. break;
  8350. }
  8351. }
  8352. $annots .= '>>';
  8353. // create new annotation object
  8354. $this->_out($this->_getobj($annot_obj_id)."\n".$annots."\n".'endobj');
  8355. if ($formfield AND !isset($this->radiobutton_groups[$n][$pl['txt']])) {
  8356. // store reference of form object
  8357. $this->form_obj_id[] = $annot_obj_id;
  8358. }
  8359. }
  8360. }
  8361. } // end for each page
  8362. }
  8363. /**
  8364. * Put appearance streams XObject used to define annotation's appearance states.
  8365. * @param $w (int) annotation width
  8366. * @param $h (int) annotation height
  8367. * @param $stream (string) appearance stream
  8368. * @return int object ID
  8369. * @protected
  8370. * @since 4.8.001 (2009-09-09)
  8371. */
  8372. protected function _putAPXObject($w=0, $h=0, $stream='') {
  8373. $stream = trim($stream);
  8374. $out = $this->_getobj()."\n";
  8375. $this->xobjects['AX'.$this->n] = array('n' => $this->n);
  8376. $out .= '<<';
  8377. $out .= ' /Type /XObject';
  8378. $out .= ' /Subtype /Form';
  8379. $out .= ' /FormType 1';
  8380. if ($this->compress) {
  8381. $stream = gzcompress($stream);
  8382. $out .= ' /Filter /FlateDecode';
  8383. }
  8384. $rect = sprintf('%F %F', $w, $h);
  8385. $out .= ' /BBox [0 0 '.$rect.']';
  8386. $out .= ' /Matrix [1 0 0 1 0 0]';
  8387. $out .= ' /Resources 2 0 R';
  8388. $stream = $this->_getrawstream($stream);
  8389. $out .= ' /Length '.strlen($stream);
  8390. $out .= ' >>';
  8391. $out .= ' stream'."\n".$stream."\n".'endstream';
  8392. $out .= "\n".'endobj';
  8393. $this->_out($out);
  8394. return $this->n;
  8395. }
  8396. /**
  8397. * Output fonts.
  8398. * @author Nicola Asuni
  8399. * @protected
  8400. */
  8401. protected function _putfonts() {
  8402. $nf = $this->n;
  8403. foreach ($this->diffs as $diff) {
  8404. //Encodings
  8405. $this->_newobj();
  8406. $this->_out('<< /Type /Encoding /BaseEncoding /WinAnsiEncoding /Differences ['.$diff.'] >>'."\n".'endobj');
  8407. }
  8408. $mqr = TCPDF_STATIC::get_mqr();
  8409. TCPDF_STATIC::set_mqr(false);
  8410. foreach ($this->FontFiles as $file => $info) {
  8411. // search and get font file to embedd
  8412. $fontfile = TCPDF_FONTS::getFontFullPath($file, $info['fontdir']);
  8413. if (!TCPDF_STATIC::empty_string($fontfile)) {
  8414. $font = file_get_contents($fontfile);
  8415. $compressed = (substr($file, -2) == '.z');
  8416. if ((!$compressed) AND (isset($info['length2']))) {
  8417. $header = (ord($font[0]) == 128);
  8418. if ($header) {
  8419. // strip first binary header
  8420. $font = substr($font, 6);
  8421. }
  8422. if ($header AND (ord($font[$info['length1']]) == 128)) {
  8423. // strip second binary header
  8424. $font = substr($font, 0, $info['length1']).substr($font, ($info['length1'] + 6));
  8425. }
  8426. } elseif ($info['subset'] AND ((!$compressed) OR ($compressed AND function_exists('gzcompress')))) {
  8427. if ($compressed) {
  8428. // uncompress font
  8429. $font = gzuncompress($font);
  8430. }
  8431. // merge subset characters
  8432. $subsetchars = array(); // used chars
  8433. foreach ($info['fontkeys'] as $fontkey) {
  8434. $fontinfo = $this->getFontBuffer($fontkey);
  8435. $subsetchars += $fontinfo['subsetchars'];
  8436. }
  8437. // rebuild a font subset
  8438. $font = TCPDF_FONTS::_getTrueTypeFontSubset($font, $subsetchars);
  8439. // calculate new font length
  8440. $info['length1'] = strlen($font);
  8441. if ($compressed) {
  8442. // recompress font
  8443. $font = gzcompress($font);
  8444. }
  8445. }
  8446. $this->_newobj();
  8447. $this->FontFiles[$file]['n'] = $this->n;
  8448. $stream = $this->_getrawstream($font);
  8449. $out = '<< /Length '.strlen($stream);
  8450. if ($compressed) {
  8451. $out .= ' /Filter /FlateDecode';
  8452. }
  8453. $out .= ' /Length1 '.$info['length1'];
  8454. if (isset($info['length2'])) {
  8455. $out .= ' /Length2 '.$info['length2'].' /Length3 0';
  8456. }
  8457. $out .= ' >>';
  8458. $out .= ' stream'."\n".$stream."\n".'endstream';
  8459. $out .= "\n".'endobj';
  8460. $this->_out($out);
  8461. }
  8462. }
  8463. TCPDF_STATIC::set_mqr($mqr);
  8464. foreach ($this->fontkeys as $k) {
  8465. //Font objects
  8466. $font = $this->getFontBuffer($k);
  8467. $type = $font['type'];
  8468. $name = $font['name'];
  8469. if ($type == 'core') {
  8470. // standard core font
  8471. $out = $this->_getobj($this->font_obj_ids[$k])."\n";
  8472. $out .= '<</Type /Font';
  8473. $out .= ' /Subtype /Type1';
  8474. $out .= ' /BaseFont /'.$name;
  8475. $out .= ' /Name /F'.$font['i'];
  8476. if ((strtolower($name) != 'symbol') AND (strtolower($name) != 'zapfdingbats')) {
  8477. $out .= ' /Encoding /WinAnsiEncoding';
  8478. }
  8479. if ($k == 'helvetica') {
  8480. // add default font for annotations
  8481. $this->annotation_fonts[$k] = $font['i'];
  8482. }
  8483. $out .= ' >>';
  8484. $out .= "\n".'endobj';
  8485. $this->_out($out);
  8486. } elseif (($type == 'Type1') OR ($type == 'TrueType')) {
  8487. // additional Type1 or TrueType font
  8488. $out = $this->_getobj($this->font_obj_ids[$k])."\n";
  8489. $out .= '<</Type /Font';
  8490. $out .= ' /Subtype /'.$type;
  8491. $out .= ' /BaseFont /'.$name;
  8492. $out .= ' /Name /F'.$font['i'];
  8493. $out .= ' /FirstChar 32 /LastChar 255';
  8494. $out .= ' /Widths '.($this->n + 1).' 0 R';
  8495. $out .= ' /FontDescriptor '.($this->n + 2).' 0 R';
  8496. if ($font['enc']) {
  8497. if (isset($font['diff'])) {
  8498. $out .= ' /Encoding '.($nf + $font['diff']).' 0 R';
  8499. } else {
  8500. $out .= ' /Encoding /WinAnsiEncoding';
  8501. }
  8502. }
  8503. $out .= ' >>';
  8504. $out .= "\n".'endobj';
  8505. $this->_out($out);
  8506. // Widths
  8507. $this->_newobj();
  8508. $s = '[';
  8509. for ($i = 32; $i < 256; ++$i) {
  8510. if (isset($font['cw'][$i])) {
  8511. $s .= $font['cw'][$i].' ';
  8512. } else {
  8513. $s .= $font['dw'].' ';
  8514. }
  8515. }
  8516. $s .= ']';
  8517. $s .= "\n".'endobj';
  8518. $this->_out($s);
  8519. //Descriptor
  8520. $this->_newobj();
  8521. $s = '<</Type /FontDescriptor /FontName /'.$name;
  8522. foreach ($font['desc'] as $fdk => $fdv) {
  8523. if (is_float($fdv)) {
  8524. $fdv = sprintf('%F', $fdv);
  8525. }
  8526. $s .= ' /'.$fdk.' '.$fdv.'';
  8527. }
  8528. if (!TCPDF_STATIC::empty_string($font['file'])) {
  8529. $s .= ' /FontFile'.($type == 'Type1' ? '' : '2').' '.$this->FontFiles[$font['file']]['n'].' 0 R';
  8530. }
  8531. $s .= '>>';
  8532. $s .= "\n".'endobj';
  8533. $this->_out($s);
  8534. } else {
  8535. // additional types
  8536. $mtd = '_put'.strtolower($type);
  8537. if (!method_exists($this, $mtd)) {
  8538. $this->Error('Unsupported font type: '.$type);
  8539. }
  8540. $this->$mtd($font);
  8541. }
  8542. }
  8543. }
  8544. /**
  8545. * Adds unicode fonts.<br>
  8546. * Based on PDF Reference 1.3 (section 5)
  8547. * @param $font (array) font data
  8548. * @protected
  8549. * @author Nicola Asuni
  8550. * @since 1.52.0.TC005 (2005-01-05)
  8551. */
  8552. protected function _puttruetypeunicode($font) {
  8553. $fontname = '';
  8554. if ($font['subset']) {
  8555. // change name for font subsetting
  8556. $subtag = sprintf('%06u', $font['i']);
  8557. $subtag = strtr($subtag, '0123456789', 'ABCDEFGHIJ');
  8558. $fontname .= $subtag.'+';
  8559. }
  8560. $fontname .= $font['name'];
  8561. // Type0 Font
  8562. // A composite font composed of other fonts, organized hierarchically
  8563. $out = $this->_getobj($this->font_obj_ids[$font['fontkey']])."\n";
  8564. $out .= '<< /Type /Font';
  8565. $out .= ' /Subtype /Type0';
  8566. $out .= ' /BaseFont /'.$fontname;
  8567. $out .= ' /Name /F'.$font['i'];
  8568. $out .= ' /Encoding /'.$font['enc'];
  8569. $out .= ' /ToUnicode '.($this->n + 1).' 0 R';
  8570. $out .= ' /DescendantFonts ['.($this->n + 2).' 0 R]';
  8571. $out .= ' >>';
  8572. $out .= "\n".'endobj';
  8573. $this->_out($out);
  8574. // ToUnicode map for Identity-H
  8575. $stream = TCPDF_FONT_DATA::$uni_identity_h;
  8576. // ToUnicode Object
  8577. $this->_newobj();
  8578. $stream = ($this->compress) ? gzcompress($stream) : $stream;
  8579. $filter = ($this->compress) ? '/Filter /FlateDecode ' : '';
  8580. $stream = $this->_getrawstream($stream);
  8581. $this->_out('<<'.$filter.'/Length '.strlen($stream).'>> stream'."\n".$stream."\n".'endstream'."\n".'endobj');
  8582. // CIDFontType2
  8583. // A CIDFont whose glyph descriptions are based on TrueType font technology
  8584. $oid = $this->_newobj();
  8585. $out = '<< /Type /Font';
  8586. $out .= ' /Subtype /CIDFontType2';
  8587. $out .= ' /BaseFont /'.$fontname;
  8588. // A dictionary containing entries that define the character collection of the CIDFont.
  8589. $cidinfo = '/Registry '.$this->_datastring($font['cidinfo']['Registry'], $oid);
  8590. $cidinfo .= ' /Ordering '.$this->_datastring($font['cidinfo']['Ordering'], $oid);
  8591. $cidinfo .= ' /Supplement '.$font['cidinfo']['Supplement'];
  8592. $out .= ' /CIDSystemInfo << '.$cidinfo.' >>';
  8593. $out .= ' /FontDescriptor '.($this->n + 1).' 0 R';
  8594. $out .= ' /DW '.$font['dw']; // default width
  8595. $out .= "\n".TCPDF_FONTS::_putfontwidths($font, 0);
  8596. if (isset($font['ctg']) AND (!TCPDF_STATIC::empty_string($font['ctg']))) {
  8597. $out .= "\n".'/CIDToGIDMap '.($this->n + 2).' 0 R';
  8598. }
  8599. $out .= ' >>';
  8600. $out .= "\n".'endobj';
  8601. $this->_out($out);
  8602. // Font descriptor
  8603. // A font descriptor describing the CIDFont default metrics other than its glyph widths
  8604. $this->_newobj();
  8605. $out = '<< /Type /FontDescriptor';
  8606. $out .= ' /FontName /'.$fontname;
  8607. foreach ($font['desc'] as $key => $value) {
  8608. if (is_float($value)) {
  8609. $value = sprintf('%F', $value);
  8610. }
  8611. $out .= ' /'.$key.' '.$value;
  8612. }
  8613. $fontdir = false;
  8614. if (!TCPDF_STATIC::empty_string($font['file'])) {
  8615. // A stream containing a TrueType font
  8616. $out .= ' /FontFile2 '.$this->FontFiles[$font['file']]['n'].' 0 R';
  8617. $fontdir = $this->FontFiles[$font['file']]['fontdir'];
  8618. }
  8619. $out .= ' >>';
  8620. $out .= "\n".'endobj';
  8621. $this->_out($out);
  8622. if (isset($font['ctg']) AND (!TCPDF_STATIC::empty_string($font['ctg']))) {
  8623. $this->_newobj();
  8624. // Embed CIDToGIDMap
  8625. // A specification of the mapping from CIDs to glyph indices
  8626. // search and get CTG font file to embedd
  8627. $ctgfile = strtolower($font['ctg']);
  8628. // search and get ctg font file to embedd
  8629. $fontfile = TCPDF_FONTS::getFontFullPath($ctgfile, $fontdir);
  8630. if (TCPDF_STATIC::empty_string($fontfile)) {
  8631. $this->Error('Font file not found: '.$ctgfile);
  8632. }
  8633. $stream = $this->_getrawstream(file_get_contents($fontfile));
  8634. $out = '<< /Length '.strlen($stream).'';
  8635. if (substr($fontfile, -2) == '.z') { // check file extension
  8636. // Decompresses data encoded using the public-domain
  8637. // zlib/deflate compression method, reproducing the
  8638. // original text or binary data
  8639. $out .= ' /Filter /FlateDecode';
  8640. }
  8641. $out .= ' >>';
  8642. $out .= ' stream'."\n".$stream."\n".'endstream';
  8643. $out .= "\n".'endobj';
  8644. $this->_out($out);
  8645. }
  8646. }
  8647. /**
  8648. * Output CID-0 fonts.
  8649. * A Type 0 CIDFont contains glyph descriptions based on the Adobe Type 1 font format
  8650. * @param $font (array) font data
  8651. * @protected
  8652. * @author Andrew Whitehead, Nicola Asuni, Yukihiro Nakadaira
  8653. * @since 3.2.000 (2008-06-23)
  8654. */
  8655. protected function _putcidfont0($font) {
  8656. $cidoffset = 0;
  8657. if (!isset($font['cw'][1])) {
  8658. $cidoffset = 31;
  8659. }
  8660. if (isset($font['cidinfo']['uni2cid'])) {
  8661. // convert unicode to cid.
  8662. $uni2cid = $font['cidinfo']['uni2cid'];
  8663. $cw = array();
  8664. foreach ($font['cw'] as $uni => $width) {
  8665. if (isset($uni2cid[$uni])) {
  8666. $cw[($uni2cid[$uni] + $cidoffset)] = $width;
  8667. } elseif ($uni < 256) {
  8668. $cw[$uni] = $width;
  8669. } // else unknown character
  8670. }
  8671. $font = array_merge($font, array('cw' => $cw));
  8672. }
  8673. $name = $font['name'];
  8674. $enc = $font['enc'];
  8675. if ($enc) {
  8676. $longname = $name.'-'.$enc;
  8677. } else {
  8678. $longname = $name;
  8679. }
  8680. $out = $this->_getobj($this->font_obj_ids[$font['fontkey']])."\n";
  8681. $out .= '<</Type /Font';
  8682. $out .= ' /Subtype /Type0';
  8683. $out .= ' /BaseFont /'.$longname;
  8684. $out .= ' /Name /F'.$font['i'];
  8685. if ($enc) {
  8686. $out .= ' /Encoding /'.$enc;
  8687. }
  8688. $out .= ' /DescendantFonts ['.($this->n + 1).' 0 R]';
  8689. $out .= ' >>';
  8690. $out .= "\n".'endobj';
  8691. $this->_out($out);
  8692. $oid = $this->_newobj();
  8693. $out = '<</Type /Font';
  8694. $out .= ' /Subtype /CIDFontType0';
  8695. $out .= ' /BaseFont /'.$name;
  8696. $cidinfo = '/Registry '.$this->_datastring($font['cidinfo']['Registry'], $oid);
  8697. $cidinfo .= ' /Ordering '.$this->_datastring($font['cidinfo']['Ordering'], $oid);
  8698. $cidinfo .= ' /Supplement '.$font['cidinfo']['Supplement'];
  8699. $out .= ' /CIDSystemInfo <<'.$cidinfo.'>>';
  8700. $out .= ' /FontDescriptor '.($this->n + 1).' 0 R';
  8701. $out .= ' /DW '.$font['dw'];
  8702. $out .= "\n".TCPDF_FONTS::_putfontwidths($font, $cidoffset);
  8703. $out .= ' >>';
  8704. $out .= "\n".'endobj';
  8705. $this->_out($out);
  8706. $this->_newobj();
  8707. $s = '<</Type /FontDescriptor /FontName /'.$name;
  8708. foreach ($font['desc'] as $k => $v) {
  8709. if ($k != 'Style') {
  8710. if (is_float($v)) {
  8711. $v = sprintf('%F', $v);
  8712. }
  8713. $s .= ' /'.$k.' '.$v.'';
  8714. }
  8715. }
  8716. $s .= '>>';
  8717. $s .= "\n".'endobj';
  8718. $this->_out($s);
  8719. }
  8720. /**
  8721. * Output images.
  8722. * @protected
  8723. */
  8724. protected function _putimages() {
  8725. $filter = ($this->compress) ? '/Filter /FlateDecode ' : '';
  8726. foreach ($this->imagekeys as $file) {
  8727. $info = $this->getImageBuffer($file);
  8728. // set object for alternate images array
  8729. if ((!$this->pdfa_mode) AND isset($info['altimgs']) AND !empty($info['altimgs'])) {
  8730. $altoid = $this->_newobj();
  8731. $out = '[';
  8732. foreach ($info['altimgs'] as $altimage) {
  8733. if (isset($this->xobjects['I'.$altimage[0]]['n'])) {
  8734. $out .= ' << /Image '.$this->xobjects['I'.$altimage[0]]['n'].' 0 R';
  8735. $out .= ' /DefaultForPrinting';
  8736. if ($altimage[1] === true) {
  8737. $out .= ' true';
  8738. } else {
  8739. $out .= ' false';
  8740. }
  8741. $out .= ' >>';
  8742. }
  8743. }
  8744. $out .= ' ]';
  8745. $out .= "\n".'endobj';
  8746. $this->_out($out);
  8747. }
  8748. // set image object
  8749. $oid = $this->_newobj();
  8750. $this->xobjects['I'.$info['i']] = array('n' => $oid);
  8751. $this->setImageSubBuffer($file, 'n', $this->n);
  8752. $out = '<</Type /XObject';
  8753. $out .= ' /Subtype /Image';
  8754. $out .= ' /Width '.$info['w'];
  8755. $out .= ' /Height '.$info['h'];
  8756. if (array_key_exists('masked', $info)) {
  8757. $out .= ' /SMask '.($this->n - 1).' 0 R';
  8758. }
  8759. // set color space
  8760. $icc = false;
  8761. if (isset($info['icc']) AND ($info['icc'] !== false)) {
  8762. // ICC Colour Space
  8763. $icc = true;
  8764. $out .= ' /ColorSpace [/ICCBased '.($this->n + 1).' 0 R]';
  8765. } elseif ($info['cs'] == 'Indexed') {
  8766. // Indexed Colour Space
  8767. $out .= ' /ColorSpace [/Indexed /DeviceRGB '.((strlen($info['pal']) / 3) - 1).' '.($this->n + 1).' 0 R]';
  8768. } else {
  8769. // Device Colour Space
  8770. $out .= ' /ColorSpace /'.$info['cs'];
  8771. }
  8772. if ($info['cs'] == 'DeviceCMYK') {
  8773. $out .= ' /Decode [1 0 1 0 1 0 1 0]';
  8774. }
  8775. $out .= ' /BitsPerComponent '.$info['bpc'];
  8776. if (isset($altoid) AND ($altoid > 0)) {
  8777. // reference to alternate images dictionary
  8778. $out .= ' /Alternates '.$altoid.' 0 R';
  8779. }
  8780. if (isset($info['exurl']) AND !empty($info['exurl'])) {
  8781. // external stream
  8782. $out .= ' /Length 0';
  8783. $out .= ' /F << /FS /URL /F '.$this->_datastring($info['exurl'], $oid).' >>';
  8784. if (isset($info['f'])) {
  8785. $out .= ' /FFilter /'.$info['f'];
  8786. }
  8787. $out .= ' >>';
  8788. $out .= ' stream'."\n".'endstream';
  8789. } else {
  8790. if (isset($info['f'])) {
  8791. $out .= ' /Filter /'.$info['f'];
  8792. }
  8793. if (isset($info['parms'])) {
  8794. $out .= ' '.$info['parms'];
  8795. }
  8796. if (isset($info['trns']) AND is_array($info['trns'])) {
  8797. $trns = '';
  8798. $count_info = count($info['trns']);
  8799. if ($info['cs'] == 'Indexed') {
  8800. $maxval =(pow(2, $info['bpc']) - 1);
  8801. for ($i = 0; $i < $count_info; ++$i) {
  8802. if (($info['trns'][$i] != 0) AND ($info['trns'][$i] != $maxval)) {
  8803. // this is not a binary type mask @TODO: create a SMask
  8804. $trns = '';
  8805. break;
  8806. } elseif (empty($trns) AND ($info['trns'][$i] == 0)) {
  8807. // store the first fully transparent value
  8808. $trns .= $i.' '.$i.' ';
  8809. }
  8810. }
  8811. } else {
  8812. // grayscale or RGB
  8813. for ($i = 0; $i < $count_info; ++$i) {
  8814. if ($info['trns'][$i] == 0) {
  8815. $trns .= $info['trns'][$i].' '.$info['trns'][$i].' ';
  8816. }
  8817. }
  8818. }
  8819. // Colour Key Masking
  8820. if (!empty($trns)) {
  8821. $out .= ' /Mask ['.$trns.']';
  8822. }
  8823. }
  8824. $stream = $this->_getrawstream($info['data']);
  8825. $out .= ' /Length '.strlen($stream).' >>';
  8826. $out .= ' stream'."\n".$stream."\n".'endstream';
  8827. }
  8828. $out .= "\n".'endobj';
  8829. $this->_out($out);
  8830. if ($icc) {
  8831. // ICC colour profile
  8832. $this->_newobj();
  8833. $icc = ($this->compress) ? gzcompress($info['icc']) : $info['icc'];
  8834. $icc = $this->_getrawstream($icc);
  8835. $this->_out('<</N '.$info['ch'].' /Alternate /'.$info['cs'].' '.$filter.'/Length '.strlen($icc).'>> stream'."\n".$icc."\n".'endstream'."\n".'endobj');
  8836. } elseif ($info['cs'] == 'Indexed') {
  8837. // colour palette
  8838. $this->_newobj();
  8839. $pal = ($this->compress) ? gzcompress($info['pal']) : $info['pal'];
  8840. $pal = $this->_getrawstream($pal);
  8841. $this->_out('<<'.$filter.'/Length '.strlen($pal).'>> stream'."\n".$pal."\n".'endstream'."\n".'endobj');
  8842. }
  8843. }
  8844. }
  8845. /**
  8846. * Output Form XObjects Templates.
  8847. * @author Nicola Asuni
  8848. * @since 5.8.017 (2010-08-24)
  8849. * @protected
  8850. * @see startTemplate(), endTemplate(), printTemplate()
  8851. */
  8852. protected function _putxobjects() {
  8853. foreach ($this->xobjects as $key => $data) {
  8854. if (isset($data['outdata'])) {
  8855. $stream = str_replace($this->epsmarker, '', trim($data['outdata']));
  8856. $out = $this->_getobj($data['n'])."\n";
  8857. $out .= '<<';
  8858. $out .= ' /Type /XObject';
  8859. $out .= ' /Subtype /Form';
  8860. $out .= ' /FormType 1';
  8861. if ($this->compress) {
  8862. $stream = gzcompress($stream);
  8863. $out .= ' /Filter /FlateDecode';
  8864. }
  8865. $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));
  8866. $out .= ' /Matrix [1 0 0 1 0 0]';
  8867. $out .= ' /Resources <<';
  8868. $out .= ' /ProcSet [/PDF /Text /ImageB /ImageC /ImageI]';
  8869. if (!$this->pdfa_mode) {
  8870. // transparency
  8871. if (isset($data['extgstates']) AND !empty($data['extgstates'])) {
  8872. $out .= ' /ExtGState <<';
  8873. foreach ($data['extgstates'] as $k => $extgstate) {
  8874. if (isset($this->extgstates[$k]['name'])) {
  8875. $out .= ' /'.$this->extgstates[$k]['name'];
  8876. } else {
  8877. $out .= ' /GS'.$k;
  8878. }
  8879. $out .= ' '.$this->extgstates[$k]['n'].' 0 R';
  8880. }
  8881. $out .= ' >>';
  8882. }
  8883. if (isset($data['gradients']) AND !empty($data['gradients'])) {
  8884. $gp = '';
  8885. $gs = '';
  8886. foreach ($data['gradients'] as $id => $grad) {
  8887. // gradient patterns
  8888. $gp .= ' /p'.$id.' '.$this->gradients[$id]['pattern'].' 0 R';
  8889. // gradient shadings
  8890. $gs .= ' /Sh'.$id.' '.$this->gradients[$id]['id'].' 0 R';
  8891. }
  8892. $out .= ' /Pattern <<'.$gp.' >>';
  8893. $out .= ' /Shading <<'.$gs.' >>';
  8894. }
  8895. }
  8896. // spot colors
  8897. if (isset($data['spot_colors']) AND !empty($data['spot_colors'])) {
  8898. $out .= ' /ColorSpace <<';
  8899. foreach ($data['spot_colors'] as $name => $color) {
  8900. $out .= ' /CS'.$color['i'].' '.$this->spot_colors[$name]['n'].' 0 R';
  8901. }
  8902. $out .= ' >>';
  8903. }
  8904. // fonts
  8905. if (!empty($data['fonts'])) {
  8906. $out .= ' /Font <<';
  8907. foreach ($data['fonts'] as $fontkey => $fontid) {
  8908. $out .= ' /F'.$fontid.' '.$this->font_obj_ids[$fontkey].' 0 R';
  8909. }
  8910. $out .= ' >>';
  8911. }
  8912. // images or nested xobjects
  8913. if (!empty($data['images']) OR !empty($data['xobjects'])) {
  8914. $out .= ' /XObject <<';
  8915. foreach ($data['images'] as $imgid) {
  8916. $out .= ' /I'.$imgid.' '.$this->xobjects['I'.$imgid]['n'].' 0 R';
  8917. }
  8918. foreach ($data['xobjects'] as $sub_id => $sub_objid) {
  8919. $out .= ' /'.$sub_id.' '.$sub_objid['n'].' 0 R';
  8920. }
  8921. $out .= ' >>';
  8922. }
  8923. $out .= ' >>'; //end resources
  8924. if (isset($data['group']) AND ($data['group'] !== false)) {
  8925. // set transparency group
  8926. $out .= ' /Group << /Type /Group /S /Transparency';
  8927. if (is_array($data['group'])) {
  8928. if (isset($data['group']['CS']) AND !empty($data['group']['CS'])) {
  8929. $out .= ' /CS /'.$data['group']['CS'];
  8930. }
  8931. if (isset($data['group']['I'])) {
  8932. $out .= ' /I /'.($data['group']['I']===true?'true':'false');
  8933. }
  8934. if (isset($data['group']['K'])) {
  8935. $out .= ' /K /'.($data['group']['K']===true?'true':'false');
  8936. }
  8937. }
  8938. $out .= ' >>';
  8939. }
  8940. $stream = $this->_getrawstream($stream, $data['n']);
  8941. $out .= ' /Length '.strlen($stream);
  8942. $out .= ' >>';
  8943. $out .= ' stream'."\n".$stream."\n".'endstream';
  8944. $out .= "\n".'endobj';
  8945. $this->_out($out);
  8946. }
  8947. }
  8948. }
  8949. /**
  8950. * Output Spot Colors Resources.
  8951. * @protected
  8952. * @since 4.0.024 (2008-09-12)
  8953. */
  8954. protected function _putspotcolors() {
  8955. foreach ($this->spot_colors as $name => $color) {
  8956. $this->_newobj();
  8957. $this->spot_colors[$name]['n'] = $this->n;
  8958. $out = '[/Separation /'.str_replace(' ', '#20', $name);
  8959. $out .= ' /DeviceCMYK <<';
  8960. $out .= ' /Range [0 1 0 1 0 1 0 1] /C0 [0 0 0 0]';
  8961. $out .= ' '.sprintf('/C1 [%F %F %F %F] ', ($color['C'] / 100), ($color['M'] / 100), ($color['Y'] / 100), ($color['K'] / 100));
  8962. $out .= ' /FunctionType 2 /Domain [0 1] /N 1>>]';
  8963. $out .= "\n".'endobj';
  8964. $this->_out($out);
  8965. }
  8966. }
  8967. /**
  8968. * Return XObjects Dictionary.
  8969. * @return string XObjects dictionary
  8970. * @protected
  8971. * @since 5.8.014 (2010-08-23)
  8972. */
  8973. protected function _getxobjectdict() {
  8974. $out = '';
  8975. foreach ($this->xobjects as $id => $objid) {
  8976. $out .= ' /'.$id.' '.$objid['n'].' 0 R';
  8977. }
  8978. return $out;
  8979. }
  8980. /**
  8981. * Output Resources Dictionary.
  8982. * @protected
  8983. */
  8984. protected function _putresourcedict() {
  8985. $out = $this->_getobj(2)."\n";
  8986. $out .= '<< /ProcSet [/PDF /Text /ImageB /ImageC /ImageI]';
  8987. $out .= ' /Font <<';
  8988. foreach ($this->fontkeys as $fontkey) {
  8989. $font = $this->getFontBuffer($fontkey);
  8990. $out .= ' /F'.$font['i'].' '.$font['n'].' 0 R';
  8991. }
  8992. $out .= ' >>';
  8993. $out .= ' /XObject <<';
  8994. $out .= $this->_getxobjectdict();
  8995. $out .= ' >>';
  8996. // layers
  8997. if (!empty($this->pdflayers)) {
  8998. $out .= ' /Properties <<';
  8999. foreach ($this->pdflayers as $layer) {
  9000. $out .= ' /'.$layer['layer'].' '.$layer['objid'].' 0 R';
  9001. }
  9002. $out .= ' >>';
  9003. }
  9004. if (!$this->pdfa_mode) {
  9005. // transparency
  9006. if (isset($this->extgstates) AND !empty($this->extgstates)) {
  9007. $out .= ' /ExtGState <<';
  9008. foreach ($this->extgstates as $k => $extgstate) {
  9009. if (isset($extgstate['name'])) {
  9010. $out .= ' /'.$extgstate['name'];
  9011. } else {
  9012. $out .= ' /GS'.$k;
  9013. }
  9014. $out .= ' '.$extgstate['n'].' 0 R';
  9015. }
  9016. $out .= ' >>';
  9017. }
  9018. if (isset($this->gradients) AND !empty($this->gradients)) {
  9019. $gp = '';
  9020. $gs = '';
  9021. foreach ($this->gradients as $id => $grad) {
  9022. // gradient patterns
  9023. $gp .= ' /p'.$id.' '.$grad['pattern'].' 0 R';
  9024. // gradient shadings
  9025. $gs .= ' /Sh'.$id.' '.$grad['id'].' 0 R';
  9026. }
  9027. $out .= ' /Pattern <<'.$gp.' >>';
  9028. $out .= ' /Shading <<'.$gs.' >>';
  9029. }
  9030. }
  9031. // spot colors
  9032. if (isset($this->spot_colors) AND !empty($this->spot_colors)) {
  9033. $out .= ' /ColorSpace <<';
  9034. foreach ($this->spot_colors as $color) {
  9035. $out .= ' /CS'.$color['i'].' '.$color['n'].' 0 R';
  9036. }
  9037. $out .= ' >>';
  9038. }
  9039. $out .= ' >>';
  9040. $out .= "\n".'endobj';
  9041. $this->_out($out);
  9042. }
  9043. /**
  9044. * Output Resources.
  9045. * @protected
  9046. */
  9047. protected function _putresources() {
  9048. $this->_putextgstates();
  9049. $this->_putocg();
  9050. $this->_putfonts();
  9051. $this->_putimages();
  9052. $this->_putspotcolors();
  9053. $this->_putshaders();
  9054. $this->_putxobjects();
  9055. $this->_putresourcedict();
  9056. $this->_putdests();
  9057. $this->_putEmbeddedFiles();
  9058. $this->_putannotsobjs();
  9059. $this->_putjavascript();
  9060. $this->_putbookmarks();
  9061. $this->_putencryption();
  9062. }
  9063. /**
  9064. * Adds some Metadata information (Document Information Dictionary)
  9065. * (see Chapter 14.3.3 Document Information Dictionary of PDF32000_2008.pdf Reference)
  9066. * @return int object id
  9067. * @protected
  9068. */
  9069. protected function _putinfo() {
  9070. $oid = $this->_newobj();
  9071. $out = '<<';
  9072. // store current isunicode value
  9073. $prev_isunicode = $this->isunicode;
  9074. if ($this->docinfounicode) {
  9075. $this->isunicode = true;
  9076. }
  9077. if (!TCPDF_STATIC::empty_string($this->title)) {
  9078. // The document's title.
  9079. $out .= ' /Title '.$this->_textstring($this->title, $oid);
  9080. }
  9081. if (!TCPDF_STATIC::empty_string($this->author)) {
  9082. // The name of the person who created the document.
  9083. $out .= ' /Author '.$this->_textstring($this->author, $oid);
  9084. }
  9085. if (!TCPDF_STATIC::empty_string($this->subject)) {
  9086. // The subject of the document.
  9087. $out .= ' /Subject '.$this->_textstring($this->subject, $oid);
  9088. }
  9089. if (!TCPDF_STATIC::empty_string($this->keywords)) {
  9090. // Keywords associated with the document.
  9091. $out .= ' /Keywords '.$this->_textstring($this->keywords, $oid);
  9092. }
  9093. if (!TCPDF_STATIC::empty_string($this->creator)) {
  9094. // 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.
  9095. $out .= ' /Creator '.$this->_textstring($this->creator, $oid);
  9096. }
  9097. // restore previous isunicode value
  9098. $this->isunicode = $prev_isunicode;
  9099. // default producer
  9100. $out .= ' /Producer '.$this->_textstring(TCPDF_STATIC::getTCPDFProducer(), $oid);
  9101. // The date and time the document was created, in human-readable form
  9102. $out .= ' /CreationDate '.$this->_datestring(0, $this->doc_creation_timestamp);
  9103. // The date and time the document was most recently modified, in human-readable form
  9104. $out .= ' /ModDate '.$this->_datestring(0, $this->doc_modification_timestamp);
  9105. // A name object indicating whether the document has been modified to include trapping information
  9106. $out .= ' /Trapped /False';
  9107. $out .= ' >>';
  9108. $out .= "\n".'endobj';
  9109. $this->_out($out);
  9110. return $oid;
  9111. }
  9112. /**
  9113. * Set additional XMP data to be added on the default XMP data just before the end of "x:xmpmeta" tag.
  9114. * IMPORTANT: This data is added as-is without controls, so you have to validate your data before using this method!
  9115. * @param $xmp (string) Custom XMP data.
  9116. * @since 5.9.128 (2011-10-06)
  9117. * @public
  9118. */
  9119. public function setExtraXMP($xmp) {
  9120. $this->custom_xmp = $xmp;
  9121. }
  9122. /**
  9123. * Set additional XMP data to be added on the default XMP data just before the end of "rdf:RDF" tag.
  9124. * IMPORTANT: This data is added as-is without controls, so you have to validate your data before using this method!
  9125. * @param $xmp (string) Custom XMP RDF data.
  9126. * @since 6.3.0 (2019-09-19)
  9127. * @public
  9128. */
  9129. public function setExtraXMPRDF($xmp) {
  9130. $this->custom_xmp_rdf = $xmp;
  9131. }
  9132. /**
  9133. * Put XMP data object and return ID.
  9134. * @return (int) The object ID.
  9135. * @since 5.9.121 (2011-09-28)
  9136. * @protected
  9137. */
  9138. protected function _putXMP() {
  9139. $oid = $this->_newobj();
  9140. // store current isunicode value
  9141. $prev_isunicode = $this->isunicode;
  9142. $this->isunicode = true;
  9143. $prev_encrypted = $this->encrypted;
  9144. $this->encrypted = false;
  9145. // set XMP data
  9146. $xmp = '<?xpacket begin="'.TCPDF_FONTS::unichr(0xfeff, $this->isunicode).'" id="W5M0MpCehiHzreSzNTczkc9d"?>'."\n";
  9147. $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";
  9148. $xmp .= "\t".'<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">'."\n";
  9149. $xmp .= "\t\t".'<rdf:Description rdf:about="" xmlns:dc="http://purl.org/dc/elements/1.1/">'."\n";
  9150. $xmp .= "\t\t\t".'<dc:format>application/pdf</dc:format>'."\n";
  9151. $xmp .= "\t\t\t".'<dc:title>'."\n";
  9152. $xmp .= "\t\t\t\t".'<rdf:Alt>'."\n";
  9153. $xmp .= "\t\t\t\t\t".'<rdf:li xml:lang="x-default">'.TCPDF_STATIC::_escapeXML($this->title).'</rdf:li>'."\n";
  9154. $xmp .= "\t\t\t\t".'</rdf:Alt>'."\n";
  9155. $xmp .= "\t\t\t".'</dc:title>'."\n";
  9156. $xmp .= "\t\t\t".'<dc:creator>'."\n";
  9157. $xmp .= "\t\t\t\t".'<rdf:Seq>'."\n";
  9158. $xmp .= "\t\t\t\t\t".'<rdf:li>'.TCPDF_STATIC::_escapeXML($this->author).'</rdf:li>'."\n";
  9159. $xmp .= "\t\t\t\t".'</rdf:Seq>'."\n";
  9160. $xmp .= "\t\t\t".'</dc:creator>'."\n";
  9161. $xmp .= "\t\t\t".'<dc:description>'."\n";
  9162. $xmp .= "\t\t\t\t".'<rdf:Alt>'."\n";
  9163. $xmp .= "\t\t\t\t\t".'<rdf:li xml:lang="x-default">'.TCPDF_STATIC::_escapeXML($this->subject).'</rdf:li>'."\n";
  9164. $xmp .= "\t\t\t\t".'</rdf:Alt>'."\n";
  9165. $xmp .= "\t\t\t".'</dc:description>'."\n";
  9166. $xmp .= "\t\t\t".'<dc:subject>'."\n";
  9167. $xmp .= "\t\t\t\t".'<rdf:Bag>'."\n";
  9168. $xmp .= "\t\t\t\t\t".'<rdf:li>'.TCPDF_STATIC::_escapeXML($this->keywords).'</rdf:li>'."\n";
  9169. $xmp .= "\t\t\t\t".'</rdf:Bag>'."\n";
  9170. $xmp .= "\t\t\t".'</dc:subject>'."\n";
  9171. $xmp .= "\t\t".'</rdf:Description>'."\n";
  9172. // convert doc creation date format
  9173. $dcdate = TCPDF_STATIC::getFormattedDate($this->doc_creation_timestamp);
  9174. $doccreationdate = substr($dcdate, 0, 4).'-'.substr($dcdate, 4, 2).'-'.substr($dcdate, 6, 2);
  9175. $doccreationdate .= 'T'.substr($dcdate, 8, 2).':'.substr($dcdate, 10, 2).':'.substr($dcdate, 12, 2);
  9176. $doccreationdate .= substr($dcdate, 14, 3).':'.substr($dcdate, 18, 2);
  9177. $doccreationdate = TCPDF_STATIC::_escapeXML($doccreationdate);
  9178. // convert doc modification date format
  9179. $dmdate = TCPDF_STATIC::getFormattedDate($this->doc_modification_timestamp);
  9180. $docmoddate = substr($dmdate, 0, 4).'-'.substr($dmdate, 4, 2).'-'.substr($dmdate, 6, 2);
  9181. $docmoddate .= 'T'.substr($dmdate, 8, 2).':'.substr($dmdate, 10, 2).':'.substr($dmdate, 12, 2);
  9182. $docmoddate .= substr($dmdate, 14, 3).':'.substr($dmdate, 18, 2);
  9183. $docmoddate = TCPDF_STATIC::_escapeXML($docmoddate);
  9184. $xmp .= "\t\t".'<rdf:Description rdf:about="" xmlns:xmp="http://ns.adobe.com/xap/1.0/">'."\n";
  9185. $xmp .= "\t\t\t".'<xmp:CreateDate>'.$doccreationdate.'</xmp:CreateDate>'."\n";
  9186. $xmp .= "\t\t\t".'<xmp:CreatorTool>'.$this->creator.'</xmp:CreatorTool>'."\n";
  9187. $xmp .= "\t\t\t".'<xmp:ModifyDate>'.$docmoddate.'</xmp:ModifyDate>'."\n";
  9188. $xmp .= "\t\t\t".'<xmp:MetadataDate>'.$doccreationdate.'</xmp:MetadataDate>'."\n";
  9189. $xmp .= "\t\t".'</rdf:Description>'."\n";
  9190. $xmp .= "\t\t".'<rdf:Description rdf:about="" xmlns:pdf="http://ns.adobe.com/pdf/1.3/">'."\n";
  9191. $xmp .= "\t\t\t".'<pdf:Keywords>'.TCPDF_STATIC::_escapeXML($this->keywords).'</pdf:Keywords>'."\n";
  9192. $xmp .= "\t\t\t".'<pdf:Producer>'.TCPDF_STATIC::_escapeXML(TCPDF_STATIC::getTCPDFProducer()).'</pdf:Producer>'."\n";
  9193. $xmp .= "\t\t".'</rdf:Description>'."\n";
  9194. $xmp .= "\t\t".'<rdf:Description rdf:about="" xmlns:xmpMM="http://ns.adobe.com/xap/1.0/mm/">'."\n";
  9195. $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);
  9196. $xmp .= "\t\t\t".'<xmpMM:DocumentID>'.$uuid.'</xmpMM:DocumentID>'."\n";
  9197. $xmp .= "\t\t\t".'<xmpMM:InstanceID>'.$uuid.'</xmpMM:InstanceID>'."\n";
  9198. $xmp .= "\t\t".'</rdf:Description>'."\n";
  9199. if ($this->pdfa_mode) {
  9200. $xmp .= "\t\t".'<rdf:Description rdf:about="" xmlns:pdfaid="http://www.aiim.org/pdfa/ns/id/">'."\n";
  9201. $xmp .= "\t\t\t".'<pdfaid:part>'.$this->pdfa_version.'</pdfaid:part>'."\n";
  9202. $xmp .= "\t\t\t".'<pdfaid:conformance>B</pdfaid:conformance>'."\n";
  9203. $xmp .= "\t\t".'</rdf:Description>'."\n";
  9204. }
  9205. // XMP extension schemas
  9206. $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";
  9207. $xmp .= "\t\t\t".'<pdfaExtension:schemas>'."\n";
  9208. $xmp .= "\t\t\t\t".'<rdf:Bag>'."\n";
  9209. $xmp .= "\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
  9210. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:namespaceURI>http://ns.adobe.com/pdf/1.3/</pdfaSchema:namespaceURI>'."\n";
  9211. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:prefix>pdf</pdfaSchema:prefix>'."\n";
  9212. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:schema>Adobe PDF Schema</pdfaSchema:schema>'."\n";
  9213. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:property>'."\n";
  9214. $xmp .= "\t\t\t\t\t\t\t".'<rdf:Seq>'."\n";
  9215. $xmp .= "\t\t\t\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
  9216. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:category>internal</pdfaProperty:category>'."\n";
  9217. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:description>Adobe PDF Schema</pdfaProperty:description>'."\n";
  9218. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:name>InstanceID</pdfaProperty:name>'."\n";
  9219. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:valueType>URI</pdfaProperty:valueType>'."\n";
  9220. $xmp .= "\t\t\t\t\t\t\t\t".'</rdf:li>'."\n";
  9221. $xmp .= "\t\t\t\t\t\t\t".'</rdf:Seq>'."\n";
  9222. $xmp .= "\t\t\t\t\t\t".'</pdfaSchema:property>'."\n";
  9223. $xmp .= "\t\t\t\t\t".'</rdf:li>'."\n";
  9224. $xmp .= "\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
  9225. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:namespaceURI>http://ns.adobe.com/xap/1.0/mm/</pdfaSchema:namespaceURI>'."\n";
  9226. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:prefix>xmpMM</pdfaSchema:prefix>'."\n";
  9227. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:schema>XMP Media Management Schema</pdfaSchema:schema>'."\n";
  9228. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:property>'."\n";
  9229. $xmp .= "\t\t\t\t\t\t\t".'<rdf:Seq>'."\n";
  9230. $xmp .= "\t\t\t\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
  9231. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:category>internal</pdfaProperty:category>'."\n";
  9232. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:description>UUID based identifier for specific incarnation of a document</pdfaProperty:description>'."\n";
  9233. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:name>InstanceID</pdfaProperty:name>'."\n";
  9234. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:valueType>URI</pdfaProperty:valueType>'."\n";
  9235. $xmp .= "\t\t\t\t\t\t\t\t".'</rdf:li>'."\n";
  9236. $xmp .= "\t\t\t\t\t\t\t".'</rdf:Seq>'."\n";
  9237. $xmp .= "\t\t\t\t\t\t".'</pdfaSchema:property>'."\n";
  9238. $xmp .= "\t\t\t\t\t".'</rdf:li>'."\n";
  9239. $xmp .= "\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
  9240. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:namespaceURI>http://www.aiim.org/pdfa/ns/id/</pdfaSchema:namespaceURI>'."\n";
  9241. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:prefix>pdfaid</pdfaSchema:prefix>'."\n";
  9242. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:schema>PDF/A ID Schema</pdfaSchema:schema>'."\n";
  9243. $xmp .= "\t\t\t\t\t\t".'<pdfaSchema:property>'."\n";
  9244. $xmp .= "\t\t\t\t\t\t\t".'<rdf:Seq>'."\n";
  9245. $xmp .= "\t\t\t\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
  9246. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:category>internal</pdfaProperty:category>'."\n";
  9247. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:description>Part of PDF/A standard</pdfaProperty:description>'."\n";
  9248. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:name>part</pdfaProperty:name>'."\n";
  9249. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:valueType>Integer</pdfaProperty:valueType>'."\n";
  9250. $xmp .= "\t\t\t\t\t\t\t\t".'</rdf:li>'."\n";
  9251. $xmp .= "\t\t\t\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
  9252. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:category>internal</pdfaProperty:category>'."\n";
  9253. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:description>Amendment of PDF/A standard</pdfaProperty:description>'."\n";
  9254. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:name>amd</pdfaProperty:name>'."\n";
  9255. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:valueType>Text</pdfaProperty:valueType>'."\n";
  9256. $xmp .= "\t\t\t\t\t\t\t\t".'</rdf:li>'."\n";
  9257. $xmp .= "\t\t\t\t\t\t\t\t".'<rdf:li rdf:parseType="Resource">'."\n";
  9258. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:category>internal</pdfaProperty:category>'."\n";
  9259. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:description>Conformance level of PDF/A standard</pdfaProperty:description>'."\n";
  9260. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:name>conformance</pdfaProperty:name>'."\n";
  9261. $xmp .= "\t\t\t\t\t\t\t\t\t".'<pdfaProperty:valueType>Text</pdfaProperty:valueType>'."\n";
  9262. $xmp .= "\t\t\t\t\t\t\t\t".'</rdf:li>'."\n";
  9263. $xmp .= "\t\t\t\t\t\t\t".'</rdf:Seq>'."\n";
  9264. $xmp .= "\t\t\t\t\t\t".'</pdfaSchema:property>'."\n";
  9265. $xmp .= "\t\t\t\t\t".'</rdf:li>'."\n";
  9266. $xmp .= "\t\t\t\t".'</rdf:Bag>'."\n";
  9267. $xmp .= "\t\t\t".'</pdfaExtension:schemas>'."\n";
  9268. $xmp .= "\t\t".'</rdf:Description>'."\n";
  9269. $xmp .= $this->custom_xmp_rdf;
  9270. $xmp .= "\t".'</rdf:RDF>'."\n";
  9271. $xmp .= $this->custom_xmp;
  9272. $xmp .= '</x:xmpmeta>'."\n";
  9273. $xmp .= '<?xpacket end="w"?>';
  9274. $out = '<< /Type /Metadata /Subtype /XML /Length '.strlen($xmp).' >> stream'."\n".$xmp."\n".'endstream'."\n".'endobj';
  9275. // restore previous isunicode value
  9276. $this->isunicode = $prev_isunicode;
  9277. $this->encrypted = $prev_encrypted;
  9278. $this->_out($out);
  9279. return $oid;
  9280. }
  9281. /**
  9282. * Output Catalog.
  9283. * @return int object id
  9284. * @protected
  9285. */
  9286. protected function _putcatalog() {
  9287. // put XMP
  9288. $xmpobj = $this->_putXMP();
  9289. // if required, add standard sRGB ICC colour profile
  9290. if ($this->pdfa_mode OR $this->force_srgb) {
  9291. $iccobj = $this->_newobj();
  9292. $icc = file_get_contents(dirname(__FILE__).'/include/sRGB.icc');
  9293. $filter = '';
  9294. if ($this->compress) {
  9295. $filter = ' /Filter /FlateDecode';
  9296. $icc = gzcompress($icc);
  9297. }
  9298. $icc = $this->_getrawstream($icc);
  9299. $this->_out('<</N 3 '.$filter.'/Length '.strlen($icc).'>> stream'."\n".$icc."\n".'endstream'."\n".'endobj');
  9300. }
  9301. // start catalog
  9302. $oid = $this->_newobj();
  9303. $out = '<< /Type /Catalog';
  9304. $out .= ' /Version /'.$this->PDFVersion;
  9305. //$out .= ' /Extensions <<>>';
  9306. $out .= ' /Pages 1 0 R';
  9307. //$out .= ' /PageLabels ' //...;
  9308. $out .= ' /Names <<';
  9309. if ((!$this->pdfa_mode) AND !empty($this->n_js)) {
  9310. $out .= ' /JavaScript '.$this->n_js;
  9311. }
  9312. if (!empty($this->efnames)) {
  9313. $out .= ' /EmbeddedFiles <</Names [';
  9314. foreach ($this->efnames AS $fn => $fref) {
  9315. $out .= ' '.$this->_datastring($fn).' '.$fref;
  9316. }
  9317. $out .= ' ]>>';
  9318. }
  9319. $out .= ' >>';
  9320. if (!empty($this->dests)) {
  9321. $out .= ' /Dests '.($this->n_dests).' 0 R';
  9322. }
  9323. $out .= $this->_putviewerpreferences();
  9324. if (isset($this->LayoutMode) AND (!TCPDF_STATIC::empty_string($this->LayoutMode))) {
  9325. $out .= ' /PageLayout /'.$this->LayoutMode;
  9326. }
  9327. if (isset($this->PageMode) AND (!TCPDF_STATIC::empty_string($this->PageMode))) {
  9328. $out .= ' /PageMode /'.$this->PageMode;
  9329. }
  9330. if (count($this->outlines) > 0) {
  9331. $out .= ' /Outlines '.$this->OutlineRoot.' 0 R';
  9332. $out .= ' /PageMode /UseOutlines';
  9333. }
  9334. //$out .= ' /Threads []';
  9335. if ($this->ZoomMode == 'fullpage') {
  9336. $out .= ' /OpenAction ['.$this->page_obj_id[1].' 0 R /Fit]';
  9337. } elseif ($this->ZoomMode == 'fullwidth') {
  9338. $out .= ' /OpenAction ['.$this->page_obj_id[1].' 0 R /FitH null]';
  9339. } elseif ($this->ZoomMode == 'real') {
  9340. $out .= ' /OpenAction ['.$this->page_obj_id[1].' 0 R /XYZ null null 1]';
  9341. } elseif (!is_string($this->ZoomMode)) {
  9342. $out .= sprintf(' /OpenAction ['.$this->page_obj_id[1].' 0 R /XYZ null null %F]', ($this->ZoomMode / 100));
  9343. }
  9344. //$out .= ' /AA <<>>';
  9345. //$out .= ' /URI <<>>';
  9346. $out .= ' /Metadata '.$xmpobj.' 0 R';
  9347. //$out .= ' /StructTreeRoot <<>>';
  9348. //$out .= ' /MarkInfo <<>>';
  9349. if (isset($this->l['a_meta_language'])) {
  9350. $out .= ' /Lang '.$this->_textstring($this->l['a_meta_language'], $oid);
  9351. }
  9352. //$out .= ' /SpiderInfo <<>>';
  9353. // set OutputIntent to sRGB IEC61966-2.1 if required
  9354. if ($this->pdfa_mode OR $this->force_srgb) {
  9355. $out .= ' /OutputIntents [<<';
  9356. $out .= ' /Type /OutputIntent';
  9357. $out .= ' /S /GTS_PDFA1';
  9358. $out .= ' /OutputCondition '.$this->_textstring('sRGB IEC61966-2.1', $oid);
  9359. $out .= ' /OutputConditionIdentifier '.$this->_textstring('sRGB IEC61966-2.1', $oid);
  9360. $out .= ' /RegistryName '.$this->_textstring('http://www.color.org', $oid);
  9361. $out .= ' /Info '.$this->_textstring('sRGB IEC61966-2.1', $oid);
  9362. $out .= ' /DestOutputProfile '.$iccobj.' 0 R';
  9363. $out .= ' >>]';
  9364. }
  9365. //$out .= ' /PieceInfo <<>>';
  9366. if (!empty($this->pdflayers)) {
  9367. $lyrobjs = '';
  9368. $lyrobjs_off = '';
  9369. $lyrobjs_lock = '';
  9370. foreach ($this->pdflayers as $layer) {
  9371. $layer_obj_ref = ' '.$layer['objid'].' 0 R';
  9372. $lyrobjs .= $layer_obj_ref;
  9373. if ($layer['view'] === false) {
  9374. $lyrobjs_off .= $layer_obj_ref;
  9375. }
  9376. if ($layer['lock']) {
  9377. $lyrobjs_lock .= $layer_obj_ref;
  9378. }
  9379. }
  9380. $out .= ' /OCProperties << /OCGs ['.$lyrobjs.']';
  9381. $out .= ' /D <<';
  9382. $out .= ' /Name '.$this->_textstring('Layers', $oid);
  9383. $out .= ' /Creator '.$this->_textstring('TCPDF', $oid);
  9384. $out .= ' /BaseState /ON';
  9385. $out .= ' /OFF ['.$lyrobjs_off.']';
  9386. $out .= ' /Locked ['.$lyrobjs_lock.']';
  9387. $out .= ' /Intent /View';
  9388. $out .= ' /AS [';
  9389. $out .= ' << /Event /Print /OCGs ['.$lyrobjs.'] /Category [/Print] >>';
  9390. $out .= ' << /Event /View /OCGs ['.$lyrobjs.'] /Category [/View] >>';
  9391. $out .= ' ]';
  9392. $out .= ' /Order ['.$lyrobjs.']';
  9393. $out .= ' /ListMode /AllPages';
  9394. //$out .= ' /RBGroups ['..']';
  9395. //$out .= ' /Locked ['..']';
  9396. $out .= ' >>';
  9397. $out .= ' >>';
  9398. }
  9399. // AcroForm
  9400. if (!empty($this->form_obj_id)
  9401. OR ($this->sign AND isset($this->signature_data['cert_type']))
  9402. OR !empty($this->empty_signature_appearance)) {
  9403. $out .= ' /AcroForm <<';
  9404. $objrefs = '';
  9405. if ($this->sign AND isset($this->signature_data['cert_type'])) {
  9406. // set reference for signature object
  9407. $objrefs .= $this->sig_obj_id.' 0 R';
  9408. }
  9409. if (!empty($this->empty_signature_appearance)) {
  9410. foreach ($this->empty_signature_appearance as $esa) {
  9411. // set reference for empty signature objects
  9412. $objrefs .= ' '.$esa['objid'].' 0 R';
  9413. }
  9414. }
  9415. if (!empty($this->form_obj_id)) {
  9416. foreach($this->form_obj_id as $objid) {
  9417. $objrefs .= ' '.$objid.' 0 R';
  9418. }
  9419. }
  9420. $out .= ' /Fields ['.$objrefs.']';
  9421. // It's better to turn off this value and set the appearance stream for each annotation (/AP) to avoid conflicts with signature fields.
  9422. if (empty($this->signature_data['approval']) OR ($this->signature_data['approval'] != 'A')) {
  9423. $out .= ' /NeedAppearances false';
  9424. }
  9425. if ($this->sign AND isset($this->signature_data['cert_type'])) {
  9426. if ($this->signature_data['cert_type'] > 0) {
  9427. $out .= ' /SigFlags 3';
  9428. } else {
  9429. $out .= ' /SigFlags 1';
  9430. }
  9431. }
  9432. //$out .= ' /CO ';
  9433. if (isset($this->annotation_fonts) AND !empty($this->annotation_fonts)) {
  9434. $out .= ' /DR <<';
  9435. $out .= ' /Font <<';
  9436. foreach ($this->annotation_fonts as $fontkey => $fontid) {
  9437. $out .= ' /F'.$fontid.' '.$this->font_obj_ids[$fontkey].' 0 R';
  9438. }
  9439. $out .= ' >> >>';
  9440. }
  9441. $font = $this->getFontBuffer('helvetica');
  9442. $out .= ' /DA (/F'.$font['i'].' 0 Tf 0 g)';
  9443. $out .= ' /Q '.(($this->rtl)?'2':'0');
  9444. //$out .= ' /XFA ';
  9445. $out .= ' >>';
  9446. // signatures
  9447. if ($this->sign AND isset($this->signature_data['cert_type'])
  9448. AND (empty($this->signature_data['approval']) OR ($this->signature_data['approval'] != 'A'))) {
  9449. if ($this->signature_data['cert_type'] > 0) {
  9450. $out .= ' /Perms << /DocMDP '.($this->sig_obj_id + 1).' 0 R >>';
  9451. } else {
  9452. $out .= ' /Perms << /UR3 '.($this->sig_obj_id + 1).' 0 R >>';
  9453. }
  9454. }
  9455. }
  9456. //$out .= ' /Legal <<>>';
  9457. //$out .= ' /Requirements []';
  9458. //$out .= ' /Collection <<>>';
  9459. //$out .= ' /NeedsRendering true';
  9460. $out .= ' >>';
  9461. $out .= "\n".'endobj';
  9462. $this->_out($out);
  9463. return $oid;
  9464. }
  9465. /**
  9466. * Output viewer preferences.
  9467. * @return string for viewer preferences
  9468. * @author Nicola asuni
  9469. * @since 3.1.000 (2008-06-09)
  9470. * @protected
  9471. */
  9472. protected function _putviewerpreferences() {
  9473. $vp = $this->viewer_preferences;
  9474. $out = ' /ViewerPreferences <<';
  9475. if ($this->rtl) {
  9476. $out .= ' /Direction /R2L';
  9477. } else {
  9478. $out .= ' /Direction /L2R';
  9479. }
  9480. if (isset($vp['HideToolbar']) AND ($vp['HideToolbar'])) {
  9481. $out .= ' /HideToolbar true';
  9482. }
  9483. if (isset($vp['HideMenubar']) AND ($vp['HideMenubar'])) {
  9484. $out .= ' /HideMenubar true';
  9485. }
  9486. if (isset($vp['HideWindowUI']) AND ($vp['HideWindowUI'])) {
  9487. $out .= ' /HideWindowUI true';
  9488. }
  9489. if (isset($vp['FitWindow']) AND ($vp['FitWindow'])) {
  9490. $out .= ' /FitWindow true';
  9491. }
  9492. if (isset($vp['CenterWindow']) AND ($vp['CenterWindow'])) {
  9493. $out .= ' /CenterWindow true';
  9494. }
  9495. if (isset($vp['DisplayDocTitle']) AND ($vp['DisplayDocTitle'])) {
  9496. $out .= ' /DisplayDocTitle true';
  9497. }
  9498. if (isset($vp['NonFullScreenPageMode'])) {
  9499. $out .= ' /NonFullScreenPageMode /'.$vp['NonFullScreenPageMode'];
  9500. }
  9501. if (isset($vp['ViewArea'])) {
  9502. $out .= ' /ViewArea /'.$vp['ViewArea'];
  9503. }
  9504. if (isset($vp['ViewClip'])) {
  9505. $out .= ' /ViewClip /'.$vp['ViewClip'];
  9506. }
  9507. if (isset($vp['PrintArea'])) {
  9508. $out .= ' /PrintArea /'.$vp['PrintArea'];
  9509. }
  9510. if (isset($vp['PrintClip'])) {
  9511. $out .= ' /PrintClip /'.$vp['PrintClip'];
  9512. }
  9513. if (isset($vp['PrintScaling'])) {
  9514. $out .= ' /PrintScaling /'.$vp['PrintScaling'];
  9515. }
  9516. if (isset($vp['Duplex']) AND (!TCPDF_STATIC::empty_string($vp['Duplex']))) {
  9517. $out .= ' /Duplex /'.$vp['Duplex'];
  9518. }
  9519. if (isset($vp['PickTrayByPDFSize'])) {
  9520. if ($vp['PickTrayByPDFSize']) {
  9521. $out .= ' /PickTrayByPDFSize true';
  9522. } else {
  9523. $out .= ' /PickTrayByPDFSize false';
  9524. }
  9525. }
  9526. if (isset($vp['PrintPageRange'])) {
  9527. $PrintPageRangeNum = '';
  9528. foreach ($vp['PrintPageRange'] as $k => $v) {
  9529. $PrintPageRangeNum .= ' '.($v - 1).'';
  9530. }
  9531. $out .= ' /PrintPageRange ['.substr($PrintPageRangeNum,1).']';
  9532. }
  9533. if (isset($vp['NumCopies'])) {
  9534. $out .= ' /NumCopies '.intval($vp['NumCopies']);
  9535. }
  9536. $out .= ' >>';
  9537. return $out;
  9538. }
  9539. /**
  9540. * Output PDF File Header (7.5.2).
  9541. * @protected
  9542. */
  9543. protected function _putheader() {
  9544. $this->_out('%PDF-'.$this->PDFVersion);
  9545. $this->_out('%'.chr(0xe2).chr(0xe3).chr(0xcf).chr(0xd3));
  9546. }
  9547. /**
  9548. * Output end of document (EOF).
  9549. * @protected
  9550. */
  9551. protected function _enddoc() {
  9552. if (isset($this->CurrentFont['fontkey']) AND isset($this->CurrentFont['subsetchars'])) {
  9553. // save subset chars of the previous font
  9554. $this->setFontSubBuffer($this->CurrentFont['fontkey'], 'subsetchars', $this->CurrentFont['subsetchars']);
  9555. }
  9556. $this->state = 1;
  9557. $this->_putheader();
  9558. $this->_putpages();
  9559. $this->_putresources();
  9560. // empty signature fields
  9561. if (!empty($this->empty_signature_appearance)) {
  9562. foreach ($this->empty_signature_appearance as $key => $esa) {
  9563. // widget annotation for empty signature
  9564. $out = $this->_getobj($esa['objid'])."\n";
  9565. $out .= '<< /Type /Annot';
  9566. $out .= ' /Subtype /Widget';
  9567. $out .= ' /Rect ['.$esa['rect'].']';
  9568. $out .= ' /P '.$this->page_obj_id[($esa['page'])].' 0 R'; // link to signature appearance page
  9569. $out .= ' /F 4';
  9570. $out .= ' /FT /Sig';
  9571. $signame = $esa['name'].sprintf(' [%03d]', ($key + 1));
  9572. $out .= ' /T '.$this->_textstring($signame, $esa['objid']);
  9573. $out .= ' /Ff 0';
  9574. $out .= ' >>';
  9575. $out .= "\n".'endobj';
  9576. $this->_out($out);
  9577. }
  9578. }
  9579. // Signature
  9580. if ($this->sign AND isset($this->signature_data['cert_type'])) {
  9581. // widget annotation for signature
  9582. $out = $this->_getobj($this->sig_obj_id)."\n";
  9583. $out .= '<< /Type /Annot';
  9584. $out .= ' /Subtype /Widget';
  9585. $out .= ' /Rect ['.$this->signature_appearance['rect'].']';
  9586. $out .= ' /P '.$this->page_obj_id[($this->signature_appearance['page'])].' 0 R'; // link to signature appearance page
  9587. $out .= ' /F 4';
  9588. $out .= ' /FT /Sig';
  9589. $out .= ' /T '.$this->_textstring($this->signature_appearance['name'], $this->sig_obj_id);
  9590. $out .= ' /Ff 0';
  9591. $out .= ' /V '.($this->sig_obj_id + 1).' 0 R';
  9592. $out .= ' >>';
  9593. $out .= "\n".'endobj';
  9594. $this->_out($out);
  9595. // signature
  9596. $this->_putsignature();
  9597. }
  9598. // Info
  9599. $objid_info = $this->_putinfo();
  9600. // Catalog
  9601. $objid_catalog = $this->_putcatalog();
  9602. // Cross-ref
  9603. $o = $this->bufferlen;
  9604. // XREF section
  9605. $this->_out('xref');
  9606. $this->_out('0 '.($this->n + 1));
  9607. $this->_out('0000000000 65535 f ');
  9608. $freegen = ($this->n + 2);
  9609. for ($i=1; $i <= $this->n; ++$i) {
  9610. if (!isset($this->offsets[$i]) AND ($i > 1)) {
  9611. $this->_out(sprintf('0000000000 %05d f ', $freegen));
  9612. ++$freegen;
  9613. } else {
  9614. $this->_out(sprintf('%010d 00000 n ', $this->offsets[$i]));
  9615. }
  9616. }
  9617. // TRAILER
  9618. $out = 'trailer'."\n";
  9619. $out .= '<<';
  9620. $out .= ' /Size '.($this->n + 1);
  9621. $out .= ' /Root '.$objid_catalog.' 0 R';
  9622. $out .= ' /Info '.$objid_info.' 0 R';
  9623. if ($this->encrypted) {
  9624. $out .= ' /Encrypt '.$this->encryptdata['objid'].' 0 R';
  9625. }
  9626. $out .= ' /ID [ <'.$this->file_id.'> <'.$this->file_id.'> ]';
  9627. $out .= ' >>';
  9628. $this->_out($out);
  9629. $this->_out('startxref');
  9630. $this->_out($o);
  9631. $this->_out('%%EOF');
  9632. $this->state = 3; // end-of-doc
  9633. }
  9634. /**
  9635. * Initialize a new page.
  9636. * @param $orientation (string) page orientation. Possible values are (case insensitive):<ul><li>P or PORTRAIT (default)</li><li>L or LANDSCAPE</li></ul>
  9637. * @param $format (mixed) The format used for pages. It can be either: one of the string values specified at getPageSizeFromFormat() or an array of parameters specified at setPageFormat().
  9638. * @protected
  9639. * @see getPageSizeFromFormat(), setPageFormat()
  9640. */
  9641. protected function _beginpage($orientation='', $format='') {
  9642. ++$this->page;
  9643. $this->pageobjects[$this->page] = array();
  9644. $this->setPageBuffer($this->page, '');
  9645. // initialize array for graphics tranformation positions inside a page buffer
  9646. $this->transfmrk[$this->page] = array();
  9647. $this->state = 2;
  9648. if (TCPDF_STATIC::empty_string($orientation)) {
  9649. if (isset($this->CurOrientation)) {
  9650. $orientation = $this->CurOrientation;
  9651. } elseif ($this->fwPt > $this->fhPt) {
  9652. // landscape
  9653. $orientation = 'L';
  9654. } else {
  9655. // portrait
  9656. $orientation = 'P';
  9657. }
  9658. }
  9659. if (TCPDF_STATIC::empty_string($format)) {
  9660. $this->pagedim[$this->page] = $this->pagedim[($this->page - 1)];
  9661. $this->setPageOrientation($orientation);
  9662. } else {
  9663. $this->setPageFormat($format, $orientation);
  9664. }
  9665. if ($this->rtl) {
  9666. $this->x = $this->w - $this->rMargin;
  9667. } else {
  9668. $this->x = $this->lMargin;
  9669. }
  9670. $this->y = $this->tMargin;
  9671. if (isset($this->newpagegroup[$this->page])) {
  9672. // start a new group
  9673. $this->currpagegroup = $this->newpagegroup[$this->page];
  9674. $this->pagegroups[$this->currpagegroup] = 1;
  9675. } elseif (isset($this->currpagegroup) AND ($this->currpagegroup > 0)) {
  9676. ++$this->pagegroups[$this->currpagegroup];
  9677. }
  9678. }
  9679. /**
  9680. * Mark end of page.
  9681. * @protected
  9682. */
  9683. protected function _endpage() {
  9684. $this->setVisibility('all');
  9685. $this->state = 1;
  9686. }
  9687. /**
  9688. * Begin a new object and return the object number.
  9689. * @return int object number
  9690. * @protected
  9691. */
  9692. protected function _newobj() {
  9693. $this->_out($this->_getobj());
  9694. return $this->n;
  9695. }
  9696. /**
  9697. * Return the starting object string for the selected object ID.
  9698. * @param $objid (int) Object ID (leave empty to get a new ID).
  9699. * @return string the starting object string
  9700. * @protected
  9701. * @since 5.8.009 (2010-08-20)
  9702. */
  9703. protected function _getobj($objid='') {
  9704. if ($objid === '') {
  9705. ++$this->n;
  9706. $objid = $this->n;
  9707. }
  9708. $this->offsets[$objid] = $this->bufferlen;
  9709. $this->pageobjects[$this->page][] = $objid;
  9710. return $objid.' 0 obj';
  9711. }
  9712. /**
  9713. * Underline text.
  9714. * @param $x (int) X coordinate
  9715. * @param $y (int) Y coordinate
  9716. * @param $txt (string) text to underline
  9717. * @protected
  9718. */
  9719. protected function _dounderline($x, $y, $txt) {
  9720. $w = $this->GetStringWidth($txt);
  9721. return $this->_dounderlinew($x, $y, $w);
  9722. }
  9723. /**
  9724. * Underline for rectangular text area.
  9725. * @param $x (int) X coordinate
  9726. * @param $y (int) Y coordinate
  9727. * @param $w (int) width to underline
  9728. * @protected
  9729. * @since 4.8.008 (2009-09-29)
  9730. */
  9731. protected function _dounderlinew($x, $y, $w) {
  9732. $linew = - $this->CurrentFont['ut'] / 1000 * $this->FontSizePt;
  9733. return sprintf('%F %F %F %F re f', $x * $this->k, ((($this->h - $y) * $this->k) + $linew), $w * $this->k, $linew);
  9734. }
  9735. /**
  9736. * Line through text.
  9737. * @param $x (int) X coordinate
  9738. * @param $y (int) Y coordinate
  9739. * @param $txt (string) text to linethrough
  9740. * @protected
  9741. */
  9742. protected function _dolinethrough($x, $y, $txt) {
  9743. $w = $this->GetStringWidth($txt);
  9744. return $this->_dolinethroughw($x, $y, $w);
  9745. }
  9746. /**
  9747. * Line through for rectangular text area.
  9748. * @param $x (int) X coordinate
  9749. * @param $y (int) Y coordinate
  9750. * @param $w (int) line length (width)
  9751. * @protected
  9752. * @since 4.9.008 (2009-09-29)
  9753. */
  9754. protected function _dolinethroughw($x, $y, $w) {
  9755. $linew = - $this->CurrentFont['ut'] / 1000 * $this->FontSizePt;
  9756. return sprintf('%F %F %F %F re f', $x * $this->k, ((($this->h - $y) * $this->k) + $linew + ($this->FontSizePt / 3)), $w * $this->k, $linew);
  9757. }
  9758. /**
  9759. * Overline text.
  9760. * @param $x (int) X coordinate
  9761. * @param $y (int) Y coordinate
  9762. * @param $txt (string) text to overline
  9763. * @protected
  9764. * @since 4.9.015 (2010-04-19)
  9765. */
  9766. protected function _dooverline($x, $y, $txt) {
  9767. $w = $this->GetStringWidth($txt);
  9768. return $this->_dooverlinew($x, $y, $w);
  9769. }
  9770. /**
  9771. * Overline for rectangular text area.
  9772. * @param $x (int) X coordinate
  9773. * @param $y (int) Y coordinate
  9774. * @param $w (int) width to overline
  9775. * @protected
  9776. * @since 4.9.015 (2010-04-19)
  9777. */
  9778. protected function _dooverlinew($x, $y, $w) {
  9779. $linew = - $this->CurrentFont['ut'] / 1000 * $this->FontSizePt;
  9780. return sprintf('%F %F %F %F re f', $x * $this->k, (($this->h - $y + $this->FontAscent) * $this->k) - $linew, $w * $this->k, $linew);
  9781. }
  9782. /**
  9783. * Format a data string for meta information
  9784. * @param $s (string) data string to escape.
  9785. * @param $n (int) object ID
  9786. * @return string escaped string.
  9787. * @protected
  9788. */
  9789. protected function _datastring($s, $n=0) {
  9790. if ($n == 0) {
  9791. $n = $this->n;
  9792. }
  9793. $s = $this->_encrypt_data($n, $s);
  9794. return '('. TCPDF_STATIC::_escape($s).')';
  9795. }
  9796. /**
  9797. * Set the document creation timestamp
  9798. * @param $time (mixed) Document creation timestamp in seconds or date-time string.
  9799. * @public
  9800. * @since 5.9.152 (2012-03-23)
  9801. */
  9802. public function setDocCreationTimestamp($time) {
  9803. if (is_string($time)) {
  9804. $time = TCPDF_STATIC::getTimestamp($time);
  9805. }
  9806. $this->doc_creation_timestamp = intval($time);
  9807. }
  9808. /**
  9809. * Set the document modification timestamp
  9810. * @param $time (mixed) Document modification timestamp in seconds or date-time string.
  9811. * @public
  9812. * @since 5.9.152 (2012-03-23)
  9813. */
  9814. public function setDocModificationTimestamp($time) {
  9815. if (is_string($time)) {
  9816. $time = TCPDF_STATIC::getTimestamp($time);
  9817. }
  9818. $this->doc_modification_timestamp = intval($time);
  9819. }
  9820. /**
  9821. * Returns document creation timestamp in seconds.
  9822. * @return (int) Creation timestamp in seconds.
  9823. * @public
  9824. * @since 5.9.152 (2012-03-23)
  9825. */
  9826. public function getDocCreationTimestamp() {
  9827. return $this->doc_creation_timestamp;
  9828. }
  9829. /**
  9830. * Returns document modification timestamp in seconds.
  9831. * @return (int) Modfication timestamp in seconds.
  9832. * @public
  9833. * @since 5.9.152 (2012-03-23)
  9834. */
  9835. public function getDocModificationTimestamp() {
  9836. return $this->doc_modification_timestamp;
  9837. }
  9838. /**
  9839. * Returns a formatted date for meta information
  9840. * @param $n (int) Object ID.
  9841. * @param $timestamp (int) Timestamp to convert.
  9842. * @return string escaped date string.
  9843. * @protected
  9844. * @since 4.6.028 (2009-08-25)
  9845. */
  9846. protected function _datestring($n=0, $timestamp=0) {
  9847. if ((empty($timestamp)) OR ($timestamp < 0)) {
  9848. $timestamp = $this->doc_creation_timestamp;
  9849. }
  9850. return $this->_datastring('D:'.TCPDF_STATIC::getFormattedDate($timestamp), $n);
  9851. }
  9852. /**
  9853. * Format a text string for meta information
  9854. * @param $s (string) string to escape.
  9855. * @param $n (int) object ID
  9856. * @return string escaped string.
  9857. * @protected
  9858. */
  9859. protected function _textstring($s, $n=0) {
  9860. if ($this->isunicode) {
  9861. //Convert string to UTF-16BE
  9862. $s = TCPDF_FONTS::UTF8ToUTF16BE($s, true, $this->isunicode, $this->CurrentFont);
  9863. }
  9864. return $this->_datastring($s, $n);
  9865. }
  9866. /**
  9867. * get raw output stream.
  9868. * @param $s (string) string to output.
  9869. * @param $n (int) object reference for encryption mode
  9870. * @protected
  9871. * @author Nicola Asuni
  9872. * @since 5.5.000 (2010-06-22)
  9873. */
  9874. protected function _getrawstream($s, $n=0) {
  9875. if ($n <= 0) {
  9876. // default to current object
  9877. $n = $this->n;
  9878. }
  9879. return $this->_encrypt_data($n, $s);
  9880. }
  9881. /**
  9882. * Output a string to the document.
  9883. * @param $s (string) string to output.
  9884. * @protected
  9885. */
  9886. protected function _out($s) {
  9887. if ($this->state == 2) {
  9888. if ($this->inxobj) {
  9889. // we are inside an XObject template
  9890. $this->xobjects[$this->xobjid]['outdata'] .= $s."\n";
  9891. } elseif ((!$this->InFooter) AND isset($this->footerlen[$this->page]) AND ($this->footerlen[$this->page] > 0)) {
  9892. // puts data before page footer
  9893. $pagebuff = $this->getPageBuffer($this->page);
  9894. $page = substr($pagebuff, 0, -$this->footerlen[$this->page]);
  9895. $footer = substr($pagebuff, -$this->footerlen[$this->page]);
  9896. $this->setPageBuffer($this->page, $page.$s."\n".$footer);
  9897. // update footer position
  9898. $this->footerpos[$this->page] += strlen($s."\n");
  9899. } else {
  9900. // set page data
  9901. $this->setPageBuffer($this->page, $s."\n", true);
  9902. }
  9903. } elseif ($this->state > 0) {
  9904. // set general data
  9905. $this->setBuffer($s."\n");
  9906. }
  9907. }
  9908. /**
  9909. * Set header font.
  9910. * @param $font (array) Array describing the basic font parameters: (family, style, size).
  9911. * @public
  9912. * @since 1.1
  9913. */
  9914. public function setHeaderFont($font) {
  9915. $this->header_font = $font;
  9916. }
  9917. /**
  9918. * Get header font.
  9919. * @return array() Array describing the basic font parameters: (family, style, size).
  9920. * @public
  9921. * @since 4.0.012 (2008-07-24)
  9922. */
  9923. public function getHeaderFont() {
  9924. return $this->header_font;
  9925. }
  9926. /**
  9927. * Set footer font.
  9928. * @param $font (array) Array describing the basic font parameters: (family, style, size).
  9929. * @public
  9930. * @since 1.1
  9931. */
  9932. public function setFooterFont($font) {
  9933. $this->footer_font = $font;
  9934. }
  9935. /**
  9936. * Get Footer font.
  9937. * @return array() Array describing the basic font parameters: (family, style, size).
  9938. * @public
  9939. * @since 4.0.012 (2008-07-24)
  9940. */
  9941. public function getFooterFont() {
  9942. return $this->footer_font;
  9943. }
  9944. /**
  9945. * Set language array.
  9946. * @param $language (array)
  9947. * @public
  9948. * @since 1.1
  9949. */
  9950. public function setLanguageArray($language) {
  9951. $this->l = $language;
  9952. if (isset($this->l['a_meta_dir'])) {
  9953. $this->rtl = $this->l['a_meta_dir']=='rtl' ? true : false;
  9954. } else {
  9955. $this->rtl = false;
  9956. }
  9957. }
  9958. /**
  9959. * Returns the PDF data.
  9960. * @public
  9961. */
  9962. public function getPDFData() {
  9963. if ($this->state < 3) {
  9964. $this->Close();
  9965. }
  9966. return $this->buffer;
  9967. }
  9968. /**
  9969. * Output anchor link.
  9970. * @param $url (string) link URL or internal link (i.e.: &lt;a href="#23,4.5"&gt;link to page 23 at 4.5 Y position&lt;/a&gt;)
  9971. * @param $name (string) link name
  9972. * @param $fill (boolean) Indicates if the cell background must be painted (true) or transparent (false).
  9973. * @param $firstline (boolean) if true prints only the first line and return the remaining string.
  9974. * @param $color (array) array of RGB text color
  9975. * @param $style (string) font style (U, D, B, I)
  9976. * @param $firstblock (boolean) if true the string is the starting of a line.
  9977. * @return the number of cells used or the remaining text if $firstline = true;
  9978. * @public
  9979. */
  9980. public function addHtmlLink($url, $name, $fill=false, $firstline=false, $color='', $style=-1, $firstblock=false) {
  9981. if (isset($url[1]) AND ($url[0] == '#') AND is_numeric($url[1])) {
  9982. // convert url to internal link
  9983. $lnkdata = explode(',', $url);
  9984. if (isset($lnkdata[0]) ) {
  9985. $page = substr($lnkdata[0], 1);
  9986. if (isset($lnkdata[1]) AND (strlen($lnkdata[1]) > 0)) {
  9987. $lnky = floatval($lnkdata[1]);
  9988. } else {
  9989. $lnky = 0;
  9990. }
  9991. $url = $this->AddLink();
  9992. $this->SetLink($url, $lnky, $page);
  9993. }
  9994. }
  9995. // store current settings
  9996. $prevcolor = $this->fgcolor;
  9997. $prevstyle = $this->FontStyle;
  9998. if (empty($color)) {
  9999. $this->SetTextColorArray($this->htmlLinkColorArray);
  10000. } else {
  10001. $this->SetTextColorArray($color);
  10002. }
  10003. if ($style == -1) {
  10004. $this->SetFont('', $this->FontStyle.$this->htmlLinkFontStyle);
  10005. } else {
  10006. $this->SetFont('', $this->FontStyle.$style);
  10007. }
  10008. $ret = $this->Write($this->lasth, $name, $url, $fill, '', false, 0, $firstline, $firstblock, 0);
  10009. // restore settings
  10010. $this->SetFont('', $prevstyle);
  10011. $this->SetTextColorArray($prevcolor);
  10012. return $ret;
  10013. }
  10014. /**
  10015. * Converts pixels to User's Units.
  10016. * @param $px (int) pixels
  10017. * @return float value in user's unit
  10018. * @public
  10019. * @see setImageScale(), getImageScale()
  10020. */
  10021. public function pixelsToUnits($px) {
  10022. return ($px / ($this->imgscale * $this->k));
  10023. }
  10024. /**
  10025. * Reverse function for htmlentities.
  10026. * Convert entities in UTF-8.
  10027. * @param $text_to_convert (string) Text to convert.
  10028. * @return string converted text string
  10029. * @public
  10030. */
  10031. public function unhtmlentities($text_to_convert) {
  10032. return @html_entity_decode($text_to_convert, ENT_QUOTES, $this->encoding);
  10033. }
  10034. // ENCRYPTION METHODS ----------------------------------
  10035. /**
  10036. * Compute encryption key depending on object number where the encrypted data is stored.
  10037. * This is used for all strings and streams without crypt filter specifier.
  10038. * @param $n (int) object number
  10039. * @return int object key
  10040. * @protected
  10041. * @author Nicola Asuni
  10042. * @since 2.0.000 (2008-01-02)
  10043. */
  10044. protected function _objectkey($n) {
  10045. $objkey = $this->encryptdata['key'].pack('VXxx', $n);
  10046. if ($this->encryptdata['mode'] == 2) { // AES-128
  10047. // AES padding
  10048. $objkey .= "\x73\x41\x6C\x54"; // sAlT
  10049. }
  10050. $objkey = substr(TCPDF_STATIC::_md5_16($objkey), 0, (($this->encryptdata['Length'] / 8) + 5));
  10051. $objkey = substr($objkey, 0, 16);
  10052. return $objkey;
  10053. }
  10054. /**
  10055. * Encrypt the input string.
  10056. * @param $n (int) object number
  10057. * @param $s (string) data string to encrypt
  10058. * @return encrypted string
  10059. * @protected
  10060. * @author Nicola Asuni
  10061. * @since 5.0.005 (2010-05-11)
  10062. */
  10063. protected function _encrypt_data($n, $s) {
  10064. if (!$this->encrypted) {
  10065. return $s;
  10066. }
  10067. switch ($this->encryptdata['mode']) {
  10068. case 0: // RC4-40
  10069. case 1: { // RC4-128
  10070. $s = TCPDF_STATIC::_RC4($this->_objectkey($n), $s, $this->last_enc_key, $this->last_enc_key_c);
  10071. break;
  10072. }
  10073. case 2: { // AES-128
  10074. $s = TCPDF_STATIC::_AES($this->_objectkey($n), $s);
  10075. break;
  10076. }
  10077. case 3: { // AES-256
  10078. $s = TCPDF_STATIC::_AES($this->encryptdata['key'], $s);
  10079. break;
  10080. }
  10081. }
  10082. return $s;
  10083. }
  10084. /**
  10085. * Put encryption on PDF document.
  10086. * @protected
  10087. * @author Nicola Asuni
  10088. * @since 2.0.000 (2008-01-02)
  10089. */
  10090. protected function _putencryption() {
  10091. if (!$this->encrypted) {
  10092. return;
  10093. }
  10094. $this->encryptdata['objid'] = $this->_newobj();
  10095. $out = '<<';
  10096. if (!isset($this->encryptdata['Filter']) OR empty($this->encryptdata['Filter'])) {
  10097. $this->encryptdata['Filter'] = 'Standard';
  10098. }
  10099. $out .= ' /Filter /'.$this->encryptdata['Filter'];
  10100. if (isset($this->encryptdata['SubFilter']) AND !empty($this->encryptdata['SubFilter'])) {
  10101. $out .= ' /SubFilter /'.$this->encryptdata['SubFilter'];
  10102. }
  10103. if (!isset($this->encryptdata['V']) OR empty($this->encryptdata['V'])) {
  10104. $this->encryptdata['V'] = 1;
  10105. }
  10106. // V is a code specifying the algorithm to be used in encrypting and decrypting the document
  10107. $out .= ' /V '.$this->encryptdata['V'];
  10108. if (isset($this->encryptdata['Length']) AND !empty($this->encryptdata['Length'])) {
  10109. // The length of the encryption key, in bits. The value shall be a multiple of 8, in the range 40 to 256
  10110. $out .= ' /Length '.$this->encryptdata['Length'];
  10111. } else {
  10112. $out .= ' /Length 40';
  10113. }
  10114. if ($this->encryptdata['V'] >= 4) {
  10115. if (!isset($this->encryptdata['StmF']) OR empty($this->encryptdata['StmF'])) {
  10116. $this->encryptdata['StmF'] = 'Identity';
  10117. }
  10118. if (!isset($this->encryptdata['StrF']) OR empty($this->encryptdata['StrF'])) {
  10119. // The name of the crypt filter that shall be used when decrypting all strings in the document.
  10120. $this->encryptdata['StrF'] = 'Identity';
  10121. }
  10122. // A dictionary whose keys shall be crypt filter names and whose values shall be the corresponding crypt filter dictionaries.
  10123. if (isset($this->encryptdata['CF']) AND !empty($this->encryptdata['CF'])) {
  10124. $out .= ' /CF <<';
  10125. $out .= ' /'.$this->encryptdata['StmF'].' <<';
  10126. $out .= ' /Type /CryptFilter';
  10127. if (isset($this->encryptdata['CF']['CFM']) AND !empty($this->encryptdata['CF']['CFM'])) {
  10128. // The method used
  10129. $out .= ' /CFM /'.$this->encryptdata['CF']['CFM'];
  10130. if ($this->encryptdata['pubkey']) {
  10131. $out .= ' /Recipients [';
  10132. foreach ($this->encryptdata['Recipients'] as $rec) {
  10133. $out .= ' <'.$rec.'>';
  10134. }
  10135. $out .= ' ]';
  10136. if (isset($this->encryptdata['CF']['EncryptMetadata']) AND (!$this->encryptdata['CF']['EncryptMetadata'])) {
  10137. $out .= ' /EncryptMetadata false';
  10138. } else {
  10139. $out .= ' /EncryptMetadata true';
  10140. }
  10141. }
  10142. } else {
  10143. $out .= ' /CFM /None';
  10144. }
  10145. if (isset($this->encryptdata['CF']['AuthEvent']) AND !empty($this->encryptdata['CF']['AuthEvent'])) {
  10146. // The event to be used to trigger the authorization that is required to access encryption keys used by this filter.
  10147. $out .= ' /AuthEvent /'.$this->encryptdata['CF']['AuthEvent'];
  10148. } else {
  10149. $out .= ' /AuthEvent /DocOpen';
  10150. }
  10151. if (isset($this->encryptdata['CF']['Length']) AND !empty($this->encryptdata['CF']['Length'])) {
  10152. // The bit length of the encryption key.
  10153. $out .= ' /Length '.$this->encryptdata['CF']['Length'];
  10154. }
  10155. $out .= ' >> >>';
  10156. }
  10157. // The name of the crypt filter that shall be used by default when decrypting streams.
  10158. $out .= ' /StmF /'.$this->encryptdata['StmF'];
  10159. // The name of the crypt filter that shall be used when decrypting all strings in the document.
  10160. $out .= ' /StrF /'.$this->encryptdata['StrF'];
  10161. if (isset($this->encryptdata['EFF']) AND !empty($this->encryptdata['EFF'])) {
  10162. // The name of the crypt filter that shall be used when encrypting embedded file streams that do not have their own crypt filter specifier.
  10163. $out .= ' /EFF /'.$this->encryptdata[''];
  10164. }
  10165. }
  10166. // Additional encryption dictionary entries for the standard security handler
  10167. if ($this->encryptdata['pubkey']) {
  10168. if (($this->encryptdata['V'] < 4) AND isset($this->encryptdata['Recipients']) AND !empty($this->encryptdata['Recipients'])) {
  10169. $out .= ' /Recipients [';
  10170. foreach ($this->encryptdata['Recipients'] as $rec) {
  10171. $out .= ' <'.$rec.'>';
  10172. }
  10173. $out .= ' ]';
  10174. }
  10175. } else {
  10176. $out .= ' /R';
  10177. if ($this->encryptdata['V'] == 5) { // AES-256
  10178. $out .= ' 5';
  10179. $out .= ' /OE ('.TCPDF_STATIC::_escape($this->encryptdata['OE']).')';
  10180. $out .= ' /UE ('.TCPDF_STATIC::_escape($this->encryptdata['UE']).')';
  10181. $out .= ' /Perms ('.TCPDF_STATIC::_escape($this->encryptdata['perms']).')';
  10182. } elseif ($this->encryptdata['V'] == 4) { // AES-128
  10183. $out .= ' 4';
  10184. } elseif ($this->encryptdata['V'] < 2) { // RC-40
  10185. $out .= ' 2';
  10186. } else { // RC-128
  10187. $out .= ' 3';
  10188. }
  10189. $out .= ' /O ('.TCPDF_STATIC::_escape($this->encryptdata['O']).')';
  10190. $out .= ' /U ('.TCPDF_STATIC::_escape($this->encryptdata['U']).')';
  10191. $out .= ' /P '.$this->encryptdata['P'];
  10192. if (isset($this->encryptdata['EncryptMetadata']) AND (!$this->encryptdata['EncryptMetadata'])) {
  10193. $out .= ' /EncryptMetadata false';
  10194. } else {
  10195. $out .= ' /EncryptMetadata true';
  10196. }
  10197. }
  10198. $out .= ' >>';
  10199. $out .= "\n".'endobj';
  10200. $this->_out($out);
  10201. }
  10202. /**
  10203. * Compute U value (used for encryption)
  10204. * @return string U value
  10205. * @protected
  10206. * @since 2.0.000 (2008-01-02)
  10207. * @author Nicola Asuni
  10208. */
  10209. protected function _Uvalue() {
  10210. if ($this->encryptdata['mode'] == 0) { // RC4-40
  10211. return TCPDF_STATIC::_RC4($this->encryptdata['key'], TCPDF_STATIC::$enc_padding, $this->last_enc_key, $this->last_enc_key_c);
  10212. } elseif ($this->encryptdata['mode'] < 3) { // RC4-128, AES-128
  10213. $tmp = TCPDF_STATIC::_md5_16(TCPDF_STATIC::$enc_padding.$this->encryptdata['fileid']);
  10214. $enc = TCPDF_STATIC::_RC4($this->encryptdata['key'], $tmp, $this->last_enc_key, $this->last_enc_key_c);
  10215. $len = strlen($tmp);
  10216. for ($i = 1; $i <= 19; ++$i) {
  10217. $ek = '';
  10218. for ($j = 0; $j < $len; ++$j) {
  10219. $ek .= chr(ord($this->encryptdata['key'][$j]) ^ $i);
  10220. }
  10221. $enc = TCPDF_STATIC::_RC4($ek, $enc, $this->last_enc_key, $this->last_enc_key_c);
  10222. }
  10223. $enc .= str_repeat("\x00", 16);
  10224. return substr($enc, 0, 32);
  10225. } elseif ($this->encryptdata['mode'] == 3) { // AES-256
  10226. $seed = TCPDF_STATIC::_md5_16(TCPDF_STATIC::getRandomSeed());
  10227. // User Validation Salt
  10228. $this->encryptdata['UVS'] = substr($seed, 0, 8);
  10229. // User Key Salt
  10230. $this->encryptdata['UKS'] = substr($seed, 8, 16);
  10231. return hash('sha256', $this->encryptdata['user_password'].$this->encryptdata['UVS'], true).$this->encryptdata['UVS'].$this->encryptdata['UKS'];
  10232. }
  10233. }
  10234. /**
  10235. * Compute UE value (used for encryption)
  10236. * @return string UE value
  10237. * @protected
  10238. * @since 5.9.006 (2010-10-19)
  10239. * @author Nicola Asuni
  10240. */
  10241. protected function _UEvalue() {
  10242. $hashkey = hash('sha256', $this->encryptdata['user_password'].$this->encryptdata['UKS'], true);
  10243. return TCPDF_STATIC::_AESnopad($hashkey, $this->encryptdata['key']);
  10244. }
  10245. /**
  10246. * Compute O value (used for encryption)
  10247. * @return string O value
  10248. * @protected
  10249. * @since 2.0.000 (2008-01-02)
  10250. * @author Nicola Asuni
  10251. */
  10252. protected function _Ovalue() {
  10253. if ($this->encryptdata['mode'] < 3) { // RC4-40, RC4-128, AES-128
  10254. $tmp = TCPDF_STATIC::_md5_16($this->encryptdata['owner_password']);
  10255. if ($this->encryptdata['mode'] > 0) {
  10256. for ($i = 0; $i < 50; ++$i) {
  10257. $tmp = TCPDF_STATIC::_md5_16($tmp);
  10258. }
  10259. }
  10260. $owner_key = substr($tmp, 0, ($this->encryptdata['Length'] / 8));
  10261. $enc = TCPDF_STATIC::_RC4($owner_key, $this->encryptdata['user_password'], $this->last_enc_key, $this->last_enc_key_c);
  10262. if ($this->encryptdata['mode'] > 0) {
  10263. $len = strlen($owner_key);
  10264. for ($i = 1; $i <= 19; ++$i) {
  10265. $ek = '';
  10266. for ($j = 0; $j < $len; ++$j) {
  10267. $ek .= chr(ord($owner_key[$j]) ^ $i);
  10268. }
  10269. $enc = TCPDF_STATIC::_RC4($ek, $enc, $this->last_enc_key, $this->last_enc_key_c);
  10270. }
  10271. }
  10272. return $enc;
  10273. } elseif ($this->encryptdata['mode'] == 3) { // AES-256
  10274. $seed = TCPDF_STATIC::_md5_16(TCPDF_STATIC::getRandomSeed());
  10275. // Owner Validation Salt
  10276. $this->encryptdata['OVS'] = substr($seed, 0, 8);
  10277. // Owner Key Salt
  10278. $this->encryptdata['OKS'] = substr($seed, 8, 16);
  10279. return hash('sha256', $this->encryptdata['owner_password'].$this->encryptdata['OVS'].$this->encryptdata['U'], true).$this->encryptdata['OVS'].$this->encryptdata['OKS'];
  10280. }
  10281. }
  10282. /**
  10283. * Compute OE value (used for encryption)
  10284. * @return string OE value
  10285. * @protected
  10286. * @since 5.9.006 (2010-10-19)
  10287. * @author Nicola Asuni
  10288. */
  10289. protected function _OEvalue() {
  10290. $hashkey = hash('sha256', $this->encryptdata['owner_password'].$this->encryptdata['OKS'].$this->encryptdata['U'], true);
  10291. return TCPDF_STATIC::_AESnopad($hashkey, $this->encryptdata['key']);
  10292. }
  10293. /**
  10294. * Convert password for AES-256 encryption mode
  10295. * @param $password (string) password
  10296. * @return string password
  10297. * @protected
  10298. * @since 5.9.006 (2010-10-19)
  10299. * @author Nicola Asuni
  10300. */
  10301. protected function _fixAES256Password($password) {
  10302. $psw = ''; // password to be returned
  10303. $psw_array = TCPDF_FONTS::utf8Bidi(TCPDF_FONTS::UTF8StringToArray($password, $this->isunicode, $this->CurrentFont), $password, $this->rtl, $this->isunicode, $this->CurrentFont);
  10304. foreach ($psw_array as $c) {
  10305. $psw .= TCPDF_FONTS::unichr($c, $this->isunicode);
  10306. }
  10307. return substr($psw, 0, 127);
  10308. }
  10309. /**
  10310. * Compute encryption key
  10311. * @protected
  10312. * @since 2.0.000 (2008-01-02)
  10313. * @author Nicola Asuni
  10314. */
  10315. protected function _generateencryptionkey() {
  10316. $keybytelen = ($this->encryptdata['Length'] / 8);
  10317. if (!$this->encryptdata['pubkey']) { // standard mode
  10318. if ($this->encryptdata['mode'] == 3) { // AES-256
  10319. // generate 256 bit random key
  10320. $this->encryptdata['key'] = substr(hash('sha256', TCPDF_STATIC::getRandomSeed(), true), 0, $keybytelen);
  10321. // truncate passwords
  10322. $this->encryptdata['user_password'] = $this->_fixAES256Password($this->encryptdata['user_password']);
  10323. $this->encryptdata['owner_password'] = $this->_fixAES256Password($this->encryptdata['owner_password']);
  10324. // Compute U value
  10325. $this->encryptdata['U'] = $this->_Uvalue();
  10326. // Compute UE value
  10327. $this->encryptdata['UE'] = $this->_UEvalue();
  10328. // Compute O value
  10329. $this->encryptdata['O'] = $this->_Ovalue();
  10330. // Compute OE value
  10331. $this->encryptdata['OE'] = $this->_OEvalue();
  10332. // Compute P value
  10333. $this->encryptdata['P'] = $this->encryptdata['protection'];
  10334. // Computing the encryption dictionary's Perms (permissions) value
  10335. $perms = TCPDF_STATIC::getEncPermissionsString($this->encryptdata['protection']); // bytes 0-3
  10336. $perms .= chr(255).chr(255).chr(255).chr(255); // bytes 4-7
  10337. if (isset($this->encryptdata['CF']['EncryptMetadata']) AND (!$this->encryptdata['CF']['EncryptMetadata'])) { // byte 8
  10338. $perms .= 'F';
  10339. } else {
  10340. $perms .= 'T';
  10341. }
  10342. $perms .= 'adb'; // bytes 9-11
  10343. $perms .= 'nick'; // bytes 12-15
  10344. $this->encryptdata['perms'] = TCPDF_STATIC::_AESnopad($this->encryptdata['key'], $perms);
  10345. } else { // RC4-40, RC4-128, AES-128
  10346. // Pad passwords
  10347. $this->encryptdata['user_password'] = substr($this->encryptdata['user_password'].TCPDF_STATIC::$enc_padding, 0, 32);
  10348. $this->encryptdata['owner_password'] = substr($this->encryptdata['owner_password'].TCPDF_STATIC::$enc_padding, 0, 32);
  10349. // Compute O value
  10350. $this->encryptdata['O'] = $this->_Ovalue();
  10351. // get default permissions (reverse byte order)
  10352. $permissions = TCPDF_STATIC::getEncPermissionsString($this->encryptdata['protection']);
  10353. // Compute encryption key
  10354. $tmp = TCPDF_STATIC::_md5_16($this->encryptdata['user_password'].$this->encryptdata['O'].$permissions.$this->encryptdata['fileid']);
  10355. if ($this->encryptdata['mode'] > 0) {
  10356. for ($i = 0; $i < 50; ++$i) {
  10357. $tmp = TCPDF_STATIC::_md5_16(substr($tmp, 0, $keybytelen));
  10358. }
  10359. }
  10360. $this->encryptdata['key'] = substr($tmp, 0, $keybytelen);
  10361. // Compute U value
  10362. $this->encryptdata['U'] = $this->_Uvalue();
  10363. // Compute P value
  10364. $this->encryptdata['P'] = $this->encryptdata['protection'];
  10365. }
  10366. } else { // Public-Key mode
  10367. // random 20-byte seed
  10368. $seed = sha1(TCPDF_STATIC::getRandomSeed(), true);
  10369. $recipient_bytes = '';
  10370. foreach ($this->encryptdata['pubkeys'] as $pubkey) {
  10371. // for each public certificate
  10372. if (isset($pubkey['p'])) {
  10373. $pkprotection = TCPDF_STATIC::getUserPermissionCode($pubkey['p'], $this->encryptdata['mode']);
  10374. } else {
  10375. $pkprotection = $this->encryptdata['protection'];
  10376. }
  10377. // get default permissions (reverse byte order)
  10378. $pkpermissions = TCPDF_STATIC::getEncPermissionsString($pkprotection);
  10379. // envelope data
  10380. $envelope = $seed.$pkpermissions;
  10381. // write the envelope data to a temporary file
  10382. $tempkeyfile = TCPDF_STATIC::getObjFilename('key', $this->file_id);
  10383. $f = TCPDF_STATIC::fopenLocal($tempkeyfile, 'wb');
  10384. if (!$f) {
  10385. $this->Error('Unable to create temporary key file: '.$tempkeyfile);
  10386. }
  10387. $envelope_length = strlen($envelope);
  10388. fwrite($f, $envelope, $envelope_length);
  10389. fclose($f);
  10390. $tempencfile = TCPDF_STATIC::getObjFilename('enc', $this->file_id);
  10391. if (!openssl_pkcs7_encrypt($tempkeyfile, $tempencfile, $pubkey['c'], array(), PKCS7_BINARY | PKCS7_DETACHED)) {
  10392. $this->Error('Unable to encrypt the file: '.$tempkeyfile);
  10393. }
  10394. // read encryption signature
  10395. $signature = file_get_contents($tempencfile, false, null, $envelope_length);
  10396. // extract signature
  10397. $signature = substr($signature, strpos($signature, 'Content-Disposition'));
  10398. $tmparr = explode("\n\n", $signature);
  10399. $signature = trim($tmparr[1]);
  10400. unset($tmparr);
  10401. // decode signature
  10402. $signature = base64_decode($signature);
  10403. // convert signature to hex
  10404. $hexsignature = current(unpack('H*', $signature));
  10405. // store signature on recipients array
  10406. $this->encryptdata['Recipients'][] = $hexsignature;
  10407. // The bytes of each item in the Recipients array of PKCS#7 objects in the order in which they appear in the array
  10408. $recipient_bytes .= $signature;
  10409. }
  10410. // calculate encryption key
  10411. if ($this->encryptdata['mode'] == 3) { // AES-256
  10412. $this->encryptdata['key'] = substr(hash('sha256', $seed.$recipient_bytes, true), 0, $keybytelen);
  10413. } else { // RC4-40, RC4-128, AES-128
  10414. $this->encryptdata['key'] = substr(sha1($seed.$recipient_bytes, true), 0, $keybytelen);
  10415. }
  10416. }
  10417. }
  10418. /**
  10419. * Set document protection
  10420. * Remark: the protection against modification is for people who have the full Acrobat product.
  10421. * If you don't set any password, the document will open as usual. If you set a user password, the PDF viewer will ask for it before displaying the document. The master password, if different from the user one, can be used to get full access.
  10422. * Note: protecting a document requires to encrypt it, which increases the processing time a lot. This can cause a PHP time-out in some cases, especially if the document contains images or fonts.
  10423. * @param $permissions (Array) the set of permissions (specify the ones you want to block):<ul><li>print : Print the document;</li><li>modify : Modify the contents of the document by operations other than those controlled by 'fill-forms', 'extract' and 'assemble';</li><li>copy : Copy or otherwise extract text and graphics from the document;</li><li>annot-forms : Add or modify text annotations, fill in interactive form fields, and, if 'modify' is also set, create or modify interactive form fields (including signature fields);</li><li>fill-forms : Fill in existing interactive form fields (including signature fields), even if 'annot-forms' is not specified;</li><li>extract : Extract text and graphics (in support of accessibility to users with disabilities or for other purposes);</li><li>assemble : Assemble the document (insert, rotate, or delete pages and create bookmarks or thumbnail images), even if 'modify' is not set;</li><li>print-high : Print the document to a representation from which a faithful digital copy of the PDF content could be generated. When this is not set, printing is limited to a low-level representation of the appearance, possibly of degraded quality.</li><li>owner : (inverted logic - only for public-key) when set permits change of encryption and enables all other permissions.</li></ul>
  10424. * @param $user_pass (String) user password. Empty by default.
  10425. * @param $owner_pass (String) owner password. If not specified, a random value is used.
  10426. * @param $mode (int) encryption strength: 0 = RC4 40 bit; 1 = RC4 128 bit; 2 = AES 128 bit; 3 = AES 256 bit.
  10427. * @param $pubkeys (String) array of recipients containing public-key certificates ('c') and permissions ('p'). For example: array(array('c' => 'file://../examples/data/cert/tcpdf.crt', 'p' => array('print')))
  10428. * @public
  10429. * @since 2.0.000 (2008-01-02)
  10430. * @author Nicola Asuni
  10431. */
  10432. public function SetProtection($permissions=array('print', 'modify', 'copy', 'annot-forms', 'fill-forms', 'extract', 'assemble', 'print-high'), $user_pass='', $owner_pass=null, $mode=0, $pubkeys=null) {
  10433. if ($this->pdfa_mode) {
  10434. // encryption is not allowed in PDF/A mode
  10435. return;
  10436. }
  10437. $this->encryptdata['protection'] = TCPDF_STATIC::getUserPermissionCode($permissions, $mode);
  10438. if (($pubkeys !== null) AND (is_array($pubkeys))) {
  10439. // public-key mode
  10440. $this->encryptdata['pubkeys'] = $pubkeys;
  10441. if ($mode == 0) {
  10442. // public-Key Security requires at least 128 bit
  10443. $mode = 1;
  10444. }
  10445. if (!function_exists('openssl_pkcs7_encrypt')) {
  10446. $this->Error('Public-Key Security requires openssl library.');
  10447. }
  10448. // Set Public-Key filter (available are: Entrust.PPKEF, Adobe.PPKLite, Adobe.PubSec)
  10449. $this->encryptdata['pubkey'] = true;
  10450. $this->encryptdata['Filter'] = 'Adobe.PubSec';
  10451. $this->encryptdata['StmF'] = 'DefaultCryptFilter';
  10452. $this->encryptdata['StrF'] = 'DefaultCryptFilter';
  10453. } else {
  10454. // standard mode (password mode)
  10455. $this->encryptdata['pubkey'] = false;
  10456. $this->encryptdata['Filter'] = 'Standard';
  10457. $this->encryptdata['StmF'] = 'StdCF';
  10458. $this->encryptdata['StrF'] = 'StdCF';
  10459. }
  10460. if ($mode > 1) { // AES
  10461. if (!extension_loaded('openssl') && !extension_loaded('mcrypt')) {
  10462. $this->Error('AES encryption requires openssl or mcrypt extension (http://www.php.net/manual/en/mcrypt.requirements.php).');
  10463. }
  10464. if (extension_loaded('openssl') && !in_array('aes-256-cbc', openssl_get_cipher_methods())) {
  10465. $this->Error('AES encryption requires openssl/aes-256-cbc cypher.');
  10466. }
  10467. if (extension_loaded('mcrypt') && mcrypt_get_cipher_name(MCRYPT_RIJNDAEL_128) === false) {
  10468. $this->Error('AES encryption requires MCRYPT_RIJNDAEL_128 cypher.');
  10469. }
  10470. if (($mode == 3) AND !function_exists('hash')) {
  10471. // the Hash extension requires no external libraries and is enabled by default as of PHP 5.1.2.
  10472. $this->Error('AES 256 encryption requires HASH Message Digest Framework (http://www.php.net/manual/en/book.hash.php).');
  10473. }
  10474. }
  10475. if ($owner_pass === null) {
  10476. $owner_pass = md5(TCPDF_STATIC::getRandomSeed());
  10477. }
  10478. $this->encryptdata['user_password'] = $user_pass;
  10479. $this->encryptdata['owner_password'] = $owner_pass;
  10480. $this->encryptdata['mode'] = $mode;
  10481. switch ($mode) {
  10482. case 0: { // RC4 40 bit
  10483. $this->encryptdata['V'] = 1;
  10484. $this->encryptdata['Length'] = 40;
  10485. $this->encryptdata['CF']['CFM'] = 'V2';
  10486. break;
  10487. }
  10488. case 1: { // RC4 128 bit
  10489. $this->encryptdata['V'] = 2;
  10490. $this->encryptdata['Length'] = 128;
  10491. $this->encryptdata['CF']['CFM'] = 'V2';
  10492. if ($this->encryptdata['pubkey']) {
  10493. $this->encryptdata['SubFilter'] = 'adbe.pkcs7.s4';
  10494. $this->encryptdata['Recipients'] = array();
  10495. }
  10496. break;
  10497. }
  10498. case 2: { // AES 128 bit
  10499. $this->encryptdata['V'] = 4;
  10500. $this->encryptdata['Length'] = 128;
  10501. $this->encryptdata['CF']['CFM'] = 'AESV2';
  10502. $this->encryptdata['CF']['Length'] = 128;
  10503. if ($this->encryptdata['pubkey']) {
  10504. $this->encryptdata['SubFilter'] = 'adbe.pkcs7.s5';
  10505. $this->encryptdata['Recipients'] = array();
  10506. }
  10507. break;
  10508. }
  10509. case 3: { // AES 256 bit
  10510. $this->encryptdata['V'] = 5;
  10511. $this->encryptdata['Length'] = 256;
  10512. $this->encryptdata['CF']['CFM'] = 'AESV3';
  10513. $this->encryptdata['CF']['Length'] = 256;
  10514. if ($this->encryptdata['pubkey']) {
  10515. $this->encryptdata['SubFilter'] = 'adbe.pkcs7.s5';
  10516. $this->encryptdata['Recipients'] = array();
  10517. }
  10518. break;
  10519. }
  10520. }
  10521. $this->encrypted = true;
  10522. $this->encryptdata['fileid'] = TCPDF_STATIC::convertHexStringToString($this->file_id);
  10523. $this->_generateencryptionkey();
  10524. }
  10525. // END OF ENCRYPTION FUNCTIONS -------------------------
  10526. // START TRANSFORMATIONS SECTION -----------------------
  10527. /**
  10528. * Starts a 2D tranformation saving current graphic state.
  10529. * This function must be called before scaling, mirroring, translation, rotation and skewing.
  10530. * Use StartTransform() before, and StopTransform() after the transformations to restore the normal behavior.
  10531. * @public
  10532. * @since 2.1.000 (2008-01-07)
  10533. * @see StartTransform(), StopTransform()
  10534. */
  10535. public function StartTransform() {
  10536. if ($this->state != 2) {
  10537. return;
  10538. }
  10539. $this->_outSaveGraphicsState();
  10540. if ($this->inxobj) {
  10541. // we are inside an XObject template
  10542. $this->xobjects[$this->xobjid]['transfmrk'][] = strlen($this->xobjects[$this->xobjid]['outdata']);
  10543. } else {
  10544. $this->transfmrk[$this->page][] = $this->pagelen[$this->page];
  10545. }
  10546. ++$this->transfmatrix_key;
  10547. $this->transfmatrix[$this->transfmatrix_key] = array();
  10548. }
  10549. /**
  10550. * Stops a 2D tranformation restoring previous graphic state.
  10551. * This function must be called after scaling, mirroring, translation, rotation and skewing.
  10552. * Use StartTransform() before, and StopTransform() after the transformations to restore the normal behavior.
  10553. * @public
  10554. * @since 2.1.000 (2008-01-07)
  10555. * @see StartTransform(), StopTransform()
  10556. */
  10557. public function StopTransform() {
  10558. if ($this->state != 2) {
  10559. return;
  10560. }
  10561. $this->_outRestoreGraphicsState();
  10562. if (isset($this->transfmatrix[$this->transfmatrix_key])) {
  10563. array_pop($this->transfmatrix[$this->transfmatrix_key]);
  10564. --$this->transfmatrix_key;
  10565. }
  10566. if ($this->inxobj) {
  10567. // we are inside an XObject template
  10568. array_pop($this->xobjects[$this->xobjid]['transfmrk']);
  10569. } else {
  10570. array_pop($this->transfmrk[$this->page]);
  10571. }
  10572. }
  10573. /**
  10574. * Horizontal Scaling.
  10575. * @param $s_x (float) scaling factor for width as percent. 0 is not allowed.
  10576. * @param $x (int) abscissa of the scaling center. Default is current x position
  10577. * @param $y (int) ordinate of the scaling center. Default is current y position
  10578. * @public
  10579. * @since 2.1.000 (2008-01-07)
  10580. * @see StartTransform(), StopTransform()
  10581. */
  10582. public function ScaleX($s_x, $x='', $y='') {
  10583. $this->Scale($s_x, 100, $x, $y);
  10584. }
  10585. /**
  10586. * Vertical Scaling.
  10587. * @param $s_y (float) scaling factor for height as percent. 0 is not allowed.
  10588. * @param $x (int) abscissa of the scaling center. Default is current x position
  10589. * @param $y (int) ordinate of the scaling center. Default is current y position
  10590. * @public
  10591. * @since 2.1.000 (2008-01-07)
  10592. * @see StartTransform(), StopTransform()
  10593. */
  10594. public function ScaleY($s_y, $x='', $y='') {
  10595. $this->Scale(100, $s_y, $x, $y);
  10596. }
  10597. /**
  10598. * Vertical and horizontal proportional Scaling.
  10599. * @param $s (float) scaling factor for width and height as percent. 0 is not allowed.
  10600. * @param $x (int) abscissa of the scaling center. Default is current x position
  10601. * @param $y (int) ordinate of the scaling center. Default is current y position
  10602. * @public
  10603. * @since 2.1.000 (2008-01-07)
  10604. * @see StartTransform(), StopTransform()
  10605. */
  10606. public function ScaleXY($s, $x='', $y='') {
  10607. $this->Scale($s, $s, $x, $y);
  10608. }
  10609. /**
  10610. * Vertical and horizontal non-proportional Scaling.
  10611. * @param $s_x (float) scaling factor for width as percent. 0 is not allowed.
  10612. * @param $s_y (float) scaling factor for height as percent. 0 is not allowed.
  10613. * @param $x (int) abscissa of the scaling center. Default is current x position
  10614. * @param $y (int) ordinate of the scaling center. Default is current y position
  10615. * @public
  10616. * @since 2.1.000 (2008-01-07)
  10617. * @see StartTransform(), StopTransform()
  10618. */
  10619. public function Scale($s_x, $s_y, $x='', $y='') {
  10620. if ($x === '') {
  10621. $x = $this->x;
  10622. }
  10623. if ($y === '') {
  10624. $y = $this->y;
  10625. }
  10626. if (($s_x == 0) OR ($s_y == 0)) {
  10627. $this->Error('Please do not use values equal to zero for scaling');
  10628. }
  10629. $y = ($this->h - $y) * $this->k;
  10630. $x *= $this->k;
  10631. //calculate elements of transformation matrix
  10632. $s_x /= 100;
  10633. $s_y /= 100;
  10634. $tm = array();
  10635. $tm[0] = $s_x;
  10636. $tm[1] = 0;
  10637. $tm[2] = 0;
  10638. $tm[3] = $s_y;
  10639. $tm[4] = $x * (1 - $s_x);
  10640. $tm[5] = $y * (1 - $s_y);
  10641. //scale the coordinate system
  10642. $this->Transform($tm);
  10643. }
  10644. /**
  10645. * Horizontal Mirroring.
  10646. * @param $x (int) abscissa of the point. Default is current x position
  10647. * @public
  10648. * @since 2.1.000 (2008-01-07)
  10649. * @see StartTransform(), StopTransform()
  10650. */
  10651. public function MirrorH($x='') {
  10652. $this->Scale(-100, 100, $x);
  10653. }
  10654. /**
  10655. * Verical Mirroring.
  10656. * @param $y (int) ordinate of the point. Default is current y position
  10657. * @public
  10658. * @since 2.1.000 (2008-01-07)
  10659. * @see StartTransform(), StopTransform()
  10660. */
  10661. public function MirrorV($y='') {
  10662. $this->Scale(100, -100, '', $y);
  10663. }
  10664. /**
  10665. * Point reflection mirroring.
  10666. * @param $x (int) abscissa of the point. Default is current x position
  10667. * @param $y (int) ordinate of the point. Default is current y position
  10668. * @public
  10669. * @since 2.1.000 (2008-01-07)
  10670. * @see StartTransform(), StopTransform()
  10671. */
  10672. public function MirrorP($x='',$y='') {
  10673. $this->Scale(-100, -100, $x, $y);
  10674. }
  10675. /**
  10676. * Reflection against a straight line through point (x, y) with the gradient angle (angle).
  10677. * @param $angle (float) gradient angle of the straight line. Default is 0 (horizontal line).
  10678. * @param $x (int) abscissa of the point. Default is current x position
  10679. * @param $y (int) ordinate of the point. Default is current y position
  10680. * @public
  10681. * @since 2.1.000 (2008-01-07)
  10682. * @see StartTransform(), StopTransform()
  10683. */
  10684. public function MirrorL($angle=0, $x='',$y='') {
  10685. $this->Scale(-100, 100, $x, $y);
  10686. $this->Rotate(-2*($angle-90), $x, $y);
  10687. }
  10688. /**
  10689. * Translate graphic object horizontally.
  10690. * @param $t_x (int) movement to the right (or left for RTL)
  10691. * @public
  10692. * @since 2.1.000 (2008-01-07)
  10693. * @see StartTransform(), StopTransform()
  10694. */
  10695. public function TranslateX($t_x) {
  10696. $this->Translate($t_x, 0);
  10697. }
  10698. /**
  10699. * Translate graphic object vertically.
  10700. * @param $t_y (int) movement to the bottom
  10701. * @public
  10702. * @since 2.1.000 (2008-01-07)
  10703. * @see StartTransform(), StopTransform()
  10704. */
  10705. public function TranslateY($t_y) {
  10706. $this->Translate(0, $t_y);
  10707. }
  10708. /**
  10709. * Translate graphic object horizontally and vertically.
  10710. * @param $t_x (int) movement to the right
  10711. * @param $t_y (int) movement to the bottom
  10712. * @public
  10713. * @since 2.1.000 (2008-01-07)
  10714. * @see StartTransform(), StopTransform()
  10715. */
  10716. public function Translate($t_x, $t_y) {
  10717. //calculate elements of transformation matrix
  10718. $tm = array();
  10719. $tm[0] = 1;
  10720. $tm[1] = 0;
  10721. $tm[2] = 0;
  10722. $tm[3] = 1;
  10723. $tm[4] = $t_x * $this->k;
  10724. $tm[5] = -$t_y * $this->k;
  10725. //translate the coordinate system
  10726. $this->Transform($tm);
  10727. }
  10728. /**
  10729. * Rotate object.
  10730. * @param $angle (float) angle in degrees for counter-clockwise rotation
  10731. * @param $x (int) abscissa of the rotation center. Default is current x position
  10732. * @param $y (int) ordinate of the rotation center. Default is current y position
  10733. * @public
  10734. * @since 2.1.000 (2008-01-07)
  10735. * @see StartTransform(), StopTransform()
  10736. */
  10737. public function Rotate($angle, $x='', $y='') {
  10738. if ($x === '') {
  10739. $x = $this->x;
  10740. }
  10741. if ($y === '') {
  10742. $y = $this->y;
  10743. }
  10744. $y = ($this->h - $y) * $this->k;
  10745. $x *= $this->k;
  10746. //calculate elements of transformation matrix
  10747. $tm = array();
  10748. $tm[0] = cos(deg2rad($angle));
  10749. $tm[1] = sin(deg2rad($angle));
  10750. $tm[2] = -$tm[1];
  10751. $tm[3] = $tm[0];
  10752. $tm[4] = $x + ($tm[1] * $y) - ($tm[0] * $x);
  10753. $tm[5] = $y - ($tm[0] * $y) - ($tm[1] * $x);
  10754. //rotate the coordinate system around ($x,$y)
  10755. $this->Transform($tm);
  10756. }
  10757. /**
  10758. * Skew horizontally.
  10759. * @param $angle_x (float) angle in degrees between -90 (skew to the left) and 90 (skew to the right)
  10760. * @param $x (int) abscissa of the skewing center. default is current x position
  10761. * @param $y (int) ordinate of the skewing center. default is current y position
  10762. * @public
  10763. * @since 2.1.000 (2008-01-07)
  10764. * @see StartTransform(), StopTransform()
  10765. */
  10766. public function SkewX($angle_x, $x='', $y='') {
  10767. $this->Skew($angle_x, 0, $x, $y);
  10768. }
  10769. /**
  10770. * Skew vertically.
  10771. * @param $angle_y (float) angle in degrees between -90 (skew to the bottom) and 90 (skew to the top)
  10772. * @param $x (int) abscissa of the skewing center. default is current x position
  10773. * @param $y (int) ordinate of the skewing center. default is current y position
  10774. * @public
  10775. * @since 2.1.000 (2008-01-07)
  10776. * @see StartTransform(), StopTransform()
  10777. */
  10778. public function SkewY($angle_y, $x='', $y='') {
  10779. $this->Skew(0, $angle_y, $x, $y);
  10780. }
  10781. /**
  10782. * Skew.
  10783. * @param $angle_x (float) angle in degrees between -90 (skew to the left) and 90 (skew to the right)
  10784. * @param $angle_y (float) angle in degrees between -90 (skew to the bottom) and 90 (skew to the top)
  10785. * @param $x (int) abscissa of the skewing center. default is current x position
  10786. * @param $y (int) ordinate of the skewing center. default is current y position
  10787. * @public
  10788. * @since 2.1.000 (2008-01-07)
  10789. * @see StartTransform(), StopTransform()
  10790. */
  10791. public function Skew($angle_x, $angle_y, $x='', $y='') {
  10792. if ($x === '') {
  10793. $x = $this->x;
  10794. }
  10795. if ($y === '') {
  10796. $y = $this->y;
  10797. }
  10798. if (($angle_x <= -90) OR ($angle_x >= 90) OR ($angle_y <= -90) OR ($angle_y >= 90)) {
  10799. $this->Error('Please use values between -90 and +90 degrees for Skewing.');
  10800. }
  10801. $x *= $this->k;
  10802. $y = ($this->h - $y) * $this->k;
  10803. //calculate elements of transformation matrix
  10804. $tm = array();
  10805. $tm[0] = 1;
  10806. $tm[1] = tan(deg2rad($angle_y));
  10807. $tm[2] = tan(deg2rad($angle_x));
  10808. $tm[3] = 1;
  10809. $tm[4] = -$tm[2] * $y;
  10810. $tm[5] = -$tm[1] * $x;
  10811. //skew the coordinate system
  10812. $this->Transform($tm);
  10813. }
  10814. /**
  10815. * Apply graphic transformations.
  10816. * @param $tm (array) transformation matrix
  10817. * @protected
  10818. * @since 2.1.000 (2008-01-07)
  10819. * @see StartTransform(), StopTransform()
  10820. */
  10821. protected function Transform($tm) {
  10822. if ($this->state != 2) {
  10823. return;
  10824. }
  10825. $this->_out(sprintf('%F %F %F %F %F %F cm', $tm[0], $tm[1], $tm[2], $tm[3], $tm[4], $tm[5]));
  10826. // add tranformation matrix
  10827. $this->transfmatrix[$this->transfmatrix_key][] = array('a' => $tm[0], 'b' => $tm[1], 'c' => $tm[2], 'd' => $tm[3], 'e' => $tm[4], 'f' => $tm[5]);
  10828. // update transformation mark
  10829. if ($this->inxobj) {
  10830. // we are inside an XObject template
  10831. if (end($this->xobjects[$this->xobjid]['transfmrk']) !== false) {
  10832. $key = key($this->xobjects[$this->xobjid]['transfmrk']);
  10833. $this->xobjects[$this->xobjid]['transfmrk'][$key] = strlen($this->xobjects[$this->xobjid]['outdata']);
  10834. }
  10835. } elseif (end($this->transfmrk[$this->page]) !== false) {
  10836. $key = key($this->transfmrk[$this->page]);
  10837. $this->transfmrk[$this->page][$key] = $this->pagelen[$this->page];
  10838. }
  10839. }
  10840. // END TRANSFORMATIONS SECTION -------------------------
  10841. // START GRAPHIC FUNCTIONS SECTION ---------------------
  10842. // The following section is based on the code provided by David Hernandez Sanz
  10843. /**
  10844. * Defines the line width. By default, the value equals 0.2 mm. The method can be called before the first page is created and the value is retained from page to page.
  10845. * @param $width (float) The width.
  10846. * @public
  10847. * @since 1.0
  10848. * @see Line(), Rect(), Cell(), MultiCell()
  10849. */
  10850. public function SetLineWidth($width) {
  10851. //Set line width
  10852. $this->LineWidth = $width;
  10853. $this->linestyleWidth = sprintf('%F w', ($width * $this->k));
  10854. if ($this->state == 2) {
  10855. $this->_out($this->linestyleWidth);
  10856. }
  10857. }
  10858. /**
  10859. * Returns the current the line width.
  10860. * @return int Line width
  10861. * @public
  10862. * @since 2.1.000 (2008-01-07)
  10863. * @see Line(), SetLineWidth()
  10864. */
  10865. public function GetLineWidth() {
  10866. return $this->LineWidth;
  10867. }
  10868. /**
  10869. * Set line style.
  10870. * @param $style (array) Line style. Array with keys among the following:
  10871. * <ul>
  10872. * <li>width (float): Width of the line in user units.</li>
  10873. * <li>cap (string): Type of cap to put on the line. Possible values are:
  10874. * butt, round, square. The difference between "square" and "butt" is that
  10875. * "square" projects a flat end past the end of the line.</li>
  10876. * <li>join (string): Type of join. Possible values are: miter, round,
  10877. * bevel.</li>
  10878. * <li>dash (mixed): Dash pattern. Is 0 (without dash) or string with
  10879. * series of length values, which are the lengths of the on and off dashes.
  10880. * For example: "2" represents 2 on, 2 off, 2 on, 2 off, ...; "2,1" is 2 on,
  10881. * 1 off, 2 on, 1 off, ...</li>
  10882. * <li>phase (integer): Modifier on the dash pattern which is used to shift
  10883. * the point at which the pattern starts.</li>
  10884. * <li>color (array): Draw color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K) or array(C,M,Y,K,SpotColorName).</li>
  10885. * </ul>
  10886. * @param $ret (boolean) if true do not send the command.
  10887. * @return string the PDF command
  10888. * @public
  10889. * @since 2.1.000 (2008-01-08)
  10890. */
  10891. public function SetLineStyle($style, $ret=false) {
  10892. $s = ''; // string to be returned
  10893. if (!is_array($style)) {
  10894. return;
  10895. }
  10896. if (isset($style['width'])) {
  10897. $this->LineWidth = $style['width'];
  10898. $this->linestyleWidth = sprintf('%F w', ($style['width'] * $this->k));
  10899. $s .= $this->linestyleWidth.' ';
  10900. }
  10901. if (isset($style['cap'])) {
  10902. $ca = array('butt' => 0, 'round'=> 1, 'square' => 2);
  10903. if (isset($ca[$style['cap']])) {
  10904. $this->linestyleCap = $ca[$style['cap']].' J';
  10905. $s .= $this->linestyleCap.' ';
  10906. }
  10907. }
  10908. if (isset($style['join'])) {
  10909. $ja = array('miter' => 0, 'round' => 1, 'bevel' => 2);
  10910. if (isset($ja[$style['join']])) {
  10911. $this->linestyleJoin = $ja[$style['join']].' j';
  10912. $s .= $this->linestyleJoin.' ';
  10913. }
  10914. }
  10915. if (isset($style['dash'])) {
  10916. $dash_string = '';
  10917. if ($style['dash']) {
  10918. if (preg_match('/^.+,/', $style['dash']) > 0) {
  10919. $tab = explode(',', $style['dash']);
  10920. } else {
  10921. $tab = array($style['dash']);
  10922. }
  10923. $dash_string = '';
  10924. foreach ($tab as $i => $v) {
  10925. if ($i) {
  10926. $dash_string .= ' ';
  10927. }
  10928. $dash_string .= sprintf('%F', $v);
  10929. }
  10930. }
  10931. if (!isset($style['phase']) OR !$style['dash']) {
  10932. $style['phase'] = 0;
  10933. }
  10934. $this->linestyleDash = sprintf('[%s] %F d', $dash_string, $style['phase']);
  10935. $s .= $this->linestyleDash.' ';
  10936. }
  10937. if (isset($style['color'])) {
  10938. $s .= $this->SetDrawColorArray($style['color'], true).' ';
  10939. }
  10940. if (!$ret AND ($this->state == 2)) {
  10941. $this->_out($s);
  10942. }
  10943. return $s;
  10944. }
  10945. /**
  10946. * Begin a new subpath by moving the current point to coordinates (x, y), omitting any connecting line segment.
  10947. * @param $x (float) Abscissa of point.
  10948. * @param $y (float) Ordinate of point.
  10949. * @protected
  10950. * @since 2.1.000 (2008-01-08)
  10951. */
  10952. protected function _outPoint($x, $y) {
  10953. if ($this->state == 2) {
  10954. $this->_out(sprintf('%F %F m', ($x * $this->k), (($this->h - $y) * $this->k)));
  10955. }
  10956. }
  10957. /**
  10958. * Append a straight line segment from the current point to the point (x, y).
  10959. * The new current point shall be (x, y).
  10960. * @param $x (float) Abscissa of end point.
  10961. * @param $y (float) Ordinate of end point.
  10962. * @protected
  10963. * @since 2.1.000 (2008-01-08)
  10964. */
  10965. protected function _outLine($x, $y) {
  10966. if ($this->state == 2) {
  10967. $this->_out(sprintf('%F %F l', ($x * $this->k), (($this->h - $y) * $this->k)));
  10968. }
  10969. }
  10970. /**
  10971. * Append a rectangle to the current path as a complete subpath, with lower-left corner (x, y) and dimensions widthand height in user space.
  10972. * @param $x (float) Abscissa of upper-left corner.
  10973. * @param $y (float) Ordinate of upper-left corner.
  10974. * @param $w (float) Width.
  10975. * @param $h (float) Height.
  10976. * @param $op (string) options
  10977. * @protected
  10978. * @since 2.1.000 (2008-01-08)
  10979. */
  10980. protected function _outRect($x, $y, $w, $h, $op) {
  10981. if ($this->state == 2) {
  10982. $this->_out(sprintf('%F %F %F %F re %s', ($x * $this->k), (($this->h - $y) * $this->k), ($w * $this->k), (-$h * $this->k), $op));
  10983. }
  10984. }
  10985. /**
  10986. * Append a cubic Bezier curve to the current path. The curve shall extend from the current point to the point (x3, y3), using (x1, y1) and (x2, y2) as the Bezier control points.
  10987. * The new current point shall be (x3, y3).
  10988. * @param $x1 (float) Abscissa of control point 1.
  10989. * @param $y1 (float) Ordinate of control point 1.
  10990. * @param $x2 (float) Abscissa of control point 2.
  10991. * @param $y2 (float) Ordinate of control point 2.
  10992. * @param $x3 (float) Abscissa of end point.
  10993. * @param $y3 (float) Ordinate of end point.
  10994. * @protected
  10995. * @since 2.1.000 (2008-01-08)
  10996. */
  10997. protected function _outCurve($x1, $y1, $x2, $y2, $x3, $y3) {
  10998. if ($this->state == 2) {
  10999. $this->_out(sprintf('%F %F %F %F %F %F c', ($x1 * $this->k), (($this->h - $y1) * $this->k), ($x2 * $this->k), (($this->h - $y2) * $this->k), ($x3 * $this->k), (($this->h - $y3) * $this->k)));
  11000. }
  11001. }
  11002. /**
  11003. * Append a cubic Bezier curve to the current path. The curve shall extend from the current point to the point (x3, y3), using the current point and (x2, y2) as the Bezier control points.
  11004. * The new current point shall be (x3, y3).
  11005. * @param $x2 (float) Abscissa of control point 2.
  11006. * @param $y2 (float) Ordinate of control point 2.
  11007. * @param $x3 (float) Abscissa of end point.
  11008. * @param $y3 (float) Ordinate of end point.
  11009. * @protected
  11010. * @since 4.9.019 (2010-04-26)
  11011. */
  11012. protected function _outCurveV($x2, $y2, $x3, $y3) {
  11013. if ($this->state == 2) {
  11014. $this->_out(sprintf('%F %F %F %F v', ($x2 * $this->k), (($this->h - $y2) * $this->k), ($x3 * $this->k), (($this->h - $y3) * $this->k)));
  11015. }
  11016. }
  11017. /**
  11018. * Append a cubic Bezier curve to the current path. The curve shall extend from the current point to the point (x3, y3), using (x1, y1) and (x3, y3) as the Bezier control points.
  11019. * The new current point shall be (x3, y3).
  11020. * @param $x1 (float) Abscissa of control point 1.
  11021. * @param $y1 (float) Ordinate of control point 1.
  11022. * @param $x3 (float) Abscissa of end point.
  11023. * @param $y3 (float) Ordinate of end point.
  11024. * @protected
  11025. * @since 2.1.000 (2008-01-08)
  11026. */
  11027. protected function _outCurveY($x1, $y1, $x3, $y3) {
  11028. if ($this->state == 2) {
  11029. $this->_out(sprintf('%F %F %F %F y', ($x1 * $this->k), (($this->h - $y1) * $this->k), ($x3 * $this->k), (($this->h - $y3) * $this->k)));
  11030. }
  11031. }
  11032. /**
  11033. * Draws a line between two points.
  11034. * @param $x1 (float) Abscissa of first point.
  11035. * @param $y1 (float) Ordinate of first point.
  11036. * @param $x2 (float) Abscissa of second point.
  11037. * @param $y2 (float) Ordinate of second point.
  11038. * @param $style (array) Line style. Array like for SetLineStyle(). Default value: default line style (empty array).
  11039. * @public
  11040. * @since 1.0
  11041. * @see SetLineWidth(), SetDrawColor(), SetLineStyle()
  11042. */
  11043. public function Line($x1, $y1, $x2, $y2, $style=array()) {
  11044. if ($this->state != 2) {
  11045. return;
  11046. }
  11047. if (is_array($style)) {
  11048. $this->SetLineStyle($style);
  11049. }
  11050. $this->_outPoint($x1, $y1);
  11051. $this->_outLine($x2, $y2);
  11052. $this->_out('S');
  11053. }
  11054. /**
  11055. * Draws a rectangle.
  11056. * @param $x (float) Abscissa of upper-left corner.
  11057. * @param $y (float) Ordinate of upper-left corner.
  11058. * @param $w (float) Width.
  11059. * @param $h (float) Height.
  11060. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  11061. * @param $border_style (array) Border style of rectangle. Array with keys among the following:
  11062. * <ul>
  11063. * <li>all: Line style of all borders. Array like for SetLineStyle().</li>
  11064. * <li>L, T, R, B or combinations: Line style of left, top, right or bottom border. Array like for SetLineStyle().</li>
  11065. * </ul>
  11066. * If a key is not present or is null, the correspondent border is not drawn. Default value: default line style (empty array).
  11067. * @param $fill_color (array) Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K) or array(C,M,Y,K,SpotColorName). Default value: default color (empty array).
  11068. * @public
  11069. * @since 1.0
  11070. * @see SetLineStyle()
  11071. */
  11072. public function Rect($x, $y, $w, $h, $style='', $border_style=array(), $fill_color=array()) {
  11073. if ($this->state != 2) {
  11074. return;
  11075. }
  11076. if (empty($style)) {
  11077. $style = 'S';
  11078. }
  11079. if (!(strpos($style, 'F') === false) AND !empty($fill_color)) {
  11080. // set background color
  11081. $this->SetFillColorArray($fill_color);
  11082. }
  11083. if (!empty($border_style)) {
  11084. if (isset($border_style['all']) AND !empty($border_style['all'])) {
  11085. //set global style for border
  11086. $this->SetLineStyle($border_style['all']);
  11087. $border_style = array();
  11088. } else {
  11089. // remove stroke operator from style
  11090. $opnostroke = array('S' => '', 'D' => '', 's' => '', 'd' => '', 'B' => 'F', 'FD' => 'F', 'DF' => 'F', 'B*' => 'F*', 'F*D' => 'F*', 'DF*' => 'F*', 'b' => 'f', 'fd' => 'f', 'df' => 'f', 'b*' => 'f*', 'f*d' => 'f*', 'df*' => 'f*' );
  11091. if (isset($opnostroke[$style])) {
  11092. $style = $opnostroke[$style];
  11093. }
  11094. }
  11095. }
  11096. if (!empty($style)) {
  11097. $op = TCPDF_STATIC::getPathPaintOperator($style);
  11098. $this->_outRect($x, $y, $w, $h, $op);
  11099. }
  11100. if (!empty($border_style)) {
  11101. $border_style2 = array();
  11102. foreach ($border_style as $line => $value) {
  11103. $length = strlen($line);
  11104. for ($i = 0; $i < $length; ++$i) {
  11105. $border_style2[$line[$i]] = $value;
  11106. }
  11107. }
  11108. $border_style = $border_style2;
  11109. if (isset($border_style['L']) AND $border_style['L']) {
  11110. $this->Line($x, $y, $x, $y + $h, $border_style['L']);
  11111. }
  11112. if (isset($border_style['T']) AND $border_style['T']) {
  11113. $this->Line($x, $y, $x + $w, $y, $border_style['T']);
  11114. }
  11115. if (isset($border_style['R']) AND $border_style['R']) {
  11116. $this->Line($x + $w, $y, $x + $w, $y + $h, $border_style['R']);
  11117. }
  11118. if (isset($border_style['B']) AND $border_style['B']) {
  11119. $this->Line($x, $y + $h, $x + $w, $y + $h, $border_style['B']);
  11120. }
  11121. }
  11122. }
  11123. /**
  11124. * Draws a Bezier curve.
  11125. * The Bezier curve is a tangent to the line between the control points at
  11126. * either end of the curve.
  11127. * @param $x0 (float) Abscissa of start point.
  11128. * @param $y0 (float) Ordinate of start point.
  11129. * @param $x1 (float) Abscissa of control point 1.
  11130. * @param $y1 (float) Ordinate of control point 1.
  11131. * @param $x2 (float) Abscissa of control point 2.
  11132. * @param $y2 (float) Ordinate of control point 2.
  11133. * @param $x3 (float) Abscissa of end point.
  11134. * @param $y3 (float) Ordinate of end point.
  11135. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  11136. * @param $line_style (array) Line style of curve. Array like for SetLineStyle(). Default value: default line style (empty array).
  11137. * @param $fill_color (array) Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K) or array(C,M,Y,K,SpotColorName). Default value: default color (empty array).
  11138. * @public
  11139. * @see SetLineStyle()
  11140. * @since 2.1.000 (2008-01-08)
  11141. */
  11142. public function Curve($x0, $y0, $x1, $y1, $x2, $y2, $x3, $y3, $style='', $line_style=array(), $fill_color=array()) {
  11143. if ($this->state != 2) {
  11144. return;
  11145. }
  11146. if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
  11147. $this->SetFillColorArray($fill_color);
  11148. }
  11149. $op = TCPDF_STATIC::getPathPaintOperator($style);
  11150. if ($line_style) {
  11151. $this->SetLineStyle($line_style);
  11152. }
  11153. $this->_outPoint($x0, $y0);
  11154. $this->_outCurve($x1, $y1, $x2, $y2, $x3, $y3);
  11155. $this->_out($op);
  11156. }
  11157. /**
  11158. * Draws a poly-Bezier curve.
  11159. * Each Bezier curve segment is a tangent to the line between the control points at
  11160. * either end of the curve.
  11161. * @param $x0 (float) Abscissa of start point.
  11162. * @param $y0 (float) Ordinate of start point.
  11163. * @param $segments (float) An array of bezier descriptions. Format: array(x1, y1, x2, y2, x3, y3).
  11164. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  11165. * @param $line_style (array) Line style of curve. Array like for SetLineStyle(). Default value: default line style (empty array).
  11166. * @param $fill_color (array) Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K) or array(C,M,Y,K,SpotColorName). Default value: default color (empty array).
  11167. * @public
  11168. * @see SetLineStyle()
  11169. * @since 3.0008 (2008-05-12)
  11170. */
  11171. public function Polycurve($x0, $y0, $segments, $style='', $line_style=array(), $fill_color=array()) {
  11172. if ($this->state != 2) {
  11173. return;
  11174. }
  11175. if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
  11176. $this->SetFillColorArray($fill_color);
  11177. }
  11178. $op = TCPDF_STATIC::getPathPaintOperator($style);
  11179. if ($op == 'f') {
  11180. $line_style = array();
  11181. }
  11182. if ($line_style) {
  11183. $this->SetLineStyle($line_style);
  11184. }
  11185. $this->_outPoint($x0, $y0);
  11186. foreach ($segments as $segment) {
  11187. list($x1, $y1, $x2, $y2, $x3, $y3) = $segment;
  11188. $this->_outCurve($x1, $y1, $x2, $y2, $x3, $y3);
  11189. }
  11190. $this->_out($op);
  11191. }
  11192. /**
  11193. * Draws an ellipse.
  11194. * An ellipse is formed from n Bezier curves.
  11195. * @param $x0 (float) Abscissa of center point.
  11196. * @param $y0 (float) Ordinate of center point.
  11197. * @param $rx (float) Horizontal radius.
  11198. * @param $ry (float) Vertical radius (if ry = 0 then is a circle, see Circle()). Default value: 0.
  11199. * @param $angle: (float) Angle oriented (anti-clockwise). Default value: 0.
  11200. * @param $astart: (float) Angle start of draw line. Default value: 0.
  11201. * @param $afinish: (float) Angle finish of draw line. Default value: 360.
  11202. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  11203. * @param $line_style (array) Line style of ellipse. Array like for SetLineStyle(). Default value: default line style (empty array).
  11204. * @param $fill_color (array) Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K) or array(C,M,Y,K,SpotColorName). Default value: default color (empty array).
  11205. * @param $nc (integer) Number of curves used to draw a 90 degrees portion of ellipse.
  11206. * @author Nicola Asuni
  11207. * @public
  11208. * @since 2.1.000 (2008-01-08)
  11209. */
  11210. public function Ellipse($x0, $y0, $rx, $ry='', $angle=0, $astart=0, $afinish=360, $style='', $line_style=array(), $fill_color=array(), $nc=2) {
  11211. if ($this->state != 2) {
  11212. return;
  11213. }
  11214. if (TCPDF_STATIC::empty_string($ry) OR ($ry == 0)) {
  11215. $ry = $rx;
  11216. }
  11217. if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
  11218. $this->SetFillColorArray($fill_color);
  11219. }
  11220. $op = TCPDF_STATIC::getPathPaintOperator($style);
  11221. if ($op == 'f') {
  11222. $line_style = array();
  11223. }
  11224. if ($line_style) {
  11225. $this->SetLineStyle($line_style);
  11226. }
  11227. $this->_outellipticalarc($x0, $y0, $rx, $ry, $angle, $astart, $afinish, false, $nc, true, true, false);
  11228. $this->_out($op);
  11229. }
  11230. /**
  11231. * Append an elliptical arc to the current path.
  11232. * An ellipse is formed from n Bezier curves.
  11233. * @param $xc (float) Abscissa of center point.
  11234. * @param $yc (float) Ordinate of center point.
  11235. * @param $rx (float) Horizontal radius.
  11236. * @param $ry (float) Vertical radius (if ry = 0 then is a circle, see Circle()). Default value: 0.
  11237. * @param $xang: (float) Angle between the X-axis and the major axis of the ellipse. Default value: 0.
  11238. * @param $angs: (float) Angle start of draw line. Default value: 0.
  11239. * @param $angf: (float) Angle finish of draw line. Default value: 360.
  11240. * @param $pie (boolean) if true do not mark the border point (used to draw pie sectors).
  11241. * @param $nc (integer) Number of curves used to draw a 90 degrees portion of ellipse.
  11242. * @param $startpoint (boolean) if true output a starting point.
  11243. * @param $ccw (boolean) if true draws in counter-clockwise.
  11244. * @param $svg (boolean) if true the angles are in svg mode (already calculated).
  11245. * @return array bounding box coordinates (x min, y min, x max, y max)
  11246. * @author Nicola Asuni
  11247. * @protected
  11248. * @since 4.9.019 (2010-04-26)
  11249. */
  11250. protected function _outellipticalarc($xc, $yc, $rx, $ry, $xang=0, $angs=0, $angf=360, $pie=false, $nc=2, $startpoint=true, $ccw=true, $svg=false) {
  11251. if (($rx <= 0) OR ($ry < 0)) {
  11252. return;
  11253. }
  11254. $k = $this->k;
  11255. if ($nc < 2) {
  11256. $nc = 2;
  11257. }
  11258. $xmin = 2147483647;
  11259. $ymin = 2147483647;
  11260. $xmax = 0;
  11261. $ymax = 0;
  11262. if ($pie) {
  11263. // center of the arc
  11264. $this->_outPoint($xc, $yc);
  11265. }
  11266. $xang = deg2rad((float) $xang);
  11267. $angs = deg2rad((float) $angs);
  11268. $angf = deg2rad((float) $angf);
  11269. if ($svg) {
  11270. $as = $angs;
  11271. $af = $angf;
  11272. } else {
  11273. $as = atan2((sin($angs) / $ry), (cos($angs) / $rx));
  11274. $af = atan2((sin($angf) / $ry), (cos($angf) / $rx));
  11275. }
  11276. if ($as < 0) {
  11277. $as += (2 * M_PI);
  11278. }
  11279. if ($af < 0) {
  11280. $af += (2 * M_PI);
  11281. }
  11282. if ($ccw AND ($as > $af)) {
  11283. // reverse rotation
  11284. $as -= (2 * M_PI);
  11285. } elseif (!$ccw AND ($as < $af)) {
  11286. // reverse rotation
  11287. $af -= (2 * M_PI);
  11288. }
  11289. $total_angle = ($af - $as);
  11290. if ($nc < 2) {
  11291. $nc = 2;
  11292. }
  11293. // total arcs to draw
  11294. $nc *= (2 * abs($total_angle) / M_PI);
  11295. $nc = round($nc) + 1;
  11296. // angle of each arc
  11297. $arcang = ($total_angle / $nc);
  11298. // center point in PDF coordinates
  11299. $x0 = $xc;
  11300. $y0 = ($this->h - $yc);
  11301. // starting angle
  11302. $ang = $as;
  11303. $alpha = sin($arcang) * ((sqrt(4 + (3 * pow(tan(($arcang) / 2), 2))) - 1) / 3);
  11304. $cos_xang = cos($xang);
  11305. $sin_xang = sin($xang);
  11306. $cos_ang = cos($ang);
  11307. $sin_ang = sin($ang);
  11308. // first arc point
  11309. $px1 = $x0 + ($rx * $cos_xang * $cos_ang) - ($ry * $sin_xang * $sin_ang);
  11310. $py1 = $y0 + ($rx * $sin_xang * $cos_ang) + ($ry * $cos_xang * $sin_ang);
  11311. // first Bezier control point
  11312. $qx1 = ($alpha * ((-$rx * $cos_xang * $sin_ang) - ($ry * $sin_xang * $cos_ang)));
  11313. $qy1 = ($alpha * ((-$rx * $sin_xang * $sin_ang) + ($ry * $cos_xang * $cos_ang)));
  11314. if ($pie) {
  11315. // line from center to arc starting point
  11316. $this->_outLine($px1, $this->h - $py1);
  11317. } elseif ($startpoint) {
  11318. // arc starting point
  11319. $this->_outPoint($px1, $this->h - $py1);
  11320. }
  11321. // draw arcs
  11322. for ($i = 1; $i <= $nc; ++$i) {
  11323. // starting angle
  11324. $ang = $as + ($i * $arcang);
  11325. if ($i == $nc) {
  11326. $ang = $af;
  11327. }
  11328. $cos_ang = cos($ang);
  11329. $sin_ang = sin($ang);
  11330. // second arc point
  11331. $px2 = $x0 + ($rx * $cos_xang * $cos_ang) - ($ry * $sin_xang * $sin_ang);
  11332. $py2 = $y0 + ($rx * $sin_xang * $cos_ang) + ($ry * $cos_xang * $sin_ang);
  11333. // second Bezier control point
  11334. $qx2 = ($alpha * ((-$rx * $cos_xang * $sin_ang) - ($ry * $sin_xang * $cos_ang)));
  11335. $qy2 = ($alpha * ((-$rx * $sin_xang * $sin_ang) + ($ry * $cos_xang * $cos_ang)));
  11336. // draw arc
  11337. $cx1 = ($px1 + $qx1);
  11338. $cy1 = ($this->h - ($py1 + $qy1));
  11339. $cx2 = ($px2 - $qx2);
  11340. $cy2 = ($this->h - ($py2 - $qy2));
  11341. $cx3 = $px2;
  11342. $cy3 = ($this->h - $py2);
  11343. $this->_outCurve($cx1, $cy1, $cx2, $cy2, $cx3, $cy3);
  11344. // get bounding box coordinates
  11345. $xmin = min($xmin, $cx1, $cx2, $cx3);
  11346. $ymin = min($ymin, $cy1, $cy2, $cy3);
  11347. $xmax = max($xmax, $cx1, $cx2, $cx3);
  11348. $ymax = max($ymax, $cy1, $cy2, $cy3);
  11349. // move to next point
  11350. $px1 = $px2;
  11351. $py1 = $py2;
  11352. $qx1 = $qx2;
  11353. $qy1 = $qy2;
  11354. }
  11355. if ($pie) {
  11356. $this->_outLine($xc, $yc);
  11357. // get bounding box coordinates
  11358. $xmin = min($xmin, $xc);
  11359. $ymin = min($ymin, $yc);
  11360. $xmax = max($xmax, $xc);
  11361. $ymax = max($ymax, $yc);
  11362. }
  11363. return array($xmin, $ymin, $xmax, $ymax);
  11364. }
  11365. /**
  11366. * Draws a circle.
  11367. * A circle is formed from n Bezier curves.
  11368. * @param $x0 (float) Abscissa of center point.
  11369. * @param $y0 (float) Ordinate of center point.
  11370. * @param $r (float) Radius.
  11371. * @param $angstr: (float) Angle start of draw line. Default value: 0.
  11372. * @param $angend: (float) Angle finish of draw line. Default value: 360.
  11373. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  11374. * @param $line_style (array) Line style of circle. Array like for SetLineStyle(). Default value: default line style (empty array).
  11375. * @param $fill_color (array) Fill color. Format: array(red, green, blue). Default value: default color (empty array).
  11376. * @param $nc (integer) Number of curves used to draw a 90 degrees portion of circle.
  11377. * @public
  11378. * @since 2.1.000 (2008-01-08)
  11379. */
  11380. public function Circle($x0, $y0, $r, $angstr=0, $angend=360, $style='', $line_style=array(), $fill_color=array(), $nc=2) {
  11381. $this->Ellipse($x0, $y0, $r, $r, 0, $angstr, $angend, $style, $line_style, $fill_color, $nc);
  11382. }
  11383. /**
  11384. * Draws a polygonal line
  11385. * @param $p (array) Points 0 to ($np - 1). Array with values (x0, y0, x1, y1,..., x(np-1), y(np - 1))
  11386. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  11387. * @param $line_style (array) Line style of polygon. Array with keys among the following:
  11388. * <ul>
  11389. * <li>all: Line style of all lines. Array like for SetLineStyle().</li>
  11390. * <li>0 to ($np - 1): Line style of each line. Array like for SetLineStyle().</li>
  11391. * </ul>
  11392. * If a key is not present or is null, not draws the line. Default value is default line style (empty array).
  11393. * @param $fill_color (array) Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K) or array(C,M,Y,K,SpotColorName). Default value: default color (empty array).
  11394. * @since 4.8.003 (2009-09-15)
  11395. * @public
  11396. */
  11397. public function PolyLine($p, $style='', $line_style=array(), $fill_color=array()) {
  11398. $this->Polygon($p, $style, $line_style, $fill_color, false);
  11399. }
  11400. /**
  11401. * Draws a polygon.
  11402. * @param $p (array) Points 0 to ($np - 1). Array with values (x0, y0, x1, y1,..., x(np-1), y(np - 1))
  11403. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  11404. * @param $line_style (array) Line style of polygon. Array with keys among the following:
  11405. * <ul>
  11406. * <li>all: Line style of all lines. Array like for SetLineStyle().</li>
  11407. * <li>0 to ($np - 1): Line style of each line. Array like for SetLineStyle().</li>
  11408. * </ul>
  11409. * If a key is not present or is null, not draws the line. Default value is default line style (empty array).
  11410. * @param $fill_color (array) Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K) or array(C,M,Y,K,SpotColorName). Default value: default color (empty array).
  11411. * @param $closed (boolean) if true the polygon is closes, otherwise will remain open
  11412. * @public
  11413. * @since 2.1.000 (2008-01-08)
  11414. */
  11415. public function Polygon($p, $style='', $line_style=array(), $fill_color=array(), $closed=true) {
  11416. if ($this->state != 2) {
  11417. return;
  11418. }
  11419. $nc = count($p); // number of coordinates
  11420. $np = $nc / 2; // number of points
  11421. if ($closed) {
  11422. // close polygon by adding the first 2 points at the end (one line)
  11423. for ($i = 0; $i < 4; ++$i) {
  11424. $p[$nc + $i] = $p[$i];
  11425. }
  11426. // copy style for the last added line
  11427. if (isset($line_style[0])) {
  11428. $line_style[$np] = $line_style[0];
  11429. }
  11430. $nc += 4;
  11431. }
  11432. if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
  11433. $this->SetFillColorArray($fill_color);
  11434. }
  11435. $op = TCPDF_STATIC::getPathPaintOperator($style);
  11436. if ($op == 'f') {
  11437. $line_style = array();
  11438. }
  11439. $draw = true;
  11440. if ($line_style) {
  11441. if (isset($line_style['all'])) {
  11442. $this->SetLineStyle($line_style['all']);
  11443. } else {
  11444. $draw = false;
  11445. if ($op == 'B') {
  11446. // draw fill
  11447. $op = 'f';
  11448. $this->_outPoint($p[0], $p[1]);
  11449. for ($i = 2; $i < $nc; $i = $i + 2) {
  11450. $this->_outLine($p[$i], $p[$i + 1]);
  11451. }
  11452. $this->_out($op);
  11453. }
  11454. // draw outline
  11455. $this->_outPoint($p[0], $p[1]);
  11456. for ($i = 2; $i < $nc; $i = $i + 2) {
  11457. $line_num = ($i / 2) - 1;
  11458. if (isset($line_style[$line_num])) {
  11459. if ($line_style[$line_num] != 0) {
  11460. if (is_array($line_style[$line_num])) {
  11461. $this->_out('S');
  11462. $this->SetLineStyle($line_style[$line_num]);
  11463. $this->_outPoint($p[$i - 2], $p[$i - 1]);
  11464. $this->_outLine($p[$i], $p[$i + 1]);
  11465. $this->_out('S');
  11466. $this->_outPoint($p[$i], $p[$i + 1]);
  11467. } else {
  11468. $this->_outLine($p[$i], $p[$i + 1]);
  11469. }
  11470. }
  11471. } else {
  11472. $this->_outLine($p[$i], $p[$i + 1]);
  11473. }
  11474. }
  11475. $this->_out($op);
  11476. }
  11477. }
  11478. if ($draw) {
  11479. $this->_outPoint($p[0], $p[1]);
  11480. for ($i = 2; $i < $nc; $i = $i + 2) {
  11481. $this->_outLine($p[$i], $p[$i + 1]);
  11482. }
  11483. $this->_out($op);
  11484. }
  11485. }
  11486. /**
  11487. * Draws a regular polygon.
  11488. * @param $x0 (float) Abscissa of center point.
  11489. * @param $y0 (float) Ordinate of center point.
  11490. * @param $r: (float) Radius of inscribed circle.
  11491. * @param $ns (integer) Number of sides.
  11492. * @param $angle (float) Angle oriented (anti-clockwise). Default value: 0.
  11493. * @param $draw_circle (boolean) Draw inscribed circle or not. Default value: false.
  11494. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  11495. * @param $line_style (array) Line style of polygon sides. Array with keys among the following:
  11496. * <ul>
  11497. * <li>all: Line style of all sides. Array like for SetLineStyle().</li>
  11498. * <li>0 to ($ns - 1): Line style of each side. Array like for SetLineStyle().</li>
  11499. * </ul>
  11500. * If a key is not present or is null, not draws the side. Default value is default line style (empty array).
  11501. * @param $fill_color (array) Fill color. Format: array(red, green, blue). Default value: default color (empty array).
  11502. * @param $circle_style (string) Style of rendering of inscribed circle (if draws). Possible values are:
  11503. * <ul>
  11504. * <li>D or empty string: Draw (default).</li>
  11505. * <li>F: Fill.</li>
  11506. * <li>DF or FD: Draw and fill.</li>
  11507. * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
  11508. * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
  11509. * </ul>
  11510. * @param $circle_outLine_style (array) Line style of inscribed circle (if draws). Array like for SetLineStyle(). Default value: default line style (empty array).
  11511. * @param $circle_fill_color (array) Fill color of inscribed circle (if draws). Format: array(red, green, blue). Default value: default color (empty array).
  11512. * @public
  11513. * @since 2.1.000 (2008-01-08)
  11514. */
  11515. public function RegularPolygon($x0, $y0, $r, $ns, $angle=0, $draw_circle=false, $style='', $line_style=array(), $fill_color=array(), $circle_style='', $circle_outLine_style=array(), $circle_fill_color=array()) {
  11516. if (3 > $ns) {
  11517. $ns = 3;
  11518. }
  11519. if ($draw_circle) {
  11520. $this->Circle($x0, $y0, $r, 0, 360, $circle_style, $circle_outLine_style, $circle_fill_color);
  11521. }
  11522. $p = array();
  11523. for ($i = 0; $i < $ns; ++$i) {
  11524. $a = $angle + ($i * 360 / $ns);
  11525. $a_rad = deg2rad((float) $a);
  11526. $p[] = $x0 + ($r * sin($a_rad));
  11527. $p[] = $y0 + ($r * cos($a_rad));
  11528. }
  11529. $this->Polygon($p, $style, $line_style, $fill_color);
  11530. }
  11531. /**
  11532. * Draws a star polygon
  11533. * @param $x0 (float) Abscissa of center point.
  11534. * @param $y0 (float) Ordinate of center point.
  11535. * @param $r (float) Radius of inscribed circle.
  11536. * @param $nv (integer) Number of vertices.
  11537. * @param $ng (integer) Number of gap (if ($ng % $nv = 1) then is a regular polygon).
  11538. * @param $angle: (float) Angle oriented (anti-clockwise). Default value: 0.
  11539. * @param $draw_circle: (boolean) Draw inscribed circle or not. Default value is false.
  11540. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  11541. * @param $line_style (array) Line style of polygon sides. Array with keys among the following:
  11542. * <ul>
  11543. * <li>all: Line style of all sides. Array like for
  11544. * SetLineStyle().</li>
  11545. * <li>0 to (n - 1): Line style of each side. Array like for SetLineStyle().</li>
  11546. * </ul>
  11547. * If a key is not present or is null, not draws the side. Default value is default line style (empty array).
  11548. * @param $fill_color (array) Fill color. Format: array(red, green, blue). Default value: default color (empty array).
  11549. * @param $circle_style (string) Style of rendering of inscribed circle (if draws). Possible values are:
  11550. * <ul>
  11551. * <li>D or empty string: Draw (default).</li>
  11552. * <li>F: Fill.</li>
  11553. * <li>DF or FD: Draw and fill.</li>
  11554. * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
  11555. * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
  11556. * </ul>
  11557. * @param $circle_outLine_style (array) Line style of inscribed circle (if draws). Array like for SetLineStyle(). Default value: default line style (empty array).
  11558. * @param $circle_fill_color (array) Fill color of inscribed circle (if draws). Format: array(red, green, blue). Default value: default color (empty array).
  11559. * @public
  11560. * @since 2.1.000 (2008-01-08)
  11561. */
  11562. public function StarPolygon($x0, $y0, $r, $nv, $ng, $angle=0, $draw_circle=false, $style='', $line_style=array(), $fill_color=array(), $circle_style='', $circle_outLine_style=array(), $circle_fill_color=array()) {
  11563. if ($nv < 2) {
  11564. $nv = 2;
  11565. }
  11566. if ($draw_circle) {
  11567. $this->Circle($x0, $y0, $r, 0, 360, $circle_style, $circle_outLine_style, $circle_fill_color);
  11568. }
  11569. $p2 = array();
  11570. $visited = array();
  11571. for ($i = 0; $i < $nv; ++$i) {
  11572. $a = $angle + ($i * 360 / $nv);
  11573. $a_rad = deg2rad((float) $a);
  11574. $p2[] = $x0 + ($r * sin($a_rad));
  11575. $p2[] = $y0 + ($r * cos($a_rad));
  11576. $visited[] = false;
  11577. }
  11578. $p = array();
  11579. $i = 0;
  11580. do {
  11581. $p[] = $p2[$i * 2];
  11582. $p[] = $p2[($i * 2) + 1];
  11583. $visited[$i] = true;
  11584. $i += $ng;
  11585. $i %= $nv;
  11586. } while (!$visited[$i]);
  11587. $this->Polygon($p, $style, $line_style, $fill_color);
  11588. }
  11589. /**
  11590. * Draws a rounded rectangle.
  11591. * @param $x (float) Abscissa of upper-left corner.
  11592. * @param $y (float) Ordinate of upper-left corner.
  11593. * @param $w (float) Width.
  11594. * @param $h (float) Height.
  11595. * @param $r (float) the radius of the circle used to round off the corners of the rectangle.
  11596. * @param $round_corner (string) Draws rounded corner or not. String with a 0 (not rounded i-corner) or 1 (rounded i-corner) in i-position. Positions are, in order and begin to 0: top right, bottom right, bottom left and top left. Default value: all rounded corner ("1111").
  11597. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  11598. * @param $border_style (array) Border style of rectangle. Array like for SetLineStyle(). Default value: default line style (empty array).
  11599. * @param $fill_color (array) Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K) or array(C,M,Y,K,SpotColorName). Default value: default color (empty array).
  11600. * @public
  11601. * @since 2.1.000 (2008-01-08)
  11602. */
  11603. public function RoundedRect($x, $y, $w, $h, $r, $round_corner='1111', $style='', $border_style=array(), $fill_color=array()) {
  11604. $this->RoundedRectXY($x, $y, $w, $h, $r, $r, $round_corner, $style, $border_style, $fill_color);
  11605. }
  11606. /**
  11607. * Draws a rounded rectangle.
  11608. * @param $x (float) Abscissa of upper-left corner.
  11609. * @param $y (float) Ordinate of upper-left corner.
  11610. * @param $w (float) Width.
  11611. * @param $h (float) Height.
  11612. * @param $rx (float) the x-axis radius of the ellipse used to round off the corners of the rectangle.
  11613. * @param $ry (float) the y-axis radius of the ellipse used to round off the corners of the rectangle.
  11614. * @param $round_corner (string) Draws rounded corner or not. String with a 0 (not rounded i-corner) or 1 (rounded i-corner) in i-position. Positions are, in order and begin to 0: top right, bottom right, bottom left and top left. Default value: all rounded corner ("1111").
  11615. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  11616. * @param $border_style (array) Border style of rectangle. Array like for SetLineStyle(). Default value: default line style (empty array).
  11617. * @param $fill_color (array) Fill color. Format: array(GREY) or array(R,G,B) or array(C,M,Y,K) or array(C,M,Y,K,SpotColorName). Default value: default color (empty array).
  11618. * @public
  11619. * @since 4.9.019 (2010-04-22)
  11620. */
  11621. public function RoundedRectXY($x, $y, $w, $h, $rx, $ry, $round_corner='1111', $style='', $border_style=array(), $fill_color=array()) {
  11622. if ($this->state != 2) {
  11623. return;
  11624. }
  11625. if (($round_corner == '0000') OR (($rx == $ry) AND ($rx == 0))) {
  11626. // Not rounded
  11627. $this->Rect($x, $y, $w, $h, $style, $border_style, $fill_color);
  11628. return;
  11629. }
  11630. // Rounded
  11631. if (!(false === strpos($style, 'F')) AND isset($fill_color)) {
  11632. $this->SetFillColorArray($fill_color);
  11633. }
  11634. $op = TCPDF_STATIC::getPathPaintOperator($style);
  11635. if ($op == 'f') {
  11636. $border_style = array();
  11637. }
  11638. if ($border_style) {
  11639. $this->SetLineStyle($border_style);
  11640. }
  11641. $MyArc = 4 / 3 * (sqrt(2) - 1);
  11642. $this->_outPoint($x + $rx, $y);
  11643. $xc = $x + $w - $rx;
  11644. $yc = $y + $ry;
  11645. $this->_outLine($xc, $y);
  11646. if ($round_corner[0]) {
  11647. $this->_outCurve($xc + ($rx * $MyArc), $yc - $ry, $xc + $rx, $yc - ($ry * $MyArc), $xc + $rx, $yc);
  11648. } else {
  11649. $this->_outLine($x + $w, $y);
  11650. }
  11651. $xc = $x + $w - $rx;
  11652. $yc = $y + $h - $ry;
  11653. $this->_outLine($x + $w, $yc);
  11654. if ($round_corner[1]) {
  11655. $this->_outCurve($xc + $rx, $yc + ($ry * $MyArc), $xc + ($rx * $MyArc), $yc + $ry, $xc, $yc + $ry);
  11656. } else {
  11657. $this->_outLine($x + $w, $y + $h);
  11658. }
  11659. $xc = $x + $rx;
  11660. $yc = $y + $h - $ry;
  11661. $this->_outLine($xc, $y + $h);
  11662. if ($round_corner[2]) {
  11663. $this->_outCurve($xc - ($rx * $MyArc), $yc + $ry, $xc - $rx, $yc + ($ry * $MyArc), $xc - $rx, $yc);
  11664. } else {
  11665. $this->_outLine($x, $y + $h);
  11666. }
  11667. $xc = $x + $rx;
  11668. $yc = $y + $ry;
  11669. $this->_outLine($x, $yc);
  11670. if ($round_corner[3]) {
  11671. $this->_outCurve($xc - $rx, $yc - ($ry * $MyArc), $xc - ($rx * $MyArc), $yc - $ry, $xc, $yc - $ry);
  11672. } else {
  11673. $this->_outLine($x, $y);
  11674. $this->_outLine($x + $rx, $y);
  11675. }
  11676. $this->_out($op);
  11677. }
  11678. /**
  11679. * Draws a grahic arrow.
  11680. * @param $x0 (float) Abscissa of first point.
  11681. * @param $y0 (float) Ordinate of first point.
  11682. * @param $x1 (float) Abscissa of second point.
  11683. * @param $y1 (float) Ordinate of second point.
  11684. * @param $head_style (int) (0 = draw only arrowhead arms, 1 = draw closed arrowhead, but no fill, 2 = closed and filled arrowhead, 3 = filled arrowhead)
  11685. * @param $arm_size (float) length of arrowhead arms
  11686. * @param $arm_angle (int) angle between an arm and the shaft
  11687. * @author Piotr Galecki, Nicola Asuni, Andy Meier
  11688. * @since 4.6.018 (2009-07-10)
  11689. */
  11690. public function Arrow($x0, $y0, $x1, $y1, $head_style=0, $arm_size=5, $arm_angle=15) {
  11691. // getting arrow direction angle
  11692. // 0 deg angle is when both arms go along X axis. angle grows clockwise.
  11693. $dir_angle = atan2(($y0 - $y1), ($x0 - $x1));
  11694. if ($dir_angle < 0) {
  11695. $dir_angle += (2 * M_PI);
  11696. }
  11697. $arm_angle = deg2rad($arm_angle);
  11698. $sx1 = $x1;
  11699. $sy1 = $y1;
  11700. if ($head_style > 0) {
  11701. // calculate the stopping point for the arrow shaft
  11702. $sx1 = $x1 + (($arm_size - $this->LineWidth) * cos($dir_angle));
  11703. $sy1 = $y1 + (($arm_size - $this->LineWidth) * sin($dir_angle));
  11704. }
  11705. // main arrow line / shaft
  11706. $this->Line($x0, $y0, $sx1, $sy1);
  11707. // left arrowhead arm tip
  11708. $x2L = $x1 + ($arm_size * cos($dir_angle + $arm_angle));
  11709. $y2L = $y1 + ($arm_size * sin($dir_angle + $arm_angle));
  11710. // right arrowhead arm tip
  11711. $x2R = $x1 + ($arm_size * cos($dir_angle - $arm_angle));
  11712. $y2R = $y1 + ($arm_size * sin($dir_angle - $arm_angle));
  11713. $mode = 'D';
  11714. $style = array();
  11715. switch ($head_style) {
  11716. case 0: {
  11717. // draw only arrowhead arms
  11718. $mode = 'D';
  11719. $style = array(1, 1, 0);
  11720. break;
  11721. }
  11722. case 1: {
  11723. // draw closed arrowhead, but no fill
  11724. $mode = 'D';
  11725. break;
  11726. }
  11727. case 2: {
  11728. // closed and filled arrowhead
  11729. $mode = 'DF';
  11730. break;
  11731. }
  11732. case 3: {
  11733. // filled arrowhead
  11734. $mode = 'F';
  11735. break;
  11736. }
  11737. }
  11738. $this->Polygon(array($x2L, $y2L, $x1, $y1, $x2R, $y2R), $mode, $style, array());
  11739. }
  11740. // END GRAPHIC FUNCTIONS SECTION -----------------------
  11741. /**
  11742. * Add a Named Destination.
  11743. * NOTE: destination names are unique, so only last entry will be saved.
  11744. * @param $name (string) Destination name.
  11745. * @param $y (float) Y position in user units of the destiantion on the selected page (default = -1 = current position; 0 = page start;).
  11746. * @param $page (int|string) Target page number (leave empty for current page). If you prefix a page number with the * character, then this page will not be changed when adding/deleting/moving pages.
  11747. * @param $x (float) X position in user units of the destiantion on the selected page (default = -1 = current position;).
  11748. * @return (string) Stripped named destination identifier or false in case of error.
  11749. * @public
  11750. * @author Christian Deligant, Nicola Asuni
  11751. * @since 5.9.097 (2011-06-23)
  11752. */
  11753. public function setDestination($name, $y=-1, $page='', $x=-1) {
  11754. // remove unsupported characters
  11755. $name = TCPDF_STATIC::encodeNameObject($name);
  11756. if (TCPDF_STATIC::empty_string($name)) {
  11757. return false;
  11758. }
  11759. if ($y == -1) {
  11760. $y = $this->GetY();
  11761. } elseif ($y < 0) {
  11762. $y = 0;
  11763. } elseif ($y > $this->h) {
  11764. $y = $this->h;
  11765. }
  11766. if ($x == -1) {
  11767. $x = $this->GetX();
  11768. } elseif ($x < 0) {
  11769. $x = 0;
  11770. } elseif ($x > $this->w) {
  11771. $x = $this->w;
  11772. }
  11773. $fixed = false;
  11774. if (!empty($page) AND (substr($page, 0, 1) == '*')) {
  11775. $page = intval(substr($page, 1));
  11776. // this page number will not be changed when moving/add/deleting pages
  11777. $fixed = true;
  11778. }
  11779. if (empty($page)) {
  11780. $page = $this->PageNo();
  11781. if (empty($page)) {
  11782. return;
  11783. }
  11784. }
  11785. $this->dests[$name] = array('x' => $x, 'y' => $y, 'p' => $page, 'f' => $fixed);
  11786. return $name;
  11787. }
  11788. /**
  11789. * Return the Named Destination array.
  11790. * @return (array) Named Destination array.
  11791. * @public
  11792. * @author Nicola Asuni
  11793. * @since 5.9.097 (2011-06-23)
  11794. */
  11795. public function getDestination() {
  11796. return $this->dests;
  11797. }
  11798. /**
  11799. * Insert Named Destinations.
  11800. * @protected
  11801. * @author Johannes G\FCntert, Nicola Asuni
  11802. * @since 5.9.098 (2011-06-23)
  11803. */
  11804. protected function _putdests() {
  11805. if (empty($this->dests)) {
  11806. return;
  11807. }
  11808. $this->n_dests = $this->_newobj();
  11809. $out = ' <<';
  11810. foreach($this->dests as $name => $o) {
  11811. $out .= ' /'.$name.' '.sprintf('[%u 0 R /XYZ %F %F null]', $this->page_obj_id[($o['p'])], ($o['x'] * $this->k), ($this->pagedim[$o['p']]['h'] - ($o['y'] * $this->k)));
  11812. }
  11813. $out .= ' >>';
  11814. $out .= "\n".'endobj';
  11815. $this->_out($out);
  11816. }
  11817. /**
  11818. * Adds a bookmark - alias for Bookmark().
  11819. * @param $txt (string) Bookmark description.
  11820. * @param $level (int) Bookmark level (minimum value is 0).
  11821. * @param $y (float) Y position in user units of the bookmark on the selected page (default = -1 = current position; 0 = page start;).
  11822. * @param $page (int|string) Target page number (leave empty for current page). If you prefix a page number with the * character, then this page will not be changed when adding/deleting/moving pages.
  11823. * @param $style (string) Font style: B = Bold, I = Italic, BI = Bold + Italic.
  11824. * @param $color (array) RGB color array (values from 0 to 255).
  11825. * @param $x (float) X position in user units of the bookmark on the selected page (default = -1 = current position;).
  11826. * @param $link (mixed) URL, or numerical link ID, or named destination (# character followed by the destination name), or embedded file (* character followed by the file name).
  11827. * @public
  11828. */
  11829. public function setBookmark($txt, $level=0, $y=-1, $page='', $style='', $color=array(0,0,0), $x=-1, $link='') {
  11830. $this->Bookmark($txt, $level, $y, $page, $style, $color, $x, $link);
  11831. }
  11832. /**
  11833. * Adds a bookmark.
  11834. * @param $txt (string) Bookmark description.
  11835. * @param $level (int) Bookmark level (minimum value is 0).
  11836. * @param $y (float) Y position in user units of the bookmark on the selected page (default = -1 = current position; 0 = page start;).
  11837. * @param $page (int|string) Target page number (leave empty for current page). If you prefix a page number with the * character, then this page will not be changed when adding/deleting/moving pages.
  11838. * @param $style (string) Font style: B = Bold, I = Italic, BI = Bold + Italic.
  11839. * @param $color (array) RGB color array (values from 0 to 255).
  11840. * @param $x (float) X position in user units of the bookmark on the selected page (default = -1 = current position;).
  11841. * @param $link (mixed) URL, or numerical link ID, or named destination (# character followed by the destination name), or embedded file (* character followed by the file name).
  11842. * @public
  11843. * @since 2.1.002 (2008-02-12)
  11844. */
  11845. public function Bookmark($txt, $level=0, $y=-1, $page='', $style='', $color=array(0,0,0), $x=-1, $link='') {
  11846. if ($level < 0) {
  11847. $level = 0;
  11848. }
  11849. if (isset($this->outlines[0])) {
  11850. $lastoutline = end($this->outlines);
  11851. $maxlevel = $lastoutline['l'] + 1;
  11852. } else {
  11853. $maxlevel = 0;
  11854. }
  11855. if ($level > $maxlevel) {
  11856. $level = $maxlevel;
  11857. }
  11858. if ($y == -1) {
  11859. $y = $this->GetY();
  11860. } elseif ($y < 0) {
  11861. $y = 0;
  11862. } elseif ($y > $this->h) {
  11863. $y = $this->h;
  11864. }
  11865. if ($x == -1) {
  11866. $x = $this->GetX();
  11867. } elseif ($x < 0) {
  11868. $x = 0;
  11869. } elseif ($x > $this->w) {
  11870. $x = $this->w;
  11871. }
  11872. $fixed = false;
  11873. $pageAsString = (string) $page;
  11874. if ($pageAsString && $pageAsString[0] == '*') {
  11875. $page = intval(substr($page, 1));
  11876. // this page number will not be changed when moving/add/deleting pages
  11877. $fixed = true;
  11878. }
  11879. if (empty($page)) {
  11880. $page = $this->PageNo();
  11881. if (empty($page)) {
  11882. return;
  11883. }
  11884. }
  11885. $this->outlines[] = array('t' => $txt, 'l' => $level, 'x' => $x, 'y' => $y, 'p' => $page, 'f' => $fixed, 's' => strtoupper($style), 'c' => $color, 'u' => $link);
  11886. }
  11887. /**
  11888. * Sort bookmarks for page and key.
  11889. * @protected
  11890. * @since 5.9.119 (2011-09-19)
  11891. */
  11892. protected function sortBookmarks() {
  11893. // get sorting columns
  11894. $outline_p = array();
  11895. $outline_y = array();
  11896. foreach ($this->outlines as $key => $row) {
  11897. $outline_p[$key] = $row['p'];
  11898. $outline_k[$key] = $key;
  11899. }
  11900. // sort outlines by page and original position
  11901. array_multisort($outline_p, SORT_NUMERIC, SORT_ASC, $outline_k, SORT_NUMERIC, SORT_ASC, $this->outlines);
  11902. }
  11903. /**
  11904. * Create a bookmark PDF string.
  11905. * @protected
  11906. * @author Olivier Plathey, Nicola Asuni
  11907. * @since 2.1.002 (2008-02-12)
  11908. */
  11909. protected function _putbookmarks() {
  11910. $nb = count($this->outlines);
  11911. if ($nb == 0) {
  11912. return;
  11913. }
  11914. // sort bookmarks
  11915. $this->sortBookmarks();
  11916. $lru = array();
  11917. $level = 0;
  11918. foreach ($this->outlines as $i => $o) {
  11919. if ($o['l'] > 0) {
  11920. $parent = $lru[($o['l'] - 1)];
  11921. //Set parent and last pointers
  11922. $this->outlines[$i]['parent'] = $parent;
  11923. $this->outlines[$parent]['last'] = $i;
  11924. if ($o['l'] > $level) {
  11925. //Level increasing: set first pointer
  11926. $this->outlines[$parent]['first'] = $i;
  11927. }
  11928. } else {
  11929. $this->outlines[$i]['parent'] = $nb;
  11930. }
  11931. if (($o['l'] <= $level) AND ($i > 0)) {
  11932. //Set prev and next pointers
  11933. $prev = $lru[$o['l']];
  11934. $this->outlines[$prev]['next'] = $i;
  11935. $this->outlines[$i]['prev'] = $prev;
  11936. }
  11937. $lru[$o['l']] = $i;
  11938. $level = $o['l'];
  11939. }
  11940. //Outline items
  11941. $n = $this->n + 1;
  11942. $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';
  11943. foreach ($this->outlines as $i => $o) {
  11944. $oid = $this->_newobj();
  11945. // covert HTML title to string
  11946. $title = preg_replace($nltags, "\n", $o['t']);
  11947. $title = preg_replace("/[\r]+/si", '', $title);
  11948. $title = preg_replace("/[\n]+/si", "\n", $title);
  11949. $title = strip_tags($title);
  11950. $title = $this->stringTrim($title);
  11951. $out = '<</Title '.$this->_textstring($title, $oid);
  11952. $out .= ' /Parent '.($n + $o['parent']).' 0 R';
  11953. if (isset($o['prev'])) {
  11954. $out .= ' /Prev '.($n + $o['prev']).' 0 R';
  11955. }
  11956. if (isset($o['next'])) {
  11957. $out .= ' /Next '.($n + $o['next']).' 0 R';
  11958. }
  11959. if (isset($o['first'])) {
  11960. $out .= ' /First '.($n + $o['first']).' 0 R';
  11961. }
  11962. if (isset($o['last'])) {
  11963. $out .= ' /Last '.($n + $o['last']).' 0 R';
  11964. }
  11965. if (isset($o['u']) AND !empty($o['u'])) {
  11966. // link
  11967. if (is_string($o['u'])) {
  11968. if ($o['u'][0] == '#') {
  11969. // internal destination
  11970. $out .= ' /Dest /'.TCPDF_STATIC::encodeNameObject(substr($o['u'], 1));
  11971. } elseif ($o['u'][0] == '%') {
  11972. // embedded PDF file
  11973. $filename = basename(substr($o['u'], 1));
  11974. $out .= ' /A <</S /GoToE /D [0 /Fit] /NewWindow true /T << /R /C /P '.($o['p'] - 1).' /A '.$this->embeddedfiles[$filename]['a'].' >> >>';
  11975. } elseif ($o['u'][0] == '*') {
  11976. // embedded generic file
  11977. $filename = basename(substr($o['u'], 1));
  11978. $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});';
  11979. $out .= ' /A <</S /JavaScript /JS '.$this->_textstring($jsa, $oid).'>>';
  11980. } else {
  11981. // external URI link
  11982. $out .= ' /A <</S /URI /URI '.$this->_datastring($this->unhtmlentities($o['u']), $oid).'>>';
  11983. }
  11984. } elseif (isset($this->links[$o['u']])) {
  11985. // internal link ID
  11986. $l = $this->links[$o['u']];
  11987. if (isset($this->page_obj_id[($l['p'])])) {
  11988. $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)));
  11989. }
  11990. }
  11991. } elseif (isset($this->page_obj_id[($o['p'])])) {
  11992. // link to a page
  11993. $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)));
  11994. }
  11995. // set font style
  11996. $style = 0;
  11997. if (!empty($o['s'])) {
  11998. // bold
  11999. if (strpos($o['s'], 'B') !== false) {
  12000. $style |= 2;
  12001. }
  12002. // oblique
  12003. if (strpos($o['s'], 'I') !== false) {
  12004. $style |= 1;
  12005. }
  12006. }
  12007. $out .= sprintf(' /F %d', $style);
  12008. // set bookmark color
  12009. if (isset($o['c']) AND is_array($o['c']) AND (count($o['c']) == 3)) {
  12010. $color = array_values($o['c']);
  12011. $out .= sprintf(' /C [%F %F %F]', ($color[0] / 255), ($color[1] / 255), ($color[2] / 255));
  12012. } else {
  12013. // black
  12014. $out .= ' /C [0.0 0.0 0.0]';
  12015. }
  12016. $out .= ' /Count 0'; // normally closed item
  12017. $out .= ' >>';
  12018. $out .= "\n".'endobj';
  12019. $this->_out($out);
  12020. }
  12021. //Outline root
  12022. $this->OutlineRoot = $this->_newobj();
  12023. $this->_out('<< /Type /Outlines /First '.$n.' 0 R /Last '.($n + $lru[0]).' 0 R >>'."\n".'endobj');
  12024. }
  12025. // --- JAVASCRIPT ------------------------------------------------------
  12026. /**
  12027. * Adds a javascript
  12028. * @param $script (string) Javascript code
  12029. * @public
  12030. * @author Johannes G\FCntert, Nicola Asuni
  12031. * @since 2.1.002 (2008-02-12)
  12032. */
  12033. public function IncludeJS($script) {
  12034. $this->javascript .= $script;
  12035. }
  12036. /**
  12037. * Adds a javascript object and return object ID
  12038. * @param $script (string) Javascript code
  12039. * @param $onload (boolean) if true executes this object when opening the document
  12040. * @return int internal object ID
  12041. * @public
  12042. * @author Nicola Asuni
  12043. * @since 4.8.000 (2009-09-07)
  12044. */
  12045. public function addJavascriptObject($script, $onload=false) {
  12046. if ($this->pdfa_mode) {
  12047. // javascript is not allowed in PDF/A mode
  12048. return false;
  12049. }
  12050. ++$this->n;
  12051. $this->js_objects[$this->n] = array('n' => $this->n, 'js' => $script, 'onload' => $onload);
  12052. return $this->n;
  12053. }
  12054. /**
  12055. * Create a javascript PDF string.
  12056. * @protected
  12057. * @author Johannes G\FCntert, Nicola Asuni
  12058. * @since 2.1.002 (2008-02-12)
  12059. */
  12060. protected function _putjavascript() {
  12061. if ($this->pdfa_mode OR (empty($this->javascript) AND empty($this->js_objects))) {
  12062. return;
  12063. }
  12064. if (strpos($this->javascript, 'this.addField') > 0) {
  12065. if (!$this->ur['enabled']) {
  12066. //$this->setUserRights();
  12067. }
  12068. // the following two lines are used to avoid form fields duplication after saving
  12069. // The addField method only works when releasing user rights (UR3)
  12070. $jsa = sprintf("ftcpdfdocsaved=this.addField('%s','%s',%d,[%F,%F,%F,%F]);", 'tcpdfdocsaved', 'text', 0, 0, 1, 0, 1);
  12071. $jsb = "getField('tcpdfdocsaved').value='saved';";
  12072. $this->javascript = $jsa."\n".$this->javascript."\n".$jsb;
  12073. }
  12074. // name tree for javascript
  12075. $this->n_js = '<< /Names [';
  12076. if (!empty($this->javascript)) {
  12077. $this->n_js .= ' (EmbeddedJS) '.($this->n + 1).' 0 R';
  12078. }
  12079. if (!empty($this->js_objects)) {
  12080. foreach ($this->js_objects as $key => $val) {
  12081. if ($val['onload']) {
  12082. $this->n_js .= ' (JS'.$key.') '.$key.' 0 R';
  12083. }
  12084. }
  12085. }
  12086. $this->n_js .= ' ] >>';
  12087. // default Javascript object
  12088. if (!empty($this->javascript)) {
  12089. $obj_id = $this->_newobj();
  12090. $out = '<< /S /JavaScript';
  12091. $out .= ' /JS '.$this->_textstring($this->javascript, $obj_id);
  12092. $out .= ' >>';
  12093. $out .= "\n".'endobj';
  12094. $this->_out($out);
  12095. }
  12096. // additional Javascript objects
  12097. if (!empty($this->js_objects)) {
  12098. foreach ($this->js_objects as $key => $val) {
  12099. $out = $this->_getobj($key)."\n".' << /S /JavaScript /JS '.$this->_textstring($val['js'], $key).' >>'."\n".'endobj';
  12100. $this->_out($out);
  12101. }
  12102. }
  12103. }
  12104. /**
  12105. * Adds a javascript form field.
  12106. * @param $type (string) field type
  12107. * @param $name (string) field name
  12108. * @param $x (int) horizontal position
  12109. * @param $y (int) vertical position
  12110. * @param $w (int) width
  12111. * @param $h (int) height
  12112. * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
  12113. * @protected
  12114. * @author Denis Van Nuffelen, Nicola Asuni
  12115. * @since 2.1.002 (2008-02-12)
  12116. */
  12117. protected function _addfield($type, $name, $x, $y, $w, $h, $prop) {
  12118. if ($this->rtl) {
  12119. $x = $x - $w;
  12120. }
  12121. // the followind avoid fields duplication after saving the document
  12122. $this->javascript .= "if (getField('tcpdfdocsaved').value != 'saved') {";
  12123. $k = $this->k;
  12124. $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";
  12125. $this->javascript .= 'f'.$name.'.textSize='.$this->FontSizePt.";\n";
  12126. foreach($prop as $key => $val) {
  12127. if (strcmp(substr($key, -5), 'Color') == 0) {
  12128. $val = TCPDF_COLORS::_JScolor($val);
  12129. } else {
  12130. $val = "'".$val."'";
  12131. }
  12132. $this->javascript .= 'f'.$name.'.'.$key.'='.$val.";\n";
  12133. }
  12134. if ($this->rtl) {
  12135. $this->x -= $w;
  12136. } else {
  12137. $this->x += $w;
  12138. }
  12139. $this->javascript .= '}';
  12140. }
  12141. // --- FORM FIELDS -----------------------------------------------------
  12142. /**
  12143. * Set default properties for form fields.
  12144. * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
  12145. * @public
  12146. * @author Nicola Asuni
  12147. * @since 4.8.000 (2009-09-06)
  12148. */
  12149. public function setFormDefaultProp($prop=array()) {
  12150. $this->default_form_prop = $prop;
  12151. }
  12152. /**
  12153. * Return the default properties for form fields.
  12154. * @return array $prop javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
  12155. * @public
  12156. * @author Nicola Asuni
  12157. * @since 4.8.000 (2009-09-06)
  12158. */
  12159. public function getFormDefaultProp() {
  12160. return $this->default_form_prop;
  12161. }
  12162. /**
  12163. * Creates a text field
  12164. * @param $name (string) field name
  12165. * @param $w (float) Width of the rectangle
  12166. * @param $h (float) Height of the rectangle
  12167. * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
  12168. * @param $opt (array) annotation parameters. Possible values are described on official PDF32000_2008 reference.
  12169. * @param $x (float) Abscissa of the upper-left corner of the rectangle
  12170. * @param $y (float) Ordinate of the upper-left corner of the rectangle
  12171. * @param $js (boolean) if true put the field using JavaScript (requires Acrobat Writer to be rendered).
  12172. * @public
  12173. * @author Nicola Asuni
  12174. * @since 4.8.000 (2009-09-07)
  12175. */
  12176. public function TextField($name, $w, $h, $prop=array(), $opt=array(), $x='', $y='', $js=false) {
  12177. if ($x === '') {
  12178. $x = $this->x;
  12179. }
  12180. if ($y === '') {
  12181. $y = $this->y;
  12182. }
  12183. // check page for no-write regions and adapt page margins if necessary
  12184. list($x, $y) = $this->checkPageRegions($h, $x, $y);
  12185. if ($js) {
  12186. $this->_addfield('text', $name, $x, $y, $w, $h, $prop);
  12187. return;
  12188. }
  12189. // get default style
  12190. $prop = array_merge($this->getFormDefaultProp(), $prop);
  12191. // get annotation data
  12192. $popt = TCPDF_STATIC::getAnnotOptFromJSProp($prop, $this->spot_colors, $this->rtl);
  12193. // set default appearance stream
  12194. $this->annotation_fonts[$this->CurrentFont['fontkey']] = $this->CurrentFont['i'];
  12195. $fontstyle = sprintf('/F%d %F Tf %s', $this->CurrentFont['i'], $this->FontSizePt, $this->TextColor);
  12196. $popt['da'] = $fontstyle;
  12197. // build appearance stream
  12198. $popt['ap'] = array();
  12199. $popt['ap']['n'] = '/Tx BMC q '.$fontstyle.' ';
  12200. $text = '';
  12201. if (isset($prop['value']) AND !empty($prop['value'])) {
  12202. $text = $prop['value'];
  12203. } elseif (isset($opt['v']) AND !empty($opt['v'])) {
  12204. $text = $opt['v'];
  12205. }
  12206. $tmpid = $this->startTemplate($w, $h, false);
  12207. $align = '';
  12208. if (isset($popt['q'])) {
  12209. switch ($popt['q']) {
  12210. case 0: {
  12211. $align = 'L';
  12212. break;
  12213. }
  12214. case 1: {
  12215. $align = 'C';
  12216. break;
  12217. }
  12218. case 2: {
  12219. $align = 'R';
  12220. break;
  12221. }
  12222. default: {
  12223. $align = '';
  12224. break;
  12225. }
  12226. }
  12227. }
  12228. $this->MultiCell($w, $h, $text, 0, $align, false, 0, 0, 0, true, 0, false, true, 0, 'T', false);
  12229. $this->endTemplate();
  12230. --$this->n;
  12231. $popt['ap']['n'] .= $this->xobjects[$tmpid]['outdata'];
  12232. unset($this->xobjects[$tmpid]);
  12233. $popt['ap']['n'] .= 'Q EMC';
  12234. // merge options
  12235. $opt = array_merge($popt, $opt);
  12236. // remove some conflicting options
  12237. unset($opt['bs']);
  12238. // set remaining annotation data
  12239. $opt['Subtype'] = 'Widget';
  12240. $opt['ft'] = 'Tx';
  12241. $opt['t'] = $name;
  12242. // Additional annotation's parameters (check _putannotsobj() method):
  12243. //$opt['f']
  12244. //$opt['as']
  12245. //$opt['bs']
  12246. //$opt['be']
  12247. //$opt['c']
  12248. //$opt['border']
  12249. //$opt['h']
  12250. //$opt['mk'];
  12251. //$opt['mk']['r']
  12252. //$opt['mk']['bc'];
  12253. //$opt['mk']['bg'];
  12254. unset($opt['mk']['ca']);
  12255. unset($opt['mk']['rc']);
  12256. unset($opt['mk']['ac']);
  12257. unset($opt['mk']['i']);
  12258. unset($opt['mk']['ri']);
  12259. unset($opt['mk']['ix']);
  12260. unset($opt['mk']['if']);
  12261. //$opt['mk']['if']['sw'];
  12262. //$opt['mk']['if']['s'];
  12263. //$opt['mk']['if']['a'];
  12264. //$opt['mk']['if']['fb'];
  12265. unset($opt['mk']['tp']);
  12266. //$opt['tu']
  12267. //$opt['tm']
  12268. //$opt['ff']
  12269. //$opt['v']
  12270. //$opt['dv']
  12271. //$opt['a']
  12272. //$opt['aa']
  12273. //$opt['q']
  12274. $this->Annotation($x, $y, $w, $h, $name, $opt, 0);
  12275. if ($this->rtl) {
  12276. $this->x -= $w;
  12277. } else {
  12278. $this->x += $w;
  12279. }
  12280. }
  12281. /**
  12282. * Creates a RadioButton field.
  12283. * @param $name (string) Field name.
  12284. * @param $w (int) Width of the radio button.
  12285. * @param $prop (array) Javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
  12286. * @param $opt (array) Annotation parameters. Possible values are described on official PDF32000_2008 reference.
  12287. * @param $onvalue (string) Value to be returned if selected.
  12288. * @param $checked (boolean) Define the initial state.
  12289. * @param $x (float) Abscissa of the upper-left corner of the rectangle
  12290. * @param $y (float) Ordinate of the upper-left corner of the rectangle
  12291. * @param $js (boolean) If true put the field using JavaScript (requires Acrobat Writer to be rendered).
  12292. * @public
  12293. * @author Nicola Asuni
  12294. * @since 4.8.000 (2009-09-07)
  12295. */
  12296. public function RadioButton($name, $w, $prop=array(), $opt=array(), $onvalue='On', $checked=false, $x='', $y='', $js=false) {
  12297. if ($x === '') {
  12298. $x = $this->x;
  12299. }
  12300. if ($y === '') {
  12301. $y = $this->y;
  12302. }
  12303. // check page for no-write regions and adapt page margins if necessary
  12304. list($x, $y) = $this->checkPageRegions($w, $x, $y);
  12305. if ($js) {
  12306. $this->_addfield('radiobutton', $name, $x, $y, $w, $w, $prop);
  12307. return;
  12308. }
  12309. if (TCPDF_STATIC::empty_string($onvalue)) {
  12310. $onvalue = 'On';
  12311. }
  12312. if ($checked) {
  12313. $defval = $onvalue;
  12314. } else {
  12315. $defval = 'Off';
  12316. }
  12317. // set font
  12318. $font = 'zapfdingbats';
  12319. if ($this->pdfa_mode) {
  12320. // all fonts must be embedded
  12321. $font = 'pdfa'.$font;
  12322. }
  12323. $this->AddFont($font);
  12324. $tmpfont = $this->getFontBuffer($font);
  12325. // set data for parent group
  12326. if (!isset($this->radiobutton_groups[$this->page])) {
  12327. $this->radiobutton_groups[$this->page] = array();
  12328. }
  12329. if (!isset($this->radiobutton_groups[$this->page][$name])) {
  12330. $this->radiobutton_groups[$this->page][$name] = array();
  12331. ++$this->n;
  12332. $this->radiobutton_groups[$this->page][$name]['n'] = $this->n;
  12333. $this->radio_groups[] = $this->n;
  12334. }
  12335. $kid = ($this->n + 1);
  12336. // save object ID to be added on Kids entry on parent object
  12337. $this->radiobutton_groups[$this->page][$name][] = array('kid' => $kid, 'def' => $defval);
  12338. // get default style
  12339. $prop = array_merge($this->getFormDefaultProp(), $prop);
  12340. $prop['NoToggleToOff'] = 'true';
  12341. $prop['Radio'] = 'true';
  12342. $prop['borderStyle'] = 'inset';
  12343. // get annotation data
  12344. $popt = TCPDF_STATIC::getAnnotOptFromJSProp($prop, $this->spot_colors, $this->rtl);
  12345. // set additional default options
  12346. $this->annotation_fonts[$tmpfont['fontkey']] = $tmpfont['i'];
  12347. $fontstyle = sprintf('/F%d %F Tf %s', $tmpfont['i'], $this->FontSizePt, $this->TextColor);
  12348. $popt['da'] = $fontstyle;
  12349. // build appearance stream
  12350. $popt['ap'] = array();
  12351. $popt['ap']['n'] = array();
  12352. $fx = ((($w - $this->getAbsFontMeasure($tmpfont['cw'][108])) / 2) * $this->k);
  12353. $fy = (($w - ((($tmpfont['desc']['Ascent'] - $tmpfont['desc']['Descent']) * $this->FontSizePt / 1000) / $this->k)) * $this->k);
  12354. $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);
  12355. $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);
  12356. if (!isset($popt['mk'])) {
  12357. $popt['mk'] = array();
  12358. }
  12359. $popt['mk']['ca'] = '(l)';
  12360. // merge options
  12361. $opt = array_merge($popt, $opt);
  12362. // set remaining annotation data
  12363. $opt['Subtype'] = 'Widget';
  12364. $opt['ft'] = 'Btn';
  12365. if ($checked) {
  12366. $opt['v'] = array('/'.$onvalue);
  12367. $opt['as'] = $onvalue;
  12368. } else {
  12369. $opt['as'] = 'Off';
  12370. }
  12371. // store readonly flag
  12372. if (!isset($this->radiobutton_groups[$this->page][$name]['#readonly#'])) {
  12373. $this->radiobutton_groups[$this->page][$name]['#readonly#'] = false;
  12374. }
  12375. $this->radiobutton_groups[$this->page][$name]['#readonly#'] |= ($opt['f'] & 64);
  12376. $this->Annotation($x, $y, $w, $w, $name, $opt, 0);
  12377. if ($this->rtl) {
  12378. $this->x -= $w;
  12379. } else {
  12380. $this->x += $w;
  12381. }
  12382. }
  12383. /**
  12384. * Creates a List-box field
  12385. * @param $name (string) field name
  12386. * @param $w (int) width
  12387. * @param $h (int) height
  12388. * @param $values (array) array containing the list of values.
  12389. * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
  12390. * @param $opt (array) annotation parameters. Possible values are described on official PDF32000_2008 reference.
  12391. * @param $x (float) Abscissa of the upper-left corner of the rectangle
  12392. * @param $y (float) Ordinate of the upper-left corner of the rectangle
  12393. * @param $js (boolean) if true put the field using JavaScript (requires Acrobat Writer to be rendered).
  12394. * @public
  12395. * @author Nicola Asuni
  12396. * @since 4.8.000 (2009-09-07)
  12397. */
  12398. public function ListBox($name, $w, $h, $values, $prop=array(), $opt=array(), $x='', $y='', $js=false) {
  12399. if ($x === '') {
  12400. $x = $this->x;
  12401. }
  12402. if ($y === '') {
  12403. $y = $this->y;
  12404. }
  12405. // check page for no-write regions and adapt page margins if necessary
  12406. list($x, $y) = $this->checkPageRegions($h, $x, $y);
  12407. if ($js) {
  12408. $this->_addfield('listbox', $name, $x, $y, $w, $h, $prop);
  12409. $s = '';
  12410. foreach ($values as $value) {
  12411. if (is_array($value)) {
  12412. $s .= ',[\''.addslashes($value[1]).'\',\''.addslashes($value[0]).'\']';
  12413. } else {
  12414. $s .= ',[\''.addslashes($value).'\',\''.addslashes($value).'\']';
  12415. }
  12416. }
  12417. $this->javascript .= 'f'.$name.'.setItems('.substr($s, 1).');'."\n";
  12418. return;
  12419. }
  12420. // get default style
  12421. $prop = array_merge($this->getFormDefaultProp(), $prop);
  12422. // get annotation data
  12423. $popt = TCPDF_STATIC::getAnnotOptFromJSProp($prop, $this->spot_colors, $this->rtl);
  12424. // set additional default values
  12425. $this->annotation_fonts[$this->CurrentFont['fontkey']] = $this->CurrentFont['i'];
  12426. $fontstyle = sprintf('/F%d %F Tf %s', $this->CurrentFont['i'], $this->FontSizePt, $this->TextColor);
  12427. $popt['da'] = $fontstyle;
  12428. // build appearance stream
  12429. $popt['ap'] = array();
  12430. $popt['ap']['n'] = '/Tx BMC q '.$fontstyle.' ';
  12431. $text = '';
  12432. foreach($values as $item) {
  12433. if (is_array($item)) {
  12434. $text .= $item[1]."\n";
  12435. } else {
  12436. $text .= $item."\n";
  12437. }
  12438. }
  12439. $tmpid = $this->startTemplate($w, $h, false);
  12440. $this->MultiCell($w, $h, $text, 0, '', false, 0, 0, 0, true, 0, false, true, 0, 'T', false);
  12441. $this->endTemplate();
  12442. --$this->n;
  12443. $popt['ap']['n'] .= $this->xobjects[$tmpid]['outdata'];
  12444. unset($this->xobjects[$tmpid]);
  12445. $popt['ap']['n'] .= 'Q EMC';
  12446. // merge options
  12447. $opt = array_merge($popt, $opt);
  12448. // set remaining annotation data
  12449. $opt['Subtype'] = 'Widget';
  12450. $opt['ft'] = 'Ch';
  12451. $opt['t'] = $name;
  12452. $opt['opt'] = $values;
  12453. unset($opt['mk']['ca']);
  12454. unset($opt['mk']['rc']);
  12455. unset($opt['mk']['ac']);
  12456. unset($opt['mk']['i']);
  12457. unset($opt['mk']['ri']);
  12458. unset($opt['mk']['ix']);
  12459. unset($opt['mk']['if']);
  12460. unset($opt['mk']['tp']);
  12461. $this->Annotation($x, $y, $w, $h, $name, $opt, 0);
  12462. if ($this->rtl) {
  12463. $this->x -= $w;
  12464. } else {
  12465. $this->x += $w;
  12466. }
  12467. }
  12468. /**
  12469. * Creates a Combo-box field
  12470. * @param $name (string) field name
  12471. * @param $w (int) width
  12472. * @param $h (int) height
  12473. * @param $values (array) array containing the list of values.
  12474. * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
  12475. * @param $opt (array) annotation parameters. Possible values are described on official PDF32000_2008 reference.
  12476. * @param $x (float) Abscissa of the upper-left corner of the rectangle
  12477. * @param $y (float) Ordinate of the upper-left corner of the rectangle
  12478. * @param $js (boolean) if true put the field using JavaScript (requires Acrobat Writer to be rendered).
  12479. * @public
  12480. * @author Nicola Asuni
  12481. * @since 4.8.000 (2009-09-07)
  12482. */
  12483. public function ComboBox($name, $w, $h, $values, $prop=array(), $opt=array(), $x='', $y='', $js=false) {
  12484. if ($x === '') {
  12485. $x = $this->x;
  12486. }
  12487. if ($y === '') {
  12488. $y = $this->y;
  12489. }
  12490. // check page for no-write regions and adapt page margins if necessary
  12491. list($x, $y) = $this->checkPageRegions($h, $x, $y);
  12492. if ($js) {
  12493. $this->_addfield('combobox', $name, $x, $y, $w, $h, $prop);
  12494. $s = '';
  12495. foreach ($values as $value) {
  12496. if (is_array($value)) {
  12497. $s .= ',[\''.addslashes($value[1]).'\',\''.addslashes($value[0]).'\']';
  12498. } else {
  12499. $s .= ',[\''.addslashes($value).'\',\''.addslashes($value).'\']';
  12500. }
  12501. }
  12502. $this->javascript .= 'f'.$name.'.setItems('.substr($s, 1).');'."\n";
  12503. return;
  12504. }
  12505. // get default style
  12506. $prop = array_merge($this->getFormDefaultProp(), $prop);
  12507. $prop['Combo'] = true;
  12508. // get annotation data
  12509. $popt = TCPDF_STATIC::getAnnotOptFromJSProp($prop, $this->spot_colors, $this->rtl);
  12510. // set additional default options
  12511. $this->annotation_fonts[$this->CurrentFont['fontkey']] = $this->CurrentFont['i'];
  12512. $fontstyle = sprintf('/F%d %F Tf %s', $this->CurrentFont['i'], $this->FontSizePt, $this->TextColor);
  12513. $popt['da'] = $fontstyle;
  12514. // build appearance stream
  12515. $popt['ap'] = array();
  12516. $popt['ap']['n'] = '/Tx BMC q '.$fontstyle.' ';
  12517. $text = '';
  12518. foreach($values as $item) {
  12519. if (is_array($item)) {
  12520. $text .= $item[1]."\n";
  12521. } else {
  12522. $text .= $item."\n";
  12523. }
  12524. }
  12525. $tmpid = $this->startTemplate($w, $h, false);
  12526. $this->MultiCell($w, $h, $text, 0, '', false, 0, 0, 0, true, 0, false, true, 0, 'T', false);
  12527. $this->endTemplate();
  12528. --$this->n;
  12529. $popt['ap']['n'] .= $this->xobjects[$tmpid]['outdata'];
  12530. unset($this->xobjects[$tmpid]);
  12531. $popt['ap']['n'] .= 'Q EMC';
  12532. // merge options
  12533. $opt = array_merge($popt, $opt);
  12534. // set remaining annotation data
  12535. $opt['Subtype'] = 'Widget';
  12536. $opt['ft'] = 'Ch';
  12537. $opt['t'] = $name;
  12538. $opt['opt'] = $values;
  12539. unset($opt['mk']['ca']);
  12540. unset($opt['mk']['rc']);
  12541. unset($opt['mk']['ac']);
  12542. unset($opt['mk']['i']);
  12543. unset($opt['mk']['ri']);
  12544. unset($opt['mk']['ix']);
  12545. unset($opt['mk']['if']);
  12546. unset($opt['mk']['tp']);
  12547. $this->Annotation($x, $y, $w, $h, $name, $opt, 0);
  12548. if ($this->rtl) {
  12549. $this->x -= $w;
  12550. } else {
  12551. $this->x += $w;
  12552. }
  12553. }
  12554. /**
  12555. * Creates a CheckBox field
  12556. * @param $name (string) field name
  12557. * @param $w (int) width
  12558. * @param $checked (boolean) define the initial state.
  12559. * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
  12560. * @param $opt (array) annotation parameters. Possible values are described on official PDF32000_2008 reference.
  12561. * @param $onvalue (string) value to be returned if selected.
  12562. * @param $x (float) Abscissa of the upper-left corner of the rectangle
  12563. * @param $y (float) Ordinate of the upper-left corner of the rectangle
  12564. * @param $js (boolean) if true put the field using JavaScript (requires Acrobat Writer to be rendered).
  12565. * @public
  12566. * @author Nicola Asuni
  12567. * @since 4.8.000 (2009-09-07)
  12568. */
  12569. public function CheckBox($name, $w, $checked=false, $prop=array(), $opt=array(), $onvalue='Yes', $x='', $y='', $js=false) {
  12570. if ($x === '') {
  12571. $x = $this->x;
  12572. }
  12573. if ($y === '') {
  12574. $y = $this->y;
  12575. }
  12576. // check page for no-write regions and adapt page margins if necessary
  12577. list($x, $y) = $this->checkPageRegions($w, $x, $y);
  12578. if ($js) {
  12579. $this->_addfield('checkbox', $name, $x, $y, $w, $w, $prop);
  12580. return;
  12581. }
  12582. if (!isset($prop['value'])) {
  12583. $prop['value'] = array('Yes');
  12584. }
  12585. // get default style
  12586. $prop = array_merge($this->getFormDefaultProp(), $prop);
  12587. $prop['borderStyle'] = 'inset';
  12588. // get annotation data
  12589. $popt = TCPDF_STATIC::getAnnotOptFromJSProp($prop, $this->spot_colors, $this->rtl);
  12590. // set additional default options
  12591. $font = 'zapfdingbats';
  12592. if ($this->pdfa_mode) {
  12593. // all fonts must be embedded
  12594. $font = 'pdfa'.$font;
  12595. }
  12596. $this->AddFont($font);
  12597. $tmpfont = $this->getFontBuffer($font);
  12598. $this->annotation_fonts[$tmpfont['fontkey']] = $tmpfont['i'];
  12599. $fontstyle = sprintf('/F%d %F Tf %s', $tmpfont['i'], $this->FontSizePt, $this->TextColor);
  12600. $popt['da'] = $fontstyle;
  12601. // build appearance stream
  12602. $popt['ap'] = array();
  12603. $popt['ap']['n'] = array();
  12604. $fx = ((($w - $this->getAbsFontMeasure($tmpfont['cw'][110])) / 2) * $this->k);
  12605. $fy = (($w - ((($tmpfont['desc']['Ascent'] - $tmpfont['desc']['Descent']) * $this->FontSizePt / 1000) / $this->k)) * $this->k);
  12606. $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);
  12607. $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);
  12608. // merge options
  12609. $opt = array_merge($popt, $opt);
  12610. // set remaining annotation data
  12611. $opt['Subtype'] = 'Widget';
  12612. $opt['ft'] = 'Btn';
  12613. $opt['t'] = $name;
  12614. if (TCPDF_STATIC::empty_string($onvalue)) {
  12615. $onvalue = 'Yes';
  12616. }
  12617. $opt['opt'] = array($onvalue);
  12618. if ($checked) {
  12619. $opt['v'] = array('/Yes');
  12620. $opt['as'] = 'Yes';
  12621. } else {
  12622. $opt['v'] = array('/Off');
  12623. $opt['as'] = 'Off';
  12624. }
  12625. $this->Annotation($x, $y, $w, $w, $name, $opt, 0);
  12626. if ($this->rtl) {
  12627. $this->x -= $w;
  12628. } else {
  12629. $this->x += $w;
  12630. }
  12631. }
  12632. /**
  12633. * Creates a button field
  12634. * @param $name (string) field name
  12635. * @param $w (int) width
  12636. * @param $h (int) height
  12637. * @param $caption (string) caption.
  12638. * @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.
  12639. * @param $prop (array) javascript field properties. Possible values are described on official Javascript for Acrobat API reference.
  12640. * @param $opt (array) annotation parameters. Possible values are described on official PDF32000_2008 reference.
  12641. * @param $x (float) Abscissa of the upper-left corner of the rectangle
  12642. * @param $y (float) Ordinate of the upper-left corner of the rectangle
  12643. * @param $js (boolean) if true put the field using JavaScript (requires Acrobat Writer to be rendered).
  12644. * @public
  12645. * @author Nicola Asuni
  12646. * @since 4.8.000 (2009-09-07)
  12647. */
  12648. public function Button($name, $w, $h, $caption, $action, $prop=array(), $opt=array(), $x='', $y='', $js=false) {
  12649. if ($x === '') {
  12650. $x = $this->x;
  12651. }
  12652. if ($y === '') {
  12653. $y = $this->y;
  12654. }
  12655. // check page for no-write regions and adapt page margins if necessary
  12656. list($x, $y) = $this->checkPageRegions($h, $x, $y);
  12657. if ($js) {
  12658. $this->_addfield('button', $name, $this->x, $this->y, $w, $h, $prop);
  12659. $this->javascript .= 'f'.$name.".buttonSetCaption('".addslashes($caption)."');\n";
  12660. $this->javascript .= 'f'.$name.".setAction('MouseUp','".addslashes($action)."');\n";
  12661. $this->javascript .= 'f'.$name.".highlight='push';\n";
  12662. $this->javascript .= 'f'.$name.".print=false;\n";
  12663. return;
  12664. }
  12665. // get default style
  12666. $prop = array_merge($this->getFormDefaultProp(), $prop);
  12667. $prop['Pushbutton'] = 'true';
  12668. $prop['highlight'] = 'push';
  12669. $prop['display'] = 'display.noPrint';
  12670. // get annotation data
  12671. $popt = TCPDF_STATIC::getAnnotOptFromJSProp($prop, $this->spot_colors, $this->rtl);
  12672. $this->annotation_fonts[$this->CurrentFont['fontkey']] = $this->CurrentFont['i'];
  12673. $fontstyle = sprintf('/F%d %F Tf %s', $this->CurrentFont['i'], $this->FontSizePt, $this->TextColor);
  12674. $popt['da'] = $fontstyle;
  12675. // build appearance stream
  12676. $popt['ap'] = array();
  12677. $popt['ap']['n'] = '/Tx BMC q '.$fontstyle.' ';
  12678. $tmpid = $this->startTemplate($w, $h, false);
  12679. $bw = (2 / $this->k); // border width
  12680. $border = array(
  12681. 'L' => array('width' => $bw, 'cap' => 'square', 'join' => 'miter', 'dash' => 0, 'color' => array(231)),
  12682. 'R' => array('width' => $bw, 'cap' => 'square', 'join' => 'miter', 'dash' => 0, 'color' => array(51)),
  12683. 'T' => array('width' => $bw, 'cap' => 'square', 'join' => 'miter', 'dash' => 0, 'color' => array(231)),
  12684. 'B' => array('width' => $bw, 'cap' => 'square', 'join' => 'miter', 'dash' => 0, 'color' => array(51)));
  12685. $this->SetFillColor(204);
  12686. $this->Cell($w, $h, $caption, $border, 0, 'C', true, '', 1, false, 'T', 'M');
  12687. $this->endTemplate();
  12688. --$this->n;
  12689. $popt['ap']['n'] .= $this->xobjects[$tmpid]['outdata'];
  12690. unset($this->xobjects[$tmpid]);
  12691. $popt['ap']['n'] .= 'Q EMC';
  12692. // set additional default options
  12693. if (!isset($popt['mk'])) {
  12694. $popt['mk'] = array();
  12695. }
  12696. $ann_obj_id = ($this->n + 1);
  12697. if (!empty($action) AND !is_array($action)) {
  12698. $ann_obj_id = ($this->n + 2);
  12699. }
  12700. $popt['mk']['ca'] = $this->_textstring($caption, $ann_obj_id);
  12701. $popt['mk']['rc'] = $this->_textstring($caption, $ann_obj_id);
  12702. $popt['mk']['ac'] = $this->_textstring($caption, $ann_obj_id);
  12703. // merge options
  12704. $opt = array_merge($popt, $opt);
  12705. // set remaining annotation data
  12706. $opt['Subtype'] = 'Widget';
  12707. $opt['ft'] = 'Btn';
  12708. $opt['t'] = $caption;
  12709. $opt['v'] = $name;
  12710. if (!empty($action)) {
  12711. if (is_array($action)) {
  12712. // form action options as on section 12.7.5 of PDF32000_2008.
  12713. $opt['aa'] = '/D <<';
  12714. $bmode = array('SubmitForm', 'ResetForm', 'ImportData');
  12715. foreach ($action AS $key => $val) {
  12716. if (($key == 'S') AND in_array($val, $bmode)) {
  12717. $opt['aa'] .= ' /S /'.$val;
  12718. } elseif (($key == 'F') AND (!empty($val))) {
  12719. $opt['aa'] .= ' /F '.$this->_datastring($val, $ann_obj_id);
  12720. } elseif (($key == 'Fields') AND is_array($val) AND !empty($val)) {
  12721. $opt['aa'] .= ' /Fields [';
  12722. foreach ($val AS $field) {
  12723. $opt['aa'] .= ' '.$this->_textstring($field, $ann_obj_id);
  12724. }
  12725. $opt['aa'] .= ']';
  12726. } elseif (($key == 'Flags')) {
  12727. $ff = 0;
  12728. if (is_array($val)) {
  12729. foreach ($val AS $flag) {
  12730. switch ($flag) {
  12731. case 'Include/Exclude': {
  12732. $ff += 1 << 0;
  12733. break;
  12734. }
  12735. case 'IncludeNoValueFields': {
  12736. $ff += 1 << 1;
  12737. break;
  12738. }
  12739. case 'ExportFormat': {
  12740. $ff += 1 << 2;
  12741. break;
  12742. }
  12743. case 'GetMethod': {
  12744. $ff += 1 << 3;
  12745. break;
  12746. }
  12747. case 'SubmitCoordinates': {
  12748. $ff += 1 << 4;
  12749. break;
  12750. }
  12751. case 'XFDF': {
  12752. $ff += 1 << 5;
  12753. break;
  12754. }
  12755. case 'IncludeAppendSaves': {
  12756. $ff += 1 << 6;
  12757. break;
  12758. }
  12759. case 'IncludeAnnotations': {
  12760. $ff += 1 << 7;
  12761. break;
  12762. }
  12763. case 'SubmitPDF': {
  12764. $ff += 1 << 8;
  12765. break;
  12766. }
  12767. case 'CanonicalFormat': {
  12768. $ff += 1 << 9;
  12769. break;
  12770. }
  12771. case 'ExclNonUserAnnots': {
  12772. $ff += 1 << 10;
  12773. break;
  12774. }
  12775. case 'ExclFKey': {
  12776. $ff += 1 << 11;
  12777. break;
  12778. }
  12779. case 'EmbedForm': {
  12780. $ff += 1 << 13;
  12781. break;
  12782. }
  12783. }
  12784. }
  12785. } else {
  12786. $ff = intval($val);
  12787. }
  12788. $opt['aa'] .= ' /Flags '.$ff;
  12789. }
  12790. }
  12791. $opt['aa'] .= ' >>';
  12792. } else {
  12793. // Javascript action or raw action command
  12794. $js_obj_id = $this->addJavascriptObject($action);
  12795. $opt['aa'] = '/D '.$js_obj_id.' 0 R';
  12796. }
  12797. }
  12798. $this->Annotation($x, $y, $w, $h, $name, $opt, 0);
  12799. if ($this->rtl) {
  12800. $this->x -= $w;
  12801. } else {
  12802. $this->x += $w;
  12803. }
  12804. }
  12805. // --- END FORMS FIELDS ------------------------------------------------
  12806. /**
  12807. * Add certification signature (DocMDP or UR3)
  12808. * You can set only one signature type
  12809. * @protected
  12810. * @author Nicola Asuni
  12811. * @since 4.6.008 (2009-05-07)
  12812. */
  12813. protected function _putsignature() {
  12814. if ((!$this->sign) OR (!isset($this->signature_data['cert_type']))) {
  12815. return;
  12816. }
  12817. $sigobjid = ($this->sig_obj_id + 1);
  12818. $out = $this->_getobj($sigobjid)."\n";
  12819. $out .= '<< /Type /Sig';
  12820. $out .= ' /Filter /Adobe.PPKLite';
  12821. $out .= ' /SubFilter /adbe.pkcs7.detached';
  12822. $out .= ' '.TCPDF_STATIC::$byterange_string;
  12823. $out .= ' /Contents<'.str_repeat('0', $this->signature_max_length).'>';
  12824. if (empty($this->signature_data['approval']) OR ($this->signature_data['approval'] != 'A')) {
  12825. $out .= ' /Reference ['; // array of signature reference dictionaries
  12826. $out .= ' << /Type /SigRef';
  12827. if ($this->signature_data['cert_type'] > 0) {
  12828. $out .= ' /TransformMethod /DocMDP';
  12829. $out .= ' /TransformParams <<';
  12830. $out .= ' /Type /TransformParams';
  12831. $out .= ' /P '.$this->signature_data['cert_type'];
  12832. $out .= ' /V /1.2';
  12833. } else {
  12834. $out .= ' /TransformMethod /UR3';
  12835. $out .= ' /TransformParams <<';
  12836. $out .= ' /Type /TransformParams';
  12837. $out .= ' /V /2.2';
  12838. if (!TCPDF_STATIC::empty_string($this->ur['document'])) {
  12839. $out .= ' /Document['.$this->ur['document'].']';
  12840. }
  12841. if (!TCPDF_STATIC::empty_string($this->ur['form'])) {
  12842. $out .= ' /Form['.$this->ur['form'].']';
  12843. }
  12844. if (!TCPDF_STATIC::empty_string($this->ur['signature'])) {
  12845. $out .= ' /Signature['.$this->ur['signature'].']';
  12846. }
  12847. if (!TCPDF_STATIC::empty_string($this->ur['annots'])) {
  12848. $out .= ' /Annots['.$this->ur['annots'].']';
  12849. }
  12850. if (!TCPDF_STATIC::empty_string($this->ur['ef'])) {
  12851. $out .= ' /EF['.$this->ur['ef'].']';
  12852. }
  12853. if (!TCPDF_STATIC::empty_string($this->ur['formex'])) {
  12854. $out .= ' /FormEX['.$this->ur['formex'].']';
  12855. }
  12856. }
  12857. $out .= ' >>'; // close TransformParams
  12858. // optional digest data (values must be calculated and replaced later)
  12859. //$out .= ' /Data ********** 0 R';
  12860. //$out .= ' /DigestMethod/MD5';
  12861. //$out .= ' /DigestLocation[********** 34]';
  12862. //$out .= ' /DigestValue<********************************>';
  12863. $out .= ' >>';
  12864. $out .= ' ]'; // end of reference
  12865. }
  12866. if (isset($this->signature_data['info']['Name']) AND !TCPDF_STATIC::empty_string($this->signature_data['info']['Name'])) {
  12867. $out .= ' /Name '.$this->_textstring($this->signature_data['info']['Name'], $sigobjid);
  12868. }
  12869. if (isset($this->signature_data['info']['Location']) AND !TCPDF_STATIC::empty_string($this->signature_data['info']['Location'])) {
  12870. $out .= ' /Location '.$this->_textstring($this->signature_data['info']['Location'], $sigobjid);
  12871. }
  12872. if (isset($this->signature_data['info']['Reason']) AND !TCPDF_STATIC::empty_string($this->signature_data['info']['Reason'])) {
  12873. $out .= ' /Reason '.$this->_textstring($this->signature_data['info']['Reason'], $sigobjid);
  12874. }
  12875. if (isset($this->signature_data['info']['ContactInfo']) AND !TCPDF_STATIC::empty_string($this->signature_data['info']['ContactInfo'])) {
  12876. $out .= ' /ContactInfo '.$this->_textstring($this->signature_data['info']['ContactInfo'], $sigobjid);
  12877. }
  12878. $out .= ' /M '.$this->_datestring($sigobjid, $this->doc_modification_timestamp);
  12879. $out .= ' >>';
  12880. $out .= "\n".'endobj';
  12881. $this->_out($out);
  12882. }
  12883. /**
  12884. * Set User's Rights for PDF Reader
  12885. * WARNING: This is experimental and currently do not work.
  12886. * Check the PDF Reference 8.7.1 Transform Methods,
  12887. * Table 8.105 Entries in the UR transform parameters dictionary
  12888. * @param $enable (boolean) if true enable user's rights on PDF reader
  12889. * @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.
  12890. * @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.
  12891. * @param $form (string) Names specifying additional form-field-related usage rights for the document. Valid names are: /Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate
  12892. * @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.
  12893. * @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
  12894. Names specifying additional embedded-files-related usage rights for the document.
  12895. * @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.
  12896. * @public
  12897. * @author Nicola Asuni
  12898. * @since 2.9.000 (2008-03-26)
  12899. */
  12900. public function setUserRights(
  12901. $enable=true,
  12902. $document='/FullSave',
  12903. $annots='/Create/Delete/Modify/Copy/Import/Export',
  12904. $form='/Add/Delete/FillIn/Import/Export/SubmitStandalone/SpawnTemplate',
  12905. $signature='/Modify',
  12906. $ef='/Create/Delete/Modify/Import',
  12907. $formex='') {
  12908. $this->ur['enabled'] = $enable;
  12909. $this->ur['document'] = $document;
  12910. $this->ur['annots'] = $annots;
  12911. $this->ur['form'] = $form;
  12912. $this->ur['signature'] = $signature;
  12913. $this->ur['ef'] = $ef;
  12914. $this->ur['formex'] = $formex;
  12915. if (!$this->sign) {
  12916. $this->setSignature('', '', '', '', 0, array());
  12917. }
  12918. }
  12919. /**
  12920. * Enable document signature (requires the OpenSSL Library).
  12921. * The digital signature improve document authenticity and integrity and allows o enable extra features on Acrobat Reader.
  12922. * To create self-signed signature: openssl req -x509 -nodes -days 365000 -newkey rsa:1024 -keyout tcpdf.crt -out tcpdf.crt
  12923. * To export crt to p12: openssl pkcs12 -export -in tcpdf.crt -out tcpdf.p12
  12924. * To convert pfx certificate to pem: openssl pkcs12 -in tcpdf.pfx -out tcpdf.crt -nodes
  12925. * @param $signing_cert (mixed) signing certificate (string or filename prefixed with 'file://')
  12926. * @param $private_key (mixed) private key (string or filename prefixed with 'file://')
  12927. * @param $private_key_password (string) password
  12928. * @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.
  12929. * @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.
  12930. * @param $info (array) array of option information: Name, Location, Reason, ContactInfo.
  12931. * @param $approval (string) Enable approval signature eg. for PDF incremental update
  12932. * @public
  12933. * @author Nicola Asuni
  12934. * @since 4.6.005 (2009-04-24)
  12935. */
  12936. public function setSignature($signing_cert='', $private_key='', $private_key_password='', $extracerts='', $cert_type=2, $info=array(), $approval='') {
  12937. // to create self-signed signature: openssl req -x509 -nodes -days 365000 -newkey rsa:1024 -keyout tcpdf.crt -out tcpdf.crt
  12938. // to export crt to p12: openssl pkcs12 -export -in tcpdf.crt -out tcpdf.p12
  12939. // to convert pfx certificate to pem: openssl
  12940. // OpenSSL> pkcs12 -in <cert.pfx> -out <cert.crt> -nodes
  12941. $this->sign = true;
  12942. ++$this->n;
  12943. $this->sig_obj_id = $this->n; // signature widget
  12944. ++$this->n; // signature object ($this->sig_obj_id + 1)
  12945. $this->signature_data = array();
  12946. if (strlen($signing_cert) == 0) {
  12947. $this->Error('Please provide a certificate file and password!');
  12948. }
  12949. if (strlen($private_key) == 0) {
  12950. $private_key = $signing_cert;
  12951. }
  12952. $this->signature_data['signcert'] = $signing_cert;
  12953. $this->signature_data['privkey'] = $private_key;
  12954. $this->signature_data['password'] = $private_key_password;
  12955. $this->signature_data['extracerts'] = $extracerts;
  12956. $this->signature_data['cert_type'] = $cert_type;
  12957. $this->signature_data['info'] = $info;
  12958. $this->signature_data['approval'] = $approval;
  12959. }
  12960. /**
  12961. * Set the digital signature appearance (a cliccable rectangle area to get signature properties)
  12962. * @param $x (float) Abscissa of the upper-left corner.
  12963. * @param $y (float) Ordinate of the upper-left corner.
  12964. * @param $w (float) Width of the signature area.
  12965. * @param $h (float) Height of the signature area.
  12966. * @param $page (int) option page number (if < 0 the current page is used).
  12967. * @param $name (string) Name of the signature.
  12968. * @public
  12969. * @author Nicola Asuni
  12970. * @since 5.3.011 (2010-06-17)
  12971. */
  12972. public function setSignatureAppearance($x=0, $y=0, $w=0, $h=0, $page=-1, $name='') {
  12973. $this->signature_appearance = $this->getSignatureAppearanceArray($x, $y, $w, $h, $page, $name);
  12974. }
  12975. /**
  12976. * Add an empty digital signature appearance (a cliccable rectangle area to get signature properties)
  12977. * @param $x (float) Abscissa of the upper-left corner.
  12978. * @param $y (float) Ordinate of the upper-left corner.
  12979. * @param $w (float) Width of the signature area.
  12980. * @param $h (float) Height of the signature area.
  12981. * @param $page (int) option page number (if < 0 the current page is used).
  12982. * @param $name (string) Name of the signature.
  12983. * @public
  12984. * @author Nicola Asuni
  12985. * @since 5.9.101 (2011-07-06)
  12986. */
  12987. public function addEmptySignatureAppearance($x=0, $y=0, $w=0, $h=0, $page=-1, $name='') {
  12988. ++$this->n;
  12989. $this->empty_signature_appearance[] = array('objid' => $this->n) + $this->getSignatureAppearanceArray($x, $y, $w, $h, $page, $name);
  12990. }
  12991. /**
  12992. * Get the array that defines the signature appearance (page and rectangle coordinates).
  12993. * @param $x (float) Abscissa of the upper-left corner.
  12994. * @param $y (float) Ordinate of the upper-left corner.
  12995. * @param $w (float) Width of the signature area.
  12996. * @param $h (float) Height of the signature area.
  12997. * @param $page (int) option page number (if < 0 the current page is used).
  12998. * @param $name (string) Name of the signature.
  12999. * @return (array) Array defining page and rectangle coordinates of signature appearance.
  13000. * @protected
  13001. * @author Nicola Asuni
  13002. * @since 5.9.101 (2011-07-06)
  13003. */
  13004. protected function getSignatureAppearanceArray($x=0, $y=0, $w=0, $h=0, $page=-1, $name='') {
  13005. $sigapp = array();
  13006. if (($page < 1) OR ($page > $this->numpages)) {
  13007. $sigapp['page'] = $this->page;
  13008. } else {
  13009. $sigapp['page'] = intval($page);
  13010. }
  13011. if (empty($name)) {
  13012. $sigapp['name'] = 'Signature';
  13013. } else {
  13014. $sigapp['name'] = $name;
  13015. }
  13016. $a = $x * $this->k;
  13017. $b = $this->pagedim[($sigapp['page'])]['h'] - (($y + $h) * $this->k);
  13018. $c = $w * $this->k;
  13019. $d = $h * $this->k;
  13020. $sigapp['rect'] = sprintf('%F %F %F %F', $a, $b, ($a + $c), ($b + $d));
  13021. return $sigapp;
  13022. }
  13023. /**
  13024. * Enable document timestamping (requires the OpenSSL Library).
  13025. * The trusted timestamping improve document security that means that no one should be able to change the document once it has been recorded.
  13026. * Use with digital signature only!
  13027. * @param $tsa_host (string) Time Stamping Authority (TSA) server (prefixed with 'https://')
  13028. * @param $tsa_username (string) Specifies the username for TSA authorization (optional) OR specifies the TSA authorization PEM file (see: example_66.php, optional)
  13029. * @param $tsa_password (string) Specifies the password for TSA authorization (optional)
  13030. * @param $tsa_cert (string) Specifies the location of TSA certificate for authorization (optional for cURL)
  13031. * @public
  13032. * @author Richard Stockinger
  13033. * @since 6.0.090 (2014-06-16)
  13034. */
  13035. public function setTimeStamp($tsa_host='', $tsa_username='', $tsa_password='', $tsa_cert='') {
  13036. $this->tsa_data = array();
  13037. if (!function_exists('curl_init')) {
  13038. $this->Error('Please enable cURL PHP extension!');
  13039. }
  13040. if (strlen($tsa_host) == 0) {
  13041. $this->Error('Please specify the host of Time Stamping Authority (TSA)!');
  13042. }
  13043. $this->tsa_data['tsa_host'] = $tsa_host;
  13044. if (is_file($tsa_username)) {
  13045. $this->tsa_data['tsa_auth'] = $tsa_username;
  13046. } else {
  13047. $this->tsa_data['tsa_username'] = $tsa_username;
  13048. }
  13049. $this->tsa_data['tsa_password'] = $tsa_password;
  13050. $this->tsa_data['tsa_cert'] = $tsa_cert;
  13051. $this->tsa_timestamp = true;
  13052. }
  13053. /**
  13054. * NOT YET IMPLEMENTED
  13055. * Request TSA for a timestamp
  13056. * @param $signature (string) Digital signature as binary string
  13057. * @return (string) Timestamped digital signature
  13058. * @protected
  13059. * @author Richard Stockinger
  13060. * @since 6.0.090 (2014-06-16)
  13061. */
  13062. protected function applyTSA($signature) {
  13063. if (!$this->tsa_timestamp) {
  13064. return $signature;
  13065. }
  13066. //@TODO: implement this feature
  13067. return $signature;
  13068. }
  13069. /**
  13070. * Create a new page group.
  13071. * NOTE: call this function before calling AddPage()
  13072. * @param $page (int) starting group page (leave empty for next page).
  13073. * @public
  13074. * @since 3.0.000 (2008-03-27)
  13075. */
  13076. public function startPageGroup($page='') {
  13077. if (empty($page)) {
  13078. $page = $this->page + 1;
  13079. }
  13080. $this->newpagegroup[$page] = sizeof($this->newpagegroup) + 1;
  13081. }
  13082. /**
  13083. * Set the starting page number.
  13084. * @param $num (int) Starting page number.
  13085. * @since 5.9.093 (2011-06-16)
  13086. * @public
  13087. */
  13088. public function setStartingPageNumber($num=1) {
  13089. $this->starting_page_number = max(0, intval($num));
  13090. }
  13091. /**
  13092. * Returns the string alias used right align page numbers.
  13093. * If the current font is unicode type, the returned string wil contain an additional open curly brace.
  13094. * @return string
  13095. * @since 5.9.099 (2011-06-27)
  13096. * @public
  13097. */
  13098. public function getAliasRightShift() {
  13099. // calculate aproximatively the ratio between widths of aliases and replacements.
  13100. $ref = '{'.TCPDF_STATIC::$alias_right_shift.'}{'.TCPDF_STATIC::$alias_tot_pages.'}{'.TCPDF_STATIC::$alias_num_page.'}';
  13101. $rep = str_repeat(' ', $this->GetNumChars($ref));
  13102. $wrep = $this->GetStringWidth($rep);
  13103. if ($wrep > 0) {
  13104. $wdiff = max(1, ($this->GetStringWidth($ref) / $wrep));
  13105. } else {
  13106. $wdiff = 1;
  13107. }
  13108. $sdiff = sprintf('%F', $wdiff);
  13109. $alias = TCPDF_STATIC::$alias_right_shift.$sdiff.'}';
  13110. if ($this->isUnicodeFont()) {
  13111. $alias = '{'.$alias;
  13112. }
  13113. return $alias;
  13114. }
  13115. /**
  13116. * Returns the string alias used for the total number of pages.
  13117. * If the current font is unicode type, the returned string is surrounded by additional curly braces.
  13118. * This alias will be replaced by the total number of pages in the document.
  13119. * @return string
  13120. * @since 4.0.018 (2008-08-08)
  13121. * @public
  13122. */
  13123. public function getAliasNbPages() {
  13124. if ($this->isUnicodeFont()) {
  13125. return '{'.TCPDF_STATIC::$alias_tot_pages.'}';
  13126. }
  13127. return TCPDF_STATIC::$alias_tot_pages;
  13128. }
  13129. /**
  13130. * Returns the string alias used for the page number.
  13131. * If the current font is unicode type, the returned string is surrounded by additional curly braces.
  13132. * This alias will be replaced by the page number.
  13133. * @return string
  13134. * @since 4.5.000 (2009-01-02)
  13135. * @public
  13136. */
  13137. public function getAliasNumPage() {
  13138. if ($this->isUnicodeFont()) {
  13139. return '{'.TCPDF_STATIC::$alias_num_page.'}';
  13140. }
  13141. return TCPDF_STATIC::$alias_num_page;
  13142. }
  13143. /**
  13144. * Return the alias for the total number of pages in the current page group.
  13145. * If the current font is unicode type, the returned string is surrounded by additional curly braces.
  13146. * This alias will be replaced by the total number of pages in this group.
  13147. * @return alias of the current page group
  13148. * @public
  13149. * @since 3.0.000 (2008-03-27)
  13150. */
  13151. public function getPageGroupAlias() {
  13152. if ($this->isUnicodeFont()) {
  13153. return '{'.TCPDF_STATIC::$alias_group_tot_pages.'}';
  13154. }
  13155. return TCPDF_STATIC::$alias_group_tot_pages;
  13156. }
  13157. /**
  13158. * Return the alias for the page number on the current page group.
  13159. * If the current font is unicode type, the returned string is surrounded by additional curly braces.
  13160. * This alias will be replaced by the page number (relative to the belonging group).
  13161. * @return alias of the current page group
  13162. * @public
  13163. * @since 4.5.000 (2009-01-02)
  13164. */
  13165. public function getPageNumGroupAlias() {
  13166. if ($this->isUnicodeFont()) {
  13167. return '{'.TCPDF_STATIC::$alias_group_num_page.'}';
  13168. }
  13169. return TCPDF_STATIC::$alias_group_num_page;
  13170. }
  13171. /**
  13172. * Return the current page in the group.
  13173. * @return current page in the group
  13174. * @public
  13175. * @since 3.0.000 (2008-03-27)
  13176. */
  13177. public function getGroupPageNo() {
  13178. return $this->pagegroups[$this->currpagegroup];
  13179. }
  13180. /**
  13181. * Returns the current group page number formatted as a string.
  13182. * @public
  13183. * @since 4.3.003 (2008-11-18)
  13184. * @see PaneNo(), formatPageNumber()
  13185. */
  13186. public function getGroupPageNoFormatted() {
  13187. return TCPDF_STATIC::formatPageNumber($this->getGroupPageNo());
  13188. }
  13189. /**
  13190. * Returns the current page number formatted as a string.
  13191. * @public
  13192. * @since 4.2.005 (2008-11-06)
  13193. * @see PaneNo(), formatPageNumber()
  13194. */
  13195. public function PageNoFormatted() {
  13196. return TCPDF_STATIC::formatPageNumber($this->PageNo());
  13197. }
  13198. /**
  13199. * Put pdf layers.
  13200. * @protected
  13201. * @since 3.0.000 (2008-03-27)
  13202. */
  13203. protected function _putocg() {
  13204. if (empty($this->pdflayers)) {
  13205. return;
  13206. }
  13207. foreach ($this->pdflayers as $key => $layer) {
  13208. $this->pdflayers[$key]['objid'] = $this->_newobj();
  13209. $out = '<< /Type /OCG';
  13210. $out .= ' /Name '.$this->_textstring($layer['name'], $this->pdflayers[$key]['objid']);
  13211. $out .= ' /Usage <<';
  13212. if (isset($layer['print']) AND ($layer['print'] !== NULL)) {
  13213. $out .= ' /Print <</PrintState /'.($layer['print']?'ON':'OFF').'>>';
  13214. }
  13215. $out .= ' /View <</ViewState /'.($layer['view']?'ON':'OFF').'>>';
  13216. $out .= ' >> >>';
  13217. $out .= "\n".'endobj';
  13218. $this->_out($out);
  13219. }
  13220. }
  13221. /**
  13222. * Start a new pdf layer.
  13223. * @param $name (string) Layer name (only a-z letters and numbers). Leave empty for automatic name.
  13224. * @param $print (boolean|null) Set to TRUE to print this layer, FALSE to not print and NULL to not set this option
  13225. * @param $view (boolean) Set to true to view this layer.
  13226. * @param $lock (boolean) If true lock the layer
  13227. * @public
  13228. * @since 5.9.102 (2011-07-13)
  13229. */
  13230. public function startLayer($name='', $print=true, $view=true, $lock=true) {
  13231. if ($this->state != 2) {
  13232. return;
  13233. }
  13234. $layer = sprintf('LYR%03d', (count($this->pdflayers) + 1));
  13235. if (empty($name)) {
  13236. $name = $layer;
  13237. } else {
  13238. $name = preg_replace('/[^a-zA-Z0-9_\-]/', '', $name);
  13239. }
  13240. $this->pdflayers[] = array('layer' => $layer, 'name' => $name, 'print' => $print, 'view' => $view, 'lock' => $lock);
  13241. $this->openMarkedContent = true;
  13242. $this->_out('/OC /'.$layer.' BDC');
  13243. }
  13244. /**
  13245. * End the current PDF layer.
  13246. * @public
  13247. * @since 5.9.102 (2011-07-13)
  13248. */
  13249. public function endLayer() {
  13250. if ($this->state != 2) {
  13251. return;
  13252. }
  13253. if ($this->openMarkedContent) {
  13254. // close existing open marked-content layer
  13255. $this->_out('EMC');
  13256. $this->openMarkedContent = false;
  13257. }
  13258. }
  13259. /**
  13260. * Set the visibility of the successive elements.
  13261. * This can be useful, for instance, to put a background
  13262. * image or color that will show on screen but won't print.
  13263. * @param $v (string) visibility mode. Legal values are: all, print, screen or view.
  13264. * @public
  13265. * @since 3.0.000 (2008-03-27)
  13266. */
  13267. public function setVisibility($v) {
  13268. if ($this->state != 2) {
  13269. return;
  13270. }
  13271. $this->endLayer();
  13272. switch($v) {
  13273. case 'print': {
  13274. $this->startLayer('Print', true, false);
  13275. break;
  13276. }
  13277. case 'view':
  13278. case 'screen': {
  13279. $this->startLayer('View', false, true);
  13280. break;
  13281. }
  13282. case 'all': {
  13283. $this->_out('');
  13284. break;
  13285. }
  13286. default: {
  13287. $this->Error('Incorrect visibility: '.$v);
  13288. break;
  13289. }
  13290. }
  13291. }
  13292. /**
  13293. * Add transparency parameters to the current extgstate
  13294. * @param $parms (array) parameters
  13295. * @return the number of extgstates
  13296. * @protected
  13297. * @since 3.0.000 (2008-03-27)
  13298. */
  13299. protected function addExtGState($parms) {
  13300. if ($this->pdfa_mode) {
  13301. // transparencies are not allowed in PDF/A mode
  13302. return;
  13303. }
  13304. // check if this ExtGState already exist
  13305. foreach ($this->extgstates as $i => $ext) {
  13306. if ($ext['parms'] == $parms) {
  13307. if ($this->inxobj) {
  13308. // we are inside an XObject template
  13309. $this->xobjects[$this->xobjid]['extgstates'][$i] = $ext;
  13310. }
  13311. // return reference to existing ExtGState
  13312. return $i;
  13313. }
  13314. }
  13315. $n = (count($this->extgstates) + 1);
  13316. $this->extgstates[$n] = array('parms' => $parms);
  13317. if ($this->inxobj) {
  13318. // we are inside an XObject template
  13319. $this->xobjects[$this->xobjid]['extgstates'][$n] = $this->extgstates[$n];
  13320. }
  13321. return $n;
  13322. }
  13323. /**
  13324. * Add an extgstate
  13325. * @param $gs (array) extgstate
  13326. * @protected
  13327. * @since 3.0.000 (2008-03-27)
  13328. */
  13329. protected function setExtGState($gs) {
  13330. if ($this->pdfa_mode OR ($this->state != 2)) {
  13331. // transparency is not allowed in PDF/A mode
  13332. return;
  13333. }
  13334. $this->_out(sprintf('/GS%d gs', $gs));
  13335. }
  13336. /**
  13337. * Put extgstates for object transparency
  13338. * @protected
  13339. * @since 3.0.000 (2008-03-27)
  13340. */
  13341. protected function _putextgstates() {
  13342. foreach ($this->extgstates as $i => $ext) {
  13343. $this->extgstates[$i]['n'] = $this->_newobj();
  13344. $out = '<< /Type /ExtGState';
  13345. foreach ($ext['parms'] as $k => $v) {
  13346. if (is_float($v)) {
  13347. $v = sprintf('%F', $v);
  13348. } elseif ($v === true) {
  13349. $v = 'true';
  13350. } elseif ($v === false) {
  13351. $v = 'false';
  13352. }
  13353. $out .= ' /'.$k.' '.$v;
  13354. }
  13355. $out .= ' >>';
  13356. $out .= "\n".'endobj';
  13357. $this->_out($out);
  13358. }
  13359. }
  13360. /**
  13361. * Set overprint mode for stroking (OP) and non-stroking (op) painting operations.
  13362. * (Check the "Entries in a Graphics State Parameter Dictionary" on PDF 32000-1:2008).
  13363. * @param $stroking (boolean) If true apply overprint for stroking operations.
  13364. * @param $nonstroking (boolean) If true apply overprint for painting operations other than stroking.
  13365. * @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).
  13366. * @public
  13367. * @since 5.9.152 (2012-03-23)
  13368. */
  13369. public function setOverprint($stroking=true, $nonstroking='', $mode=0) {
  13370. if ($this->state != 2) {
  13371. return;
  13372. }
  13373. $stroking = $stroking ? true : false;
  13374. if (TCPDF_STATIC::empty_string($nonstroking)) {
  13375. // default value if not set
  13376. $nonstroking = $stroking;
  13377. } else {
  13378. $nonstroking = $nonstroking ? true : false;
  13379. }
  13380. if (($mode != 0) AND ($mode != 1)) {
  13381. $mode = 0;
  13382. }
  13383. $this->overprint = array('OP' => $stroking, 'op' => $nonstroking, 'OPM' => $mode);
  13384. $gs = $this->addExtGState($this->overprint);
  13385. $this->setExtGState($gs);
  13386. }
  13387. /**
  13388. * Get the overprint mode array (OP, op, OPM).
  13389. * (Check the "Entries in a Graphics State Parameter Dictionary" on PDF 32000-1:2008).
  13390. * @return array.
  13391. * @public
  13392. * @since 5.9.152 (2012-03-23)
  13393. */
  13394. public function getOverprint() {
  13395. return $this->overprint;
  13396. }
  13397. /**
  13398. * Set alpha for stroking (CA) and non-stroking (ca) operations.
  13399. * @param $stroking (float) Alpha value for stroking operations: real value from 0 (transparent) to 1 (opaque).
  13400. * @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
  13401. * @param $nonstroking (float) Alpha value for non-stroking operations: real value from 0 (transparent) to 1 (opaque).
  13402. * @param $ais (boolean)
  13403. * @public
  13404. * @since 3.0.000 (2008-03-27)
  13405. */
  13406. public function setAlpha($stroking=1, $bm='Normal', $nonstroking='', $ais=false) {
  13407. if ($this->pdfa_mode) {
  13408. // transparency is not allowed in PDF/A mode
  13409. return;
  13410. }
  13411. $stroking = floatval($stroking);
  13412. if (TCPDF_STATIC::empty_string($nonstroking)) {
  13413. // default value if not set
  13414. $nonstroking = $stroking;
  13415. } else {
  13416. $nonstroking = floatval($nonstroking);
  13417. }
  13418. if ($bm[0] == '/') {
  13419. // remove trailing slash
  13420. $bm = substr($bm, 1);
  13421. }
  13422. if (!in_array($bm, array('Normal', 'Multiply', 'Screen', 'Overlay', 'Darken', 'Lighten', 'ColorDodge', 'ColorBurn', 'HardLight', 'SoftLight', 'Difference', 'Exclusion', 'Hue', 'Saturation', 'Color', 'Luminosity'))) {
  13423. $bm = 'Normal';
  13424. }
  13425. $ais = $ais ? true : false;
  13426. $this->alpha = array('CA' => $stroking, 'ca' => $nonstroking, 'BM' => '/'.$bm, 'AIS' => $ais);
  13427. $gs = $this->addExtGState($this->alpha);
  13428. $this->setExtGState($gs);
  13429. }
  13430. /**
  13431. * Get the alpha mode array (CA, ca, BM, AIS).
  13432. * (Check the "Entries in a Graphics State Parameter Dictionary" on PDF 32000-1:2008).
  13433. * @return array.
  13434. * @public
  13435. * @since 5.9.152 (2012-03-23)
  13436. */
  13437. public function getAlpha() {
  13438. return $this->alpha;
  13439. }
  13440. /**
  13441. * Set the default JPEG compression quality (1-100)
  13442. * @param $quality (int) JPEG quality, integer between 1 and 100
  13443. * @public
  13444. * @since 3.0.000 (2008-03-27)
  13445. */
  13446. public function setJPEGQuality($quality) {
  13447. if (($quality < 1) OR ($quality > 100)) {
  13448. $quality = 75;
  13449. }
  13450. $this->jpeg_quality = intval($quality);
  13451. }
  13452. /**
  13453. * Set the default number of columns in a row for HTML tables.
  13454. * @param $cols (int) number of columns
  13455. * @public
  13456. * @since 3.0.014 (2008-06-04)
  13457. */
  13458. public function setDefaultTableColumns($cols=4) {
  13459. $this->default_table_columns = intval($cols);
  13460. }
  13461. /**
  13462. * Set the height of the cell (line height) respect the font height.
  13463. * @param $h (int) cell proportion respect font height (typical value = 1.25).
  13464. * @public
  13465. * @since 3.0.014 (2008-06-04)
  13466. */
  13467. public function setCellHeightRatio($h) {
  13468. $this->cell_height_ratio = $h;
  13469. }
  13470. /**
  13471. * return the height of cell repect font height.
  13472. * @public
  13473. * @since 4.0.012 (2008-07-24)
  13474. */
  13475. public function getCellHeightRatio() {
  13476. return $this->cell_height_ratio;
  13477. }
  13478. /**
  13479. * Set the PDF version (check PDF reference for valid values).
  13480. * @param $version (string) PDF document version.
  13481. * @public
  13482. * @since 3.1.000 (2008-06-09)
  13483. */
  13484. public function setPDFVersion($version='1.7') {
  13485. if ($this->pdfa_mode && $this->pdfa_version == 1 ) {
  13486. // PDF/A mode
  13487. $this->PDFVersion = '1.4';
  13488. } else {
  13489. $this->PDFVersion = $version;
  13490. }
  13491. }
  13492. /**
  13493. * Set the viewer preferences dictionary controlling the way the document is to be presented on the screen or in print.
  13494. * (see Section 8.1 of PDF reference, "Viewer Preferences").
  13495. * <ul><li>HideToolbar boolean (Optional) A flag specifying whether to hide the viewer application's tool bars when the document is active. Default value: false.</li><li>HideMenubar boolean (Optional) A flag specifying whether to hide the viewer application's menu bar when the document is active. Default value: false.</li><li>HideWindowUI boolean (Optional) A flag specifying whether to hide user interface elements in the document's window (such as scroll bars and navigation controls), leaving only the document's contents displayed. Default value: false.</li><li>FitWindow boolean (Optional) A flag specifying whether to resize the document's window to fit the size of the first displayed page. Default value: false.</li><li>CenterWindow boolean (Optional) A flag specifying whether to position the document's window in the center of the screen. Default value: false.</li><li>DisplayDocTitle boolean (Optional; PDF 1.4) A flag specifying whether the window's title bar should display the document title taken from the Title entry of the document information dictionary (see Section 10.2.1, "Document Information Dictionary"). If false, the title bar should instead display the name of the PDF file containing the document. Default value: false.</li><li>NonFullScreenPageMode name (Optional) The document's page mode, specifying how to display the document on exiting full-screen mode:<ul><li>UseNone Neither document outline nor thumbnail images visible</li><li>UseOutlines Document outline visible</li><li>UseThumbs Thumbnail images visible</li><li>UseOC Optional content group panel visible</li></ul>This entry is meaningful only if the value of the PageMode entry in the catalog dictionary (see Section 3.6.1, "Document Catalog") is FullScreen; it is ignored otherwise. Default value: UseNone.</li><li>ViewArea name (Optional; PDF 1.4) The name of the page boundary representing the area of a page to be displayed when viewing the document on the screen. Valid values are (see Section 10.10.1, "Page Boundaries").:<ul><li>MediaBox</li><li>CropBox (default)</li><li>BleedBox</li><li>TrimBox</li><li>ArtBox</li></ul></li><li>ViewClip name (Optional; PDF 1.4) The name of the page boundary to which the contents of a page are to be clipped when viewing the document on the screen. Valid values are (see Section 10.10.1, "Page Boundaries").:<ul><li>MediaBox</li><li>CropBox (default)</li><li>BleedBox</li><li>TrimBox</li><li>ArtBox</li></ul></li><li>PrintArea name (Optional; PDF 1.4) The name of the page boundary representing the area of a page to be rendered when printing the document. Valid values are (see Section 10.10.1, "Page Boundaries").:<ul><li>MediaBox</li><li>CropBox (default)</li><li>BleedBox</li><li>TrimBox</li><li>ArtBox</li></ul></li><li>PrintClip name (Optional; PDF 1.4) The name of the page boundary to which the contents of a page are to be clipped when printing the document. Valid values are (see Section 10.10.1, "Page Boundaries").:<ul><li>MediaBox</li><li>CropBox (default)</li><li>BleedBox</li><li>TrimBox</li><li>ArtBox</li></ul></li><li>PrintScaling name (Optional; PDF 1.6) The page scaling option to be selected when a print dialog is displayed for this document. Valid values are: <ul><li>None, which indicates that the print dialog should reflect no page scaling</li><li>AppDefault (default), which indicates that applications should use the current print scaling</li></ul></li><li>Duplex name (Optional; PDF 1.7) The paper handling option to use when printing the file from the print dialog. The following values are valid:<ul><li>Simplex - Print single-sided</li><li>DuplexFlipShortEdge - Duplex and flip on the short edge of the sheet</li><li>DuplexFlipLongEdge - Duplex and flip on the long edge of the sheet</li></ul>Default value: none</li><li>PickTrayByPDFSize boolean (Optional; PDF 1.7) A flag specifying whether the PDF page size is used to select the input paper tray. This setting influences only the preset values used to populate the print dialog presented by a PDF viewer application. If PickTrayByPDFSize is true, the check box in the pri
  13496. * @param $preferences (array) array of options.
  13497. * @author Nicola Asuni
  13498. * @public
  13499. * @since 3.1.000 (2008-06-09)
  13500. */
  13501. public function setViewerPreferences($preferences) {
  13502. $this->viewer_preferences = $preferences;
  13503. }
  13504. /**
  13505. * Paints color transition registration bars
  13506. * @param $x (float) abscissa of the top left corner of the rectangle.
  13507. * @param $y (float) ordinate of the top left corner of the rectangle.
  13508. * @param $w (float) width of the rectangle.
  13509. * @param $h (float) height of the rectangle.
  13510. * @param $transition (boolean) if true prints tcolor transitions to white.
  13511. * @param $vertical (boolean) if true prints bar vertically.
  13512. * @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.
  13513. * @author Nicola Asuni
  13514. * @since 4.9.000 (2010-03-26)
  13515. * @public
  13516. */
  13517. public function colorRegistrationBar($x, $y, $w, $h, $transition=true, $vertical=false, $colors='A,R,G,B,C,M,Y,K') {
  13518. if (strpos($colors, 'ALLSPOT') !== false) {
  13519. // expand spot colors
  13520. $spot_colors = '';
  13521. foreach ($this->spot_colors as $spot_color_name => $v) {
  13522. $spot_colors .= ','.$spot_color_name;
  13523. }
  13524. if (!empty($spot_colors)) {
  13525. $spot_colors = substr($spot_colors, 1);
  13526. $colors = str_replace('ALLSPOT', $spot_colors, $colors);
  13527. } else {
  13528. $colors = str_replace('ALLSPOT', 'NONE', $colors);
  13529. }
  13530. }
  13531. $bars = explode(',', $colors);
  13532. $numbars = count($bars); // number of bars to print
  13533. if ($numbars <= 0) {
  13534. return;
  13535. }
  13536. // set bar measures
  13537. if ($vertical) {
  13538. $coords = array(0, 0, 0, 1);
  13539. $wb = $w / $numbars; // bar width
  13540. $hb = $h; // bar height
  13541. $xd = $wb; // delta x
  13542. $yd = 0; // delta y
  13543. } else {
  13544. $coords = array(1, 0, 0, 0);
  13545. $wb = $w; // bar width
  13546. $hb = $h / $numbars; // bar height
  13547. $xd = 0; // delta x
  13548. $yd = $hb; // delta y
  13549. }
  13550. $xb = $x;
  13551. $yb = $y;
  13552. foreach ($bars as $col) {
  13553. switch ($col) {
  13554. // set transition colors
  13555. case 'A': { // BLACK (GRAYSCALE)
  13556. $col_a = array(255);
  13557. $col_b = array(0);
  13558. break;
  13559. }
  13560. case 'W': { // WHITE (GRAYSCALE)
  13561. $col_a = array(0);
  13562. $col_b = array(255);
  13563. break;
  13564. }
  13565. case 'R': { // RED (RGB)
  13566. $col_a = array(255,255,255);
  13567. $col_b = array(255,0,0);
  13568. break;
  13569. }
  13570. case 'G': { // GREEN (RGB)
  13571. $col_a = array(255,255,255);
  13572. $col_b = array(0,255,0);
  13573. break;
  13574. }
  13575. case 'B': { // BLUE (RGB)
  13576. $col_a = array(255,255,255);
  13577. $col_b = array(0,0,255);
  13578. break;
  13579. }
  13580. case 'C': { // CYAN (CMYK)
  13581. $col_a = array(0,0,0,0);
  13582. $col_b = array(100,0,0,0);
  13583. break;
  13584. }
  13585. case 'M': { // MAGENTA (CMYK)
  13586. $col_a = array(0,0,0,0);
  13587. $col_b = array(0,100,0,0);
  13588. break;
  13589. }
  13590. case 'Y': { // YELLOW (CMYK)
  13591. $col_a = array(0,0,0,0);
  13592. $col_b = array(0,0,100,0);
  13593. break;
  13594. }
  13595. case 'K': { // KEY - BLACK (CMYK)
  13596. $col_a = array(0,0,0,0);
  13597. $col_b = array(0,0,0,100);
  13598. break;
  13599. }
  13600. case 'RGB': { // BLACK REGISTRATION (RGB)
  13601. $col_a = array(255,255,255);
  13602. $col_b = array(0,0,0);
  13603. break;
  13604. }
  13605. case 'CMYK': { // BLACK REGISTRATION (CMYK)
  13606. $col_a = array(0,0,0,0);
  13607. $col_b = array(100,100,100,100);
  13608. break;
  13609. }
  13610. case 'ALL': { // SPOT COLOR REGISTRATION
  13611. $col_a = array(0,0,0,0,'None');
  13612. $col_b = array(100,100,100,100,'All');
  13613. break;
  13614. }
  13615. case 'NONE': { // SKIP THIS COLOR
  13616. $col_a = array(0,0,0,0,'None');
  13617. $col_b = array(0,0,0,0,'None');
  13618. break;
  13619. }
  13620. default: { // SPECIFIC SPOT COLOR NAME
  13621. $col_a = array(0,0,0,0,'None');
  13622. $col_b = TCPDF_COLORS::getSpotColor($col, $this->spot_colors);
  13623. if ($col_b === false) {
  13624. // in case of error defaults to the registration color
  13625. $col_b = array(100,100,100,100,'All');
  13626. }
  13627. break;
  13628. }
  13629. }
  13630. if ($col != 'NONE') {
  13631. if ($transition) {
  13632. // color gradient
  13633. $this->LinearGradient($xb, $yb, $wb, $hb, $col_a, $col_b, $coords);
  13634. } else {
  13635. $this->SetFillColorArray($col_b);
  13636. // colored rectangle
  13637. $this->Rect($xb, $yb, $wb, $hb, 'F', array());
  13638. }
  13639. $xb += $xd;
  13640. $yb += $yd;
  13641. }
  13642. }
  13643. }
  13644. /**
  13645. * Paints crop marks.
  13646. * @param $x (float) abscissa of the crop mark center.
  13647. * @param $y (float) ordinate of the crop mark center.
  13648. * @param $w (float) width of the crop mark.
  13649. * @param $h (float) height of the crop mark.
  13650. * @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.
  13651. * @param $color (array) crop mark color (default spot registration color).
  13652. * @author Nicola Asuni
  13653. * @since 4.9.000 (2010-03-26)
  13654. * @public
  13655. */
  13656. public function cropMark($x, $y, $w, $h, $type='T,R,B,L', $color=array(100,100,100,100,'All')) {
  13657. $this->SetLineStyle(array('width' => (0.5 / $this->k), 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => $color));
  13658. $type = strtoupper($type);
  13659. $type = preg_replace('/[^A-Z\-\,]*/', '', $type);
  13660. // split type in single components
  13661. $type = str_replace('-', ',', $type);
  13662. $type = str_replace('TL', 'T,L', $type);
  13663. $type = str_replace('TR', 'T,R', $type);
  13664. $type = str_replace('BL', 'F,L', $type);
  13665. $type = str_replace('BR', 'F,R', $type);
  13666. $type = str_replace('A', 'T,L', $type);
  13667. $type = str_replace('B', 'T,R', $type);
  13668. $type = str_replace('T,RO', 'BO', $type);
  13669. $type = str_replace('C', 'F,L', $type);
  13670. $type = str_replace('D', 'F,R', $type);
  13671. $crops = explode(',', strtoupper($type));
  13672. // remove duplicates
  13673. $crops = array_unique($crops);
  13674. $dw = ($w / 4); // horizontal space to leave before the intersection point
  13675. $dh = ($h / 4); // vertical space to leave before the intersection point
  13676. foreach ($crops as $crop) {
  13677. switch ($crop) {
  13678. case 'T':
  13679. case 'TOP': {
  13680. $x1 = $x;
  13681. $y1 = ($y - $h);
  13682. $x2 = $x;
  13683. $y2 = ($y - $dh);
  13684. break;
  13685. }
  13686. case 'F':
  13687. case 'BOTTOM': {
  13688. $x1 = $x;
  13689. $y1 = ($y + $dh);
  13690. $x2 = $x;
  13691. $y2 = ($y + $h);
  13692. break;
  13693. }
  13694. case 'L':
  13695. case 'LEFT': {
  13696. $x1 = ($x - $w);
  13697. $y1 = $y;
  13698. $x2 = ($x - $dw);
  13699. $y2 = $y;
  13700. break;
  13701. }
  13702. case 'R':
  13703. case 'RIGHT': {
  13704. $x1 = ($x + $dw);
  13705. $y1 = $y;
  13706. $x2 = ($x + $w);
  13707. $y2 = $y;
  13708. break;
  13709. }
  13710. }
  13711. $this->Line($x1, $y1, $x2, $y2);
  13712. }
  13713. }
  13714. /**
  13715. * Paints a registration mark
  13716. * @param $x (float) abscissa of the registration mark center.
  13717. * @param $y (float) ordinate of the registration mark center.
  13718. * @param $r (float) radius of the crop mark.
  13719. * @param $double (boolean) if true print two concentric crop marks.
  13720. * @param $cola (array) crop mark color (default spot registration color 'All').
  13721. * @param $colb (array) second crop mark color (default spot registration color 'None').
  13722. * @author Nicola Asuni
  13723. * @since 4.9.000 (2010-03-26)
  13724. * @public
  13725. */
  13726. public function registrationMark($x, $y, $r, $double=false, $cola=array(100,100,100,100,'All'), $colb=array(0,0,0,0,'None')) {
  13727. $line_style = array('width' => max((0.5 / $this->k),($r / 30)), 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => $cola);
  13728. $this->SetFillColorArray($cola);
  13729. $this->PieSector($x, $y, $r, 90, 180, 'F');
  13730. $this->PieSector($x, $y, $r, 270, 360, 'F');
  13731. $this->Circle($x, $y, $r, 0, 360, 'C', $line_style, array(), 8);
  13732. if ($double) {
  13733. $ri = $r * 0.5;
  13734. $this->SetFillColorArray($colb);
  13735. $this->PieSector($x, $y, $ri, 90, 180, 'F');
  13736. $this->PieSector($x, $y, $ri, 270, 360, 'F');
  13737. $this->SetFillColorArray($cola);
  13738. $this->PieSector($x, $y, $ri, 0, 90, 'F');
  13739. $this->PieSector($x, $y, $ri, 180, 270, 'F');
  13740. $this->Circle($x, $y, $ri, 0, 360, 'C', $line_style, array(), 8);
  13741. }
  13742. }
  13743. /**
  13744. * Paints a CMYK registration mark
  13745. * @param $x (float) abscissa of the registration mark center.
  13746. * @param $y (float) ordinate of the registration mark center.
  13747. * @param $r (float) radius of the crop mark.
  13748. * @author Nicola Asuni
  13749. * @since 6.0.038 (2013-09-30)
  13750. * @public
  13751. */
  13752. public function registrationMarkCMYK($x, $y, $r) {
  13753. // line width
  13754. $lw = max((0.5 / $this->k),($r / 8));
  13755. // internal radius
  13756. $ri = ($r * 0.6);
  13757. // external radius
  13758. $re = ($r * 1.3);
  13759. // Cyan
  13760. $this->SetFillColorArray(array(100,0,0,0));
  13761. $this->PieSector($x, $y, $ri, 270, 360, 'F');
  13762. // Magenta
  13763. $this->SetFillColorArray(array(0,100,0,0));
  13764. $this->PieSector($x, $y, $ri, 0, 90, 'F');
  13765. // Yellow
  13766. $this->SetFillColorArray(array(0,0,100,0));
  13767. $this->PieSector($x, $y, $ri, 90, 180, 'F');
  13768. // Key - black
  13769. $this->SetFillColorArray(array(0,0,0,100));
  13770. $this->PieSector($x, $y, $ri, 180, 270, 'F');
  13771. // registration color
  13772. $line_style = array('width' => $lw, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(100,100,100,100,'All'));
  13773. $this->SetFillColorArray(array(100,100,100,100,'All'));
  13774. // external circle
  13775. $this->Circle($x, $y, $r, 0, 360, 'C', $line_style, array(), 8);
  13776. // cross lines
  13777. $this->Line($x, ($y - $re), $x, ($y - $ri));
  13778. $this->Line($x, ($y + $ri), $x, ($y + $re));
  13779. $this->Line(($x - $re), $y, ($x - $ri), $y);
  13780. $this->Line(($x + $ri), $y, ($x + $re), $y);
  13781. }
  13782. /**
  13783. * Paints a linear colour gradient.
  13784. * @param $x (float) abscissa of the top left corner of the rectangle.
  13785. * @param $y (float) ordinate of the top left corner of the rectangle.
  13786. * @param $w (float) width of the rectangle.
  13787. * @param $h (float) height of the rectangle.
  13788. * @param $col1 (array) first color (Grayscale, RGB or CMYK components).
  13789. * @param $col2 (array) second color (Grayscale, RGB or CMYK components).
  13790. * @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).
  13791. * @author Andreas W\FCrmser, Nicola Asuni
  13792. * @since 3.1.000 (2008-06-09)
  13793. * @public
  13794. */
  13795. public function LinearGradient($x, $y, $w, $h, $col1=array(), $col2=array(), $coords=array(0,0,1,0)) {
  13796. $this->Clip($x, $y, $w, $h);
  13797. $this->Gradient(2, $coords, array(array('color' => $col1, 'offset' => 0, 'exponent' => 1), array('color' => $col2, 'offset' => 1, 'exponent' => 1)), array(), false);
  13798. }
  13799. /**
  13800. * Paints a radial colour gradient.
  13801. * @param $x (float) abscissa of the top left corner of the rectangle.
  13802. * @param $y (float) ordinate of the top left corner of the rectangle.
  13803. * @param $w (float) width of the rectangle.
  13804. * @param $h (float) height of the rectangle.
  13805. * @param $col1 (array) first color (Grayscale, RGB or CMYK components).
  13806. * @param $col2 (array) second color (Grayscale, RGB or CMYK components).
  13807. * @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.
  13808. * @author Andreas W\FCrmser, Nicola Asuni
  13809. * @since 3.1.000 (2008-06-09)
  13810. * @public
  13811. */
  13812. public function RadialGradient($x, $y, $w, $h, $col1=array(), $col2=array(), $coords=array(0.5,0.5,0.5,0.5,1)) {
  13813. $this->Clip($x, $y, $w, $h);
  13814. $this->Gradient(3, $coords, array(array('color' => $col1, 'offset' => 0, 'exponent' => 1), array('color' => $col2, 'offset' => 1, 'exponent' => 1)), array(), false);
  13815. }
  13816. /**
  13817. * Paints a coons patch mesh.
  13818. * @param $x (float) abscissa of the top left corner of the rectangle.
  13819. * @param $y (float) ordinate of the top left corner of the rectangle.
  13820. * @param $w (float) width of the rectangle.
  13821. * @param $h (float) height of the rectangle.
  13822. * @param $col1 (array) first color (lower left corner) (RGB components).
  13823. * @param $col2 (array) second color (lower right corner) (RGB components).
  13824. * @param $col3 (array) third color (upper right corner) (RGB components).
  13825. * @param $col4 (array) fourth color (upper left corner) (RGB components).
  13826. * @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>
  13827. * @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
  13828. * @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
  13829. * @param $antialias (boolean) A flag indicating whether to filter the shading function to prevent aliasing artifacts.
  13830. * @author Andreas W\FCrmser, Nicola Asuni
  13831. * @since 3.1.000 (2008-06-09)
  13832. * @public
  13833. */
  13834. 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) {
  13835. if ($this->pdfa_mode OR ($this->state != 2)) {
  13836. return;
  13837. }
  13838. $this->Clip($x, $y, $w, $h);
  13839. $n = count($this->gradients) + 1;
  13840. $this->gradients[$n] = array();
  13841. $this->gradients[$n]['type'] = 6; //coons patch mesh
  13842. $this->gradients[$n]['coords'] = array();
  13843. $this->gradients[$n]['antialias'] = $antialias;
  13844. $this->gradients[$n]['colors'] = array();
  13845. $this->gradients[$n]['transparency'] = false;
  13846. //check the coords array if it is the simple array or the multi patch array
  13847. if (!isset($coords[0]['f'])) {
  13848. //simple array -> convert to multi patch array
  13849. if (!isset($col1[1])) {
  13850. $col1[1] = $col1[2] = $col1[0];
  13851. }
  13852. if (!isset($col2[1])) {
  13853. $col2[1] = $col2[2] = $col2[0];
  13854. }
  13855. if (!isset($col3[1])) {
  13856. $col3[1] = $col3[2] = $col3[0];
  13857. }
  13858. if (!isset($col4[1])) {
  13859. $col4[1] = $col4[2] = $col4[0];
  13860. }
  13861. $patch_array[0]['f'] = 0;
  13862. $patch_array[0]['points'] = $coords;
  13863. $patch_array[0]['colors'][0]['r'] = $col1[0];
  13864. $patch_array[0]['colors'][0]['g'] = $col1[1];
  13865. $patch_array[0]['colors'][0]['b'] = $col1[2];
  13866. $patch_array[0]['colors'][1]['r'] = $col2[0];
  13867. $patch_array[0]['colors'][1]['g'] = $col2[1];
  13868. $patch_array[0]['colors'][1]['b'] = $col2[2];
  13869. $patch_array[0]['colors'][2]['r'] = $col3[0];
  13870. $patch_array[0]['colors'][2]['g'] = $col3[1];
  13871. $patch_array[0]['colors'][2]['b'] = $col3[2];
  13872. $patch_array[0]['colors'][3]['r'] = $col4[0];
  13873. $patch_array[0]['colors'][3]['g'] = $col4[1];
  13874. $patch_array[0]['colors'][3]['b'] = $col4[2];
  13875. } else {
  13876. //multi patch array
  13877. $patch_array = $coords;
  13878. }
  13879. $bpcd = 65535; //16 bits per coordinate
  13880. //build the data stream
  13881. $this->gradients[$n]['stream'] = '';
  13882. $count_patch = count($patch_array);
  13883. for ($i=0; $i < $count_patch; ++$i) {
  13884. $this->gradients[$n]['stream'] .= chr($patch_array[$i]['f']); //start with the edge flag as 8 bit
  13885. $count_points = count($patch_array[$i]['points']);
  13886. for ($j=0; $j < $count_points; ++$j) {
  13887. //each point as 16 bit
  13888. $patch_array[$i]['points'][$j] = (($patch_array[$i]['points'][$j] - $coords_min) / ($coords_max - $coords_min)) * $bpcd;
  13889. if ($patch_array[$i]['points'][$j] < 0) {
  13890. $patch_array[$i]['points'][$j] = 0;
  13891. }
  13892. if ($patch_array[$i]['points'][$j] > $bpcd) {
  13893. $patch_array[$i]['points'][$j] = $bpcd;
  13894. }
  13895. $this->gradients[$n]['stream'] .= chr(floor($patch_array[$i]['points'][$j] / 256));
  13896. $this->gradients[$n]['stream'] .= chr(floor($patch_array[$i]['points'][$j] % 256));
  13897. }
  13898. $count_cols = count($patch_array[$i]['colors']);
  13899. for ($j=0; $j < $count_cols; ++$j) {
  13900. //each color component as 8 bit
  13901. $this->gradients[$n]['stream'] .= chr($patch_array[$i]['colors'][$j]['r']);
  13902. $this->gradients[$n]['stream'] .= chr($patch_array[$i]['colors'][$j]['g']);
  13903. $this->gradients[$n]['stream'] .= chr($patch_array[$i]['colors'][$j]['b']);
  13904. }
  13905. }
  13906. //paint the gradient
  13907. $this->_out('/Sh'.$n.' sh');
  13908. //restore previous Graphic State
  13909. $this->_outRestoreGraphicsState();
  13910. if ($this->inxobj) {
  13911. // we are inside an XObject template
  13912. $this->xobjects[$this->xobjid]['gradients'][$n] = $this->gradients[$n];
  13913. }
  13914. }
  13915. /**
  13916. * Set a rectangular clipping area.
  13917. * @param $x (float) abscissa of the top left corner of the rectangle (or top right corner for RTL mode).
  13918. * @param $y (float) ordinate of the top left corner of the rectangle.
  13919. * @param $w (float) width of the rectangle.
  13920. * @param $h (float) height of the rectangle.
  13921. * @author Andreas W\FCrmser, Nicola Asuni
  13922. * @since 3.1.000 (2008-06-09)
  13923. * @protected
  13924. */
  13925. protected function Clip($x, $y, $w, $h) {
  13926. if ($this->state != 2) {
  13927. return;
  13928. }
  13929. if ($this->rtl) {
  13930. $x = $this->w - $x - $w;
  13931. }
  13932. //save current Graphic State
  13933. $s = 'q';
  13934. //set clipping area
  13935. $s .= sprintf(' %F %F %F %F re W n', $x*$this->k, ($this->h-$y)*$this->k, $w*$this->k, -$h*$this->k);
  13936. //set up transformation matrix for gradient
  13937. $s .= sprintf(' %F 0 0 %F %F %F cm', $w*$this->k, $h*$this->k, $x*$this->k, ($this->h-($y+$h))*$this->k);
  13938. $this->_out($s);
  13939. }
  13940. /**
  13941. * Output gradient.
  13942. * @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)
  13943. * @param $coords (array) array of coordinates.
  13944. * @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).
  13945. * @param $background (array) An array of colour components appropriate to the colour space, specifying a single background colour value.
  13946. * @param $antialias (boolean) A flag indicating whether to filter the shading function to prevent aliasing artifacts.
  13947. * @author Nicola Asuni
  13948. * @since 3.1.000 (2008-06-09)
  13949. * @public
  13950. */
  13951. public function Gradient($type, $coords, $stops, $background=array(), $antialias=false) {
  13952. if ($this->pdfa_mode OR ($this->state != 2)) {
  13953. return;
  13954. }
  13955. $n = count($this->gradients) + 1;
  13956. $this->gradients[$n] = array();
  13957. $this->gradients[$n]['type'] = $type;
  13958. $this->gradients[$n]['coords'] = $coords;
  13959. $this->gradients[$n]['antialias'] = $antialias;
  13960. $this->gradients[$n]['colors'] = array();
  13961. $this->gradients[$n]['transparency'] = false;
  13962. // color space
  13963. $numcolspace = count($stops[0]['color']);
  13964. $bcolor = array_values($background);
  13965. switch($numcolspace) {
  13966. case 5: // SPOT
  13967. case 4: { // CMYK
  13968. $this->gradients[$n]['colspace'] = 'DeviceCMYK';
  13969. if (!empty($background)) {
  13970. $this->gradients[$n]['background'] = sprintf('%F %F %F %F', $bcolor[0]/100, $bcolor[1]/100, $bcolor[2]/100, $bcolor[3]/100);
  13971. }
  13972. break;
  13973. }
  13974. case 3: { // RGB
  13975. $this->gradients[$n]['colspace'] = 'DeviceRGB';
  13976. if (!empty($background)) {
  13977. $this->gradients[$n]['background'] = sprintf('%F %F %F', $bcolor[0]/255, $bcolor[1]/255, $bcolor[2]/255);
  13978. }
  13979. break;
  13980. }
  13981. case 1: { // GRAY SCALE
  13982. $this->gradients[$n]['colspace'] = 'DeviceGray';
  13983. if (!empty($background)) {
  13984. $this->gradients[$n]['background'] = sprintf('%F', $bcolor[0]/255);
  13985. }
  13986. break;
  13987. }
  13988. }
  13989. $num_stops = count($stops);
  13990. $last_stop_id = $num_stops - 1;
  13991. foreach ($stops as $key => $stop) {
  13992. $this->gradients[$n]['colors'][$key] = array();
  13993. // offset represents a location along the gradient vector
  13994. if (isset($stop['offset'])) {
  13995. $this->gradients[$n]['colors'][$key]['offset'] = $stop['offset'];
  13996. } else {
  13997. if ($key == 0) {
  13998. $this->gradients[$n]['colors'][$key]['offset'] = 0;
  13999. } elseif ($key == $last_stop_id) {
  14000. $this->gradients[$n]['colors'][$key]['offset'] = 1;
  14001. } else {
  14002. $offsetstep = (1 - $this->gradients[$n]['colors'][($key - 1)]['offset']) / ($num_stops - $key);
  14003. $this->gradients[$n]['colors'][$key]['offset'] = $this->gradients[$n]['colors'][($key - 1)]['offset'] + $offsetstep;
  14004. }
  14005. }
  14006. if (isset($stop['opacity'])) {
  14007. $this->gradients[$n]['colors'][$key]['opacity'] = $stop['opacity'];
  14008. if ((!$this->pdfa_mode) AND ($stop['opacity'] < 1)) {
  14009. $this->gradients[$n]['transparency'] = true;
  14010. }
  14011. } else {
  14012. $this->gradients[$n]['colors'][$key]['opacity'] = 1;
  14013. }
  14014. // exponent for the exponential interpolation function
  14015. if (isset($stop['exponent'])) {
  14016. $this->gradients[$n]['colors'][$key]['exponent'] = $stop['exponent'];
  14017. } else {
  14018. $this->gradients[$n]['colors'][$key]['exponent'] = 1;
  14019. }
  14020. // set colors
  14021. $color = array_values($stop['color']);
  14022. switch($numcolspace) {
  14023. case 5: // SPOT
  14024. case 4: { // CMYK
  14025. $this->gradients[$n]['colors'][$key]['color'] = sprintf('%F %F %F %F', $color[0]/100, $color[1]/100, $color[2]/100, $color[3]/100);
  14026. break;
  14027. }
  14028. case 3: { // RGB
  14029. $this->gradients[$n]['colors'][$key]['color'] = sprintf('%F %F %F', $color[0]/255, $color[1]/255, $color[2]/255);
  14030. break;
  14031. }
  14032. case 1: { // GRAY SCALE
  14033. $this->gradients[$n]['colors'][$key]['color'] = sprintf('%F', $color[0]/255);
  14034. break;
  14035. }
  14036. }
  14037. }
  14038. if ($this->gradients[$n]['transparency']) {
  14039. // paint luminosity gradient
  14040. $this->_out('/TGS'.$n.' gs');
  14041. }
  14042. //paint the gradient
  14043. $this->_out('/Sh'.$n.' sh');
  14044. //restore previous Graphic State
  14045. $this->_outRestoreGraphicsState();
  14046. if ($this->inxobj) {
  14047. // we are inside an XObject template
  14048. $this->xobjects[$this->xobjid]['gradients'][$n] = $this->gradients[$n];
  14049. }
  14050. }
  14051. /**
  14052. * Output gradient shaders.
  14053. * @author Nicola Asuni
  14054. * @since 3.1.000 (2008-06-09)
  14055. * @protected
  14056. */
  14057. function _putshaders() {
  14058. if ($this->pdfa_mode) {
  14059. return;
  14060. }
  14061. $idt = count($this->gradients); //index for transparency gradients
  14062. foreach ($this->gradients as $id => $grad) {
  14063. if (($grad['type'] == 2) OR ($grad['type'] == 3)) {
  14064. $fc = $this->_newobj();
  14065. $out = '<<';
  14066. $out .= ' /FunctionType 3';
  14067. $out .= ' /Domain [0 1]';
  14068. $functions = '';
  14069. $bounds = '';
  14070. $encode = '';
  14071. $i = 1;
  14072. $num_cols = count($grad['colors']);
  14073. $lastcols = $num_cols - 1;
  14074. for ($i = 1; $i < $num_cols; ++$i) {
  14075. $functions .= ($fc + $i).' 0 R ';
  14076. if ($i < $lastcols) {
  14077. $bounds .= sprintf('%F ', $grad['colors'][$i]['offset']);
  14078. }
  14079. $encode .= '0 1 ';
  14080. }
  14081. $out .= ' /Functions ['.trim($functions).']';
  14082. $out .= ' /Bounds ['.trim($bounds).']';
  14083. $out .= ' /Encode ['.trim($encode).']';
  14084. $out .= ' >>';
  14085. $out .= "\n".'endobj';
  14086. $this->_out($out);
  14087. for ($i = 1; $i < $num_cols; ++$i) {
  14088. $this->_newobj();
  14089. $out = '<<';
  14090. $out .= ' /FunctionType 2';
  14091. $out .= ' /Domain [0 1]';
  14092. $out .= ' /C0 ['.$grad['colors'][($i - 1)]['color'].']';
  14093. $out .= ' /C1 ['.$grad['colors'][$i]['color'].']';
  14094. $out .= ' /N '.$grad['colors'][$i]['exponent'];
  14095. $out .= ' >>';
  14096. $out .= "\n".'endobj';
  14097. $this->_out($out);
  14098. }
  14099. // set transparency functions
  14100. if ($grad['transparency']) {
  14101. $ft = $this->_newobj();
  14102. $out = '<<';
  14103. $out .= ' /FunctionType 3';
  14104. $out .= ' /Domain [0 1]';
  14105. $functions = '';
  14106. $i = 1;
  14107. $num_cols = count($grad['colors']);
  14108. for ($i = 1; $i < $num_cols; ++$i) {
  14109. $functions .= ($ft + $i).' 0 R ';
  14110. }
  14111. $out .= ' /Functions ['.trim($functions).']';
  14112. $out .= ' /Bounds ['.trim($bounds).']';
  14113. $out .= ' /Encode ['.trim($encode).']';
  14114. $out .= ' >>';
  14115. $out .= "\n".'endobj';
  14116. $this->_out($out);
  14117. for ($i = 1; $i < $num_cols; ++$i) {
  14118. $this->_newobj();
  14119. $out = '<<';
  14120. $out .= ' /FunctionType 2';
  14121. $out .= ' /Domain [0 1]';
  14122. $out .= ' /C0 ['.$grad['colors'][($i - 1)]['opacity'].']';
  14123. $out .= ' /C1 ['.$grad['colors'][$i]['opacity'].']';
  14124. $out .= ' /N '.$grad['colors'][$i]['exponent'];
  14125. $out .= ' >>';
  14126. $out .= "\n".'endobj';
  14127. $this->_out($out);
  14128. }
  14129. }
  14130. }
  14131. // set shading object
  14132. $this->_newobj();
  14133. $out = '<< /ShadingType '.$grad['type'];
  14134. if (isset($grad['colspace'])) {
  14135. $out .= ' /ColorSpace /'.$grad['colspace'];
  14136. } else {
  14137. $out .= ' /ColorSpace /DeviceRGB';
  14138. }
  14139. if (isset($grad['background']) AND !empty($grad['background'])) {
  14140. $out .= ' /Background ['.$grad['background'].']';
  14141. }
  14142. if (isset($grad['antialias']) AND ($grad['antialias'] === true)) {
  14143. $out .= ' /AntiAlias true';
  14144. }
  14145. if ($grad['type'] == 2) {
  14146. $out .= ' '.sprintf('/Coords [%F %F %F %F]', $grad['coords'][0], $grad['coords'][1], $grad['coords'][2], $grad['coords'][3]);
  14147. $out .= ' /Domain [0 1]';
  14148. $out .= ' /Function '.$fc.' 0 R';
  14149. $out .= ' /Extend [true true]';
  14150. $out .= ' >>';
  14151. } elseif ($grad['type'] == 3) {
  14152. //x0, y0, r0, x1, y1, r1
  14153. //at this this time radius of inner circle is 0
  14154. $out .= ' '.sprintf('/Coords [%F %F 0 %F %F %F]', $grad['coords'][0], $grad['coords'][1], $grad['coords'][2], $grad['coords'][3], $grad['coords'][4]);
  14155. $out .= ' /Domain [0 1]';
  14156. $out .= ' /Function '.$fc.' 0 R';
  14157. $out .= ' /Extend [true true]';
  14158. $out .= ' >>';
  14159. } elseif ($grad['type'] == 6) {
  14160. $out .= ' /BitsPerCoordinate 16';
  14161. $out .= ' /BitsPerComponent 8';
  14162. $out .= ' /Decode[0 1 0 1 0 1 0 1 0 1]';
  14163. $out .= ' /BitsPerFlag 8';
  14164. $stream = $this->_getrawstream($grad['stream']);
  14165. $out .= ' /Length '.strlen($stream);
  14166. $out .= ' >>';
  14167. $out .= ' stream'."\n".$stream."\n".'endstream';
  14168. }
  14169. $out .= "\n".'endobj';
  14170. $this->_out($out);
  14171. if ($grad['transparency']) {
  14172. $shading_transparency = preg_replace('/\/ColorSpace \/[^\s]+/si', '/ColorSpace /DeviceGray', $out);
  14173. $shading_transparency = preg_replace('/\/Function [0-9]+ /si', '/Function '.$ft.' ', $shading_transparency);
  14174. }
  14175. $this->gradients[$id]['id'] = $this->n;
  14176. // set pattern object
  14177. $this->_newobj();
  14178. $out = '<< /Type /Pattern /PatternType 2';
  14179. $out .= ' /Shading '.$this->gradients[$id]['id'].' 0 R';
  14180. $out .= ' >>';
  14181. $out .= "\n".'endobj';
  14182. $this->_out($out);
  14183. $this->gradients[$id]['pattern'] = $this->n;
  14184. // set shading and pattern for transparency mask
  14185. if ($grad['transparency']) {
  14186. // luminosity pattern
  14187. $idgs = $id + $idt;
  14188. $this->_newobj();
  14189. $this->_out($shading_transparency);
  14190. $this->gradients[$idgs]['id'] = $this->n;
  14191. $this->_newobj();
  14192. $out = '<< /Type /Pattern /PatternType 2';
  14193. $out .= ' /Shading '.$this->gradients[$idgs]['id'].' 0 R';
  14194. $out .= ' >>';
  14195. $out .= "\n".'endobj';
  14196. $this->_out($out);
  14197. $this->gradients[$idgs]['pattern'] = $this->n;
  14198. // luminosity XObject
  14199. $oid = $this->_newobj();
  14200. $this->xobjects['LX'.$oid] = array('n' => $oid);
  14201. $filter = '';
  14202. $stream = 'q /a0 gs /Pattern cs /p'.$idgs.' scn 0 0 '.$this->wPt.' '.$this->hPt.' re f Q';
  14203. if ($this->compress) {
  14204. $filter = ' /Filter /FlateDecode';
  14205. $stream = gzcompress($stream);
  14206. }
  14207. $stream = $this->_getrawstream($stream);
  14208. $out = '<< /Type /XObject /Subtype /Form /FormType 1'.$filter;
  14209. $out .= ' /Length '.strlen($stream);
  14210. $rect = sprintf('%F %F', $this->wPt, $this->hPt);
  14211. $out .= ' /BBox [0 0 '.$rect.']';
  14212. $out .= ' /Group << /Type /Group /S /Transparency /CS /DeviceGray >>';
  14213. $out .= ' /Resources <<';
  14214. $out .= ' /ExtGState << /a0 << /ca 1 /CA 1 >> >>';
  14215. $out .= ' /Pattern << /p'.$idgs.' '.$this->gradients[$idgs]['pattern'].' 0 R >>';
  14216. $out .= ' >>';
  14217. $out .= ' >> ';
  14218. $out .= ' stream'."\n".$stream."\n".'endstream';
  14219. $out .= "\n".'endobj';
  14220. $this->_out($out);
  14221. // SMask
  14222. $this->_newobj();
  14223. $out = '<< /Type /Mask /S /Luminosity /G '.($this->n - 1).' 0 R >>'."\n".'endobj';
  14224. $this->_out($out);
  14225. // ExtGState
  14226. $this->_newobj();
  14227. $out = '<< /Type /ExtGState /SMask '.($this->n - 1).' 0 R /AIS false >>'."\n".'endobj';
  14228. $this->_out($out);
  14229. $this->extgstates[] = array('n' => $this->n, 'name' => 'TGS'.$id);
  14230. }
  14231. }
  14232. }
  14233. /**
  14234. * Draw the sector of a circle.
  14235. * It can be used for instance to render pie charts.
  14236. * @param $xc (float) abscissa of the center.
  14237. * @param $yc (float) ordinate of the center.
  14238. * @param $r (float) radius.
  14239. * @param $a (float) start angle (in degrees).
  14240. * @param $b (float) end angle (in degrees).
  14241. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  14242. * @param $cw: (float) indicates whether to go clockwise (default: true).
  14243. * @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.
  14244. * @author Maxime Delorme, Nicola Asuni
  14245. * @since 3.1.000 (2008-06-09)
  14246. * @public
  14247. */
  14248. public function PieSector($xc, $yc, $r, $a, $b, $style='FD', $cw=true, $o=90) {
  14249. $this->PieSectorXY($xc, $yc, $r, $r, $a, $b, $style, $cw, $o);
  14250. }
  14251. /**
  14252. * Draw the sector of an ellipse.
  14253. * It can be used for instance to render pie charts.
  14254. * @param $xc (float) abscissa of the center.
  14255. * @param $yc (float) ordinate of the center.
  14256. * @param $rx (float) the x-axis radius.
  14257. * @param $ry (float) the y-axis radius.
  14258. * @param $a (float) start angle (in degrees).
  14259. * @param $b (float) end angle (in degrees).
  14260. * @param $style (string) Style of rendering. See the getPathPaintOperator() function for more information.
  14261. * @param $cw: (float) indicates whether to go clockwise.
  14262. * @param $o: (float) origin of angles (0 for 3 o'clock, 90 for noon, 180 for 9 o'clock, 270 for 6 o'clock).
  14263. * @param $nc (integer) Number of curves used to draw a 90 degrees portion of arc.
  14264. * @author Maxime Delorme, Nicola Asuni
  14265. * @since 3.1.000 (2008-06-09)
  14266. * @public
  14267. */
  14268. public function PieSectorXY($xc, $yc, $rx, $ry, $a, $b, $style='FD', $cw=false, $o=0, $nc=2) {
  14269. if ($this->state != 2) {
  14270. return;
  14271. }
  14272. if ($this->rtl) {
  14273. $xc = ($this->w - $xc);
  14274. }
  14275. $op = TCPDF_STATIC::getPathPaintOperator($style);
  14276. if ($op == 'f') {
  14277. $line_style = array();
  14278. }
  14279. if ($cw) {
  14280. $d = $b;
  14281. $b = (360 - $a + $o);
  14282. $a = (360 - $d + $o);
  14283. } else {
  14284. $b += $o;
  14285. $a += $o;
  14286. }
  14287. $this->_outellipticalarc($xc, $yc, $rx, $ry, 0, $a, $b, true, $nc);
  14288. $this->_out($op);
  14289. }
  14290. /**
  14291. * Embed vector-based Adobe Illustrator (AI) or AI-compatible EPS files.
  14292. * NOTE: EPS is not yet fully implemented, use the setRasterizeVectorImages() method to enable/disable rasterization of vector images using ImageMagick library.
  14293. * Only vector drawing is supported, not text or bitmap.
  14294. * 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).
  14295. * @param $file (string) Name of the file containing the image or a '@' character followed by the EPS/AI data string.
  14296. * @param $x (float) Abscissa of the upper-left corner.
  14297. * @param $y (float) Ordinate of the upper-left corner.
  14298. * @param $w (float) Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
  14299. * @param $h (float) Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
  14300. * @param $link (mixed) URL or identifier returned by AddLink().
  14301. * @param $useBoundingBox (boolean) specifies whether to position the bounding box (true) or the complete canvas (false) at location (x,y). Default value is true.
  14302. * @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>
  14303. * @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>
  14304. * @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)))
  14305. * @param $fitonpage (boolean) if true the image is resized to not exceed page dimensions.
  14306. * @param $fixoutvals (boolean) if true remove values outside the bounding box.
  14307. * @author Valentin Schmidt, Nicola Asuni
  14308. * @since 3.1.000 (2008-06-09)
  14309. * @public
  14310. */
  14311. public function ImageEps($file, $x='', $y='', $w=0, $h=0, $link='', $useBoundingBox=true, $align='', $palign='', $border=0, $fitonpage=false, $fixoutvals=false) {
  14312. if ($this->state != 2) {
  14313. return;
  14314. }
  14315. if ($this->rasterize_vector_images AND ($w > 0) AND ($h > 0)) {
  14316. // convert EPS to raster image using GD or ImageMagick libraries
  14317. return $this->Image($file, $x, $y, $w, $h, 'EPS', $link, $align, true, 300, $palign, false, false, $border, false, false, $fitonpage);
  14318. }
  14319. if ($x === '') {
  14320. $x = $this->x;
  14321. }
  14322. if ($y === '') {
  14323. $y = $this->y;
  14324. }
  14325. // check page for no-write regions and adapt page margins if necessary
  14326. list($x, $y) = $this->checkPageRegions($h, $x, $y);
  14327. $k = $this->k;
  14328. if ($file[0] === '@') { // image from string
  14329. $data = substr($file, 1);
  14330. } else { // EPS/AI file
  14331. $data = TCPDF_STATIC::fileGetContents($file);
  14332. }
  14333. if ($data === FALSE) {
  14334. $this->Error('EPS file not found: '.$file);
  14335. }
  14336. $regs = array();
  14337. // EPS/AI compatibility check (only checks files created by Adobe Illustrator!)
  14338. preg_match("/%%Creator:([^\r\n]+)/", $data, $regs); # find Creator
  14339. if (count($regs) > 1) {
  14340. $version_str = trim($regs[1]); # e.g. "Adobe Illustrator(R) 8.0"
  14341. if (strpos($version_str, 'Adobe Illustrator') !== false) {
  14342. $versexp = explode(' ', $version_str);
  14343. $version = (float)array_pop($versexp);
  14344. if ($version >= 9) {
  14345. $this->Error('This version of Adobe Illustrator file is not supported: '.$file);
  14346. }
  14347. }
  14348. }
  14349. // strip binary bytes in front of PS-header
  14350. $start = strpos($data, '%!PS-Adobe');
  14351. if ($start > 0) {
  14352. $data = substr($data, $start);
  14353. }
  14354. // find BoundingBox params
  14355. preg_match("/%%BoundingBox:([^\r\n]+)/", $data, $regs);
  14356. if (count($regs) > 1) {
  14357. list($x1, $y1, $x2, $y2) = explode(' ', trim($regs[1]));
  14358. } else {
  14359. $this->Error('No BoundingBox found in EPS/AI file: '.$file);
  14360. }
  14361. $start = strpos($data, '%%EndSetup');
  14362. if ($start === false) {
  14363. $start = strpos($data, '%%EndProlog');
  14364. }
  14365. if ($start === false) {
  14366. $start = strpos($data, '%%BoundingBox');
  14367. }
  14368. $data = substr($data, $start);
  14369. $end = strpos($data, '%%PageTrailer');
  14370. if ($end===false) {
  14371. $end = strpos($data, 'showpage');
  14372. }
  14373. if ($end) {
  14374. $data = substr($data, 0, $end);
  14375. }
  14376. // calculate image width and height on document
  14377. if (($w <= 0) AND ($h <= 0)) {
  14378. $w = ($x2 - $x1) / $k;
  14379. $h = ($y2 - $y1) / $k;
  14380. } elseif ($w <= 0) {
  14381. $w = ($x2-$x1) / $k * ($h / (($y2 - $y1) / $k));
  14382. } elseif ($h <= 0) {
  14383. $h = ($y2 - $y1) / $k * ($w / (($x2 - $x1) / $k));
  14384. }
  14385. // fit the image on available space
  14386. list($w, $h, $x, $y) = $this->fitBlock($w, $h, $x, $y, $fitonpage);
  14387. if ($this->rasterize_vector_images) {
  14388. // convert EPS to raster image using GD or ImageMagick libraries
  14389. return $this->Image($file, $x, $y, $w, $h, 'EPS', $link, $align, true, 300, $palign, false, false, $border, false, false, $fitonpage);
  14390. }
  14391. // set scaling factors
  14392. $scale_x = $w / (($x2 - $x1) / $k);
  14393. $scale_y = $h / (($y2 - $y1) / $k);
  14394. // set alignment
  14395. $this->img_rb_y = $y + $h;
  14396. // set alignment
  14397. if ($this->rtl) {
  14398. if ($palign == 'L') {
  14399. $ximg = $this->lMargin;
  14400. } elseif ($palign == 'C') {
  14401. $ximg = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
  14402. } elseif ($palign == 'R') {
  14403. $ximg = $this->w - $this->rMargin - $w;
  14404. } else {
  14405. $ximg = $x - $w;
  14406. }
  14407. $this->img_rb_x = $ximg;
  14408. } else {
  14409. if ($palign == 'L') {
  14410. $ximg = $this->lMargin;
  14411. } elseif ($palign == 'C') {
  14412. $ximg = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
  14413. } elseif ($palign == 'R') {
  14414. $ximg = $this->w - $this->rMargin - $w;
  14415. } else {
  14416. $ximg = $x;
  14417. }
  14418. $this->img_rb_x = $ximg + $w;
  14419. }
  14420. if ($useBoundingBox) {
  14421. $dx = $ximg * $k - $x1;
  14422. $dy = $y * $k - $y1;
  14423. } else {
  14424. $dx = $ximg * $k;
  14425. $dy = $y * $k;
  14426. }
  14427. // save the current graphic state
  14428. $this->_out('q'.$this->epsmarker);
  14429. // translate
  14430. $this->_out(sprintf('%F %F %F %F %F %F cm', 1, 0, 0, 1, $dx, $dy + ($this->hPt - (2 * $y * $k) - ($y2 - $y1))));
  14431. // scale
  14432. if (isset($scale_x)) {
  14433. $this->_out(sprintf('%F %F %F %F %F %F cm', $scale_x, 0, 0, $scale_y, $x1 * (1 - $scale_x), $y2 * (1 - $scale_y)));
  14434. }
  14435. // handle pc/unix/mac line endings
  14436. $lines = preg_split('/[\r\n]+/si', $data, -1, PREG_SPLIT_NO_EMPTY);
  14437. $u=0;
  14438. $cnt = count($lines);
  14439. for ($i=0; $i < $cnt; ++$i) {
  14440. $line = $lines[$i];
  14441. if (($line == '') OR ($line[0] == '%')) {
  14442. continue;
  14443. }
  14444. $len = strlen($line);
  14445. // check for spot color names
  14446. $color_name = '';
  14447. if (strcasecmp('x', substr(trim($line), -1)) == 0) {
  14448. if (preg_match('/\([^\)]*\)/', $line, $matches) > 0) {
  14449. // extract spot color name
  14450. $color_name = $matches[0];
  14451. // remove color name from string
  14452. $line = str_replace(' '.$color_name, '', $line);
  14453. // remove pharentesis from color name
  14454. $color_name = substr($color_name, 1, -1);
  14455. }
  14456. }
  14457. $chunks = explode(' ', $line);
  14458. $cmd = trim(array_pop($chunks));
  14459. // RGB
  14460. if (($cmd == 'Xa') OR ($cmd == 'XA')) {
  14461. $b = array_pop($chunks);
  14462. $g = array_pop($chunks);
  14463. $r = array_pop($chunks);
  14464. $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!
  14465. continue;
  14466. }
  14467. $skip = false;
  14468. if ($fixoutvals) {
  14469. // check for values outside the bounding box
  14470. switch ($cmd) {
  14471. case 'm':
  14472. case 'l':
  14473. case 'L': {
  14474. // skip values outside bounding box
  14475. foreach ($chunks as $key => $val) {
  14476. if ((($key % 2) == 0) AND (($val < $x1) OR ($val > $x2))) {
  14477. $skip = true;
  14478. } elseif ((($key % 2) != 0) AND (($val < $y1) OR ($val > $y2))) {
  14479. $skip = true;
  14480. }
  14481. }
  14482. }
  14483. }
  14484. }
  14485. switch ($cmd) {
  14486. case 'm':
  14487. case 'l':
  14488. case 'v':
  14489. case 'y':
  14490. case 'c':
  14491. case 'k':
  14492. case 'K':
  14493. case 'g':
  14494. case 'G':
  14495. case 's':
  14496. case 'S':
  14497. case 'J':
  14498. case 'j':
  14499. case 'w':
  14500. case 'M':
  14501. case 'd':
  14502. case 'n': {
  14503. if ($skip) {
  14504. break;
  14505. }
  14506. $this->_out($line);
  14507. break;
  14508. }
  14509. case 'x': {// custom fill color
  14510. if (empty($color_name)) {
  14511. // CMYK color
  14512. list($col_c, $col_m, $col_y, $col_k) = $chunks;
  14513. $this->_out(''.$col_c.' '.$col_m.' '.$col_y.' '.$col_k.' k');
  14514. } else {
  14515. // Spot Color (CMYK + tint)
  14516. list($col_c, $col_m, $col_y, $col_k, $col_t) = $chunks;
  14517. $this->AddSpotColor($color_name, ($col_c * 100), ($col_m * 100), ($col_y * 100), ($col_k * 100));
  14518. $color_cmd = sprintf('/CS%d cs %F scn', $this->spot_colors[$color_name]['i'], (1 - $col_t));
  14519. $this->_out($color_cmd);
  14520. }
  14521. break;
  14522. }
  14523. case 'X': { // custom stroke color
  14524. if (empty($color_name)) {
  14525. // CMYK color
  14526. list($col_c, $col_m, $col_y, $col_k) = $chunks;
  14527. $this->_out(''.$col_c.' '.$col_m.' '.$col_y.' '.$col_k.' K');
  14528. } else {
  14529. // Spot Color (CMYK + tint)
  14530. list($col_c, $col_m, $col_y, $col_k, $col_t) = $chunks;
  14531. $this->AddSpotColor($color_name, ($col_c * 100), ($col_m * 100), ($col_y * 100), ($col_k * 100));
  14532. $color_cmd = sprintf('/CS%d CS %F SCN', $this->spot_colors[$color_name]['i'], (1 - $col_t));
  14533. $this->_out($color_cmd);
  14534. }
  14535. break;
  14536. }
  14537. case 'Y':
  14538. case 'N':
  14539. case 'V':
  14540. case 'L':
  14541. case 'C': {
  14542. if ($skip) {
  14543. break;
  14544. }
  14545. $line[($len - 1)] = strtolower($cmd);
  14546. $this->_out($line);
  14547. break;
  14548. }
  14549. case 'b':
  14550. case 'B': {
  14551. $this->_out($cmd . '*');
  14552. break;
  14553. }
  14554. case 'f':
  14555. case 'F': {
  14556. if ($u > 0) {
  14557. $isU = false;
  14558. $max = min(($i + 5), $cnt);
  14559. for ($j = ($i + 1); $j < $max; ++$j) {
  14560. $isU = ($isU OR (($lines[$j] == 'U') OR ($lines[$j] == '*U')));
  14561. }
  14562. if ($isU) {
  14563. $this->_out('f*');
  14564. }
  14565. } else {
  14566. $this->_out('f*');
  14567. }
  14568. break;
  14569. }
  14570. case '*u': {
  14571. ++$u;
  14572. break;
  14573. }
  14574. case '*U': {
  14575. --$u;
  14576. break;
  14577. }
  14578. }
  14579. }
  14580. // restore previous graphic state
  14581. $this->_out($this->epsmarker.'Q');
  14582. if (!empty($border)) {
  14583. $bx = $this->x;
  14584. $by = $this->y;
  14585. $this->x = $ximg;
  14586. if ($this->rtl) {
  14587. $this->x += $w;
  14588. }
  14589. $this->y = $y;
  14590. $this->Cell($w, $h, '', $border, 0, '', 0, '', 0, true);
  14591. $this->x = $bx;
  14592. $this->y = $by;
  14593. }
  14594. if ($link) {
  14595. $this->Link($ximg, $y, $w, $h, $link, 0);
  14596. }
  14597. // set pointer to align the next text/objects
  14598. switch($align) {
  14599. case 'T':{
  14600. $this->y = $y;
  14601. $this->x = $this->img_rb_x;
  14602. break;
  14603. }
  14604. case 'M':{
  14605. $this->y = $y + round($h/2);
  14606. $this->x = $this->img_rb_x;
  14607. break;
  14608. }
  14609. case 'B':{
  14610. $this->y = $this->img_rb_y;
  14611. $this->x = $this->img_rb_x;
  14612. break;
  14613. }
  14614. case 'N':{
  14615. $this->SetY($this->img_rb_y);
  14616. break;
  14617. }
  14618. default:{
  14619. break;
  14620. }
  14621. }
  14622. $this->endlinex = $this->img_rb_x;
  14623. }
  14624. /**
  14625. * Set document barcode.
  14626. * @param $bc (string) barcode
  14627. * @public
  14628. */
  14629. public function setBarcode($bc='') {
  14630. $this->barcode = $bc;
  14631. }
  14632. /**
  14633. * Get current barcode.
  14634. * @return string
  14635. * @public
  14636. * @since 4.0.012 (2008-07-24)
  14637. */
  14638. public function getBarcode() {
  14639. return $this->barcode;
  14640. }
  14641. /**
  14642. * Print a Linear Barcode.
  14643. * @param $code (string) code to print
  14644. * @param $type (string) type of barcode (see tcpdf_barcodes_1d.php for supported formats).
  14645. * @param $x (int) x position in user units (empty string = current x position)
  14646. * @param $y (int) y position in user units (empty string = current y position)
  14647. * @param $w (int) width in user units (empty string = remaining page width)
  14648. * @param $h (int) height in user units (empty string = remaining page height)
  14649. * @param $xres (float) width of the smallest bar in user units (empty string = default value = 0.4mm)
  14650. * @param $style (array) array of options:<ul>
  14651. * <li>boolean $style['border'] if true prints a border</li>
  14652. * <li>int $style['padding'] padding to leave around the barcode in user units (set to 'auto' for automatic padding)</li>
  14653. * <li>int $style['hpadding'] horizontal padding in user units (set to 'auto' for automatic padding)</li>
  14654. * <li>int $style['vpadding'] vertical padding in user units (set to 'auto' for automatic padding)</li>
  14655. * <li>array $style['fgcolor'] color array for bars and text</li>
  14656. * <li>mixed $style['bgcolor'] color array for background (set to false for transparent)</li>
  14657. * <li>boolean $style['text'] if true prints text below the barcode</li>
  14658. * <li>string $style['label'] override default label</li>
  14659. * <li>string $style['font'] font name for text</li><li>int $style['fontsize'] font size for text</li>
  14660. * <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>
  14661. * <li>string $style['position'] horizontal position of the containing barcode cell on the page: L = left margin; C = center; R = right margin.</li>
  14662. * <li>string $style['align'] horizontal position of the barcode on the containing rectangle: L = left; C = center; R = right.</li>
  14663. * <li>string $style['stretch'] if true stretch the barcode to best fit the available width, otherwise uses $xres resolution for a single bar.</li>
  14664. * <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>
  14665. * <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>
  14666. * @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>
  14667. * @author Nicola Asuni
  14668. * @since 3.1.000 (2008-06-09)
  14669. * @public
  14670. */
  14671. public function write1DBarcode($code, $type, $x='', $y='', $w='', $h='', $xres='', $style=array(), $align='') {
  14672. if (TCPDF_STATIC::empty_string(trim($code))) {
  14673. return;
  14674. }
  14675. require_once(dirname(__FILE__).'/tcpdf_barcodes_1d.php');
  14676. // save current graphic settings
  14677. $gvars = $this->getGraphicVars();
  14678. // create new barcode object
  14679. $barcodeobj = new TCPDFBarcode($code, $type);
  14680. $arrcode = $barcodeobj->getBarcodeArray();
  14681. if (($arrcode === false) OR empty($arrcode) OR ($arrcode['maxw'] <= 0)) {
  14682. $this->Error('Error in 1D barcode string');
  14683. }
  14684. if ($arrcode['maxh'] <= 0) {
  14685. $arrcode['maxh'] = 1;
  14686. }
  14687. // set default values
  14688. if (!isset($style['position'])) {
  14689. $style['position'] = '';
  14690. } elseif ($style['position'] == 'S') {
  14691. // keep this for backward compatibility
  14692. $style['position'] = '';
  14693. $style['stretch'] = true;
  14694. }
  14695. if (!isset($style['fitwidth'])) {
  14696. if (!isset($style['stretch'])) {
  14697. $style['fitwidth'] = true;
  14698. } else {
  14699. $style['fitwidth'] = false;
  14700. }
  14701. }
  14702. if ($style['fitwidth']) {
  14703. // disable stretch
  14704. $style['stretch'] = false;
  14705. }
  14706. if (!isset($style['stretch'])) {
  14707. if (($w === '') OR ($w <= 0)) {
  14708. $style['stretch'] = false;
  14709. } else {
  14710. $style['stretch'] = true;
  14711. }
  14712. }
  14713. if (!isset($style['fgcolor'])) {
  14714. $style['fgcolor'] = array(0,0,0); // default black
  14715. }
  14716. if (!isset($style['bgcolor'])) {
  14717. $style['bgcolor'] = false; // default transparent
  14718. }
  14719. if (!isset($style['border'])) {
  14720. $style['border'] = false;
  14721. }
  14722. $fontsize = 0;
  14723. if (!isset($style['text'])) {
  14724. $style['text'] = false;
  14725. }
  14726. if ($style['text'] AND isset($style['font'])) {
  14727. if (isset($style['fontsize'])) {
  14728. $fontsize = $style['fontsize'];
  14729. }
  14730. $this->SetFont($style['font'], '', $fontsize);
  14731. }
  14732. if (!isset($style['stretchtext'])) {
  14733. $style['stretchtext'] = 4;
  14734. }
  14735. if ($x === '') {
  14736. $x = $this->x;
  14737. }
  14738. if ($y === '') {
  14739. $y = $this->y;
  14740. }
  14741. // check page for no-write regions and adapt page margins if necessary
  14742. list($x, $y) = $this->checkPageRegions($h, $x, $y);
  14743. if (($w === '') OR ($w <= 0)) {
  14744. if ($this->rtl) {
  14745. $w = $x - $this->lMargin;
  14746. } else {
  14747. $w = $this->w - $this->rMargin - $x;
  14748. }
  14749. }
  14750. // padding
  14751. if (!isset($style['padding'])) {
  14752. $padding = 0;
  14753. } elseif ($style['padding'] === 'auto') {
  14754. $padding = 10 * ($w / ($arrcode['maxw'] + 20));
  14755. } else {
  14756. $padding = floatval($style['padding']);
  14757. }
  14758. // horizontal padding
  14759. if (!isset($style['hpadding'])) {
  14760. $hpadding = $padding;
  14761. } elseif ($style['hpadding'] === 'auto') {
  14762. $hpadding = 10 * ($w / ($arrcode['maxw'] + 20));
  14763. } else {
  14764. $hpadding = floatval($style['hpadding']);
  14765. }
  14766. // vertical padding
  14767. if (!isset($style['vpadding'])) {
  14768. $vpadding = $padding;
  14769. } elseif ($style['vpadding'] === 'auto') {
  14770. $vpadding = ($hpadding / 2);
  14771. } else {
  14772. $vpadding = floatval($style['vpadding']);
  14773. }
  14774. // calculate xres (single bar width)
  14775. $max_xres = ($w - (2 * $hpadding)) / $arrcode['maxw'];
  14776. if ($style['stretch']) {
  14777. $xres = $max_xres;
  14778. } else {
  14779. if (TCPDF_STATIC::empty_string($xres)) {
  14780. $xres = (0.141 * $this->k); // default bar width = 0.4 mm
  14781. }
  14782. if ($xres > $max_xres) {
  14783. // correct xres to fit on $w
  14784. $xres = $max_xres;
  14785. }
  14786. if ((isset($style['padding']) AND ($style['padding'] === 'auto'))
  14787. OR (isset($style['hpadding']) AND ($style['hpadding'] === 'auto'))) {
  14788. $hpadding = 10 * $xres;
  14789. if (isset($style['vpadding']) AND ($style['vpadding'] === 'auto')) {
  14790. $vpadding = ($hpadding / 2);
  14791. }
  14792. }
  14793. }
  14794. if ($style['fitwidth']) {
  14795. $wold = $w;
  14796. $w = (($arrcode['maxw'] * $xres) + (2 * $hpadding));
  14797. if (isset($style['cellfitalign'])) {
  14798. switch ($style['cellfitalign']) {
  14799. case 'L': {
  14800. if ($this->rtl) {
  14801. $x -= ($wold - $w);
  14802. }
  14803. break;
  14804. }
  14805. case 'R': {
  14806. if (!$this->rtl) {
  14807. $x += ($wold - $w);
  14808. }
  14809. break;
  14810. }
  14811. case 'C': {
  14812. if ($this->rtl) {
  14813. $x -= (($wold - $w) / 2);
  14814. } else {
  14815. $x += (($wold - $w) / 2);
  14816. }
  14817. break;
  14818. }
  14819. default : {
  14820. break;
  14821. }
  14822. }
  14823. }
  14824. }
  14825. $text_height = $this->getCellHeight($fontsize / $this->k);
  14826. // height
  14827. if (($h === '') OR ($h <= 0)) {
  14828. // set default height
  14829. $h = (($arrcode['maxw'] * $xres) / 3) + (2 * $vpadding) + $text_height;
  14830. }
  14831. $barh = $h - $text_height - (2 * $vpadding);
  14832. if ($barh <=0) {
  14833. // try to reduce font or padding to fit barcode on available height
  14834. if ($text_height > $h) {
  14835. $fontsize = (($h * $this->k) / (4 * $this->cell_height_ratio));
  14836. $text_height = $this->getCellHeight($fontsize / $this->k);
  14837. $this->SetFont($style['font'], '', $fontsize);
  14838. }
  14839. if ($vpadding > 0) {
  14840. $vpadding = (($h - $text_height) / 4);
  14841. }
  14842. $barh = $h - $text_height - (2 * $vpadding);
  14843. }
  14844. // fit the barcode on available space
  14845. list($w, $h, $x, $y) = $this->fitBlock($w, $h, $x, $y, false);
  14846. // set alignment
  14847. $this->img_rb_y = $y + $h;
  14848. // set alignment
  14849. if ($this->rtl) {
  14850. if ($style['position'] == 'L') {
  14851. $xpos = $this->lMargin;
  14852. } elseif ($style['position'] == 'C') {
  14853. $xpos = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
  14854. } elseif ($style['position'] == 'R') {
  14855. $xpos = $this->w - $this->rMargin - $w;
  14856. } else {
  14857. $xpos = $x - $w;
  14858. }
  14859. $this->img_rb_x = $xpos;
  14860. } else {
  14861. if ($style['position'] == 'L') {
  14862. $xpos = $this->lMargin;
  14863. } elseif ($style['position'] == 'C') {
  14864. $xpos = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
  14865. } elseif ($style['position'] == 'R') {
  14866. $xpos = $this->w - $this->rMargin - $w;
  14867. } else {
  14868. $xpos = $x;
  14869. }
  14870. $this->img_rb_x = $xpos + $w;
  14871. }
  14872. $xpos_rect = $xpos;
  14873. if (!isset($style['align'])) {
  14874. $style['align'] = 'C';
  14875. }
  14876. switch ($style['align']) {
  14877. case 'L': {
  14878. $xpos = $xpos_rect + $hpadding;
  14879. break;
  14880. }
  14881. case 'R': {
  14882. $xpos = $xpos_rect + ($w - ($arrcode['maxw'] * $xres)) - $hpadding;
  14883. break;
  14884. }
  14885. case 'C':
  14886. default : {
  14887. $xpos = $xpos_rect + (($w - ($arrcode['maxw'] * $xres)) / 2);
  14888. break;
  14889. }
  14890. }
  14891. $xpos_text = $xpos;
  14892. // barcode is always printed in LTR direction
  14893. $tempRTL = $this->rtl;
  14894. $this->rtl = false;
  14895. // print background color
  14896. if ($style['bgcolor']) {
  14897. $this->Rect($xpos_rect, $y, $w, $h, $style['border'] ? 'DF' : 'F', '', $style['bgcolor']);
  14898. } elseif ($style['border']) {
  14899. $this->Rect($xpos_rect, $y, $w, $h, 'D');
  14900. }
  14901. // set foreground color
  14902. $this->SetDrawColorArray($style['fgcolor']);
  14903. $this->SetTextColorArray($style['fgcolor']);
  14904. // print bars
  14905. foreach ($arrcode['bcode'] as $k => $v) {
  14906. $bw = ($v['w'] * $xres);
  14907. if ($v['t']) {
  14908. // draw a vertical bar
  14909. $ypos = $y + $vpadding + ($v['p'] * $barh / $arrcode['maxh']);
  14910. $this->Rect($xpos, $ypos, $bw, ($v['h'] * $barh / $arrcode['maxh']), 'F', array(), $style['fgcolor']);
  14911. }
  14912. $xpos += $bw;
  14913. }
  14914. // print text
  14915. if ($style['text']) {
  14916. if (isset($style['label']) AND !TCPDF_STATIC::empty_string($style['label'])) {
  14917. $label = $style['label'];
  14918. } else {
  14919. $label = $code;
  14920. }
  14921. $txtwidth = ($arrcode['maxw'] * $xres);
  14922. if ($this->GetStringWidth($label) > $txtwidth) {
  14923. $style['stretchtext'] = 2;
  14924. }
  14925. // print text
  14926. $this->x = $xpos_text;
  14927. $this->y = $y + $vpadding + $barh;
  14928. $cellpadding = $this->cell_padding;
  14929. $this->SetCellPadding(0);
  14930. $this->Cell($txtwidth, '', $label, 0, 0, 'C', false, '', $style['stretchtext'], false, 'T', 'T');
  14931. $this->cell_padding = $cellpadding;
  14932. }
  14933. // restore original direction
  14934. $this->rtl = $tempRTL;
  14935. // restore previous settings
  14936. $this->setGraphicVars($gvars);
  14937. // set pointer to align the next text/objects
  14938. switch($align) {
  14939. case 'T':{
  14940. $this->y = $y;
  14941. $this->x = $this->img_rb_x;
  14942. break;
  14943. }
  14944. case 'M':{
  14945. $this->y = $y + round($h / 2);
  14946. $this->x = $this->img_rb_x;
  14947. break;
  14948. }
  14949. case 'B':{
  14950. $this->y = $this->img_rb_y;
  14951. $this->x = $this->img_rb_x;
  14952. break;
  14953. }
  14954. case 'N':{
  14955. $this->SetY($this->img_rb_y);
  14956. break;
  14957. }
  14958. default:{
  14959. break;
  14960. }
  14961. }
  14962. $this->endlinex = $this->img_rb_x;
  14963. }
  14964. /**
  14965. * Print 2D Barcode.
  14966. * @param $code (string) code to print
  14967. * @param $type (string) type of barcode (see tcpdf_barcodes_2d.php for supported formats).
  14968. * @param $x (int) x position in user units
  14969. * @param $y (int) y position in user units
  14970. * @param $w (int) width in user units
  14971. * @param $h (int) height in user units
  14972. * @param $style (array) array of options:<ul>
  14973. * <li>boolean $style['border'] if true prints a border around the barcode</li>
  14974. * <li>int $style['padding'] padding to leave around the barcode in barcode units (set to 'auto' for automatic padding)</li>
  14975. * <li>int $style['hpadding'] horizontal padding in barcode units (set to 'auto' for automatic padding)</li>
  14976. * <li>int $style['vpadding'] vertical padding in barcode units (set to 'auto' for automatic padding)</li>
  14977. * <li>int $style['module_width'] width of a single module in points</li>
  14978. * <li>int $style['module_height'] height of a single module in points</li>
  14979. * <li>array $style['fgcolor'] color array for bars and text</li>
  14980. * <li>mixed $style['bgcolor'] color array for background or false for transparent</li>
  14981. * <li>string $style['position'] barcode position on the page: L = left margin; C = center; R = right margin; S = stretch</li>
  14982. * @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>
  14983. * @param $distort (boolean) if true distort the barcode to fit width and height, otherwise preserve aspect ratio
  14984. * @author Nicola Asuni
  14985. * @since 4.5.037 (2009-04-07)
  14986. * @public
  14987. */
  14988. public function write2DBarcode($code, $type, $x='', $y='', $w='', $h='', $style=array(), $align='', $distort=false) {
  14989. if (TCPDF_STATIC::empty_string(trim($code))) {
  14990. return;
  14991. }
  14992. require_once(dirname(__FILE__).'/tcpdf_barcodes_2d.php');
  14993. // save current graphic settings
  14994. $gvars = $this->getGraphicVars();
  14995. // create new barcode object
  14996. $barcodeobj = new TCPDF2DBarcode($code, $type);
  14997. $arrcode = $barcodeobj->getBarcodeArray();
  14998. 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)) {
  14999. $this->Error('Error in 2D barcode string');
  15000. }
  15001. // set default values
  15002. if (!isset($style['position'])) {
  15003. $style['position'] = '';
  15004. }
  15005. if (!isset($style['fgcolor'])) {
  15006. $style['fgcolor'] = array(0,0,0); // default black
  15007. }
  15008. if (!isset($style['bgcolor'])) {
  15009. $style['bgcolor'] = false; // default transparent
  15010. }
  15011. if (!isset($style['border'])) {
  15012. $style['border'] = false;
  15013. }
  15014. // padding
  15015. if (!isset($style['padding'])) {
  15016. $style['padding'] = 0;
  15017. } elseif ($style['padding'] === 'auto') {
  15018. $style['padding'] = 4;
  15019. }
  15020. if (!isset($style['hpadding'])) {
  15021. $style['hpadding'] = $style['padding'];
  15022. } elseif ($style['hpadding'] === 'auto') {
  15023. $style['hpadding'] = 4;
  15024. }
  15025. if (!isset($style['vpadding'])) {
  15026. $style['vpadding'] = $style['padding'];
  15027. } elseif ($style['vpadding'] === 'auto') {
  15028. $style['vpadding'] = 4;
  15029. }
  15030. $hpad = (2 * $style['hpadding']);
  15031. $vpad = (2 * $style['vpadding']);
  15032. // cell (module) dimension
  15033. if (!isset($style['module_width'])) {
  15034. $style['module_width'] = 1; // width of a single module in points
  15035. }
  15036. if (!isset($style['module_height'])) {
  15037. $style['module_height'] = 1; // height of a single module in points
  15038. }
  15039. if ($x === '') {
  15040. $x = $this->x;
  15041. }
  15042. if ($y === '') {
  15043. $y = $this->y;
  15044. }
  15045. // check page for no-write regions and adapt page margins if necessary
  15046. list($x, $y) = $this->checkPageRegions($h, $x, $y);
  15047. // number of barcode columns and rows
  15048. $rows = $arrcode['num_rows'];
  15049. $cols = $arrcode['num_cols'];
  15050. if (($rows <= 0) || ($cols <= 0)){
  15051. $this->Error('Error in 2D barcode string');
  15052. }
  15053. // module width and height
  15054. $mw = $style['module_width'];
  15055. $mh = $style['module_height'];
  15056. if (($mw <= 0) OR ($mh <= 0)) {
  15057. $this->Error('Error in 2D barcode string');
  15058. }
  15059. // get max dimensions
  15060. if ($this->rtl) {
  15061. $maxw = $x - $this->lMargin;
  15062. } else {
  15063. $maxw = $this->w - $this->rMargin - $x;
  15064. }
  15065. $maxh = ($this->h - $this->tMargin - $this->bMargin);
  15066. $ratioHW = ((($rows * $mh) + $hpad) / (($cols * $mw) + $vpad));
  15067. $ratioWH = ((($cols * $mw) + $vpad) / (($rows * $mh) + $hpad));
  15068. if (!$distort) {
  15069. if (($maxw * $ratioHW) > $maxh) {
  15070. $maxw = $maxh * $ratioWH;
  15071. }
  15072. if (($maxh * $ratioWH) > $maxw) {
  15073. $maxh = $maxw * $ratioHW;
  15074. }
  15075. }
  15076. // set maximum dimensions
  15077. if ($w > $maxw) {
  15078. $w = $maxw;
  15079. }
  15080. if ($h > $maxh) {
  15081. $h = $maxh;
  15082. }
  15083. // set dimensions
  15084. if ((($w === '') OR ($w <= 0)) AND (($h === '') OR ($h <= 0))) {
  15085. $w = ($cols + $hpad) * ($mw / $this->k);
  15086. $h = ($rows + $vpad) * ($mh / $this->k);
  15087. } elseif (($w === '') OR ($w <= 0)) {
  15088. $w = $h * $ratioWH;
  15089. } elseif (($h === '') OR ($h <= 0)) {
  15090. $h = $w * $ratioHW;
  15091. }
  15092. // barcode size (excluding padding)
  15093. $bw = ($w * $cols) / ($cols + $hpad);
  15094. $bh = ($h * $rows) / ($rows + $vpad);
  15095. // dimension of single barcode cell unit
  15096. $cw = $bw / $cols;
  15097. $ch = $bh / $rows;
  15098. if (!$distort) {
  15099. if (($cw / $ch) > ($mw / $mh)) {
  15100. // correct horizontal distortion
  15101. $cw = $ch * $mw / $mh;
  15102. $bw = $cw * $cols;
  15103. $style['hpadding'] = ($w - $bw) / (2 * $cw);
  15104. } else {
  15105. // correct vertical distortion
  15106. $ch = $cw * $mh / $mw;
  15107. $bh = $ch * $rows;
  15108. $style['vpadding'] = ($h - $bh) / (2 * $ch);
  15109. }
  15110. }
  15111. // fit the barcode on available space
  15112. list($w, $h, $x, $y) = $this->fitBlock($w, $h, $x, $y, false);
  15113. // set alignment
  15114. $this->img_rb_y = $y + $h;
  15115. // set alignment
  15116. if ($this->rtl) {
  15117. if ($style['position'] == 'L') {
  15118. $xpos = $this->lMargin;
  15119. } elseif ($style['position'] == 'C') {
  15120. $xpos = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
  15121. } elseif ($style['position'] == 'R') {
  15122. $xpos = $this->w - $this->rMargin - $w;
  15123. } else {
  15124. $xpos = $x - $w;
  15125. }
  15126. $this->img_rb_x = $xpos;
  15127. } else {
  15128. if ($style['position'] == 'L') {
  15129. $xpos = $this->lMargin;
  15130. } elseif ($style['position'] == 'C') {
  15131. $xpos = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
  15132. } elseif ($style['position'] == 'R') {
  15133. $xpos = $this->w - $this->rMargin - $w;
  15134. } else {
  15135. $xpos = $x;
  15136. }
  15137. $this->img_rb_x = $xpos + $w;
  15138. }
  15139. $xstart = $xpos + ($style['hpadding'] * $cw);
  15140. $ystart = $y + ($style['vpadding'] * $ch);
  15141. // barcode is always printed in LTR direction
  15142. $tempRTL = $this->rtl;
  15143. $this->rtl = false;
  15144. // print background color
  15145. if ($style['bgcolor']) {
  15146. $this->Rect($xpos, $y, $w, $h, $style['border'] ? 'DF' : 'F', '', $style['bgcolor']);
  15147. } elseif ($style['border']) {
  15148. $this->Rect($xpos, $y, $w, $h, 'D');
  15149. }
  15150. // set foreground color
  15151. $this->SetDrawColorArray($style['fgcolor']);
  15152. // print barcode cells
  15153. // for each row
  15154. for ($r = 0; $r < $rows; ++$r) {
  15155. $xr = $xstart;
  15156. // for each column
  15157. for ($c = 0; $c < $cols; ++$c) {
  15158. if ($arrcode['bcode'][$r][$c] == 1) {
  15159. // draw a single barcode cell
  15160. $this->Rect($xr, $ystart, $cw, $ch, 'F', array(), $style['fgcolor']);
  15161. }
  15162. $xr += $cw;
  15163. }
  15164. $ystart += $ch;
  15165. }
  15166. // restore original direction
  15167. $this->rtl = $tempRTL;
  15168. // restore previous settings
  15169. $this->setGraphicVars($gvars);
  15170. // set pointer to align the next text/objects
  15171. switch($align) {
  15172. case 'T':{
  15173. $this->y = $y;
  15174. $this->x = $this->img_rb_x;
  15175. break;
  15176. }
  15177. case 'M':{
  15178. $this->y = $y + round($h/2);
  15179. $this->x = $this->img_rb_x;
  15180. break;
  15181. }
  15182. case 'B':{
  15183. $this->y = $this->img_rb_y;
  15184. $this->x = $this->img_rb_x;
  15185. break;
  15186. }
  15187. case 'N':{
  15188. $this->SetY($this->img_rb_y);
  15189. break;
  15190. }
  15191. default:{
  15192. break;
  15193. }
  15194. }
  15195. $this->endlinex = $this->img_rb_x;
  15196. }
  15197. /**
  15198. * Returns an array containing current margins:
  15199. * <ul>
  15200. <li>$ret['left'] = left margin</li>
  15201. <li>$ret['right'] = right margin</li>
  15202. <li>$ret['top'] = top margin</li>
  15203. <li>$ret['bottom'] = bottom margin</li>
  15204. <li>$ret['header'] = header margin</li>
  15205. <li>$ret['footer'] = footer margin</li>
  15206. <li>$ret['cell'] = cell padding array</li>
  15207. <li>$ret['padding_left'] = cell left padding</li>
  15208. <li>$ret['padding_top'] = cell top padding</li>
  15209. <li>$ret['padding_right'] = cell right padding</li>
  15210. <li>$ret['padding_bottom'] = cell bottom padding</li>
  15211. * </ul>
  15212. * @return array containing all margins measures
  15213. * @public
  15214. * @since 3.2.000 (2008-06-23)
  15215. */
  15216. public function getMargins() {
  15217. $ret = array(
  15218. 'left' => $this->lMargin,
  15219. 'right' => $this->rMargin,
  15220. 'top' => $this->tMargin,
  15221. 'bottom' => $this->bMargin,
  15222. 'header' => $this->header_margin,
  15223. 'footer' => $this->footer_margin,
  15224. 'cell' => $this->cell_padding,
  15225. 'padding_left' => $this->cell_padding['L'],
  15226. 'padding_top' => $this->cell_padding['T'],
  15227. 'padding_right' => $this->cell_padding['R'],
  15228. 'padding_bottom' => $this->cell_padding['B']
  15229. );
  15230. return $ret;
  15231. }
  15232. /**
  15233. * Returns an array containing original margins:
  15234. * <ul>
  15235. <li>$ret['left'] = left margin</li>
  15236. <li>$ret['right'] = right margin</li>
  15237. * </ul>
  15238. * @return array containing all margins measures
  15239. * @public
  15240. * @since 4.0.012 (2008-07-24)
  15241. */
  15242. public function getOriginalMargins() {
  15243. $ret = array(
  15244. 'left' => $this->original_lMargin,
  15245. 'right' => $this->original_rMargin
  15246. );
  15247. return $ret;
  15248. }
  15249. /**
  15250. * Returns the current font size.
  15251. * @return current font size
  15252. * @public
  15253. * @since 3.2.000 (2008-06-23)
  15254. */
  15255. public function getFontSize() {
  15256. return $this->FontSize;
  15257. }
  15258. /**
  15259. * Returns the current font size in points unit.
  15260. * @return current font size in points unit
  15261. * @public
  15262. * @since 3.2.000 (2008-06-23)
  15263. */
  15264. public function getFontSizePt() {
  15265. return $this->FontSizePt;
  15266. }
  15267. /**
  15268. * Returns the current font family name.
  15269. * @return string current font family name
  15270. * @public
  15271. * @since 4.3.008 (2008-12-05)
  15272. */
  15273. public function getFontFamily() {
  15274. return $this->FontFamily;
  15275. }
  15276. /**
  15277. * Returns the current font style.
  15278. * @return string current font style
  15279. * @public
  15280. * @since 4.3.008 (2008-12-05)
  15281. */
  15282. public function getFontStyle() {
  15283. return $this->FontStyle;
  15284. }
  15285. /**
  15286. * Cleanup HTML code (requires HTML Tidy library).
  15287. * @param $html (string) htmlcode to fix
  15288. * @param $default_css (string) CSS commands to add
  15289. * @param $tagvs (array) parameters for setHtmlVSpace method
  15290. * @param $tidy_options (array) options for tidy_parse_string function
  15291. * @return string XHTML code cleaned up
  15292. * @author Nicola Asuni
  15293. * @public
  15294. * @since 5.9.017 (2010-11-16)
  15295. * @see setHtmlVSpace()
  15296. */
  15297. public function fixHTMLCode($html, $default_css='', $tagvs='', $tidy_options='') {
  15298. return TCPDF_STATIC::fixHTMLCode($html, $default_css, $tagvs, $tidy_options, $this->tagvspaces);
  15299. }
  15300. /**
  15301. * Returns the border width from CSS property
  15302. * @param $width (string) border width
  15303. * @return int with in user units
  15304. * @protected
  15305. * @since 5.7.000 (2010-08-02)
  15306. */
  15307. protected function getCSSBorderWidth($width) {
  15308. if ($width == 'thin') {
  15309. $width = (2 / $this->k);
  15310. } elseif ($width == 'medium') {
  15311. $width = (4 / $this->k);
  15312. } elseif ($width == 'thick') {
  15313. $width = (6 / $this->k);
  15314. } else {
  15315. $width = $this->getHTMLUnitToUnits($width, 1, 'px', false);
  15316. }
  15317. return $width;
  15318. }
  15319. /**
  15320. * Returns the border dash style from CSS property
  15321. * @param $style (string) border style to convert
  15322. * @return int sash style (return -1 in case of none or hidden border)
  15323. * @protected
  15324. * @since 5.7.000 (2010-08-02)
  15325. */
  15326. protected function getCSSBorderDashStyle($style) {
  15327. switch (strtolower($style)) {
  15328. case 'none':
  15329. case 'hidden': {
  15330. $dash = -1;
  15331. break;
  15332. }
  15333. case 'dotted': {
  15334. $dash = 1;
  15335. break;
  15336. }
  15337. case 'dashed': {
  15338. $dash = 3;
  15339. break;
  15340. }
  15341. case 'double':
  15342. case 'groove':
  15343. case 'ridge':
  15344. case 'inset':
  15345. case 'outset':
  15346. case 'solid':
  15347. default: {
  15348. $dash = 0;
  15349. break;
  15350. }
  15351. }
  15352. return $dash;
  15353. }
  15354. /**
  15355. * Returns the border style array from CSS border properties
  15356. * @param $cssborder (string) border properties
  15357. * @return array containing border properties
  15358. * @protected
  15359. * @since 5.7.000 (2010-08-02)
  15360. */
  15361. protected function getCSSBorderStyle($cssborder) {
  15362. $bprop = preg_split('/[\s]+/', trim($cssborder));
  15363. $border = array(); // value to be returned
  15364. switch (count($bprop)) {
  15365. case 3: {
  15366. $width = $bprop[0];
  15367. $style = $bprop[1];
  15368. $color = $bprop[2];
  15369. break;
  15370. }
  15371. case 2: {
  15372. $width = 'medium';
  15373. $style = $bprop[0];
  15374. $color = $bprop[1];
  15375. break;
  15376. }
  15377. case 1: {
  15378. $width = 'medium';
  15379. $style = $bprop[0];
  15380. $color = 'black';
  15381. break;
  15382. }
  15383. default: {
  15384. $width = 'medium';
  15385. $style = 'solid';
  15386. $color = 'black';
  15387. break;
  15388. }
  15389. }
  15390. if ($style == 'none') {
  15391. return array();
  15392. }
  15393. $border['cap'] = 'square';
  15394. $border['join'] = 'miter';
  15395. $border['dash'] = $this->getCSSBorderDashStyle($style);
  15396. if ($border['dash'] < 0) {
  15397. return array();
  15398. }
  15399. $border['width'] = $this->getCSSBorderWidth($width);
  15400. $border['color'] = TCPDF_COLORS::convertHTMLColorToDec($color, $this->spot_colors);
  15401. return $border;
  15402. }
  15403. /**
  15404. * Get the internal Cell padding from CSS attribute.
  15405. * @param $csspadding (string) padding properties
  15406. * @param $width (float) width of the containing element
  15407. * @return array of cell paddings
  15408. * @public
  15409. * @since 5.9.000 (2010-10-04)
  15410. */
  15411. public function getCSSPadding($csspadding, $width=0) {
  15412. $padding = preg_split('/[\s]+/', trim($csspadding));
  15413. $cell_padding = array(); // value to be returned
  15414. switch (count($padding)) {
  15415. case 4: {
  15416. $cell_padding['T'] = $padding[0];
  15417. $cell_padding['R'] = $padding[1];
  15418. $cell_padding['B'] = $padding[2];
  15419. $cell_padding['L'] = $padding[3];
  15420. break;
  15421. }
  15422. case 3: {
  15423. $cell_padding['T'] = $padding[0];
  15424. $cell_padding['R'] = $padding[1];
  15425. $cell_padding['B'] = $padding[2];
  15426. $cell_padding['L'] = $padding[1];
  15427. break;
  15428. }
  15429. case 2: {
  15430. $cell_padding['T'] = $padding[0];
  15431. $cell_padding['R'] = $padding[1];
  15432. $cell_padding['B'] = $padding[0];
  15433. $cell_padding['L'] = $padding[1];
  15434. break;
  15435. }
  15436. case 1: {
  15437. $cell_padding['T'] = $padding[0];
  15438. $cell_padding['R'] = $padding[0];
  15439. $cell_padding['B'] = $padding[0];
  15440. $cell_padding['L'] = $padding[0];
  15441. break;
  15442. }
  15443. default: {
  15444. return $this->cell_padding;
  15445. }
  15446. }
  15447. if ($width == 0) {
  15448. $width = $this->w - $this->lMargin - $this->rMargin;
  15449. }
  15450. $cell_padding['T'] = $this->getHTMLUnitToUnits($cell_padding['T'], $width, 'px', false);
  15451. $cell_padding['R'] = $this->getHTMLUnitToUnits($cell_padding['R'], $width, 'px', false);
  15452. $cell_padding['B'] = $this->getHTMLUnitToUnits($cell_padding['B'], $width, 'px', false);
  15453. $cell_padding['L'] = $this->getHTMLUnitToUnits($cell_padding['L'], $width, 'px', false);
  15454. return $cell_padding;
  15455. }
  15456. /**
  15457. * Get the internal Cell margin from CSS attribute.
  15458. * @param $cssmargin (string) margin properties
  15459. * @param $width (float) width of the containing element
  15460. * @return array of cell margins
  15461. * @public
  15462. * @since 5.9.000 (2010-10-04)
  15463. */
  15464. public function getCSSMargin($cssmargin, $width=0) {
  15465. $margin = preg_split('/[\s]+/', trim($cssmargin));
  15466. $cell_margin = array(); // value to be returned
  15467. switch (count($margin)) {
  15468. case 4: {
  15469. $cell_margin['T'] = $margin[0];
  15470. $cell_margin['R'] = $margin[1];
  15471. $cell_margin['B'] = $margin[2];
  15472. $cell_margin['L'] = $margin[3];
  15473. break;
  15474. }
  15475. case 3: {
  15476. $cell_margin['T'] = $margin[0];
  15477. $cell_margin['R'] = $margin[1];
  15478. $cell_margin['B'] = $margin[2];
  15479. $cell_margin['L'] = $margin[1];
  15480. break;
  15481. }
  15482. case 2: {
  15483. $cell_margin['T'] = $margin[0];
  15484. $cell_margin['R'] = $margin[1];
  15485. $cell_margin['B'] = $margin[0];
  15486. $cell_margin['L'] = $margin[1];
  15487. break;
  15488. }
  15489. case 1: {
  15490. $cell_margin['T'] = $margin[0];
  15491. $cell_margin['R'] = $margin[0];
  15492. $cell_margin['B'] = $margin[0];
  15493. $cell_margin['L'] = $margin[0];
  15494. break;
  15495. }
  15496. default: {
  15497. return $this->cell_margin;
  15498. }
  15499. }
  15500. if ($width == 0) {
  15501. $width = $this->w - $this->lMargin - $this->rMargin;
  15502. }
  15503. $cell_margin['T'] = $this->getHTMLUnitToUnits(str_replace('auto', '0', $cell_margin['T']), $width, 'px', false);
  15504. $cell_margin['R'] = $this->getHTMLUnitToUnits(str_replace('auto', '0', $cell_margin['R']), $width, 'px', false);
  15505. $cell_margin['B'] = $this->getHTMLUnitToUnits(str_replace('auto', '0', $cell_margin['B']), $width, 'px', false);
  15506. $cell_margin['L'] = $this->getHTMLUnitToUnits(str_replace('auto', '0', $cell_margin['L']), $width, 'px', false);
  15507. return $cell_margin;
  15508. }
  15509. /**
  15510. * Get the border-spacing from CSS attribute.
  15511. * @param $cssbspace (string) border-spacing CSS properties
  15512. * @param $width (float) width of the containing element
  15513. * @return array of border spacings
  15514. * @public
  15515. * @since 5.9.010 (2010-10-27)
  15516. */
  15517. public function getCSSBorderMargin($cssbspace, $width=0) {
  15518. $space = preg_split('/[\s]+/', trim($cssbspace));
  15519. $border_spacing = array(); // value to be returned
  15520. switch (count($space)) {
  15521. case 2: {
  15522. $border_spacing['H'] = $space[0];
  15523. $border_spacing['V'] = $space[1];
  15524. break;
  15525. }
  15526. case 1: {
  15527. $border_spacing['H'] = $space[0];
  15528. $border_spacing['V'] = $space[0];
  15529. break;
  15530. }
  15531. default: {
  15532. return array('H' => 0, 'V' => 0);
  15533. }
  15534. }
  15535. if ($width == 0) {
  15536. $width = $this->w - $this->lMargin - $this->rMargin;
  15537. }
  15538. $border_spacing['H'] = $this->getHTMLUnitToUnits($border_spacing['H'], $width, 'px', false);
  15539. $border_spacing['V'] = $this->getHTMLUnitToUnits($border_spacing['V'], $width, 'px', false);
  15540. return $border_spacing;
  15541. }
  15542. /**
  15543. * Returns the letter-spacing value from CSS value
  15544. * @param $spacing (string) letter-spacing value
  15545. * @param $parent (float) font spacing (tracking) value of the parent element
  15546. * @return float quantity to increases or decreases the space between characters in a text.
  15547. * @protected
  15548. * @since 5.9.000 (2010-10-02)
  15549. */
  15550. protected function getCSSFontSpacing($spacing, $parent=0) {
  15551. $val = 0; // value to be returned
  15552. $spacing = trim($spacing);
  15553. switch ($spacing) {
  15554. case 'normal': {
  15555. $val = 0;
  15556. break;
  15557. }
  15558. case 'inherit': {
  15559. if ($parent == 'normal') {
  15560. $val = 0;
  15561. } else {
  15562. $val = $parent;
  15563. }
  15564. break;
  15565. }
  15566. default: {
  15567. $val = $this->getHTMLUnitToUnits($spacing, 0, 'px', false);
  15568. }
  15569. }
  15570. return $val;
  15571. }
  15572. /**
  15573. * Returns the percentage of font stretching from CSS value
  15574. * @param $stretch (string) stretch mode
  15575. * @param $parent (float) stretch value of the parent element
  15576. * @return float font stretching percentage
  15577. * @protected
  15578. * @since 5.9.000 (2010-10-02)
  15579. */
  15580. protected function getCSSFontStretching($stretch, $parent=100) {
  15581. $val = 100; // value to be returned
  15582. $stretch = trim($stretch);
  15583. switch ($stretch) {
  15584. case 'ultra-condensed': {
  15585. $val = 40;
  15586. break;
  15587. }
  15588. case 'extra-condensed': {
  15589. $val = 55;
  15590. break;
  15591. }
  15592. case 'condensed': {
  15593. $val = 70;
  15594. break;
  15595. }
  15596. case 'semi-condensed': {
  15597. $val = 85;
  15598. break;
  15599. }
  15600. case 'normal': {
  15601. $val = 100;
  15602. break;
  15603. }
  15604. case 'semi-expanded': {
  15605. $val = 115;
  15606. break;
  15607. }
  15608. case 'expanded': {
  15609. $val = 130;
  15610. break;
  15611. }
  15612. case 'extra-expanded': {
  15613. $val = 145;
  15614. break;
  15615. }
  15616. case 'ultra-expanded': {
  15617. $val = 160;
  15618. break;
  15619. }
  15620. case 'wider': {
  15621. $val = ($parent + 10);
  15622. break;
  15623. }
  15624. case 'narrower': {
  15625. $val = ($parent - 10);
  15626. break;
  15627. }
  15628. case 'inherit': {
  15629. if ($parent == 'normal') {
  15630. $val = 100;
  15631. } else {
  15632. $val = $parent;
  15633. }
  15634. break;
  15635. }
  15636. default: {
  15637. $val = $this->getHTMLUnitToUnits($stretch, 100, '%', false);
  15638. }
  15639. }
  15640. return $val;
  15641. }
  15642. /**
  15643. * Convert HTML string containing font size value to points
  15644. * @param $val (string) String containing font size value and unit.
  15645. * @param $refsize (float) Reference font size in points.
  15646. * @param $parent_size (float) Parent font size in points.
  15647. * @param $defaultunit (string) Default unit (can be one of the following: %, em, ex, px, in, mm, pc, pt).
  15648. * @return float value in points
  15649. * @public
  15650. */
  15651. public function getHTMLFontUnits($val, $refsize=12, $parent_size=12, $defaultunit='pt') {
  15652. $refsize = TCPDF_FONTS::getFontRefSize($refsize);
  15653. $parent_size = TCPDF_FONTS::getFontRefSize($parent_size, $refsize);
  15654. switch ($val) {
  15655. case 'xx-small': {
  15656. $size = ($refsize - 4);
  15657. break;
  15658. }
  15659. case 'x-small': {
  15660. $size = ($refsize - 3);
  15661. break;
  15662. }
  15663. case 'small': {
  15664. $size = ($refsize - 2);
  15665. break;
  15666. }
  15667. case 'medium': {
  15668. $size = $refsize;
  15669. break;
  15670. }
  15671. case 'large': {
  15672. $size = ($refsize + 2);
  15673. break;
  15674. }
  15675. case 'x-large': {
  15676. $size = ($refsize + 4);
  15677. break;
  15678. }
  15679. case 'xx-large': {
  15680. $size = ($refsize + 6);
  15681. break;
  15682. }
  15683. case 'smaller': {
  15684. $size = ($parent_size - 3);
  15685. break;
  15686. }
  15687. case 'larger': {
  15688. $size = ($parent_size + 3);
  15689. break;
  15690. }
  15691. default: {
  15692. $size = $this->getHTMLUnitToUnits($val, $parent_size, $defaultunit, true);
  15693. }
  15694. }
  15695. return $size;
  15696. }
  15697. /**
  15698. * Returns the HTML DOM array.
  15699. * @param $html (string) html code
  15700. * @return array
  15701. * @protected
  15702. * @since 3.2.000 (2008-06-20)
  15703. */
  15704. protected function getHtmlDomArray($html) {
  15705. // array of CSS styles ( selector => properties).
  15706. $css = array();
  15707. // get CSS array defined at previous call
  15708. $matches = array();
  15709. if (preg_match_all('/<cssarray>([^\<]*)<\/cssarray>/isU', $html, $matches) > 0) {
  15710. if (isset($matches[1][0])) {
  15711. $css = array_merge($css, json_decode($this->unhtmlentities($matches[1][0]), true));
  15712. }
  15713. $html = preg_replace('/<cssarray>(.*?)<\/cssarray>/isU', '', $html);
  15714. }
  15715. // extract external CSS files
  15716. $matches = array();
  15717. if (preg_match_all('/<link([^\>]*)>/isU', $html, $matches) > 0) {
  15718. foreach ($matches[1] as $key => $link) {
  15719. $type = array();
  15720. if (preg_match('/type[\s]*=[\s]*"text\/css"/', $link, $type)) {
  15721. $type = array();
  15722. preg_match('/media[\s]*=[\s]*"([^"]*)"/', $link, $type);
  15723. // get 'all' and 'print' media, other media types are discarded
  15724. // (all, braille, embossed, handheld, print, projection, screen, speech, tty, tv)
  15725. if (empty($type) OR (isset($type[1]) AND (($type[1] == 'all') OR ($type[1] == 'print')))) {
  15726. $type = array();
  15727. if (preg_match('/href[\s]*=[\s]*"([^"]*)"/', $link, $type) > 0) {
  15728. // read CSS data file
  15729. $cssdata = TCPDF_STATIC::fileGetContents(trim($type[1]));
  15730. if (($cssdata !== FALSE) AND (strlen($cssdata) > 0)) {
  15731. $css = array_merge($css, TCPDF_STATIC::extractCSSproperties($cssdata));
  15732. }
  15733. }
  15734. }
  15735. }
  15736. }
  15737. }
  15738. // extract style tags
  15739. $matches = array();
  15740. if (preg_match_all('/<style([^\>]*)>([^\<]*)<\/style>/isU', $html, $matches) > 0) {
  15741. foreach ($matches[1] as $key => $media) {
  15742. $type = array();
  15743. preg_match('/media[\s]*=[\s]*"([^"]*)"/', $media, $type);
  15744. // get 'all' and 'print' media, other media types are discarded
  15745. // (all, braille, embossed, handheld, print, projection, screen, speech, tty, tv)
  15746. if (empty($type) OR (isset($type[1]) AND (($type[1] == 'all') OR ($type[1] == 'print')))) {
  15747. $cssdata = $matches[2][$key];
  15748. $css = array_merge($css, TCPDF_STATIC::extractCSSproperties($cssdata));
  15749. }
  15750. }
  15751. }
  15752. // create a special tag to contain the CSS array (used for table content)
  15753. $csstagarray = '<cssarray>'.htmlentities(json_encode($css)).'</cssarray>';
  15754. // remove head and style blocks
  15755. $html = preg_replace('/<head([^\>]*)>(.*?)<\/head>/siU', '', $html);
  15756. $html = preg_replace('/<style([^\>]*)>([^\<]*)<\/style>/isU', '', $html);
  15757. // define block tags
  15758. $blocktags = array('blockquote','br','dd','dl','div','dt','h1','h2','h3','h4','h5','h6','hr','li','ol','p','pre','ul','tcpdf','table','tr','td');
  15759. // define self-closing tags
  15760. $selfclosingtags = array('area','base','basefont','br','hr','input','img','link','meta');
  15761. // remove all unsupported tags (the line below lists all supported tags)
  15762. $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>');
  15763. //replace some blank characters
  15764. $html = preg_replace('/<pre/', '<xre', $html); // preserve pre tag
  15765. $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);
  15766. $html = preg_replace('@(\r\n|\r)@', "\n", $html);
  15767. $repTable = array("\t" => ' ', "\0" => ' ', "\x0B" => ' ', "\\" => "\\\\");
  15768. $html = strtr($html, $repTable);
  15769. $offset = 0;
  15770. while (($offset < strlen($html)) AND ($pos = strpos($html, '</pre>', $offset)) !== false) {
  15771. $html_a = substr($html, 0, $offset);
  15772. $html_b = substr($html, $offset, ($pos - $offset + 6));
  15773. while (preg_match("'<xre([^\>]*)>(.*?)\n(.*?)</pre>'si", $html_b)) {
  15774. // preserve newlines on <pre> tag
  15775. $html_b = preg_replace("'<xre([^\>]*)>(.*?)\n(.*?)</pre>'si", "<xre\\1>\\2<br />\\3</pre>", $html_b);
  15776. }
  15777. while (preg_match("'<xre([^\>]*)>(.*?)".$this->re_space['p']."(.*?)</pre>'".$this->re_space['m'], $html_b)) {
  15778. // preserve spaces on <pre> tag
  15779. $html_b = preg_replace("'<xre([^\>]*)>(.*?)".$this->re_space['p']."(.*?)</pre>'".$this->re_space['m'], "<xre\\1>\\2&nbsp;\\3</pre>", $html_b);
  15780. }
  15781. $html = $html_a.$html_b.substr($html, $pos + 6);
  15782. $offset = strlen($html_a.$html_b);
  15783. }
  15784. $offset = 0;
  15785. while (($offset < strlen($html)) AND ($pos = strpos($html, '</textarea>', $offset)) !== false) {
  15786. $html_a = substr($html, 0, $offset);
  15787. $html_b = substr($html, $offset, ($pos - $offset + 11));
  15788. while (preg_match("'<textarea([^\>]*)>(.*?)\n(.*?)</textarea>'si", $html_b)) {
  15789. // preserve newlines on <textarea> tag
  15790. $html_b = preg_replace("'<textarea([^\>]*)>(.*?)\n(.*?)</textarea>'si", "<textarea\\1>\\2<TBR>\\3</textarea>", $html_b);
  15791. $html_b = preg_replace("'<textarea([^\>]*)>(.*?)[\"](.*?)</textarea>'si", "<textarea\\1>\\2''\\3</textarea>", $html_b);
  15792. }
  15793. $html = $html_a.$html_b.substr($html, $pos + 11);
  15794. $offset = strlen($html_a.$html_b);
  15795. }
  15796. $html = preg_replace('/([\s]*)<option/si', '<option', $html);
  15797. $html = preg_replace('/<\/option>([\s]*)/si', '</option>', $html);
  15798. $offset = 0;
  15799. while (($offset < strlen($html)) AND ($pos = strpos($html, '</option>', $offset)) !== false) {
  15800. $html_a = substr($html, 0, $offset);
  15801. $html_b = substr($html, $offset, ($pos - $offset + 9));
  15802. while (preg_match("'<option([^\>]*)>(.*?)</option>'si", $html_b)) {
  15803. $html_b = preg_replace("'<option([\s]+)value=\"([^\"]*)\"([^\>]*)>(.*?)</option>'si", "\\2#!TaB!#\\4#!NwL!#", $html_b);
  15804. $html_b = preg_replace("'<option([^\>]*)>(.*?)</option>'si", "\\2#!NwL!#", $html_b);
  15805. }
  15806. $html = $html_a.$html_b.substr($html, $pos + 9);
  15807. $offset = strlen($html_a.$html_b);
  15808. }
  15809. if (preg_match("'</select'si", $html)) {
  15810. $html = preg_replace("'<select([^\>]*)>'si", "<select\\1 opt=\"", $html);
  15811. $html = preg_replace("'#!NwL!#</select>'si", "\" />", $html);
  15812. }
  15813. $html = str_replace("\n", ' ', $html);
  15814. // restore textarea newlines
  15815. $html = str_replace('<TBR>', "\n", $html);
  15816. // remove extra spaces from code
  15817. $html = preg_replace('/[\s]+<\/(table|tr|ul|ol|dl)>/', '</\\1>', $html);
  15818. $html = preg_replace('/'.$this->re_space['p'].'+<\/(td|th|li|dt|dd)>/'.$this->re_space['m'], '</\\1>', $html);
  15819. $html = preg_replace('/[\s]+<(tr|td|th|li|dt|dd)/', '<\\1', $html);
  15820. $html = preg_replace('/'.$this->re_space['p'].'+<(ul|ol|dl|br)/'.$this->re_space['m'], '<\\1', $html);
  15821. $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);
  15822. $html = preg_replace('/<\/(td|th)>/', '<marker style="font-size:0"/></\\1>', $html);
  15823. $html = preg_replace('/<\/table>([\s]*)<marker style="font-size:0"\/>/', '</table>', $html);
  15824. $html = preg_replace('/'.$this->re_space['p'].'+<img/'.$this->re_space['m'], chr(32).'<img', $html);
  15825. $html = preg_replace('/<img([^\>]*)>[\s]+([^\<])/xi', '<img\\1>&nbsp;\\2', $html);
  15826. $html = preg_replace('/<img([^\>]*)>/xi', '<img\\1><span><marker style="font-size:0"/></span>', $html);
  15827. $html = preg_replace('/<xre/', '<pre', $html); // restore pre tag
  15828. $html = preg_replace('/<textarea([^\>]*)>([^\<]*)<\/textarea>/xi', '<textarea\\1 value="\\2" />', $html);
  15829. $html = preg_replace('/<li([^\>]*)><\/li>/', '<li\\1>&nbsp;</li>', $html);
  15830. $html = preg_replace('/<li([^\>]*)>'.$this->re_space['p'].'*<img/'.$this->re_space['m'], '<li\\1><font size="1">&nbsp;</font><img', $html);
  15831. $html = preg_replace('/<([^\>\/]*)>[\s]/', '<\\1>&nbsp;', $html); // preserve some spaces
  15832. $html = preg_replace('/[\s]<\/([^\>]*)>/', '&nbsp;</\\1>', $html); // preserve some spaces
  15833. $html = preg_replace('/<su([bp])/', '<zws/><su\\1', $html); // fix sub/sup alignment
  15834. $html = preg_replace('/<\/su([bp])>/', '</su\\1><zws/>', $html); // fix sub/sup alignment
  15835. $html = preg_replace('/'.$this->re_space['p'].'+/'.$this->re_space['m'], chr(32), $html); // replace multiple spaces with a single space
  15836. // trim string
  15837. $html = $this->stringTrim($html);
  15838. // fix br tag after li
  15839. $html = preg_replace('/<li><br([^\>]*)>/', '<li> <br\\1>', $html);
  15840. // fix first image tag alignment
  15841. $html = preg_replace('/^<img/', '<span style="font-size:0"><br /></span> <img', $html, 1);
  15842. // pattern for generic tag
  15843. $tagpattern = '/(<[^>]+>)/';
  15844. // explodes the string
  15845. $a = preg_split($tagpattern, $html, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  15846. // count elements
  15847. $maxel = count($a);
  15848. $elkey = 0;
  15849. $key = 0;
  15850. // create an array of elements
  15851. $dom = array();
  15852. $dom[$key] = array();
  15853. // set inheritable properties fot the first void element
  15854. // 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
  15855. $dom[$key]['tag'] = false;
  15856. $dom[$key]['block'] = false;
  15857. $dom[$key]['value'] = '';
  15858. $dom[$key]['parent'] = 0;
  15859. $dom[$key]['hide'] = false;
  15860. $dom[$key]['fontname'] = $this->FontFamily;
  15861. $dom[$key]['fontstyle'] = $this->FontStyle;
  15862. $dom[$key]['fontsize'] = $this->FontSizePt;
  15863. $dom[$key]['font-stretch'] = $this->font_stretching;
  15864. $dom[$key]['letter-spacing'] = $this->font_spacing;
  15865. $dom[$key]['stroke'] = $this->textstrokewidth;
  15866. $dom[$key]['fill'] = (($this->textrendermode % 2) == 0);
  15867. $dom[$key]['clip'] = ($this->textrendermode > 3);
  15868. $dom[$key]['line-height'] = $this->cell_height_ratio;
  15869. $dom[$key]['bgcolor'] = false;
  15870. $dom[$key]['fgcolor'] = $this->fgcolor; // color
  15871. $dom[$key]['strokecolor'] = $this->strokecolor;
  15872. $dom[$key]['align'] = '';
  15873. $dom[$key]['listtype'] = '';
  15874. $dom[$key]['text-indent'] = 0;
  15875. $dom[$key]['text-transform'] = '';
  15876. $dom[$key]['border'] = array();
  15877. $dom[$key]['dir'] = $this->rtl?'rtl':'ltr';
  15878. $thead = false; // true when we are inside the THEAD tag
  15879. ++$key;
  15880. $level = array();
  15881. array_push($level, 0); // root
  15882. while ($elkey < $maxel) {
  15883. $dom[$key] = array();
  15884. $element = $a[$elkey];
  15885. $dom[$key]['elkey'] = $elkey;
  15886. if (preg_match($tagpattern, $element)) {
  15887. // html tag
  15888. $element = substr($element, 1, -1);
  15889. // get tag name
  15890. preg_match('/[\/]?([a-zA-Z0-9]*)/', $element, $tag);
  15891. $tagname = strtolower($tag[1]);
  15892. // check if we are inside a table header
  15893. if ($tagname == 'thead') {
  15894. if ($element[0] == '/') {
  15895. $thead = false;
  15896. } else {
  15897. $thead = true;
  15898. }
  15899. ++$elkey;
  15900. continue;
  15901. }
  15902. $dom[$key]['tag'] = true;
  15903. $dom[$key]['value'] = $tagname;
  15904. if (in_array($dom[$key]['value'], $blocktags)) {
  15905. $dom[$key]['block'] = true;
  15906. } else {
  15907. $dom[$key]['block'] = false;
  15908. }
  15909. if ($element[0] == '/') {
  15910. // *** closing html tag
  15911. $dom[$key]['opening'] = false;
  15912. $dom[$key]['parent'] = end($level);
  15913. array_pop($level);
  15914. $dom[$key]['hide'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['hide'];
  15915. $dom[$key]['fontname'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fontname'];
  15916. $dom[$key]['fontstyle'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fontstyle'];
  15917. $dom[$key]['fontsize'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fontsize'];
  15918. $dom[$key]['font-stretch'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['font-stretch'];
  15919. $dom[$key]['letter-spacing'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['letter-spacing'];
  15920. $dom[$key]['stroke'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['stroke'];
  15921. $dom[$key]['fill'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fill'];
  15922. $dom[$key]['clip'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['clip'];
  15923. $dom[$key]['line-height'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['line-height'];
  15924. $dom[$key]['bgcolor'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['bgcolor'];
  15925. $dom[$key]['fgcolor'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['fgcolor'];
  15926. $dom[$key]['strokecolor'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['strokecolor'];
  15927. $dom[$key]['align'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['align'];
  15928. $dom[$key]['text-transform'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['text-transform'];
  15929. $dom[$key]['dir'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['dir'];
  15930. if (isset($dom[($dom[($dom[$key]['parent'])]['parent'])]['listtype'])) {
  15931. $dom[$key]['listtype'] = $dom[($dom[($dom[$key]['parent'])]['parent'])]['listtype'];
  15932. }
  15933. // set the number of columns in table tag
  15934. if (($dom[$key]['value'] == 'tr') AND (!isset($dom[($dom[($dom[$key]['parent'])]['parent'])]['cols']))) {
  15935. $dom[($dom[($dom[$key]['parent'])]['parent'])]['cols'] = $dom[($dom[$key]['parent'])]['cols'];
  15936. }
  15937. if (($dom[$key]['value'] == 'td') OR ($dom[$key]['value'] == 'th')) {
  15938. $dom[($dom[$key]['parent'])]['content'] = $csstagarray;
  15939. for ($i = ($dom[$key]['parent'] + 1); $i < $key; ++$i) {
  15940. $dom[($dom[$key]['parent'])]['content'] .= stripslashes($a[$dom[$i]['elkey']]);
  15941. }
  15942. $key = $i;
  15943. // mark nested tables
  15944. $dom[($dom[$key]['parent'])]['content'] = str_replace('<table', '<table nested="true"', $dom[($dom[$key]['parent'])]['content']);
  15945. // remove thead sections from nested tables
  15946. $dom[($dom[$key]['parent'])]['content'] = str_replace('<thead>', '', $dom[($dom[$key]['parent'])]['content']);
  15947. $dom[($dom[$key]['parent'])]['content'] = str_replace('</thead>', '', $dom[($dom[$key]['parent'])]['content']);
  15948. }
  15949. // store header rows on a new table
  15950. if (($dom[$key]['value'] == 'tr') AND ($dom[($dom[$key]['parent'])]['thead'] === true)) {
  15951. if (TCPDF_STATIC::empty_string($dom[($dom[($dom[$key]['parent'])]['parent'])]['thead'])) {
  15952. $dom[($dom[($dom[$key]['parent'])]['parent'])]['thead'] = $csstagarray.$a[$dom[($dom[($dom[$key]['parent'])]['parent'])]['elkey']];
  15953. }
  15954. for ($i = $dom[$key]['parent']; $i <= $key; ++$i) {
  15955. $dom[($dom[($dom[$key]['parent'])]['parent'])]['thead'] .= $a[$dom[$i]['elkey']];
  15956. }
  15957. if (!isset($dom[($dom[$key]['parent'])]['attribute'])) {
  15958. $dom[($dom[$key]['parent'])]['attribute'] = array();
  15959. }
  15960. // header elements must be always contained in a single page
  15961. $dom[($dom[$key]['parent'])]['attribute']['nobr'] = 'true';
  15962. }
  15963. if (($dom[$key]['value'] == 'table') AND (!TCPDF_STATIC::empty_string($dom[($dom[$key]['parent'])]['thead']))) {
  15964. // remove the nobr attributes from the table header
  15965. $dom[($dom[$key]['parent'])]['thead'] = str_replace(' nobr="true"', '', $dom[($dom[$key]['parent'])]['thead']);
  15966. $dom[($dom[$key]['parent'])]['thead'] .= '</tablehead>';
  15967. }
  15968. } else {
  15969. // *** opening or self-closing html tag
  15970. $dom[$key]['opening'] = true;
  15971. $dom[$key]['parent'] = end($level);
  15972. if ((substr($element, -1, 1) == '/') OR (in_array($dom[$key]['value'], $selfclosingtags))) {
  15973. // self-closing tag
  15974. $dom[$key]['self'] = true;
  15975. } else {
  15976. // opening tag
  15977. array_push($level, $key);
  15978. $dom[$key]['self'] = false;
  15979. }
  15980. // copy some values from parent
  15981. $parentkey = 0;
  15982. if ($key > 0) {
  15983. $parentkey = $dom[$key]['parent'];
  15984. $dom[$key]['hide'] = $dom[$parentkey]['hide'];
  15985. $dom[$key]['fontname'] = $dom[$parentkey]['fontname'];
  15986. $dom[$key]['fontstyle'] = $dom[$parentkey]['fontstyle'];
  15987. $dom[$key]['fontsize'] = $dom[$parentkey]['fontsize'];
  15988. $dom[$key]['font-stretch'] = $dom[$parentkey]['font-stretch'];
  15989. $dom[$key]['letter-spacing'] = $dom[$parentkey]['letter-spacing'];
  15990. $dom[$key]['stroke'] = $dom[$parentkey]['stroke'];
  15991. $dom[$key]['fill'] = $dom[$parentkey]['fill'];
  15992. $dom[$key]['clip'] = $dom[$parentkey]['clip'];
  15993. $dom[$key]['line-height'] = $dom[$parentkey]['line-height'];
  15994. $dom[$key]['bgcolor'] = $dom[$parentkey]['bgcolor'];
  15995. $dom[$key]['fgcolor'] = $dom[$parentkey]['fgcolor'];
  15996. $dom[$key]['strokecolor'] = $dom[$parentkey]['strokecolor'];
  15997. $dom[$key]['align'] = $dom[$parentkey]['align'];
  15998. $dom[$key]['listtype'] = $dom[$parentkey]['listtype'];
  15999. $dom[$key]['text-indent'] = $dom[$parentkey]['text-indent'];
  16000. $dom[$key]['text-transform'] = $dom[$parentkey]['text-transform'];
  16001. $dom[$key]['border'] = array();
  16002. $dom[$key]['dir'] = $dom[$parentkey]['dir'];
  16003. }
  16004. // get attributes
  16005. preg_match_all('/([^=\s]*)[\s]*=[\s]*"([^"]*)"/', $element, $attr_array, PREG_PATTERN_ORDER);
  16006. $dom[$key]['attribute'] = array(); // reset attribute array
  16007. foreach($attr_array[1] as $id => $name) {
  16008. $dom[$key]['attribute'][strtolower($name)] = $attr_array[2][$id];
  16009. }
  16010. if (!empty($css)) {
  16011. // merge CSS style to current style
  16012. list($dom[$key]['csssel'], $dom[$key]['cssdata']) = TCPDF_STATIC::getCSSdataArray($dom, $key, $css);
  16013. $dom[$key]['attribute']['style'] = TCPDF_STATIC::getTagStyleFromCSSarray($dom[$key]['cssdata']);
  16014. }
  16015. // split style attributes
  16016. if (isset($dom[$key]['attribute']['style']) AND !empty($dom[$key]['attribute']['style'])) {
  16017. // get style attributes
  16018. preg_match_all('/([^;:\s]*):([^;]*)/', $dom[$key]['attribute']['style'], $style_array, PREG_PATTERN_ORDER);
  16019. $dom[$key]['style'] = array(); // reset style attribute array
  16020. foreach($style_array[1] as $id => $name) {
  16021. // in case of duplicate attribute the last replace the previous
  16022. $dom[$key]['style'][strtolower($name)] = trim($style_array[2][$id]);
  16023. }
  16024. // --- get some style attributes ---
  16025. // text direction
  16026. if (isset($dom[$key]['style']['direction'])) {
  16027. $dom[$key]['dir'] = $dom[$key]['style']['direction'];
  16028. }
  16029. // display
  16030. if (isset($dom[$key]['style']['display'])) {
  16031. $dom[$key]['hide'] = (trim(strtolower($dom[$key]['style']['display'])) == 'none');
  16032. }
  16033. // font family
  16034. if (isset($dom[$key]['style']['font-family'])) {
  16035. $dom[$key]['fontname'] = $this->getFontFamilyName($dom[$key]['style']['font-family']);
  16036. }
  16037. // list-style-type
  16038. if (isset($dom[$key]['style']['list-style-type'])) {
  16039. $dom[$key]['listtype'] = trim(strtolower($dom[$key]['style']['list-style-type']));
  16040. if ($dom[$key]['listtype'] == 'inherit') {
  16041. $dom[$key]['listtype'] = $dom[$parentkey]['listtype'];
  16042. }
  16043. }
  16044. // text-indent
  16045. if (isset($dom[$key]['style']['text-indent'])) {
  16046. $dom[$key]['text-indent'] = $this->getHTMLUnitToUnits($dom[$key]['style']['text-indent']);
  16047. if ($dom[$key]['text-indent'] == 'inherit') {
  16048. $dom[$key]['text-indent'] = $dom[$parentkey]['text-indent'];
  16049. }
  16050. }
  16051. // text-transform
  16052. if (isset($dom[$key]['style']['text-transform'])) {
  16053. $dom[$key]['text-transform'] = $dom[$key]['style']['text-transform'];
  16054. }
  16055. // font size
  16056. if (isset($dom[$key]['style']['font-size'])) {
  16057. $fsize = trim($dom[$key]['style']['font-size']);
  16058. $dom[$key]['fontsize'] = $this->getHTMLFontUnits($fsize, $dom[0]['fontsize'], $dom[$parentkey]['fontsize'], 'pt');
  16059. }
  16060. // font-stretch
  16061. if (isset($dom[$key]['style']['font-stretch'])) {
  16062. $dom[$key]['font-stretch'] = $this->getCSSFontStretching($dom[$key]['style']['font-stretch'], $dom[$parentkey]['font-stretch']);
  16063. }
  16064. // letter-spacing
  16065. if (isset($dom[$key]['style']['letter-spacing'])) {
  16066. $dom[$key]['letter-spacing'] = $this->getCSSFontSpacing($dom[$key]['style']['letter-spacing'], $dom[$parentkey]['letter-spacing']);
  16067. }
  16068. // line-height (internally is the cell height ratio)
  16069. if (isset($dom[$key]['style']['line-height'])) {
  16070. $lineheight = trim($dom[$key]['style']['line-height']);
  16071. switch ($lineheight) {
  16072. // A normal line height. This is default
  16073. case 'normal': {
  16074. $dom[$key]['line-height'] = $dom[0]['line-height'];
  16075. break;
  16076. }
  16077. case 'inherit': {
  16078. $dom[$key]['line-height'] = $dom[$parentkey]['line-height'];
  16079. }
  16080. default: {
  16081. if (is_numeric($lineheight)) {
  16082. // convert to percentage of font height
  16083. $lineheight = ($lineheight * 100).'%';
  16084. }
  16085. $dom[$key]['line-height'] = $this->getHTMLUnitToUnits($lineheight, 1, '%', true);
  16086. if (substr($lineheight, -1) !== '%') {
  16087. if ($dom[$key]['fontsize'] <= 0) {
  16088. $dom[$key]['line-height'] = 1;
  16089. } else {
  16090. $dom[$key]['line-height'] = (($dom[$key]['line-height'] - $this->cell_padding['T'] - $this->cell_padding['B']) / $dom[$key]['fontsize']);
  16091. }
  16092. }
  16093. }
  16094. }
  16095. }
  16096. // font style
  16097. if (isset($dom[$key]['style']['font-weight'])) {
  16098. if (strtolower($dom[$key]['style']['font-weight'][0]) == 'n') {
  16099. if (strpos($dom[$key]['fontstyle'], 'B') !== false) {
  16100. $dom[$key]['fontstyle'] = str_replace('B', '', $dom[$key]['fontstyle']);
  16101. }
  16102. } elseif (strtolower($dom[$key]['style']['font-weight'][0]) == 'b') {
  16103. $dom[$key]['fontstyle'] .= 'B';
  16104. }
  16105. }
  16106. if (isset($dom[$key]['style']['font-style']) AND (strtolower($dom[$key]['style']['font-style'][0]) == 'i')) {
  16107. $dom[$key]['fontstyle'] .= 'I';
  16108. }
  16109. // font color
  16110. if (isset($dom[$key]['style']['color']) AND (!TCPDF_STATIC::empty_string($dom[$key]['style']['color']))) {
  16111. $dom[$key]['fgcolor'] = TCPDF_COLORS::convertHTMLColorToDec($dom[$key]['style']['color'], $this->spot_colors);
  16112. } elseif ($dom[$key]['value'] == 'a') {
  16113. $dom[$key]['fgcolor'] = $this->htmlLinkColorArray;
  16114. }
  16115. // background color
  16116. if (isset($dom[$key]['style']['background-color']) AND (!TCPDF_STATIC::empty_string($dom[$key]['style']['background-color']))) {
  16117. $dom[$key]['bgcolor'] = TCPDF_COLORS::convertHTMLColorToDec($dom[$key]['style']['background-color'], $this->spot_colors);
  16118. }
  16119. // text-decoration
  16120. if (isset($dom[$key]['style']['text-decoration'])) {
  16121. $decors = explode(' ', strtolower($dom[$key]['style']['text-decoration']));
  16122. foreach ($decors as $dec) {
  16123. $dec = trim($dec);
  16124. if (!TCPDF_STATIC::empty_string($dec)) {
  16125. if ($dec[0] == 'u') {
  16126. // underline
  16127. $dom[$key]['fontstyle'] .= 'U';
  16128. } elseif ($dec[0] == 'l') {
  16129. // line-through
  16130. $dom[$key]['fontstyle'] .= 'D';
  16131. } elseif ($dec[0] == 'o') {
  16132. // overline
  16133. $dom[$key]['fontstyle'] .= 'O';
  16134. }
  16135. }
  16136. }
  16137. } elseif ($dom[$key]['value'] == 'a') {
  16138. $dom[$key]['fontstyle'] = $this->htmlLinkFontStyle;
  16139. }
  16140. // check for width attribute
  16141. if (isset($dom[$key]['style']['width'])) {
  16142. $dom[$key]['width'] = $dom[$key]['style']['width'];
  16143. }
  16144. // check for height attribute
  16145. if (isset($dom[$key]['style']['height'])) {
  16146. $dom[$key]['height'] = $dom[$key]['style']['height'];
  16147. }
  16148. // check for text alignment
  16149. if (isset($dom[$key]['style']['text-align'])) {
  16150. $dom[$key]['align'] = strtoupper($dom[$key]['style']['text-align'][0]);
  16151. }
  16152. // check for CSS border properties
  16153. if (isset($dom[$key]['style']['border'])) {
  16154. $borderstyle = $this->getCSSBorderStyle($dom[$key]['style']['border']);
  16155. if (!empty($borderstyle)) {
  16156. $dom[$key]['border']['LTRB'] = $borderstyle;
  16157. }
  16158. }
  16159. if (isset($dom[$key]['style']['border-color'])) {
  16160. $brd_colors = preg_split('/[\s]+/', trim($dom[$key]['style']['border-color']));
  16161. if (isset($brd_colors[3])) {
  16162. $dom[$key]['border']['L']['color'] = TCPDF_COLORS::convertHTMLColorToDec($brd_colors[3], $this->spot_colors);
  16163. }
  16164. if (isset($brd_colors[1])) {
  16165. $dom[$key]['border']['R']['color'] = TCPDF_COLORS::convertHTMLColorToDec($brd_colors[1], $this->spot_colors);
  16166. }
  16167. if (isset($brd_colors[0])) {
  16168. $dom[$key]['border']['T']['color'] = TCPDF_COLORS::convertHTMLColorToDec($brd_colors[0], $this->spot_colors);
  16169. }
  16170. if (isset($brd_colors[2])) {
  16171. $dom[$key]['border']['B']['color'] = TCPDF_COLORS::convertHTMLColorToDec($brd_colors[2], $this->spot_colors);
  16172. }
  16173. }
  16174. if (isset($dom[$key]['style']['border-width'])) {
  16175. $brd_widths = preg_split('/[\s]+/', trim($dom[$key]['style']['border-width']));
  16176. if (isset($brd_widths[3])) {
  16177. $dom[$key]['border']['L']['width'] = $this->getCSSBorderWidth($brd_widths[3]);
  16178. }
  16179. if (isset($brd_widths[1])) {
  16180. $dom[$key]['border']['R']['width'] = $this->getCSSBorderWidth($brd_widths[1]);
  16181. }
  16182. if (isset($brd_widths[0])) {
  16183. $dom[$key]['border']['T']['width'] = $this->getCSSBorderWidth($brd_widths[0]);
  16184. }
  16185. if (isset($brd_widths[2])) {
  16186. $dom[$key]['border']['B']['width'] = $this->getCSSBorderWidth($brd_widths[2]);
  16187. }
  16188. }
  16189. if (isset($dom[$key]['style']['border-style'])) {
  16190. $brd_styles = preg_split('/[\s]+/', trim($dom[$key]['style']['border-style']));
  16191. if (isset($brd_styles[3]) AND ($brd_styles[3]!='none')) {
  16192. $dom[$key]['border']['L']['cap'] = 'square';
  16193. $dom[$key]['border']['L']['join'] = 'miter';
  16194. $dom[$key]['border']['L']['dash'] = $this->getCSSBorderDashStyle($brd_styles[3]);
  16195. if ($dom[$key]['border']['L']['dash'] < 0) {
  16196. $dom[$key]['border']['L'] = array();
  16197. }
  16198. }
  16199. if (isset($brd_styles[1])) {
  16200. $dom[$key]['border']['R']['cap'] = 'square';
  16201. $dom[$key]['border']['R']['join'] = 'miter';
  16202. $dom[$key]['border']['R']['dash'] = $this->getCSSBorderDashStyle($brd_styles[1]);
  16203. if ($dom[$key]['border']['R']['dash'] < 0) {
  16204. $dom[$key]['border']['R'] = array();
  16205. }
  16206. }
  16207. if (isset($brd_styles[0])) {
  16208. $dom[$key]['border']['T']['cap'] = 'square';
  16209. $dom[$key]['border']['T']['join'] = 'miter';
  16210. $dom[$key]['border']['T']['dash'] = $this->getCSSBorderDashStyle($brd_styles[0]);
  16211. if ($dom[$key]['border']['T']['dash'] < 0) {
  16212. $dom[$key]['border']['T'] = array();
  16213. }
  16214. }
  16215. if (isset($brd_styles[2])) {
  16216. $dom[$key]['border']['B']['cap'] = 'square';
  16217. $dom[$key]['border']['B']['join'] = 'miter';
  16218. $dom[$key]['border']['B']['dash'] = $this->getCSSBorderDashStyle($brd_styles[2]);
  16219. if ($dom[$key]['border']['B']['dash'] < 0) {
  16220. $dom[$key]['border']['B'] = array();
  16221. }
  16222. }
  16223. }
  16224. $cellside = array('L' => 'left', 'R' => 'right', 'T' => 'top', 'B' => 'bottom');
  16225. foreach ($cellside as $bsk => $bsv) {
  16226. if (isset($dom[$key]['style']['border-'.$bsv])) {
  16227. $borderstyle = $this->getCSSBorderStyle($dom[$key]['style']['border-'.$bsv]);
  16228. if (!empty($borderstyle)) {
  16229. $dom[$key]['border'][$bsk] = $borderstyle;
  16230. }
  16231. }
  16232. if (isset($dom[$key]['style']['border-'.$bsv.'-color'])) {
  16233. $dom[$key]['border'][$bsk]['color'] = TCPDF_COLORS::convertHTMLColorToDec($dom[$key]['style']['border-'.$bsv.'-color'], $this->spot_colors);
  16234. }
  16235. if (isset($dom[$key]['style']['border-'.$bsv.'-width'])) {
  16236. $dom[$key]['border'][$bsk]['width'] = $this->getCSSBorderWidth($dom[$key]['style']['border-'.$bsv.'-width']);
  16237. }
  16238. if (isset($dom[$key]['style']['border-'.$bsv.'-style'])) {
  16239. $dom[$key]['border'][$bsk]['dash'] = $this->getCSSBorderDashStyle($dom[$key]['style']['border-'.$bsv.'-style']);
  16240. if ($dom[$key]['border'][$bsk]['dash'] < 0) {
  16241. $dom[$key]['border'][$bsk] = array();
  16242. }
  16243. }
  16244. }
  16245. // check for CSS padding properties
  16246. if (isset($dom[$key]['style']['padding'])) {
  16247. $dom[$key]['padding'] = $this->getCSSPadding($dom[$key]['style']['padding']);
  16248. } else {
  16249. $dom[$key]['padding'] = $this->cell_padding;
  16250. }
  16251. foreach ($cellside as $psk => $psv) {
  16252. if (isset($dom[$key]['style']['padding-'.$psv])) {
  16253. $dom[$key]['padding'][$psk] = $this->getHTMLUnitToUnits($dom[$key]['style']['padding-'.$psv], 0, 'px', false);
  16254. }
  16255. }
  16256. // check for CSS margin properties
  16257. if (isset($dom[$key]['style']['margin'])) {
  16258. $dom[$key]['margin'] = $this->getCSSMargin($dom[$key]['style']['margin']);
  16259. } else {
  16260. $dom[$key]['margin'] = $this->cell_margin;
  16261. }
  16262. foreach ($cellside as $psk => $psv) {
  16263. if (isset($dom[$key]['style']['margin-'.$psv])) {
  16264. $dom[$key]['margin'][$psk] = $this->getHTMLUnitToUnits(str_replace('auto', '0', $dom[$key]['style']['margin-'.$psv]), 0, 'px', false);
  16265. }
  16266. }
  16267. // check for CSS border-spacing properties
  16268. if (isset($dom[$key]['style']['border-spacing'])) {
  16269. $dom[$key]['border-spacing'] = $this->getCSSBorderMargin($dom[$key]['style']['border-spacing']);
  16270. }
  16271. // page-break-inside
  16272. if (isset($dom[$key]['style']['page-break-inside']) AND ($dom[$key]['style']['page-break-inside'] == 'avoid')) {
  16273. $dom[$key]['attribute']['nobr'] = 'true';
  16274. }
  16275. // page-break-before
  16276. if (isset($dom[$key]['style']['page-break-before'])) {
  16277. if ($dom[$key]['style']['page-break-before'] == 'always') {
  16278. $dom[$key]['attribute']['pagebreak'] = 'true';
  16279. } elseif ($dom[$key]['style']['page-break-before'] == 'left') {
  16280. $dom[$key]['attribute']['pagebreak'] = 'left';
  16281. } elseif ($dom[$key]['style']['page-break-before'] == 'right') {
  16282. $dom[$key]['attribute']['pagebreak'] = 'right';
  16283. }
  16284. }
  16285. // page-break-after
  16286. if (isset($dom[$key]['style']['page-break-after'])) {
  16287. if ($dom[$key]['style']['page-break-after'] == 'always') {
  16288. $dom[$key]['attribute']['pagebreakafter'] = 'true';
  16289. } elseif ($dom[$key]['style']['page-break-after'] == 'left') {
  16290. $dom[$key]['attribute']['pagebreakafter'] = 'left';
  16291. } elseif ($dom[$key]['style']['page-break-after'] == 'right') {
  16292. $dom[$key]['attribute']['pagebreakafter'] = 'right';
  16293. }
  16294. }
  16295. }
  16296. if (isset($dom[$key]['attribute']['display'])) {
  16297. $dom[$key]['hide'] = (trim(strtolower($dom[$key]['attribute']['display'])) == 'none');
  16298. }
  16299. if (isset($dom[$key]['attribute']['border']) AND ($dom[$key]['attribute']['border'] != 0)) {
  16300. $borderstyle = $this->getCSSBorderStyle($dom[$key]['attribute']['border'].' solid black');
  16301. if (!empty($borderstyle)) {
  16302. $dom[$key]['border']['LTRB'] = $borderstyle;
  16303. }
  16304. }
  16305. // check for font tag
  16306. if ($dom[$key]['value'] == 'font') {
  16307. // font family
  16308. if (isset($dom[$key]['attribute']['face'])) {
  16309. $dom[$key]['fontname'] = $this->getFontFamilyName($dom[$key]['attribute']['face']);
  16310. }
  16311. // font size
  16312. if (isset($dom[$key]['attribute']['size'])) {
  16313. if ($key > 0) {
  16314. if ($dom[$key]['attribute']['size'][0] == '+') {
  16315. $dom[$key]['fontsize'] = $dom[($dom[$key]['parent'])]['fontsize'] + intval(substr($dom[$key]['attribute']['size'], 1));
  16316. } elseif ($dom[$key]['attribute']['size'][0] == '-') {
  16317. $dom[$key]['fontsize'] = $dom[($dom[$key]['parent'])]['fontsize'] - intval(substr($dom[$key]['attribute']['size'], 1));
  16318. } else {
  16319. $dom[$key]['fontsize'] = intval($dom[$key]['attribute']['size']);
  16320. }
  16321. } else {
  16322. $dom[$key]['fontsize'] = intval($dom[$key]['attribute']['size']);
  16323. }
  16324. }
  16325. }
  16326. // force natural alignment for lists
  16327. if ((($dom[$key]['value'] == 'ul') OR ($dom[$key]['value'] == 'ol') OR ($dom[$key]['value'] == 'dl'))
  16328. AND (!isset($dom[$key]['align']) OR TCPDF_STATIC::empty_string($dom[$key]['align']) OR ($dom[$key]['align'] != 'J'))) {
  16329. if ($this->rtl) {
  16330. $dom[$key]['align'] = 'R';
  16331. } else {
  16332. $dom[$key]['align'] = 'L';
  16333. }
  16334. }
  16335. if (($dom[$key]['value'] == 'small') OR ($dom[$key]['value'] == 'sup') OR ($dom[$key]['value'] == 'sub')) {
  16336. if (!isset($dom[$key]['attribute']['size']) AND !isset($dom[$key]['style']['font-size'])) {
  16337. $dom[$key]['fontsize'] = $dom[$key]['fontsize'] * K_SMALL_RATIO;
  16338. }
  16339. }
  16340. if (($dom[$key]['value'] == 'strong') OR ($dom[$key]['value'] == 'b')) {
  16341. $dom[$key]['fontstyle'] .= 'B';
  16342. }
  16343. if (($dom[$key]['value'] == 'em') OR ($dom[$key]['value'] == 'i')) {
  16344. $dom[$key]['fontstyle'] .= 'I';
  16345. }
  16346. if ($dom[$key]['value'] == 'u') {
  16347. $dom[$key]['fontstyle'] .= 'U';
  16348. }
  16349. if (($dom[$key]['value'] == 'del') OR ($dom[$key]['value'] == 's') OR ($dom[$key]['value'] == 'strike')) {
  16350. $dom[$key]['fontstyle'] .= 'D';
  16351. }
  16352. if (!isset($dom[$key]['style']['text-decoration']) AND ($dom[$key]['value'] == 'a')) {
  16353. $dom[$key]['fontstyle'] = $this->htmlLinkFontStyle;
  16354. }
  16355. if (($dom[$key]['value'] == 'pre') OR ($dom[$key]['value'] == 'tt')) {
  16356. $dom[$key]['fontname'] = $this->default_monospaced_font;
  16357. }
  16358. 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)) {
  16359. // headings h1, h2, h3, h4, h5, h6
  16360. if (!isset($dom[$key]['attribute']['size']) AND !isset($dom[$key]['style']['font-size'])) {
  16361. $headsize = (4 - intval($dom[$key]['value'][1])) * 2;
  16362. $dom[$key]['fontsize'] = $dom[0]['fontsize'] + $headsize;
  16363. }
  16364. if (!isset($dom[$key]['style']['font-weight'])) {
  16365. $dom[$key]['fontstyle'] .= 'B';
  16366. }
  16367. }
  16368. if (($dom[$key]['value'] == 'table')) {
  16369. $dom[$key]['rows'] = 0; // number of rows
  16370. $dom[$key]['trids'] = array(); // IDs of TR elements
  16371. $dom[$key]['thead'] = ''; // table header rows
  16372. }
  16373. if (($dom[$key]['value'] == 'tr')) {
  16374. $dom[$key]['cols'] = 0;
  16375. if ($thead) {
  16376. $dom[$key]['thead'] = true;
  16377. // rows on thead block are printed as a separate table
  16378. } else {
  16379. $dom[$key]['thead'] = false;
  16380. // store the number of rows on table element
  16381. ++$dom[($dom[$key]['parent'])]['rows'];
  16382. // store the TR elements IDs on table element
  16383. array_push($dom[($dom[$key]['parent'])]['trids'], $key);
  16384. }
  16385. }
  16386. if (($dom[$key]['value'] == 'th') OR ($dom[$key]['value'] == 'td')) {
  16387. if (isset($dom[$key]['attribute']['colspan'])) {
  16388. $colspan = intval($dom[$key]['attribute']['colspan']);
  16389. } else {
  16390. $colspan = 1;
  16391. }
  16392. $dom[$key]['attribute']['colspan'] = $colspan;
  16393. $dom[($dom[$key]['parent'])]['cols'] += $colspan;
  16394. }
  16395. // text direction
  16396. if (isset($dom[$key]['attribute']['dir'])) {
  16397. $dom[$key]['dir'] = $dom[$key]['attribute']['dir'];
  16398. }
  16399. // set foreground color attribute
  16400. if (isset($dom[$key]['attribute']['color']) AND (!TCPDF_STATIC::empty_string($dom[$key]['attribute']['color']))) {
  16401. $dom[$key]['fgcolor'] = TCPDF_COLORS::convertHTMLColorToDec($dom[$key]['attribute']['color'], $this->spot_colors);
  16402. } elseif (!isset($dom[$key]['style']['color']) AND ($dom[$key]['value'] == 'a')) {
  16403. $dom[$key]['fgcolor'] = $this->htmlLinkColorArray;
  16404. }
  16405. // set background color attribute
  16406. if (isset($dom[$key]['attribute']['bgcolor']) AND (!TCPDF_STATIC::empty_string($dom[$key]['attribute']['bgcolor']))) {
  16407. $dom[$key]['bgcolor'] = TCPDF_COLORS::convertHTMLColorToDec($dom[$key]['attribute']['bgcolor'], $this->spot_colors);
  16408. }
  16409. // set stroke color attribute
  16410. if (isset($dom[$key]['attribute']['strokecolor']) AND (!TCPDF_STATIC::empty_string($dom[$key]['attribute']['strokecolor']))) {
  16411. $dom[$key]['strokecolor'] = TCPDF_COLORS::convertHTMLColorToDec($dom[$key]['attribute']['strokecolor'], $this->spot_colors);
  16412. }
  16413. // check for width attribute
  16414. if (isset($dom[$key]['attribute']['width'])) {
  16415. $dom[$key]['width'] = $dom[$key]['attribute']['width'];
  16416. }
  16417. // check for height attribute
  16418. if (isset($dom[$key]['attribute']['height'])) {
  16419. $dom[$key]['height'] = $dom[$key]['attribute']['height'];
  16420. }
  16421. // check for text alignment
  16422. if (isset($dom[$key]['attribute']['align']) AND (!TCPDF_STATIC::empty_string($dom[$key]['attribute']['align'])) AND ($dom[$key]['value'] !== 'img')) {
  16423. $dom[$key]['align'] = strtoupper($dom[$key]['attribute']['align'][0]);
  16424. }
  16425. // check for text rendering mode (the following attributes do not exist in HTML)
  16426. if (isset($dom[$key]['attribute']['stroke'])) {
  16427. // font stroke width
  16428. $dom[$key]['stroke'] = $this->getHTMLUnitToUnits($dom[$key]['attribute']['stroke'], $dom[$key]['fontsize'], 'pt', true);
  16429. }
  16430. if (isset($dom[$key]['attribute']['fill'])) {
  16431. // font fill
  16432. if ($dom[$key]['attribute']['fill'] == 'true') {
  16433. $dom[$key]['fill'] = true;
  16434. } else {
  16435. $dom[$key]['fill'] = false;
  16436. }
  16437. }
  16438. if (isset($dom[$key]['attribute']['clip'])) {
  16439. // clipping mode
  16440. if ($dom[$key]['attribute']['clip'] == 'true') {
  16441. $dom[$key]['clip'] = true;
  16442. } else {
  16443. $dom[$key]['clip'] = false;
  16444. }
  16445. }
  16446. } // end opening tag
  16447. } else {
  16448. // text
  16449. $dom[$key]['tag'] = false;
  16450. $dom[$key]['block'] = false;
  16451. $dom[$key]['parent'] = end($level);
  16452. $dom[$key]['dir'] = $dom[$dom[$key]['parent']]['dir'];
  16453. if (!empty($dom[$dom[$key]['parent']]['text-transform'])) {
  16454. // text-transform for unicode requires mb_convert_case (Multibyte String Functions)
  16455. if (function_exists('mb_convert_case')) {
  16456. $ttm = array('capitalize' => MB_CASE_TITLE, 'uppercase' => MB_CASE_UPPER, 'lowercase' => MB_CASE_LOWER);
  16457. if (isset($ttm[$dom[$dom[$key]['parent']]['text-transform']])) {
  16458. $element = mb_convert_case($element, $ttm[$dom[$dom[$key]['parent']]['text-transform']], $this->encoding);
  16459. }
  16460. } elseif (!$this->isunicode) {
  16461. switch ($dom[$dom[$key]['parent']]['text-transform']) {
  16462. case 'capitalize': {
  16463. $element = ucwords(strtolower($element));
  16464. break;
  16465. }
  16466. case 'uppercase': {
  16467. $element = strtoupper($element);
  16468. break;
  16469. }
  16470. case 'lowercase': {
  16471. $element = strtolower($element);
  16472. break;
  16473. }
  16474. }
  16475. }
  16476. }
  16477. $dom[$key]['value'] = stripslashes($this->unhtmlentities($element));
  16478. }
  16479. ++$elkey;
  16480. ++$key;
  16481. }
  16482. return $dom;
  16483. }
  16484. /**
  16485. * Returns the string used to find spaces
  16486. * @return string
  16487. * @protected
  16488. * @author Nicola Asuni
  16489. * @since 4.8.024 (2010-01-15)
  16490. */
  16491. protected function getSpaceString() {
  16492. $spacestr = chr(32);
  16493. if ($this->isUnicodeFont()) {
  16494. $spacestr = chr(0).chr(32);
  16495. }
  16496. return $spacestr;
  16497. }
  16498. /**
  16499. * Return an hash code used to ensure that the serialized data has been generated by this TCPDF instance.
  16500. * @param $data (string) serialized data
  16501. * @return string
  16502. * @public static
  16503. */
  16504. protected function getHashForTCPDFtagParams($data) {
  16505. return md5(strlen($data).$this->file_id.$data);
  16506. }
  16507. /**
  16508. * Serialize an array of parameters to be used with TCPDF tag in HTML code.
  16509. * @param $data (array) parameters array
  16510. * @return string containing serialized data
  16511. * @public static
  16512. */
  16513. public function serializeTCPDFtagParameters($data) {
  16514. $encoded = urlencode(json_encode($data));
  16515. return $this->getHashForTCPDFtagParams($encoded).$encoded;
  16516. }
  16517. /**
  16518. * Unserialize parameters to be used with TCPDF tag in HTML code.
  16519. * @param $data (string) serialized data
  16520. * @return array containing unserialized data
  16521. * @protected static
  16522. */
  16523. protected function unserializeTCPDFtagParameters($data) {
  16524. $hash = substr($data, 0, 32);
  16525. $encoded = substr($data, 32);
  16526. if ($hash != $this->getHashForTCPDFtagParams($encoded)) {
  16527. $this->Error('Invalid parameters');
  16528. }
  16529. return json_decode(urldecode($encoded), true);
  16530. }
  16531. /**
  16532. * Prints a cell (rectangular area) with optional borders, background color and html text string.
  16533. * 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 />
  16534. * If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting.
  16535. * IMPORTANT: The HTML must be well formatted - try to clean-up it using an application like HTML-Tidy before submitting.
  16536. * 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
  16537. * NOTE: all the HTML attributes must be enclosed in double-quote.
  16538. * @param $w (float) Cell width. If 0, the cell extends up to the right margin.
  16539. * @param $h (float) Cell minimum height. The cell extends automatically if needed.
  16540. * @param $x (float) upper-left corner X coordinate
  16541. * @param $y (float) upper-left corner Y coordinate
  16542. * @param $html (string) html text to print. Default value: empty string.
  16543. * @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)))
  16544. * @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>
  16545. Putting 1 is equivalent to putting 0 and calling Ln() just after. Default value: 0.
  16546. * @param $fill (boolean) Indicates if the cell background must be painted (true) or transparent (false).
  16547. * @param $reseth (boolean) if true reset the last cell height (default true).
  16548. * @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>
  16549. * @param $autopadding (boolean) if true, uses internal padding and automatically adjust it to account for line width.
  16550. * @see Multicell(), writeHTML()
  16551. * @public
  16552. */
  16553. public function writeHTMLCell($w, $h, $x, $y, $html='', $border=0, $ln=0, $fill=false, $reseth=true, $align='', $autopadding=true) {
  16554. return $this->MultiCell($w, $h, $html, $border, $align, $fill, $ln, $x, $y, $reseth, 0, true, $autopadding, 0, 'T', false);
  16555. }
  16556. /**
  16557. * Allows to preserve some HTML formatting (limited support).<br />
  16558. * IMPORTANT: The HTML must be well formatted - try to clean-up it using an application like HTML-Tidy before submitting.
  16559. * 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
  16560. * NOTE: all the HTML attributes must be enclosed in double-quote.
  16561. * @param $html (string) text to display
  16562. * @param $ln (boolean) if true add a new line after text (default = true)
  16563. * @param $fill (boolean) Indicates if the background must be painted (true) or transparent (false).
  16564. * @param $reseth (boolean) if true reset the last cell height (default false).
  16565. * @param $cell (boolean) if true add the current left (or right for RTL) padding to each Write (default false).
  16566. * @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>
  16567. * @public
  16568. */
  16569. public function writeHTML($html, $ln=true, $fill=false, $reseth=false, $cell=false, $align='') {
  16570. $gvars = $this->getGraphicVars();
  16571. // store current values
  16572. $prev_cell_margin = $this->cell_margin;
  16573. $prev_cell_padding = $this->cell_padding;
  16574. $prevPage = $this->page;
  16575. $prevlMargin = $this->lMargin;
  16576. $prevrMargin = $this->rMargin;
  16577. $curfontname = $this->FontFamily;
  16578. $curfontstyle = $this->FontStyle;
  16579. $curfontsize = $this->FontSizePt;
  16580. $curfontascent = $this->getFontAscent($curfontname, $curfontstyle, $curfontsize);
  16581. $curfontdescent = $this->getFontDescent($curfontname, $curfontstyle, $curfontsize);
  16582. $curfontstretcing = $this->font_stretching;
  16583. $curfonttracking = $this->font_spacing;
  16584. $this->newline = true;
  16585. $newline = true;
  16586. $startlinepage = $this->page;
  16587. $minstartliney = $this->y;
  16588. $maxbottomliney = 0;
  16589. $startlinex = $this->x;
  16590. $startliney = $this->y;
  16591. $yshift = 0;
  16592. $loop = 0;
  16593. $curpos = 0;
  16594. $this_method_vars = array();
  16595. $undo = false;
  16596. $fontaligned = false;
  16597. $reverse_dir = false; // true when the text direction is reversed
  16598. $this->premode = false;
  16599. if ($this->inxobj) {
  16600. // we are inside an XObject template
  16601. $pask = count($this->xobjects[$this->xobjid]['annotations']);
  16602. } elseif (isset($this->PageAnnots[$this->page])) {
  16603. $pask = count($this->PageAnnots[$this->page]);
  16604. } else {
  16605. $pask = 0;
  16606. }
  16607. if ($this->inxobj) {
  16608. // we are inside an XObject template
  16609. $startlinepos = strlen($this->xobjects[$this->xobjid]['outdata']);
  16610. } elseif (!$this->InFooter) {
  16611. if (isset($this->footerlen[$this->page])) {
  16612. $this->footerpos[$this->page] = $this->pagelen[$this->page] - $this->footerlen[$this->page];
  16613. } else {
  16614. $this->footerpos[$this->page] = $this->pagelen[$this->page];
  16615. }
  16616. $startlinepos = $this->footerpos[$this->page];
  16617. } else {
  16618. // we are inside the footer
  16619. $startlinepos = $this->pagelen[$this->page];
  16620. }
  16621. $lalign = $align;
  16622. $plalign = $align;
  16623. if ($this->rtl) {
  16624. $w = $this->x - $this->lMargin;
  16625. } else {
  16626. $w = $this->w - $this->rMargin - $this->x;
  16627. }
  16628. $w -= ($this->cell_padding['L'] + $this->cell_padding['R']);
  16629. if ($cell) {
  16630. if ($this->rtl) {
  16631. $this->x -= $this->cell_padding['R'];
  16632. $this->lMargin += $this->cell_padding['L'];
  16633. } else {
  16634. $this->x += $this->cell_padding['L'];
  16635. $this->rMargin += $this->cell_padding['R'];
  16636. }
  16637. }
  16638. if ($this->customlistindent >= 0) {
  16639. $this->listindent = $this->customlistindent;
  16640. } else {
  16641. $this->listindent = $this->GetStringWidth('000000');
  16642. }
  16643. $this->listindentlevel = 0;
  16644. // save previous states
  16645. $prev_cell_height_ratio = $this->cell_height_ratio;
  16646. $prev_listnum = $this->listnum;
  16647. $prev_listordered = $this->listordered;
  16648. $prev_listcount = $this->listcount;
  16649. $prev_lispacer = $this->lispacer;
  16650. $this->listnum = 0;
  16651. $this->listordered = array();
  16652. $this->listcount = array();
  16653. $this->lispacer = '';
  16654. if ((TCPDF_STATIC::empty_string($this->lasth)) OR ($reseth)) {
  16655. // reset row height
  16656. $this->resetLastH();
  16657. }
  16658. $dom = $this->getHtmlDomArray($html);
  16659. $maxel = count($dom);
  16660. $key = 0;
  16661. while ($key < $maxel) {
  16662. if ($dom[$key]['tag'] AND $dom[$key]['opening'] AND $dom[$key]['hide']) {
  16663. // store the node key
  16664. $hidden_node_key = $key;
  16665. if ($dom[$key]['self']) {
  16666. // skip just this self-closing tag
  16667. ++$key;
  16668. } else {
  16669. // skip this and all children tags
  16670. while (($key < $maxel) AND (!$dom[$key]['tag'] OR $dom[$key]['opening'] OR ($dom[$key]['parent'] != $hidden_node_key))) {
  16671. // skip hidden objects
  16672. ++$key;
  16673. }
  16674. ++$key;
  16675. }
  16676. }
  16677. if ($dom[$key]['tag'] AND isset($dom[$key]['attribute']['pagebreak'])) {
  16678. // check for pagebreak
  16679. if (($dom[$key]['attribute']['pagebreak'] == 'true') OR ($dom[$key]['attribute']['pagebreak'] == 'left') OR ($dom[$key]['attribute']['pagebreak'] == 'right')) {
  16680. // add a page (or trig AcceptPageBreak() for multicolumn mode)
  16681. $this->checkPageBreak($this->PageBreakTrigger + 1);
  16682. $this->htmlvspace = ($this->PageBreakTrigger + 1);
  16683. }
  16684. if ((($dom[$key]['attribute']['pagebreak'] == 'left') AND (((!$this->rtl) AND (($this->page % 2) == 0)) OR (($this->rtl) AND (($this->page % 2) != 0))))
  16685. OR (($dom[$key]['attribute']['pagebreak'] == 'right') AND (((!$this->rtl) AND (($this->page % 2) != 0)) OR (($this->rtl) AND (($this->page % 2) == 0))))) {
  16686. // add a page (or trig AcceptPageBreak() for multicolumn mode)
  16687. $this->checkPageBreak($this->PageBreakTrigger + 1);
  16688. $this->htmlvspace = ($this->PageBreakTrigger + 1);
  16689. }
  16690. }
  16691. if ($dom[$key]['tag'] AND $dom[$key]['opening'] AND isset($dom[$key]['attribute']['nobr']) AND ($dom[$key]['attribute']['nobr'] == 'true')) {
  16692. if (isset($dom[($dom[$key]['parent'])]['attribute']['nobr']) AND ($dom[($dom[$key]['parent'])]['attribute']['nobr'] == 'true')) {
  16693. $dom[$key]['attribute']['nobr'] = false;
  16694. } else {
  16695. // store current object
  16696. $this->startTransaction();
  16697. // save this method vars
  16698. $this_method_vars['html'] = $html;
  16699. $this_method_vars['ln'] = $ln;
  16700. $this_method_vars['fill'] = $fill;
  16701. $this_method_vars['reseth'] = $reseth;
  16702. $this_method_vars['cell'] = $cell;
  16703. $this_method_vars['align'] = $align;
  16704. $this_method_vars['gvars'] = $gvars;
  16705. $this_method_vars['prevPage'] = $prevPage;
  16706. $this_method_vars['prev_cell_margin'] = $prev_cell_margin;
  16707. $this_method_vars['prev_cell_padding'] = $prev_cell_padding;
  16708. $this_method_vars['prevlMargin'] = $prevlMargin;
  16709. $this_method_vars['prevrMargin'] = $prevrMargin;
  16710. $this_method_vars['curfontname'] = $curfontname;
  16711. $this_method_vars['curfontstyle'] = $curfontstyle;
  16712. $this_method_vars['curfontsize'] = $curfontsize;
  16713. $this_method_vars['curfontascent'] = $curfontascent;
  16714. $this_method_vars['curfontdescent'] = $curfontdescent;
  16715. $this_method_vars['curfontstretcing'] = $curfontstretcing;
  16716. $this_method_vars['curfonttracking'] = $curfonttracking;
  16717. $this_method_vars['minstartliney'] = $minstartliney;
  16718. $this_method_vars['maxbottomliney'] = $maxbottomliney;
  16719. $this_method_vars['yshift'] = $yshift;
  16720. $this_method_vars['startlinepage'] = $startlinepage;
  16721. $this_method_vars['startlinepos'] = $startlinepos;
  16722. $this_method_vars['startlinex'] = $startlinex;
  16723. $this_method_vars['startliney'] = $startliney;
  16724. $this_method_vars['newline'] = $newline;
  16725. $this_method_vars['loop'] = $loop;
  16726. $this_method_vars['curpos'] = $curpos;
  16727. $this_method_vars['pask'] = $pask;
  16728. $this_method_vars['lalign'] = $lalign;
  16729. $this_method_vars['plalign'] = $plalign;
  16730. $this_method_vars['w'] = $w;
  16731. $this_method_vars['prev_cell_height_ratio'] = $prev_cell_height_ratio;
  16732. $this_method_vars['prev_listnum'] = $prev_listnum;
  16733. $this_method_vars['prev_listordered'] = $prev_listordered;
  16734. $this_method_vars['prev_listcount'] = $prev_listcount;
  16735. $this_method_vars['prev_lispacer'] = $prev_lispacer;
  16736. $this_method_vars['fontaligned'] = $fontaligned;
  16737. $this_method_vars['key'] = $key;
  16738. $this_method_vars['dom'] = $dom;
  16739. }
  16740. }
  16741. // print THEAD block
  16742. if (($dom[$key]['value'] == 'tr') AND isset($dom[$key]['thead']) AND $dom[$key]['thead']) {
  16743. if (isset($dom[$key]['parent']) AND isset($dom[$dom[$key]['parent']]['thead']) AND !TCPDF_STATIC::empty_string($dom[$dom[$key]['parent']]['thead'])) {
  16744. $this->inthead = true;
  16745. // print table header (thead)
  16746. $this->writeHTML($this->thead, false, false, false, false, '');
  16747. // check if we are on a new page or on a new column
  16748. if (($this->y < $this->start_transaction_y) OR ($this->checkPageBreak($this->lasth, '', false))) {
  16749. // we are on a new page or on a new column and the total object height is less than the available vertical space.
  16750. // restore previous object
  16751. $this->rollbackTransaction(true);
  16752. // restore previous values
  16753. foreach ($this_method_vars as $vkey => $vval) {
  16754. $$vkey = $vval;
  16755. }
  16756. // disable table header
  16757. $tmp_thead = $this->thead;
  16758. $this->thead = '';
  16759. // add a page (or trig AcceptPageBreak() for multicolumn mode)
  16760. $pre_y = $this->y;
  16761. if ((!$this->checkPageBreak($this->PageBreakTrigger + 1)) AND ($this->y < $pre_y)) {
  16762. // fix for multicolumn mode
  16763. $startliney = $this->y;
  16764. }
  16765. $this->start_transaction_page = $this->page;
  16766. $this->start_transaction_y = $this->y;
  16767. // restore table header
  16768. $this->thead = $tmp_thead;
  16769. // fix table border properties
  16770. if (isset($dom[$dom[$key]['parent']]['attribute']['cellspacing'])) {
  16771. $tmp_cellspacing = $this->getHTMLUnitToUnits($dom[$dom[$key]['parent']]['attribute']['cellspacing'], 1, 'px');
  16772. } elseif (isset($dom[$dom[$key]['parent']]['border-spacing'])) {
  16773. $tmp_cellspacing = $dom[$dom[$key]['parent']]['border-spacing']['V'];
  16774. } else {
  16775. $tmp_cellspacing = 0;
  16776. }
  16777. $dom[$dom[$key]['parent']]['borderposition']['page'] = $this->page;
  16778. $dom[$dom[$key]['parent']]['borderposition']['column'] = $this->current_column;
  16779. $dom[$dom[$key]['parent']]['borderposition']['y'] = $this->y + $tmp_cellspacing;
  16780. $xoffset = ($this->x - $dom[$dom[$key]['parent']]['borderposition']['x']);
  16781. $dom[$dom[$key]['parent']]['borderposition']['x'] += $xoffset;
  16782. $dom[$dom[$key]['parent']]['borderposition']['xmax'] += $xoffset;
  16783. // print table header (thead)
  16784. $this->writeHTML($this->thead, false, false, false, false, '');
  16785. }
  16786. }
  16787. // move $key index forward to skip THEAD block
  16788. while ( ($key < $maxel) AND (!(
  16789. ($dom[$key]['tag'] AND $dom[$key]['opening'] AND ($dom[$key]['value'] == 'tr') AND (!isset($dom[$key]['thead']) OR !$dom[$key]['thead']))
  16790. OR ($dom[$key]['tag'] AND (!$dom[$key]['opening']) AND ($dom[$key]['value'] == 'table'))) )) {
  16791. ++$key;
  16792. }
  16793. }
  16794. if ($dom[$key]['tag'] OR ($key == 0)) {
  16795. if ((($dom[$key]['value'] == 'table') OR ($dom[$key]['value'] == 'tr')) AND (isset($dom[$key]['align']))) {
  16796. $dom[$key]['align'] = ($this->rtl) ? 'R' : 'L';
  16797. }
  16798. // vertically align image in line
  16799. if ((!$this->newline) AND ($dom[$key]['value'] == 'img') AND (isset($dom[$key]['height'])) AND ($dom[$key]['height'] > 0)) {
  16800. // get image height
  16801. $imgh = $this->getHTMLUnitToUnits($dom[$key]['height'], ($dom[$key]['fontsize'] / $this->k), 'px');
  16802. $autolinebreak = false;
  16803. if (!empty($dom[$key]['width'])) {
  16804. $imgw = $this->getHTMLUnitToUnits($dom[$key]['width'], ($dom[$key]['fontsize'] / $this->k), 'px', false);
  16805. if (($imgw <= ($this->w - $this->lMargin - $this->rMargin - $this->cell_padding['L'] - $this->cell_padding['R']))
  16806. AND ((($this->rtl) AND (($this->x - $imgw) < ($this->lMargin + $this->cell_padding['L'])))
  16807. OR ((!$this->rtl) AND (($this->x + $imgw) > ($this->w - $this->rMargin - $this->cell_padding['R']))))) {
  16808. // add automatic line break
  16809. $autolinebreak = true;
  16810. $this->Ln('', $cell);
  16811. if ((!$dom[($key-1)]['tag']) AND ($dom[($key-1)]['value'] == ' ')) {
  16812. // go back to evaluate this line break
  16813. --$key;
  16814. }
  16815. }
  16816. }
  16817. if (!$autolinebreak) {
  16818. if ($this->inPageBody()) {
  16819. $pre_y = $this->y;
  16820. // check for page break
  16821. if ((!$this->checkPageBreak($imgh)) AND ($this->y < $pre_y)) {
  16822. // fix for multicolumn mode
  16823. $startliney = $this->y;
  16824. }
  16825. }
  16826. if ($this->page > $startlinepage) {
  16827. // fix line splitted over two pages
  16828. if (isset($this->footerlen[$startlinepage])) {
  16829. $curpos = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
  16830. }
  16831. // line to be moved one page forward
  16832. $pagebuff = $this->getPageBuffer($startlinepage);
  16833. $linebeg = substr($pagebuff, $startlinepos, ($curpos - $startlinepos));
  16834. $tstart = substr($pagebuff, 0, $startlinepos);
  16835. $tend = substr($this->getPageBuffer($startlinepage), $curpos);
  16836. // remove line from previous page
  16837. $this->setPageBuffer($startlinepage, $tstart.''.$tend);
  16838. $pagebuff = $this->getPageBuffer($this->page);
  16839. $tstart = substr($pagebuff, 0, $this->cntmrk[$this->page]);
  16840. $tend = substr($pagebuff, $this->cntmrk[$this->page]);
  16841. // add line start to current page
  16842. $yshift = ($minstartliney - $this->y);
  16843. if ($fontaligned) {
  16844. $yshift += ($curfontsize / $this->k);
  16845. }
  16846. $try = sprintf('1 0 0 1 0 %F cm', ($yshift * $this->k));
  16847. $this->setPageBuffer($this->page, $tstart."\nq\n".$try."\n".$linebeg."\nQ\n".$tend);
  16848. // shift the annotations and links
  16849. if (isset($this->PageAnnots[$this->page])) {
  16850. $next_pask = count($this->PageAnnots[$this->page]);
  16851. } else {
  16852. $next_pask = 0;
  16853. }
  16854. if (isset($this->PageAnnots[$startlinepage])) {
  16855. foreach ($this->PageAnnots[$startlinepage] as $pak => $pac) {
  16856. if ($pak >= $pask) {
  16857. $this->PageAnnots[$this->page][] = $pac;
  16858. unset($this->PageAnnots[$startlinepage][$pak]);
  16859. $npak = count($this->PageAnnots[$this->page]) - 1;
  16860. $this->PageAnnots[$this->page][$npak]['y'] -= $yshift;
  16861. }
  16862. }
  16863. }
  16864. $pask = $next_pask;
  16865. $startlinepos = $this->cntmrk[$this->page];
  16866. $startlinepage = $this->page;
  16867. $startliney = $this->y;
  16868. $this->newline = false;
  16869. }
  16870. $this->y += ($this->getCellHeight($curfontsize / $this->k) - ($curfontdescent * $this->cell_height_ratio) - $imgh);
  16871. $minstartliney = min($this->y, $minstartliney);
  16872. $maxbottomliney = ($startliney + $this->getCellHeight($curfontsize / $this->k));
  16873. }
  16874. } elseif (isset($dom[$key]['fontname']) OR isset($dom[$key]['fontstyle']) OR isset($dom[$key]['fontsize']) OR isset($dom[$key]['line-height'])) {
  16875. // account for different font size
  16876. $pfontname = $curfontname;
  16877. $pfontstyle = $curfontstyle;
  16878. $pfontsize = $curfontsize;
  16879. $fontname = (isset($dom[$key]['fontname']) ? $dom[$key]['fontname'] : $curfontname);
  16880. $fontstyle = (isset($dom[$key]['fontstyle']) ? $dom[$key]['fontstyle'] : $curfontstyle);
  16881. $fontsize = (isset($dom[$key]['fontsize']) ? $dom[$key]['fontsize'] : $curfontsize);
  16882. $fontascent = $this->getFontAscent($fontname, $fontstyle, $fontsize);
  16883. $fontdescent = $this->getFontDescent($fontname, $fontstyle, $fontsize);
  16884. if (($fontname != $curfontname) OR ($fontstyle != $curfontstyle) OR ($fontsize != $curfontsize)
  16885. OR ($this->cell_height_ratio != $dom[$key]['line-height'])
  16886. OR ($dom[$key]['tag'] AND $dom[$key]['opening'] AND ($dom[$key]['value'] == 'li')) ) {
  16887. if (($key < ($maxel - 1)) AND (
  16888. ($dom[$key]['tag'] AND $dom[$key]['opening'] AND ($dom[$key]['value'] == 'li'))
  16889. OR ($this->cell_height_ratio != $dom[$key]['line-height'])
  16890. OR (!$this->newline AND is_numeric($fontsize) AND is_numeric($curfontsize)
  16891. AND ($fontsize >= 0) AND ($curfontsize >= 0)
  16892. AND (($fontsize != $curfontsize) OR ($fontstyle != $curfontstyle) OR ($fontname != $curfontname)))
  16893. )) {
  16894. if ($this->page > $startlinepage) {
  16895. // fix lines splitted over two pages
  16896. if (isset($this->footerlen[$startlinepage])) {
  16897. $curpos = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
  16898. }
  16899. // line to be moved one page forward
  16900. $pagebuff = $this->getPageBuffer($startlinepage);
  16901. $linebeg = substr($pagebuff, $startlinepos, ($curpos - $startlinepos));
  16902. $tstart = substr($pagebuff, 0, $startlinepos);
  16903. $tend = substr($this->getPageBuffer($startlinepage), $curpos);
  16904. // remove line start from previous page
  16905. $this->setPageBuffer($startlinepage, $tstart.''.$tend);
  16906. $pagebuff = $this->getPageBuffer($this->page);
  16907. $tstart = substr($pagebuff, 0, $this->cntmrk[$this->page]);
  16908. $tend = substr($pagebuff, $this->cntmrk[$this->page]);
  16909. // add line start to current page
  16910. $yshift = ($minstartliney - $this->y);
  16911. $try = sprintf('1 0 0 1 0 %F cm', ($yshift * $this->k));
  16912. $this->setPageBuffer($this->page, $tstart."\nq\n".$try."\n".$linebeg."\nQ\n".$tend);
  16913. // shift the annotations and links
  16914. if (isset($this->PageAnnots[$this->page])) {
  16915. $next_pask = count($this->PageAnnots[$this->page]);
  16916. } else {
  16917. $next_pask = 0;
  16918. }
  16919. if (isset($this->PageAnnots[$startlinepage])) {
  16920. foreach ($this->PageAnnots[$startlinepage] as $pak => $pac) {
  16921. if ($pak >= $pask) {
  16922. $this->PageAnnots[$this->page][] = $pac;
  16923. unset($this->PageAnnots[$startlinepage][$pak]);
  16924. $npak = count($this->PageAnnots[$this->page]) - 1;
  16925. $this->PageAnnots[$this->page][$npak]['y'] -= $yshift;
  16926. }
  16927. }
  16928. }
  16929. $pask = $next_pask;
  16930. $startlinepos = $this->cntmrk[$this->page];
  16931. $startlinepage = $this->page;
  16932. $startliney = $this->y;
  16933. }
  16934. if (!isset($dom[$key]['line-height'])) {
  16935. $dom[$key]['line-height'] = $this->cell_height_ratio;
  16936. }
  16937. if (!$dom[$key]['block']) {
  16938. 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']))) {
  16939. $this->y += (((($curfontsize * $this->cell_height_ratio) - ($fontsize * $dom[$key]['line-height'])) / $this->k) + $curfontascent - $fontascent - $curfontdescent + $fontdescent) / 2;
  16940. }
  16941. if (($dom[$key]['value'] != 'sup') AND ($dom[$key]['value'] != 'sub')) {
  16942. $current_line_align_data = array($key, $minstartliney, $maxbottomliney);
  16943. 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)))) {
  16944. $minstartliney = min($this->y, $line_align_data[1]);
  16945. $maxbottomliney = max(($this->y + $this->getCellHeight($fontsize / $this->k)), $line_align_data[2]);
  16946. } else {
  16947. $minstartliney = min($this->y, $minstartliney);
  16948. $maxbottomliney = max(($this->y + $this->getCellHeight($fontsize / $this->k)), $maxbottomliney);
  16949. }
  16950. $line_align_data = $current_line_align_data;
  16951. }
  16952. }
  16953. $this->cell_height_ratio = $dom[$key]['line-height'];
  16954. $fontaligned = true;
  16955. }
  16956. $this->SetFont($fontname, $fontstyle, $fontsize);
  16957. // reset row height
  16958. $this->resetLastH();
  16959. $curfontname = $fontname;
  16960. $curfontstyle = $fontstyle;
  16961. $curfontsize = $fontsize;
  16962. $curfontascent = $fontascent;
  16963. $curfontdescent = $fontdescent;
  16964. }
  16965. }
  16966. // set text rendering mode
  16967. $textstroke = isset($dom[$key]['stroke']) ? $dom[$key]['stroke'] : $this->textstrokewidth;
  16968. $textfill = isset($dom[$key]['fill']) ? $dom[$key]['fill'] : (($this->textrendermode % 2) == 0);
  16969. $textclip = isset($dom[$key]['clip']) ? $dom[$key]['clip'] : ($this->textrendermode > 3);
  16970. $this->setTextRenderingMode($textstroke, $textfill, $textclip);
  16971. if (isset($dom[$key]['font-stretch']) AND ($dom[$key]['font-stretch'] !== false)) {
  16972. $this->setFontStretching($dom[$key]['font-stretch']);
  16973. }
  16974. if (isset($dom[$key]['letter-spacing']) AND ($dom[$key]['letter-spacing'] !== false)) {
  16975. $this->setFontSpacing($dom[$key]['letter-spacing']);
  16976. }
  16977. if (($plalign == 'J') AND $dom[$key]['block']) {
  16978. $plalign = '';
  16979. }
  16980. // get current position on page buffer
  16981. $curpos = $this->pagelen[$startlinepage];
  16982. if (isset($dom[$key]['bgcolor']) AND ($dom[$key]['bgcolor'] !== false)) {
  16983. $this->SetFillColorArray($dom[$key]['bgcolor']);
  16984. $wfill = true;
  16985. } else {
  16986. $wfill = $fill | false;
  16987. }
  16988. if (isset($dom[$key]['fgcolor']) AND ($dom[$key]['fgcolor'] !== false)) {
  16989. $this->SetTextColorArray($dom[$key]['fgcolor']);
  16990. }
  16991. if (isset($dom[$key]['strokecolor']) AND ($dom[$key]['strokecolor'] !== false)) {
  16992. $this->SetDrawColorArray($dom[$key]['strokecolor']);
  16993. }
  16994. if (isset($dom[$key]['align'])) {
  16995. $lalign = $dom[$key]['align'];
  16996. }
  16997. if (TCPDF_STATIC::empty_string($lalign)) {
  16998. $lalign = $align;
  16999. }
  17000. }
  17001. // align lines
  17002. if ($this->newline AND (strlen($dom[$key]['value']) > 0) AND ($dom[$key]['value'] != 'td') AND ($dom[$key]['value'] != 'th')) {
  17003. $newline = true;
  17004. $fontaligned = false;
  17005. // we are at the beginning of a new line
  17006. if (isset($startlinex)) {
  17007. $yshift = ($minstartliney - $startliney);
  17008. if (($yshift > 0) OR ($this->page > $startlinepage)) {
  17009. $yshift = 0;
  17010. }
  17011. $t_x = 0;
  17012. // the last line must be shifted to be aligned as requested
  17013. $linew = abs($this->endlinex - $startlinex);
  17014. if ($this->inxobj) {
  17015. // we are inside an XObject template
  17016. $pstart = substr($this->xobjects[$this->xobjid]['outdata'], 0, $startlinepos);
  17017. if (isset($opentagpos)) {
  17018. $midpos = $opentagpos;
  17019. } else {
  17020. $midpos = 0;
  17021. }
  17022. if ($midpos > 0) {
  17023. $pmid = substr($this->xobjects[$this->xobjid]['outdata'], $startlinepos, ($midpos - $startlinepos));
  17024. $pend = substr($this->xobjects[$this->xobjid]['outdata'], $midpos);
  17025. } else {
  17026. $pmid = substr($this->xobjects[$this->xobjid]['outdata'], $startlinepos);
  17027. $pend = '';
  17028. }
  17029. } else {
  17030. $pstart = substr($this->getPageBuffer($startlinepage), 0, $startlinepos);
  17031. if (isset($opentagpos) AND isset($this->footerlen[$startlinepage]) AND (!$this->InFooter)) {
  17032. $this->footerpos[$startlinepage] = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
  17033. $midpos = min($opentagpos, $this->footerpos[$startlinepage]);
  17034. } elseif (isset($opentagpos)) {
  17035. $midpos = $opentagpos;
  17036. } elseif (isset($this->footerlen[$startlinepage]) AND (!$this->InFooter)) {
  17037. $this->footerpos[$startlinepage] = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
  17038. $midpos = $this->footerpos[$startlinepage];
  17039. } else {
  17040. $midpos = 0;
  17041. }
  17042. if ($midpos > 0) {
  17043. $pmid = substr($this->getPageBuffer($startlinepage), $startlinepos, ($midpos - $startlinepos));
  17044. $pend = substr($this->getPageBuffer($startlinepage), $midpos);
  17045. } else {
  17046. $pmid = substr($this->getPageBuffer($startlinepage), $startlinepos);
  17047. $pend = '';
  17048. }
  17049. }
  17050. if ((isset($plalign) AND ((($plalign == 'C') OR ($plalign == 'J') OR (($plalign == 'R') AND (!$this->rtl)) OR (($plalign == 'L') AND ($this->rtl)))))) {
  17051. // calculate shifting amount
  17052. $tw = $w;
  17053. if (($plalign == 'J') AND $this->isRTLTextDir() AND ($this->num_columns > 1)) {
  17054. $tw += $this->cell_padding['R'];
  17055. }
  17056. if ($this->lMargin != $prevlMargin) {
  17057. $tw += ($prevlMargin - $this->lMargin);
  17058. }
  17059. if ($this->rMargin != $prevrMargin) {
  17060. $tw += ($prevrMargin - $this->rMargin);
  17061. }
  17062. $one_space_width = $this->GetStringWidth(chr(32));
  17063. $no = 0; // number of spaces on a line contained on a single block
  17064. if ($this->isRTLTextDir()) { // RTL
  17065. // remove left space if exist
  17066. $pos1 = TCPDF_STATIC::revstrpos($pmid, '[(');
  17067. if ($pos1 > 0) {
  17068. $pos1 = intval($pos1);
  17069. if ($this->isUnicodeFont()) {
  17070. $pos2 = intval(TCPDF_STATIC::revstrpos($pmid, '[('.chr(0).chr(32)));
  17071. $spacelen = 2;
  17072. } else {
  17073. $pos2 = intval(TCPDF_STATIC::revstrpos($pmid, '[('.chr(32)));
  17074. $spacelen = 1;
  17075. }
  17076. if ($pos1 == $pos2) {
  17077. $pmid = substr($pmid, 0, ($pos1 + 2)).substr($pmid, ($pos1 + 2 + $spacelen));
  17078. if (substr($pmid, $pos1, 4) == '[()]') {
  17079. $linew -= $one_space_width;
  17080. } elseif ($pos1 == strpos($pmid, '[(')) {
  17081. $no = 1;
  17082. }
  17083. }
  17084. }
  17085. } else { // LTR
  17086. // remove right space if exist
  17087. $pos1 = TCPDF_STATIC::revstrpos($pmid, ')]');
  17088. if ($pos1 > 0) {
  17089. $pos1 = intval($pos1);
  17090. if ($this->isUnicodeFont()) {
  17091. $pos2 = intval(TCPDF_STATIC::revstrpos($pmid, chr(0).chr(32).')]')) + 2;
  17092. $spacelen = 2;
  17093. } else {
  17094. $pos2 = intval(TCPDF_STATIC::revstrpos($pmid, chr(32).')]')) + 1;
  17095. $spacelen = 1;
  17096. }
  17097. if ($pos1 == $pos2) {
  17098. $pmid = substr($pmid, 0, ($pos1 - $spacelen)).substr($pmid, $pos1);
  17099. $linew -= $one_space_width;
  17100. }
  17101. }
  17102. }
  17103. $mdiff = ($tw - $linew);
  17104. if ($plalign == 'C') {
  17105. if ($this->rtl) {
  17106. $t_x = -($mdiff / 2);
  17107. } else {
  17108. $t_x = ($mdiff / 2);
  17109. }
  17110. } elseif ($plalign == 'R') {
  17111. // right alignment on LTR document
  17112. $t_x = $mdiff;
  17113. } elseif ($plalign == 'L') {
  17114. // left alignment on RTL document
  17115. $t_x = -$mdiff;
  17116. } elseif (($plalign == 'J') AND ($plalign == $lalign)) {
  17117. // Justification
  17118. if ($this->isRTLTextDir()) {
  17119. // align text on the left
  17120. $t_x = -$mdiff;
  17121. }
  17122. $ns = 0; // number of spaces
  17123. $pmidtemp = $pmid;
  17124. // escape special characters
  17125. $pmidtemp = preg_replace('/[\\\][\(]/x', '\\#!#OP#!#', $pmidtemp);
  17126. $pmidtemp = preg_replace('/[\\\][\)]/x', '\\#!#CP#!#', $pmidtemp);
  17127. // search spaces
  17128. if (preg_match_all('/\[\(([^\)]*)\)\]/x', $pmidtemp, $lnstring, PREG_PATTERN_ORDER)) {
  17129. $spacestr = $this->getSpaceString();
  17130. $maxkk = count($lnstring[1]) - 1;
  17131. for ($kk=0; $kk <= $maxkk; ++$kk) {
  17132. // restore special characters
  17133. $lnstring[1][$kk] = str_replace('#!#OP#!#', '(', $lnstring[1][$kk]);
  17134. $lnstring[1][$kk] = str_replace('#!#CP#!#', ')', $lnstring[1][$kk]);
  17135. // store number of spaces on the strings
  17136. $lnstring[2][$kk] = substr_count($lnstring[1][$kk], $spacestr);
  17137. // count total spaces on line
  17138. $ns += $lnstring[2][$kk];
  17139. $lnstring[3][$kk] = $ns;
  17140. }
  17141. if ($ns == 0) {
  17142. $ns = 1;
  17143. }
  17144. // calculate additional space to add to each existing space
  17145. $spacewidth = ($mdiff / ($ns - $no)) * $this->k;
  17146. if ($this->FontSize <= 0) {
  17147. $this->FontSize = 1;
  17148. }
  17149. $spacewidthu = -1000 * ($mdiff + (($ns + $no) * $one_space_width)) / $ns / $this->FontSize;
  17150. if ($this->font_spacing != 0) {
  17151. // fixed spacing mode
  17152. $osw = -1000 * $this->font_spacing / $this->FontSize;
  17153. $spacewidthu += $osw;
  17154. }
  17155. $nsmax = $ns;
  17156. $ns = 0;
  17157. reset($lnstring);
  17158. $offset = 0;
  17159. $strcount = 0;
  17160. $prev_epsposbeg = 0;
  17161. $textpos = 0;
  17162. if ($this->isRTLTextDir()) {
  17163. $textpos = $this->wPt;
  17164. }
  17165. while (preg_match('/([0-9\.\+\-]*)[\s](Td|cm|m|l|c|re)[\s]/x', $pmid, $strpiece, PREG_OFFSET_CAPTURE, $offset) == 1) {
  17166. // check if we are inside a string section '[( ... )]'
  17167. $stroffset = strpos($pmid, '[(', $offset);
  17168. if (($stroffset !== false) AND ($stroffset <= $strpiece[2][1])) {
  17169. // set offset to the end of string section
  17170. $offset = strpos($pmid, ')]', $stroffset);
  17171. while (($offset !== false) AND ($pmid[($offset - 1)] == '\\')) {
  17172. $offset = strpos($pmid, ')]', ($offset + 1));
  17173. }
  17174. if ($offset === false) {
  17175. $this->Error('HTML Justification: malformed PDF code.');
  17176. }
  17177. continue;
  17178. }
  17179. if ($this->isRTLTextDir()) {
  17180. $spacew = ($spacewidth * ($nsmax - $ns));
  17181. } else {
  17182. $spacew = ($spacewidth * $ns);
  17183. }
  17184. $offset = $strpiece[2][1] + strlen($strpiece[2][0]);
  17185. $epsposend = strpos($pmid, $this->epsmarker.'Q', $offset);
  17186. if ($epsposend !== null) {
  17187. $epsposend += strlen($this->epsmarker.'Q');
  17188. $epsposbeg = strpos($pmid, 'q'.$this->epsmarker, $offset);
  17189. if ($epsposbeg === null) {
  17190. $epsposbeg = strpos($pmid, 'q'.$this->epsmarker, ($prev_epsposbeg - 6));
  17191. $prev_epsposbeg = $epsposbeg;
  17192. }
  17193. if (($epsposbeg > 0) AND ($epsposend > 0) AND ($offset > $epsposbeg) AND ($offset < $epsposend)) {
  17194. // shift EPS images
  17195. $trx = sprintf('1 0 0 1 %F 0 cm', $spacew);
  17196. $pmid_b = substr($pmid, 0, $epsposbeg);
  17197. $pmid_m = substr($pmid, $epsposbeg, ($epsposend - $epsposbeg));
  17198. $pmid_e = substr($pmid, $epsposend);
  17199. $pmid = $pmid_b."\nq\n".$trx."\n".$pmid_m."\nQ\n".$pmid_e;
  17200. $offset = $epsposend;
  17201. continue;
  17202. }
  17203. }
  17204. $currentxpos = 0;
  17205. // shift blocks of code
  17206. switch ($strpiece[2][0]) {
  17207. case 'Td':
  17208. case 'cm':
  17209. case 'm':
  17210. case 'l': {
  17211. // get current X position
  17212. preg_match('/([0-9\.\+\-]*)[\s]('.$strpiece[1][0].')[\s]('.$strpiece[2][0].')([\s]*)/x', $pmid, $xmatches);
  17213. if (!isset($xmatches[1])) {
  17214. break;
  17215. }
  17216. $currentxpos = $xmatches[1];
  17217. $textpos = $currentxpos;
  17218. if (($strcount <= $maxkk) AND ($strpiece[2][0] == 'Td')) {
  17219. $ns = $lnstring[3][$strcount];
  17220. if ($this->isRTLTextDir()) {
  17221. $spacew = ($spacewidth * ($nsmax - $ns));
  17222. }
  17223. ++$strcount;
  17224. }
  17225. // justify block
  17226. if (preg_match('/([0-9\.\+\-]*)[\s]('.$strpiece[1][0].')[\s]('.$strpiece[2][0].')([\s]*)/x', $pmid, $pmatch) == 1) {
  17227. $newpmid = sprintf('%F',(floatval($pmatch[1]) + $spacew)).' '.$pmatch[2].' x*#!#*x'.$pmatch[3].$pmatch[4];
  17228. $pmid = str_replace($pmatch[0], $newpmid, $pmid);
  17229. unset($pmatch, $newpmid);
  17230. }
  17231. break;
  17232. }
  17233. case 're': {
  17234. // justify block
  17235. if (!TCPDF_STATIC::empty_string($this->lispacer)) {
  17236. $this->lispacer = '';
  17237. break;
  17238. }
  17239. preg_match('/([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]([0-9\.\+\-]*)[\s]('.$strpiece[1][0].')[\s](re)([\s]*)/x', $pmid, $xmatches);
  17240. if (!isset($xmatches[1])) {
  17241. break;
  17242. }
  17243. $currentxpos = $xmatches[1];
  17244. $x_diff = 0;
  17245. $w_diff = 0;
  17246. if ($this->isRTLTextDir()) { // RTL
  17247. if ($currentxpos < $textpos) {
  17248. $x_diff = ($spacewidth * ($nsmax - $lnstring[3][$strcount]));
  17249. $w_diff = ($spacewidth * $lnstring[2][$strcount]);
  17250. } else {
  17251. if ($strcount > 0) {
  17252. $x_diff = ($spacewidth * ($nsmax - $lnstring[3][($strcount - 1)]));
  17253. $w_diff = ($spacewidth * $lnstring[2][($strcount - 1)]);
  17254. }
  17255. }
  17256. } else { // LTR
  17257. if ($currentxpos > $textpos) {
  17258. if ($strcount > 0) {
  17259. $x_diff = ($spacewidth * $lnstring[3][($strcount - 1)]);
  17260. }
  17261. $w_diff = ($spacewidth * $lnstring[2][$strcount]);
  17262. } else {
  17263. if ($strcount > 1) {
  17264. $x_diff = ($spacewidth * $lnstring[3][($strcount - 2)]);
  17265. }
  17266. if ($strcount > 0) {
  17267. $w_diff = ($spacewidth * $lnstring[2][($strcount - 1)]);
  17268. }
  17269. }
  17270. }
  17271. if (preg_match('/('.$xmatches[1].')[\s]('.$xmatches[2].')[\s]('.$xmatches[3].')[\s]('.$strpiece[1][0].')[\s](re)([\s]*)/x', $pmid, $pmatch) == 1) {
  17272. $newx = sprintf('%F',(floatval($pmatch[1]) + $x_diff));
  17273. $neww = sprintf('%F',(floatval($pmatch[3]) + $w_diff));
  17274. $newpmid = $newx.' '.$pmatch[2].' '.$neww.' '.$pmatch[4].' x*#!#*x'.$pmatch[5].$pmatch[6];
  17275. $pmid = str_replace($pmatch[0], $newpmid, $pmid);
  17276. unset($pmatch, $newpmid, $newx, $neww);
  17277. }
  17278. break;
  17279. }
  17280. case 'c': {
  17281. // get current X position
  17282. 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);
  17283. if (!isset($xmatches[1])) {
  17284. break;
  17285. }
  17286. $currentxpos = $xmatches[1];
  17287. // justify block
  17288. 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) {
  17289. $newx1 = sprintf('%F',(floatval($pmatch[1]) + $spacew));
  17290. $newx2 = sprintf('%F',(floatval($pmatch[3]) + $spacew));
  17291. $newx3 = sprintf('%F',(floatval($pmatch[5]) + $spacew));
  17292. $newpmid = $newx1.' '.$pmatch[2].' '.$newx2.' '.$pmatch[4].' '.$newx3.' '.$pmatch[6].' x*#!#*x'.$pmatch[7].$pmatch[8];
  17293. $pmid = str_replace($pmatch[0], $newpmid, $pmid);
  17294. unset($pmatch, $newpmid, $newx1, $newx2, $newx3);
  17295. }
  17296. break;
  17297. }
  17298. }
  17299. // shift the annotations and links
  17300. $cxpos = ($currentxpos / $this->k);
  17301. $lmpos = ($this->lMargin + $this->cell_padding['L'] + $this->feps);
  17302. if ($this->inxobj) {
  17303. // we are inside an XObject template
  17304. foreach ($this->xobjects[$this->xobjid]['annotations'] as $pak => $pac) {
  17305. if (($pac['y'] >= $minstartliney) AND (($pac['x'] * $this->k) >= ($currentxpos - $this->feps)) AND (($pac['x'] * $this->k) <= ($currentxpos + $this->feps))) {
  17306. if ($cxpos > $lmpos) {
  17307. $this->xobjects[$this->xobjid]['annotations'][$pak]['x'] += ($spacew / $this->k);
  17308. $this->xobjects[$this->xobjid]['annotations'][$pak]['w'] += (($spacewidth * $pac['numspaces']) / $this->k);
  17309. } else {
  17310. $this->xobjects[$this->xobjid]['annotations'][$pak]['w'] += (($spacewidth * $pac['numspaces']) / $this->k);
  17311. }
  17312. break;
  17313. }
  17314. }
  17315. } elseif (isset($this->PageAnnots[$this->page])) {
  17316. foreach ($this->PageAnnots[$this->page] as $pak => $pac) {
  17317. if (($pac['y'] >= $minstartliney) AND (($pac['x'] * $this->k) >= ($currentxpos - $this->feps)) AND (($pac['x'] * $this->k) <= ($currentxpos + $this->feps))) {
  17318. if ($cxpos > $lmpos) {
  17319. $this->PageAnnots[$this->page][$pak]['x'] += ($spacew / $this->k);
  17320. $this->PageAnnots[$this->page][$pak]['w'] += (($spacewidth * $pac['numspaces']) / $this->k);
  17321. } else {
  17322. $this->PageAnnots[$this->page][$pak]['w'] += (($spacewidth * $pac['numspaces']) / $this->k);
  17323. }
  17324. break;
  17325. }
  17326. }
  17327. }
  17328. } // end of while
  17329. // remove markers
  17330. $pmid = str_replace('x*#!#*x', '', $pmid);
  17331. if ($this->isUnicodeFont()) {
  17332. // multibyte characters
  17333. $spacew = $spacewidthu;
  17334. if ($this->font_stretching != 100) {
  17335. // word spacing is affected by stretching
  17336. $spacew /= ($this->font_stretching / 100);
  17337. }
  17338. // escape special characters
  17339. $pos = 0;
  17340. $pmid = preg_replace('/[\\\][\(]/x', '\\#!#OP#!#', $pmid);
  17341. $pmid = preg_replace('/[\\\][\)]/x', '\\#!#CP#!#', $pmid);
  17342. if (preg_match_all('/\[\(([^\)]*)\)\]/x', $pmid, $pamatch) > 0) {
  17343. foreach($pamatch[0] as $pk => $pmatch) {
  17344. $replace = $pamatch[1][$pk];
  17345. $replace = str_replace('#!#OP#!#', '(', $replace);
  17346. $replace = str_replace('#!#CP#!#', ')', $replace);
  17347. $newpmid = '[('.str_replace(chr(0).chr(32), ') '.sprintf('%F', $spacew).' (', $replace).')]';
  17348. $pos = strpos($pmid, $pmatch, $pos);
  17349. if ($pos !== FALSE) {
  17350. $pmid = substr_replace($pmid, $newpmid, $pos, strlen($pmatch));
  17351. }
  17352. ++$pos;
  17353. }
  17354. unset($pamatch);
  17355. }
  17356. if ($this->inxobj) {
  17357. // we are inside an XObject template
  17358. $this->xobjects[$this->xobjid]['outdata'] = $pstart."\n".$pmid."\n".$pend;
  17359. } else {
  17360. $this->setPageBuffer($startlinepage, $pstart."\n".$pmid."\n".$pend);
  17361. }
  17362. $endlinepos = strlen($pstart."\n".$pmid."\n");
  17363. } else {
  17364. // non-unicode (single-byte characters)
  17365. if ($this->font_stretching != 100) {
  17366. // word spacing (Tw) is affected by stretching
  17367. $spacewidth /= ($this->font_stretching / 100);
  17368. }
  17369. $rs = sprintf('%F Tw', $spacewidth);
  17370. $pmid = preg_replace("/\[\(/x", $rs.' [(', $pmid);
  17371. if ($this->inxobj) {
  17372. // we are inside an XObject template
  17373. $this->xobjects[$this->xobjid]['outdata'] = $pstart."\n".$pmid."\nBT 0 Tw ET\n".$pend;
  17374. } else {
  17375. $this->setPageBuffer($startlinepage, $pstart."\n".$pmid."\nBT 0 Tw ET\n".$pend);
  17376. }
  17377. $endlinepos = strlen($pstart."\n".$pmid."\nBT 0 Tw ET\n");
  17378. }
  17379. }
  17380. } // end of J
  17381. } // end if $startlinex
  17382. if (($t_x != 0) OR ($yshift < 0)) {
  17383. // shift the line
  17384. $trx = sprintf('1 0 0 1 %F %F cm', ($t_x * $this->k), ($yshift * $this->k));
  17385. $pstart .= "\nq\n".$trx."\n".$pmid."\nQ\n";
  17386. $endlinepos = strlen($pstart);
  17387. if ($this->inxobj) {
  17388. // we are inside an XObject template
  17389. $this->xobjects[$this->xobjid]['outdata'] = $pstart.$pend;
  17390. foreach ($this->xobjects[$this->xobjid]['annotations'] as $pak => $pac) {
  17391. if ($pak >= $pask) {
  17392. $this->xobjects[$this->xobjid]['annotations'][$pak]['x'] += $t_x;
  17393. $this->xobjects[$this->xobjid]['annotations'][$pak]['y'] -= $yshift;
  17394. }
  17395. }
  17396. } else {
  17397. $this->setPageBuffer($startlinepage, $pstart.$pend);
  17398. // shift the annotations and links
  17399. if (isset($this->PageAnnots[$this->page])) {
  17400. foreach ($this->PageAnnots[$this->page] as $pak => $pac) {
  17401. if ($pak >= $pask) {
  17402. $this->PageAnnots[$this->page][$pak]['x'] += $t_x;
  17403. $this->PageAnnots[$this->page][$pak]['y'] -= $yshift;
  17404. }
  17405. }
  17406. }
  17407. }
  17408. $this->y -= $yshift;
  17409. }
  17410. }
  17411. $pbrk = $this->checkPageBreak($this->lasth);
  17412. $this->newline = false;
  17413. $startlinex = $this->x;
  17414. $startliney = $this->y;
  17415. if ($dom[$dom[$key]['parent']]['value'] == 'sup') {
  17416. $startliney -= ((0.3 * $this->FontSizePt) / $this->k);
  17417. } elseif ($dom[$dom[$key]['parent']]['value'] == 'sub') {
  17418. $startliney -= (($this->FontSizePt / 0.7) / $this->k);
  17419. } else {
  17420. $minstartliney = $startliney;
  17421. $maxbottomliney = ($this->y + $this->getCellHeight($fontsize / $this->k));
  17422. }
  17423. $startlinepage = $this->page;
  17424. if (isset($endlinepos) AND (!$pbrk)) {
  17425. $startlinepos = $endlinepos;
  17426. } else {
  17427. if ($this->inxobj) {
  17428. // we are inside an XObject template
  17429. $startlinepos = strlen($this->xobjects[$this->xobjid]['outdata']);
  17430. } elseif (!$this->InFooter) {
  17431. if (isset($this->footerlen[$this->page])) {
  17432. $this->footerpos[$this->page] = $this->pagelen[$this->page] - $this->footerlen[$this->page];
  17433. } else {
  17434. $this->footerpos[$this->page] = $this->pagelen[$this->page];
  17435. }
  17436. $startlinepos = $this->footerpos[$this->page];
  17437. } else {
  17438. $startlinepos = $this->pagelen[$this->page];
  17439. }
  17440. }
  17441. unset($endlinepos);
  17442. $plalign = $lalign;
  17443. if (isset($this->PageAnnots[$this->page])) {
  17444. $pask = count($this->PageAnnots[$this->page]);
  17445. } else {
  17446. $pask = 0;
  17447. }
  17448. if (!($dom[$key]['tag'] AND !$dom[$key]['opening'] AND ($dom[$key]['value'] == 'table')
  17449. AND (isset($this->emptypagemrk[$this->page]))
  17450. AND ($this->emptypagemrk[$this->page] == $this->pagelen[$this->page]))) {
  17451. $this->SetFont($fontname, $fontstyle, $fontsize);
  17452. if ($wfill) {
  17453. $this->SetFillColorArray($this->bgcolor);
  17454. }
  17455. }
  17456. } // end newline
  17457. if (isset($opentagpos)) {
  17458. unset($opentagpos);
  17459. }
  17460. if ($dom[$key]['tag']) {
  17461. if ($dom[$key]['opening']) {
  17462. // get text indentation (if any)
  17463. if (isset($dom[$key]['text-indent']) AND $dom[$key]['block']) {
  17464. $this->textindent = $dom[$key]['text-indent'];
  17465. $this->newline = true;
  17466. }
  17467. // table
  17468. if (($dom[$key]['value'] == 'table') AND isset($dom[$key]['cols']) AND ($dom[$key]['cols'] > 0)) {
  17469. // available page width
  17470. if ($this->rtl) {
  17471. $wtmp = $this->x - $this->lMargin;
  17472. } else {
  17473. $wtmp = $this->w - $this->rMargin - $this->x;
  17474. }
  17475. // get cell spacing
  17476. if (isset($dom[$key]['attribute']['cellspacing'])) {
  17477. $clsp = $this->getHTMLUnitToUnits($dom[$key]['attribute']['cellspacing'], 1, 'px');
  17478. $cellspacing = array('H' => $clsp, 'V' => $clsp);
  17479. } elseif (isset($dom[$key]['border-spacing'])) {
  17480. $cellspacing = $dom[$key]['border-spacing'];
  17481. } else {
  17482. $cellspacing = array('H' => 0, 'V' => 0);
  17483. }
  17484. // table width
  17485. if (isset($dom[$key]['width'])) {
  17486. $table_width = $this->getHTMLUnitToUnits($dom[$key]['width'], $wtmp, 'px');
  17487. } else {
  17488. $table_width = $wtmp;
  17489. }
  17490. $table_width -= (2 * $cellspacing['H']);
  17491. if (!$this->inthead) {
  17492. $this->y += $cellspacing['V'];
  17493. }
  17494. if ($this->rtl) {
  17495. $cellspacingx = -$cellspacing['H'];
  17496. } else {
  17497. $cellspacingx = $cellspacing['H'];
  17498. }
  17499. // total table width without cellspaces
  17500. $table_columns_width = ($table_width - ($cellspacing['H'] * ($dom[$key]['cols'] - 1)));
  17501. // minimum column width
  17502. $table_min_column_width = ($table_columns_width / $dom[$key]['cols']);
  17503. // array of custom column widths
  17504. $table_colwidths = array_fill(0, $dom[$key]['cols'], $table_min_column_width);
  17505. }
  17506. // table row
  17507. if ($dom[$key]['value'] == 'tr') {
  17508. // reset column counter
  17509. $colid = 0;
  17510. }
  17511. // table cell
  17512. if (($dom[$key]['value'] == 'td') OR ($dom[$key]['value'] == 'th')) {
  17513. $trid = $dom[$key]['parent'];
  17514. $table_el = $dom[$trid]['parent'];
  17515. if (!isset($dom[$table_el]['cols'])) {
  17516. $dom[$table_el]['cols'] = $dom[$trid]['cols'];
  17517. }
  17518. // store border info
  17519. $tdborder = 0;
  17520. if (isset($dom[$key]['border']) AND !empty($dom[$key]['border'])) {
  17521. $tdborder = $dom[$key]['border'];
  17522. }
  17523. $colspan = intval($dom[$key]['attribute']['colspan']);
  17524. if ($colspan <= 0) {
  17525. $colspan = 1;
  17526. }
  17527. $old_cell_padding = $this->cell_padding;
  17528. if (isset($dom[($dom[$trid]['parent'])]['attribute']['cellpadding'])) {
  17529. $crclpd = $this->getHTMLUnitToUnits($dom[($dom[$trid]['parent'])]['attribute']['cellpadding'], 1, 'px');
  17530. $current_cell_padding = array('L' => $crclpd, 'T' => $crclpd, 'R' => $crclpd, 'B' => $crclpd);
  17531. } elseif (isset($dom[($dom[$trid]['parent'])]['padding'])) {
  17532. $current_cell_padding = $dom[($dom[$trid]['parent'])]['padding'];
  17533. } else {
  17534. $current_cell_padding = array('L' => 0, 'T' => 0, 'R' => 0, 'B' => 0);
  17535. }
  17536. $this->cell_padding = $current_cell_padding;
  17537. if (isset($dom[$key]['height'])) {
  17538. // minimum cell height
  17539. $cellh = $this->getHTMLUnitToUnits($dom[$key]['height'], 0, 'px');
  17540. } else {
  17541. $cellh = 0;
  17542. }
  17543. if (isset($dom[$key]['content'])) {
  17544. $cell_content = $dom[$key]['content'];
  17545. } else {
  17546. $cell_content = '&nbsp;';
  17547. }
  17548. $tagtype = $dom[$key]['value'];
  17549. $parentid = $key;
  17550. while (($key < $maxel) AND (!(($dom[$key]['tag']) AND (!$dom[$key]['opening']) AND ($dom[$key]['value'] == $tagtype) AND ($dom[$key]['parent'] == $parentid)))) {
  17551. // move $key index forward
  17552. ++$key;
  17553. }
  17554. if (!isset($dom[$trid]['startpage'])) {
  17555. $dom[$trid]['startpage'] = $this->page;
  17556. } else {
  17557. $this->setPage($dom[$trid]['startpage']);
  17558. }
  17559. if (!isset($dom[$trid]['startcolumn'])) {
  17560. $dom[$trid]['startcolumn'] = $this->current_column;
  17561. } elseif ($this->current_column != $dom[$trid]['startcolumn']) {
  17562. $tmpx = $this->x;
  17563. $this->selectColumn($dom[$trid]['startcolumn']);
  17564. $this->x = $tmpx;
  17565. }
  17566. if (!isset($dom[$trid]['starty'])) {
  17567. $dom[$trid]['starty'] = $this->y;
  17568. } else {
  17569. $this->y = $dom[$trid]['starty'];
  17570. }
  17571. if (!isset($dom[$trid]['startx'])) {
  17572. $dom[$trid]['startx'] = $this->x;
  17573. $this->x += $cellspacingx;
  17574. } else {
  17575. $this->x += ($cellspacingx / 2);
  17576. }
  17577. if (isset($dom[$parentid]['attribute']['rowspan'])) {
  17578. $rowspan = intval($dom[$parentid]['attribute']['rowspan']);
  17579. } else {
  17580. $rowspan = 1;
  17581. }
  17582. // skip row-spanned cells started on the previous rows
  17583. if (isset($dom[$table_el]['rowspans'])) {
  17584. $rsk = 0;
  17585. $rskmax = count($dom[$table_el]['rowspans']);
  17586. while ($rsk < $rskmax) {
  17587. $trwsp = $dom[$table_el]['rowspans'][$rsk];
  17588. $rsstartx = $trwsp['startx'];
  17589. $rsendx = $trwsp['endx'];
  17590. // account for margin changes
  17591. if ($trwsp['startpage'] < $this->page) {
  17592. if (($this->rtl) AND ($this->pagedim[$this->page]['orm'] != $this->pagedim[$trwsp['startpage']]['orm'])) {
  17593. $dl = ($this->pagedim[$this->page]['orm'] - $this->pagedim[$trwsp['startpage']]['orm']);
  17594. $rsstartx -= $dl;
  17595. $rsendx -= $dl;
  17596. } elseif ((!$this->rtl) AND ($this->pagedim[$this->page]['olm'] != $this->pagedim[$trwsp['startpage']]['olm'])) {
  17597. $dl = ($this->pagedim[$this->page]['olm'] - $this->pagedim[$trwsp['startpage']]['olm']);
  17598. $rsstartx += $dl;
  17599. $rsendx += $dl;
  17600. }
  17601. }
  17602. if (($trwsp['rowspan'] > 0)
  17603. AND ($rsstartx > ($this->x - $cellspacing['H'] - $current_cell_padding['L'] - $this->feps))
  17604. AND ($rsstartx < ($this->x + $cellspacing['H'] + $current_cell_padding['R'] + $this->feps))
  17605. AND (($trwsp['starty'] < ($this->y - $this->feps)) OR ($trwsp['startpage'] < $this->page) OR ($trwsp['startcolumn'] < $this->current_column))) {
  17606. // set the starting X position of the current cell
  17607. $this->x = $rsendx + $cellspacingx;
  17608. // increment column indicator
  17609. $colid += $trwsp['colspan'];
  17610. if (($trwsp['rowspan'] == 1)
  17611. AND (isset($dom[$trid]['endy']))
  17612. AND (isset($dom[$trid]['endpage']))
  17613. AND (isset($dom[$trid]['endcolumn']))
  17614. AND ($trwsp['endpage'] == $dom[$trid]['endpage'])
  17615. AND ($trwsp['endcolumn'] == $dom[$trid]['endcolumn'])) {
  17616. // set ending Y position for row
  17617. $dom[$table_el]['rowspans'][$rsk]['endy'] = max($dom[$trid]['endy'], $trwsp['endy']);
  17618. $dom[$trid]['endy'] = $dom[$table_el]['rowspans'][$rsk]['endy'];
  17619. }
  17620. $rsk = 0;
  17621. } else {
  17622. ++$rsk;
  17623. }
  17624. }
  17625. }
  17626. if (isset($dom[$parentid]['width'])) {
  17627. // user specified width
  17628. $cellw = $this->getHTMLUnitToUnits($dom[$parentid]['width'], $table_columns_width, 'px');
  17629. $tmpcw = ($cellw / $colspan);
  17630. for ($i = 0; $i < $colspan; ++$i) {
  17631. $table_colwidths[($colid + $i)] = $tmpcw;
  17632. }
  17633. } else {
  17634. // inherit column width
  17635. $cellw = 0;
  17636. for ($i = 0; $i < $colspan; ++$i) {
  17637. $cellw += (isset($table_colwidths[($colid + $i)]) ? $table_colwidths[($colid + $i)] : 0);
  17638. }
  17639. }
  17640. $cellw += (($colspan - 1) * $cellspacing['H']);
  17641. // increment column indicator
  17642. $colid += $colspan;
  17643. // add rowspan information to table element
  17644. if ($rowspan > 1) {
  17645. $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));
  17646. }
  17647. $cellid = array_push($dom[$trid]['cellpos'], array('startx' => $this->x));
  17648. if ($rowspan > 1) {
  17649. $dom[$trid]['cellpos'][($cellid - 1)]['rowspanid'] = ($trsid - 1);
  17650. }
  17651. // push background colors
  17652. if (isset($dom[$parentid]['bgcolor']) AND ($dom[$parentid]['bgcolor'] !== false)) {
  17653. $dom[$trid]['cellpos'][($cellid - 1)]['bgcolor'] = $dom[$parentid]['bgcolor'];
  17654. }
  17655. // store border info
  17656. if (isset($tdborder) AND !empty($tdborder)) {
  17657. $dom[$trid]['cellpos'][($cellid - 1)]['border'] = $tdborder;
  17658. }
  17659. $prevLastH = $this->lasth;
  17660. // store some info for multicolumn mode
  17661. if ($this->rtl) {
  17662. $this->colxshift['x'] = $this->w - $this->x - $this->rMargin;
  17663. } else {
  17664. $this->colxshift['x'] = $this->x - $this->lMargin;
  17665. }
  17666. $this->colxshift['s'] = $cellspacing;
  17667. $this->colxshift['p'] = $current_cell_padding;
  17668. // ****** write the cell content ******
  17669. $this->MultiCell($cellw, $cellh, $cell_content, false, $lalign, false, 2, '', '', true, 0, true, true, 0, 'T', false);
  17670. // restore some values
  17671. $this->colxshift = array('x' => 0, 's' => array('H' => 0, 'V' => 0), 'p' => array('L' => 0, 'T' => 0, 'R' => 0, 'B' => 0));
  17672. $this->lasth = $prevLastH;
  17673. $this->cell_padding = $old_cell_padding;
  17674. $dom[$trid]['cellpos'][($cellid - 1)]['endx'] = $this->x;
  17675. // update the end of row position
  17676. if ($rowspan <= 1) {
  17677. if (isset($dom[$trid]['endy'])) {
  17678. if (($this->page == $dom[$trid]['endpage']) AND ($this->current_column == $dom[$trid]['endcolumn'])) {
  17679. $dom[$trid]['endy'] = max($this->y, $dom[$trid]['endy']);
  17680. } elseif (($this->page > $dom[$trid]['endpage']) OR ($this->current_column > $dom[$trid]['endcolumn'])) {
  17681. $dom[$trid]['endy'] = $this->y;
  17682. }
  17683. } else {
  17684. $dom[$trid]['endy'] = $this->y;
  17685. }
  17686. if (isset($dom[$trid]['endpage'])) {
  17687. $dom[$trid]['endpage'] = max($this->page, $dom[$trid]['endpage']);
  17688. } else {
  17689. $dom[$trid]['endpage'] = $this->page;
  17690. }
  17691. if (isset($dom[$trid]['endcolumn'])) {
  17692. $dom[$trid]['endcolumn'] = max($this->current_column, $dom[$trid]['endcolumn']);
  17693. } else {
  17694. $dom[$trid]['endcolumn'] = $this->current_column;
  17695. }
  17696. } else {
  17697. // account for row-spanned cells
  17698. $dom[$table_el]['rowspans'][($trsid - 1)]['endx'] = $this->x;
  17699. $dom[$table_el]['rowspans'][($trsid - 1)]['endy'] = $this->y;
  17700. $dom[$table_el]['rowspans'][($trsid - 1)]['endpage'] = $this->page;
  17701. $dom[$table_el]['rowspans'][($trsid - 1)]['endcolumn'] = $this->current_column;
  17702. }
  17703. if (isset($dom[$table_el]['rowspans'])) {
  17704. // update endy and endpage on rowspanned cells
  17705. foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
  17706. if ($trwsp['rowspan'] > 0) {
  17707. if (isset($dom[$trid]['endpage'])) {
  17708. if (($trwsp['endpage'] == $dom[$trid]['endpage']) AND ($trwsp['endcolumn'] == $dom[$trid]['endcolumn'])) {
  17709. $dom[$table_el]['rowspans'][$k]['endy'] = max($dom[$trid]['endy'], $trwsp['endy']);
  17710. } elseif (($trwsp['endpage'] < $dom[$trid]['endpage']) OR ($trwsp['endcolumn'] < $dom[$trid]['endcolumn'])) {
  17711. $dom[$table_el]['rowspans'][$k]['endy'] = $dom[$trid]['endy'];
  17712. $dom[$table_el]['rowspans'][$k]['endpage'] = $dom[$trid]['endpage'];
  17713. $dom[$table_el]['rowspans'][$k]['endcolumn'] = $dom[$trid]['endcolumn'];
  17714. } else {
  17715. $dom[$trid]['endy'] = $this->pagedim[$dom[$trid]['endpage']]['hk'] - $this->pagedim[$dom[$trid]['endpage']]['bm'];
  17716. }
  17717. }
  17718. }
  17719. }
  17720. }
  17721. $this->x += ($cellspacingx / 2);
  17722. } else {
  17723. // opening tag (or self-closing tag)
  17724. if (!isset($opentagpos)) {
  17725. if ($this->inxobj) {
  17726. // we are inside an XObject template
  17727. $opentagpos = strlen($this->xobjects[$this->xobjid]['outdata']);
  17728. } elseif (!$this->InFooter) {
  17729. if (isset($this->footerlen[$this->page])) {
  17730. $this->footerpos[$this->page] = $this->pagelen[$this->page] - $this->footerlen[$this->page];
  17731. } else {
  17732. $this->footerpos[$this->page] = $this->pagelen[$this->page];
  17733. }
  17734. $opentagpos = $this->footerpos[$this->page];
  17735. }
  17736. }
  17737. $dom = $this->openHTMLTagHandler($dom, $key, $cell);
  17738. }
  17739. } else { // closing tag
  17740. $prev_numpages = $this->numpages;
  17741. $old_bordermrk = $this->bordermrk[$this->page];
  17742. $dom = $this->closeHTMLTagHandler($dom, $key, $cell, $maxbottomliney);
  17743. if ($this->bordermrk[$this->page] > $old_bordermrk) {
  17744. $startlinepos += ($this->bordermrk[$this->page] - $old_bordermrk);
  17745. }
  17746. if ($prev_numpages > $this->numpages) {
  17747. $startlinepage = $this->page;
  17748. }
  17749. }
  17750. } elseif (strlen($dom[$key]['value']) > 0) {
  17751. // print list-item
  17752. if (!TCPDF_STATIC::empty_string($this->lispacer) AND ($this->lispacer != '^')) {
  17753. $this->SetFont($pfontname, $pfontstyle, $pfontsize);
  17754. $this->resetLastH();
  17755. $minstartliney = $this->y;
  17756. $maxbottomliney = ($startliney + $this->getCellHeight($this->FontSize));
  17757. if (is_numeric($pfontsize) AND ($pfontsize > 0)) {
  17758. $this->putHtmlListBullet($this->listnum, $this->lispacer, $pfontsize);
  17759. }
  17760. $this->SetFont($curfontname, $curfontstyle, $curfontsize);
  17761. $this->resetLastH();
  17762. if (is_numeric($pfontsize) AND ($pfontsize > 0) AND is_numeric($curfontsize) AND ($curfontsize > 0) AND ($pfontsize != $curfontsize)) {
  17763. $pfontascent = $this->getFontAscent($pfontname, $pfontstyle, $pfontsize);
  17764. $pfontdescent = $this->getFontDescent($pfontname, $pfontstyle, $pfontsize);
  17765. $this->y += ($this->getCellHeight(($pfontsize - $curfontsize) / $this->k) + $pfontascent - $curfontascent - $pfontdescent + $curfontdescent) / 2;
  17766. $minstartliney = min($this->y, $minstartliney);
  17767. $maxbottomliney = max(($this->y + $this->getCellHeight($pfontsize / $this->k)), $maxbottomliney);
  17768. }
  17769. }
  17770. // text
  17771. $this->htmlvspace = 0;
  17772. $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']);
  17773. if ((!$this->premode) AND $this->isRTLTextDir() AND !$isRTLString) {
  17774. // reverse spaces order
  17775. $lsp = ''; // left spaces
  17776. $rsp = ''; // right spaces
  17777. if (preg_match('/^('.$this->re_space['p'].'+)/'.$this->re_space['m'], $dom[$key]['value'], $matches)) {
  17778. $lsp = $matches[1];
  17779. }
  17780. if (preg_match('/('.$this->re_space['p'].'+)$/'.$this->re_space['m'], $dom[$key]['value'], $matches)) {
  17781. $rsp = $matches[1];
  17782. }
  17783. $dom[$key]['value'] = $rsp.$this->stringTrim($dom[$key]['value']).$lsp;
  17784. }
  17785. if ($newline) {
  17786. if (!$this->premode) {
  17787. $prelen = strlen($dom[$key]['value']);
  17788. if ($this->isRTLTextDir() AND !$isRTLString) {
  17789. // right trim except non-breaking space
  17790. $dom[$key]['value'] = $this->stringRightTrim($dom[$key]['value']);
  17791. } else {
  17792. // left trim except non-breaking space
  17793. $dom[$key]['value'] = $this->stringLeftTrim($dom[$key]['value']);
  17794. }
  17795. $postlen = strlen($dom[$key]['value']);
  17796. if (($postlen == 0) AND ($prelen > 0)) {
  17797. $dom[$key]['trimmed_space'] = true;
  17798. }
  17799. }
  17800. $newline = false;
  17801. $firstblock = true;
  17802. } else {
  17803. $firstblock = false;
  17804. // replace empty multiple spaces string with a single space
  17805. $dom[$key]['value'] = preg_replace('/^'.$this->re_space['p'].'+$/'.$this->re_space['m'], chr(32), $dom[$key]['value']);
  17806. }
  17807. $strrest = '';
  17808. if ($this->rtl) {
  17809. $this->x -= $this->textindent;
  17810. } else {
  17811. $this->x += $this->textindent;
  17812. }
  17813. if (!isset($dom[$key]['trimmed_space']) OR !$dom[$key]['trimmed_space']) {
  17814. $strlinelen = $this->GetStringWidth($dom[$key]['value']);
  17815. if (!empty($this->HREF) AND (isset($this->HREF['url']))) {
  17816. // HTML <a> Link
  17817. $hrefcolor = '';
  17818. if (isset($dom[($dom[$key]['parent'])]['fgcolor']) AND ($dom[($dom[$key]['parent'])]['fgcolor'] !== false)) {
  17819. $hrefcolor = $dom[($dom[$key]['parent'])]['fgcolor'];
  17820. }
  17821. $hrefstyle = -1;
  17822. if (isset($dom[($dom[$key]['parent'])]['fontstyle']) AND ($dom[($dom[$key]['parent'])]['fontstyle'] !== false)) {
  17823. $hrefstyle = $dom[($dom[$key]['parent'])]['fontstyle'];
  17824. }
  17825. $strrest = $this->addHtmlLink($this->HREF['url'], $dom[$key]['value'], $wfill, true, $hrefcolor, $hrefstyle, true);
  17826. } else {
  17827. $wadj = 0; // space to leave for block continuity
  17828. if ($this->rtl) {
  17829. $cwa = ($this->x - $this->lMargin);
  17830. } else {
  17831. $cwa = ($this->w - $this->rMargin - $this->x);
  17832. }
  17833. if (($strlinelen < $cwa) AND (isset($dom[($key + 1)])) AND ($dom[($key + 1)]['tag']) AND (!$dom[($key + 1)]['block'])) {
  17834. // check the next text blocks for continuity
  17835. $nkey = ($key + 1);
  17836. $write_block = true;
  17837. $same_textdir = true;
  17838. $tmp_fontname = $this->FontFamily;
  17839. $tmp_fontstyle = $this->FontStyle;
  17840. $tmp_fontsize = $this->FontSizePt;
  17841. while ($write_block AND isset($dom[$nkey])) {
  17842. if ($dom[$nkey]['tag']) {
  17843. if ($dom[$nkey]['block']) {
  17844. // end of block
  17845. $write_block = false;
  17846. }
  17847. $tmp_fontname = isset($dom[$nkey]['fontname']) ? $dom[$nkey]['fontname'] : $this->FontFamily;
  17848. $tmp_fontstyle = isset($dom[$nkey]['fontstyle']) ? $dom[$nkey]['fontstyle'] : $this->FontStyle;
  17849. $tmp_fontsize = isset($dom[$nkey]['fontsize']) ? $dom[$nkey]['fontsize'] : $this->FontSizePt;
  17850. $same_textdir = ($dom[$nkey]['dir'] == $dom[$key]['dir']);
  17851. } else {
  17852. $nextstr = TCPDF_STATIC::pregSplit('/'.$this->re_space['p'].'+/', $this->re_space['m'], $dom[$nkey]['value']);
  17853. if (isset($nextstr[0]) AND $same_textdir) {
  17854. $wadj += $this->GetStringWidth($nextstr[0], $tmp_fontname, $tmp_fontstyle, $tmp_fontsize);
  17855. if (isset($nextstr[1])) {
  17856. $write_block = false;
  17857. }
  17858. }
  17859. }
  17860. ++$nkey;
  17861. }
  17862. }
  17863. if (($wadj > 0) AND (($strlinelen + $wadj) >= $cwa)) {
  17864. $wadj = 0;
  17865. $nextstr = TCPDF_STATIC::pregSplit('/'.$this->re_space['p'].'/', $this->re_space['m'], $dom[$key]['value']);
  17866. $numblks = count($nextstr);
  17867. if ($numblks > 1) {
  17868. // try to split on blank spaces
  17869. $wadj = ($cwa - $strlinelen + $this->GetStringWidth($nextstr[($numblks - 1)]));
  17870. } else {
  17871. // set the entire block on new line
  17872. $wadj = $this->GetStringWidth($nextstr[0]);
  17873. }
  17874. }
  17875. // check for reversed text direction
  17876. if (($wadj > 0) AND (($this->rtl AND ($this->tmprtl === 'L')) OR (!$this->rtl AND ($this->tmprtl === 'R')))) {
  17877. // LTR text on RTL direction or RTL text on LTR direction
  17878. $reverse_dir = true;
  17879. $this->rtl = !$this->rtl;
  17880. $revshift = ($strlinelen + $wadj + 0.000001); // add little quantity for rounding problems
  17881. if ($this->rtl) {
  17882. $this->x += $revshift;
  17883. } else {
  17884. $this->x -= $revshift;
  17885. }
  17886. $xws = $this->x;
  17887. }
  17888. // ****** write only until the end of the line and get the rest ******
  17889. $strrest = $this->Write($this->lasth, $dom[$key]['value'], '', $wfill, '', false, 0, true, $firstblock, 0, $wadj);
  17890. // restore default direction
  17891. if ($reverse_dir AND ($wadj == 0)) {
  17892. $this->x = $xws;
  17893. $this->rtl = !$this->rtl;
  17894. $reverse_dir = false;
  17895. }
  17896. }
  17897. }
  17898. $this->textindent = 0;
  17899. if (strlen($strrest) > 0) {
  17900. // store the remaining string on the previous $key position
  17901. $this->newline = true;
  17902. if ($strrest == $dom[$key]['value']) {
  17903. // used to avoid infinite loop
  17904. ++$loop;
  17905. } else {
  17906. $loop = 0;
  17907. }
  17908. $dom[$key]['value'] = $strrest;
  17909. if ($cell) {
  17910. if ($this->rtl) {
  17911. $this->x -= $this->cell_padding['R'];
  17912. } else {
  17913. $this->x += $this->cell_padding['L'];
  17914. }
  17915. }
  17916. if ($loop < 3) {
  17917. --$key;
  17918. }
  17919. } else {
  17920. $loop = 0;
  17921. // add the positive font spacing of the last character (if any)
  17922. if ($this->font_spacing > 0) {
  17923. if ($this->rtl) {
  17924. $this->x -= $this->font_spacing;
  17925. } else {
  17926. $this->x += $this->font_spacing;
  17927. }
  17928. }
  17929. }
  17930. }
  17931. ++$key;
  17932. 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')) {
  17933. // check if we are on a new page or on a new column
  17934. if ((!$undo) AND (($this->y < $this->start_transaction_y) OR (($dom[$key]['value'] == 'tr') AND ($dom[($dom[$key]['parent'])]['endy'] < $this->start_transaction_y)))) {
  17935. // we are on a new page or on a new column and the total object height is less than the available vertical space.
  17936. // restore previous object
  17937. $this->rollbackTransaction(true);
  17938. // restore previous values
  17939. foreach ($this_method_vars as $vkey => $vval) {
  17940. $$vkey = $vval;
  17941. }
  17942. if (!empty($dom[$key]['thead'])) {
  17943. $this->inthead = true;
  17944. }
  17945. // add a page (or trig AcceptPageBreak() for multicolumn mode)
  17946. $pre_y = $this->y;
  17947. if ((!$this->checkPageBreak($this->PageBreakTrigger + 1)) AND ($this->y < $pre_y)) {
  17948. $startliney = $this->y;
  17949. }
  17950. $undo = true; // avoid infinite loop
  17951. } else {
  17952. $undo = false;
  17953. }
  17954. }
  17955. } // end for each $key
  17956. // align the last line
  17957. if (isset($startlinex)) {
  17958. $yshift = ($minstartliney - $startliney);
  17959. if (($yshift > 0) OR ($this->page > $startlinepage)) {
  17960. $yshift = 0;
  17961. }
  17962. $t_x = 0;
  17963. // the last line must be shifted to be aligned as requested
  17964. $linew = abs($this->endlinex - $startlinex);
  17965. if ($this->inxobj) {
  17966. // we are inside an XObject template
  17967. $pstart = substr($this->xobjects[$this->xobjid]['outdata'], 0, $startlinepos);
  17968. if (isset($opentagpos)) {
  17969. $midpos = $opentagpos;
  17970. } else {
  17971. $midpos = 0;
  17972. }
  17973. if ($midpos > 0) {
  17974. $pmid = substr($this->xobjects[$this->xobjid]['outdata'], $startlinepos, ($midpos - $startlinepos));
  17975. $pend = substr($this->xobjects[$this->xobjid]['outdata'], $midpos);
  17976. } else {
  17977. $pmid = substr($this->xobjects[$this->xobjid]['outdata'], $startlinepos);
  17978. $pend = '';
  17979. }
  17980. } else {
  17981. $pstart = substr($this->getPageBuffer($startlinepage), 0, $startlinepos);
  17982. if (isset($opentagpos) AND isset($this->footerlen[$startlinepage]) AND (!$this->InFooter)) {
  17983. $this->footerpos[$startlinepage] = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
  17984. $midpos = min($opentagpos, $this->footerpos[$startlinepage]);
  17985. } elseif (isset($opentagpos)) {
  17986. $midpos = $opentagpos;
  17987. } elseif (isset($this->footerlen[$startlinepage]) AND (!$this->InFooter)) {
  17988. $this->footerpos[$startlinepage] = $this->pagelen[$startlinepage] - $this->footerlen[$startlinepage];
  17989. $midpos = $this->footerpos[$startlinepage];
  17990. } else {
  17991. $midpos = 0;
  17992. }
  17993. if ($midpos > 0) {
  17994. $pmid = substr($this->getPageBuffer($startlinepage), $startlinepos, ($midpos - $startlinepos));
  17995. $pend = substr($this->getPageBuffer($startlinepage), $midpos);
  17996. } else {
  17997. $pmid = substr($this->getPageBuffer($startlinepage), $startlinepos);
  17998. $pend = '';
  17999. }
  18000. }
  18001. if ((isset($plalign) AND ((($plalign == 'C') OR (($plalign == 'R') AND (!$this->rtl)) OR (($plalign == 'L') AND ($this->rtl)))))) {
  18002. // calculate shifting amount
  18003. $tw = $w;
  18004. if ($this->lMargin != $prevlMargin) {
  18005. $tw += ($prevlMargin - $this->lMargin);
  18006. }
  18007. if ($this->rMargin != $prevrMargin) {
  18008. $tw += ($prevrMargin - $this->rMargin);
  18009. }
  18010. $one_space_width = $this->GetStringWidth(chr(32));
  18011. $no = 0; // number of spaces on a line contained on a single block
  18012. if ($this->isRTLTextDir()) { // RTL
  18013. // remove left space if exist
  18014. $pos1 = TCPDF_STATIC::revstrpos($pmid, '[(');
  18015. if ($pos1 > 0) {
  18016. $pos1 = intval($pos1);
  18017. if ($this->isUnicodeFont()) {
  18018. $pos2 = intval(TCPDF_STATIC::revstrpos($pmid, '[('.chr(0).chr(32)));
  18019. $spacelen = 2;
  18020. } else {
  18021. $pos2 = intval(TCPDF_STATIC::revstrpos($pmid, '[('.chr(32)));
  18022. $spacelen = 1;
  18023. }
  18024. if ($pos1 == $pos2) {
  18025. $pmid = substr($pmid, 0, ($pos1 + 2)).substr($pmid, ($pos1 + 2 + $spacelen));
  18026. if (substr($pmid, $pos1, 4) == '[()]') {
  18027. $linew -= $one_space_width;
  18028. } elseif ($pos1 == strpos($pmid, '[(')) {
  18029. $no = 1;
  18030. }
  18031. }
  18032. }
  18033. } else { // LTR
  18034. // remove right space if exist
  18035. $pos1 = TCPDF_STATIC::revstrpos($pmid, ')]');
  18036. if ($pos1 > 0) {
  18037. $pos1 = intval($pos1);
  18038. if ($this->isUnicodeFont()) {
  18039. $pos2 = intval(TCPDF_STATIC::revstrpos($pmid, chr(0).chr(32).')]')) + 2;
  18040. $spacelen = 2;
  18041. } else {
  18042. $pos2 = intval(TCPDF_STATIC::revstrpos($pmid, chr(32).')]')) + 1;
  18043. $spacelen = 1;
  18044. }
  18045. if ($pos1 == $pos2) {
  18046. $pmid = substr($pmid, 0, ($pos1 - $spacelen)).substr($pmid, $pos1);
  18047. $linew -= $one_space_width;
  18048. }
  18049. }
  18050. }
  18051. $mdiff = ($tw - $linew);
  18052. if ($plalign == 'C') {
  18053. if ($this->rtl) {
  18054. $t_x = -($mdiff / 2);
  18055. } else {
  18056. $t_x = ($mdiff / 2);
  18057. }
  18058. } elseif ($plalign == 'R') {
  18059. // right alignment on LTR document
  18060. $t_x = $mdiff;
  18061. } elseif ($plalign == 'L') {
  18062. // left alignment on RTL document
  18063. $t_x = -$mdiff;
  18064. }
  18065. } // end if startlinex
  18066. if (($t_x != 0) OR ($yshift < 0)) {
  18067. // shift the line
  18068. $trx = sprintf('1 0 0 1 %F %F cm', ($t_x * $this->k), ($yshift * $this->k));
  18069. $pstart .= "\nq\n".$trx."\n".$pmid."\nQ\n";
  18070. $endlinepos = strlen($pstart);
  18071. if ($this->inxobj) {
  18072. // we are inside an XObject template
  18073. $this->xobjects[$this->xobjid]['outdata'] = $pstart.$pend;
  18074. foreach ($this->xobjects[$this->xobjid]['annotations'] as $pak => $pac) {
  18075. if ($pak >= $pask) {
  18076. $this->xobjects[$this->xobjid]['annotations'][$pak]['x'] += $t_x;
  18077. $this->xobjects[$this->xobjid]['annotations'][$pak]['y'] -= $yshift;
  18078. }
  18079. }
  18080. } else {
  18081. $this->setPageBuffer($startlinepage, $pstart.$pend);
  18082. // shift the annotations and links
  18083. if (isset($this->PageAnnots[$this->page])) {
  18084. foreach ($this->PageAnnots[$this->page] as $pak => $pac) {
  18085. if ($pak >= $pask) {
  18086. $this->PageAnnots[$this->page][$pak]['x'] += $t_x;
  18087. $this->PageAnnots[$this->page][$pak]['y'] -= $yshift;
  18088. }
  18089. }
  18090. }
  18091. }
  18092. $this->y -= $yshift;
  18093. $yshift = 0;
  18094. }
  18095. }
  18096. // restore previous values
  18097. $this->setGraphicVars($gvars);
  18098. if ($this->num_columns > 1) {
  18099. $this->selectColumn();
  18100. } elseif ($this->page > $prevPage) {
  18101. $this->lMargin = $this->pagedim[$this->page]['olm'];
  18102. $this->rMargin = $this->pagedim[$this->page]['orm'];
  18103. }
  18104. // restore previous list state
  18105. $this->cell_height_ratio = $prev_cell_height_ratio;
  18106. $this->listnum = $prev_listnum;
  18107. $this->listordered = $prev_listordered;
  18108. $this->listcount = $prev_listcount;
  18109. $this->lispacer = $prev_lispacer;
  18110. if ($ln AND (!($cell AND ($dom[$key-1]['value'] == 'table')))) {
  18111. $this->Ln($this->lasth);
  18112. if (($this->y < $maxbottomliney) AND ($startlinepage == $this->page)) {
  18113. $this->y = $maxbottomliney;
  18114. }
  18115. }
  18116. unset($dom);
  18117. }
  18118. /**
  18119. * Process opening tags.
  18120. * @param $dom (array) html dom array
  18121. * @param $key (int) current element id
  18122. * @param $cell (boolean) if true add the default left (or right if RTL) padding to each new line (default false).
  18123. * @return $dom array
  18124. * @protected
  18125. */
  18126. protected function openHTMLTagHandler($dom, $key, $cell) {
  18127. $tag = $dom[$key];
  18128. $parent = $dom[($dom[$key]['parent'])];
  18129. $firsttag = ($key == 1);
  18130. // check for text direction attribute
  18131. if (isset($tag['dir'])) {
  18132. $this->setTempRTL($tag['dir']);
  18133. } else {
  18134. $this->tmprtl = false;
  18135. }
  18136. if ($tag['block']) {
  18137. $hbz = 0; // distance from y to line bottom
  18138. $hb = 0; // vertical space between block tags
  18139. // calculate vertical space for block tags
  18140. if (isset($this->tagvspaces[$tag['value']][0]['h']) && !empty($this->tagvspaces[$tag['value']][0]['h']) && ($this->tagvspaces[$tag['value']][0]['h'] >= 0)) {
  18141. $cur_h = $this->tagvspaces[$tag['value']][0]['h'];
  18142. } elseif (isset($tag['fontsize'])) {
  18143. $cur_h = $this->getCellHeight($tag['fontsize'] / $this->k);
  18144. } else {
  18145. $cur_h = $this->getCellHeight($this->FontSize);
  18146. }
  18147. if (isset($this->tagvspaces[$tag['value']][0]['n'])) {
  18148. $on = $this->tagvspaces[$tag['value']][0]['n'];
  18149. } elseif (preg_match('/[h][0-9]/', $tag['value']) > 0) {
  18150. $on = 0.6;
  18151. } else {
  18152. $on = 1;
  18153. }
  18154. if ((!isset($this->tagvspaces[$tag['value']])) AND (in_array($tag['value'], array('div', 'dt', 'dd', 'li', 'br', 'hr')))) {
  18155. $hb = 0;
  18156. } else {
  18157. $hb = ($on * $cur_h);
  18158. }
  18159. if (($this->htmlvspace <= 0) AND ($on > 0)) {
  18160. if (isset($parent['fontsize'])) {
  18161. $hbz = (($parent['fontsize'] / $this->k) * $this->cell_height_ratio);
  18162. } else {
  18163. $hbz = $this->getCellHeight($this->FontSize);
  18164. }
  18165. }
  18166. if (isset($dom[($key - 1)]) AND ($dom[($key - 1)]['value'] == 'table')) {
  18167. // fix vertical space after table
  18168. $hbz = 0;
  18169. }
  18170. // closing vertical space
  18171. $hbc = 0;
  18172. if (isset($this->tagvspaces[$tag['value']][1]['h']) && !empty($this->tagvspaces[$tag['value']][1]['h']) && ($this->tagvspaces[$tag['value']][1]['h'] >= 0)) {
  18173. $pre_h = $this->tagvspaces[$tag['value']][1]['h'];
  18174. } elseif (isset($parent['fontsize'])) {
  18175. $pre_h = $this->getCellHeight($parent['fontsize'] / $this->k);
  18176. } else {
  18177. $pre_h = $this->getCellHeight($this->FontSize);
  18178. }
  18179. if (isset($this->tagvspaces[$tag['value']][1]['n'])) {
  18180. $cn = $this->tagvspaces[$tag['value']][1]['n'];
  18181. } elseif (preg_match('/[h][0-9]/', $tag['value']) > 0) {
  18182. $cn = 0.6;
  18183. } else {
  18184. $cn = 1;
  18185. }
  18186. if (isset($this->tagvspaces[$tag['value']][1])) {
  18187. $hbc = ($cn * $pre_h);
  18188. }
  18189. }
  18190. // Opening tag
  18191. switch($tag['value']) {
  18192. case 'table': {
  18193. $cp = 0;
  18194. $cs = 0;
  18195. $dom[$key]['rowspans'] = array();
  18196. if (!isset($dom[$key]['attribute']['nested']) OR ($dom[$key]['attribute']['nested'] != 'true')) {
  18197. $this->htmlvspace = 0;
  18198. // set table header
  18199. if (!TCPDF_STATIC::empty_string($dom[$key]['thead'])) {
  18200. // set table header
  18201. $this->thead = $dom[$key]['thead'];
  18202. if (!isset($this->theadMargins) OR (empty($this->theadMargins))) {
  18203. $this->theadMargins = array();
  18204. $this->theadMargins['cell_padding'] = $this->cell_padding;
  18205. $this->theadMargins['lmargin'] = $this->lMargin;
  18206. $this->theadMargins['rmargin'] = $this->rMargin;
  18207. $this->theadMargins['page'] = $this->page;
  18208. $this->theadMargins['cell'] = $cell;
  18209. $this->theadMargins['gvars'] = $this->getGraphicVars();
  18210. }
  18211. }
  18212. }
  18213. // store current margins and page
  18214. $dom[$key]['old_cell_padding'] = $this->cell_padding;
  18215. if (isset($tag['attribute']['cellpadding'])) {
  18216. $pad = $this->getHTMLUnitToUnits($tag['attribute']['cellpadding'], 1, 'px');
  18217. $this->SetCellPadding($pad);
  18218. } elseif (isset($tag['padding'])) {
  18219. $this->cell_padding = $tag['padding'];
  18220. }
  18221. if (isset($tag['attribute']['cellspacing'])) {
  18222. $cs = $this->getHTMLUnitToUnits($tag['attribute']['cellspacing'], 1, 'px');
  18223. } elseif (isset($tag['border-spacing'])) {
  18224. $cs = $tag['border-spacing']['V'];
  18225. }
  18226. $prev_y = $this->y;
  18227. if ($this->checkPageBreak(((2 * $cp) + (2 * $cs) + $this->lasth), '', false) OR ($this->y < $prev_y)) {
  18228. $this->inthead = true;
  18229. // add a page (or trig AcceptPageBreak() for multicolumn mode)
  18230. $this->checkPageBreak($this->PageBreakTrigger + 1);
  18231. }
  18232. break;
  18233. }
  18234. case 'tr': {
  18235. // array of columns positions
  18236. $dom[$key]['cellpos'] = array();
  18237. break;
  18238. }
  18239. case 'hr': {
  18240. if ((isset($tag['height'])) AND ($tag['height'] != '')) {
  18241. $hrHeight = $this->getHTMLUnitToUnits($tag['height'], 1, 'px');
  18242. } else {
  18243. $hrHeight = $this->GetLineWidth();
  18244. }
  18245. $this->addHTMLVertSpace($hbz, max($hb, ($hrHeight / 2)), $cell, $firsttag);
  18246. $x = $this->GetX();
  18247. $y = $this->GetY();
  18248. $wtmp = $this->w - $this->lMargin - $this->rMargin;
  18249. if ($cell) {
  18250. $wtmp -= ($this->cell_padding['L'] + $this->cell_padding['R']);
  18251. }
  18252. if ((isset($tag['width'])) AND ($tag['width'] != '')) {
  18253. $hrWidth = $this->getHTMLUnitToUnits($tag['width'], $wtmp, 'px');
  18254. } else {
  18255. $hrWidth = $wtmp;
  18256. }
  18257. $prevlinewidth = $this->GetLineWidth();
  18258. $this->SetLineWidth($hrHeight);
  18259. $this->Line($x, $y, $x + $hrWidth, $y);
  18260. $this->SetLineWidth($prevlinewidth);
  18261. $this->addHTMLVertSpace(max($hbc, ($hrHeight / 2)), 0, $cell, !isset($dom[($key + 1)]));
  18262. break;
  18263. }
  18264. case 'a': {
  18265. if (array_key_exists('href', $tag['attribute'])) {
  18266. $this->HREF['url'] = $tag['attribute']['href'];
  18267. }
  18268. break;
  18269. }
  18270. case 'img': {
  18271. if (empty($tag['attribute']['src'])) {
  18272. break;
  18273. }
  18274. $imgsrc = $tag['attribute']['src'];
  18275. if ($imgsrc[0] === '@') {
  18276. // data stream
  18277. $imgsrc = '@'.base64_decode(substr($imgsrc, 1));
  18278. $type = '';
  18279. } else {
  18280. if (($imgsrc[0] === '/') AND !empty($_SERVER['DOCUMENT_ROOT']) AND ($_SERVER['DOCUMENT_ROOT'] != '/')) {
  18281. // fix image path
  18282. $findroot = strpos($imgsrc, $_SERVER['DOCUMENT_ROOT']);
  18283. if (($findroot === false) OR ($findroot > 1)) {
  18284. if (substr($_SERVER['DOCUMENT_ROOT'], -1) == '/') {
  18285. $imgsrc = substr($_SERVER['DOCUMENT_ROOT'], 0, -1).$imgsrc;
  18286. } else {
  18287. $imgsrc = $_SERVER['DOCUMENT_ROOT'].$imgsrc;
  18288. }
  18289. }
  18290. $imgsrc = urldecode($imgsrc);
  18291. $testscrtype = @parse_url($imgsrc);
  18292. if (empty($testscrtype['query'])) {
  18293. // convert URL to server path
  18294. $imgsrc = str_replace(K_PATH_URL, K_PATH_MAIN, $imgsrc);
  18295. } elseif (preg_match('|^https?://|', $imgsrc) !== 1) {
  18296. // convert URL to server path
  18297. $imgsrc = str_replace(K_PATH_MAIN, K_PATH_URL, $imgsrc);
  18298. }
  18299. }
  18300. // get image type
  18301. $type = TCPDF_IMAGES::getImageFileType($imgsrc);
  18302. }
  18303. if (!isset($tag['width'])) {
  18304. $tag['width'] = 0;
  18305. }
  18306. if (!isset($tag['height'])) {
  18307. $tag['height'] = 0;
  18308. }
  18309. //if (!isset($tag['attribute']['align'])) {
  18310. // the only alignment supported is "bottom"
  18311. // further development is required for other modes.
  18312. $tag['attribute']['align'] = 'bottom';
  18313. //}
  18314. switch($tag['attribute']['align']) {
  18315. case 'top': {
  18316. $align = 'T';
  18317. break;
  18318. }
  18319. case 'middle': {
  18320. $align = 'M';
  18321. break;
  18322. }
  18323. case 'bottom': {
  18324. $align = 'B';
  18325. break;
  18326. }
  18327. default: {
  18328. $align = 'B';
  18329. break;
  18330. }
  18331. }
  18332. $prevy = $this->y;
  18333. $xpos = $this->x;
  18334. $imglink = '';
  18335. if (isset($this->HREF['url']) AND !TCPDF_STATIC::empty_string($this->HREF['url'])) {
  18336. $imglink = $this->HREF['url'];
  18337. if ($imglink[0] == '#') {
  18338. // convert url to internal link
  18339. $lnkdata = explode(',', $imglink);
  18340. if (isset($lnkdata[0])) {
  18341. $page = intval(substr($lnkdata[0], 1));
  18342. if (empty($page) OR ($page <= 0)) {
  18343. $page = $this->page;
  18344. }
  18345. if (isset($lnkdata[1]) AND (strlen($lnkdata[1]) > 0)) {
  18346. $lnky = floatval($lnkdata[1]);
  18347. } else {
  18348. $lnky = 0;
  18349. }
  18350. $imglink = $this->AddLink();
  18351. $this->SetLink($imglink, $lnky, $page);
  18352. }
  18353. }
  18354. }
  18355. $border = 0;
  18356. if (isset($tag['border']) AND !empty($tag['border'])) {
  18357. // currently only support 1 (frame) or a combination of 'LTRB'
  18358. $border = $tag['border'];
  18359. }
  18360. $iw = '';
  18361. if (isset($tag['width'])) {
  18362. $iw = $this->getHTMLUnitToUnits($tag['width'], ($tag['fontsize'] / $this->k), 'px', false);
  18363. }
  18364. $ih = '';
  18365. if (isset($tag['height'])) {
  18366. $ih = $this->getHTMLUnitToUnits($tag['height'], ($tag['fontsize'] / $this->k), 'px', false);
  18367. }
  18368. if (($type == 'eps') OR ($type == 'ai')) {
  18369. $this->ImageEps($imgsrc, $xpos, $this->y, $iw, $ih, $imglink, true, $align, '', $border, true);
  18370. } elseif ($type == 'svg') {
  18371. $this->ImageSVG($imgsrc, $xpos, $this->y, $iw, $ih, $imglink, $align, '', $border, true);
  18372. } else {
  18373. $this->Image($imgsrc, $xpos, $this->y, $iw, $ih, '', $imglink, $align, false, 300, '', false, false, $border, false, false, true);
  18374. }
  18375. switch($align) {
  18376. case 'T': {
  18377. $this->y = $prevy;
  18378. break;
  18379. }
  18380. case 'M': {
  18381. $this->y = (($this->img_rb_y + $prevy - ($this->getCellHeight($tag['fontsize'] / $this->k))) / 2);
  18382. break;
  18383. }
  18384. case 'B': {
  18385. $this->y = $this->img_rb_y - ($this->getCellHeight($tag['fontsize'] / $this->k) - ($this->getFontDescent($tag['fontname'], $tag['fontstyle'], $tag['fontsize']) * $this->cell_height_ratio));
  18386. break;
  18387. }
  18388. }
  18389. break;
  18390. }
  18391. case 'dl': {
  18392. ++$this->listnum;
  18393. if ($this->listnum == 1) {
  18394. $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
  18395. } else {
  18396. $this->addHTMLVertSpace(0, 0, $cell, $firsttag);
  18397. }
  18398. break;
  18399. }
  18400. case 'dt': {
  18401. $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
  18402. break;
  18403. }
  18404. case 'dd': {
  18405. if ($this->rtl) {
  18406. $this->rMargin += $this->listindent;
  18407. } else {
  18408. $this->lMargin += $this->listindent;
  18409. }
  18410. ++$this->listindentlevel;
  18411. $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
  18412. break;
  18413. }
  18414. case 'ul':
  18415. case 'ol': {
  18416. ++$this->listnum;
  18417. if ($tag['value'] == 'ol') {
  18418. $this->listordered[$this->listnum] = true;
  18419. } else {
  18420. $this->listordered[$this->listnum] = false;
  18421. }
  18422. if (isset($tag['attribute']['start'])) {
  18423. $this->listcount[$this->listnum] = intval($tag['attribute']['start']) - 1;
  18424. } else {
  18425. $this->listcount[$this->listnum] = 0;
  18426. }
  18427. if ($this->rtl) {
  18428. $this->rMargin += $this->listindent;
  18429. $this->x -= $this->listindent;
  18430. } else {
  18431. $this->lMargin += $this->listindent;
  18432. $this->x += $this->listindent;
  18433. }
  18434. ++$this->listindentlevel;
  18435. if ($this->listnum == 1) {
  18436. if ($key > 1) {
  18437. $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
  18438. }
  18439. } else {
  18440. $this->addHTMLVertSpace(0, 0, $cell, $firsttag);
  18441. }
  18442. break;
  18443. }
  18444. case 'li': {
  18445. if ($key > 2) {
  18446. $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
  18447. }
  18448. if ($this->listordered[$this->listnum]) {
  18449. // ordered item
  18450. if (isset($parent['attribute']['type']) AND !TCPDF_STATIC::empty_string($parent['attribute']['type'])) {
  18451. $this->lispacer = $parent['attribute']['type'];
  18452. } elseif (isset($parent['listtype']) AND !TCPDF_STATIC::empty_string($parent['listtype'])) {
  18453. $this->lispacer = $parent['listtype'];
  18454. } elseif (isset($this->lisymbol) AND !TCPDF_STATIC::empty_string($this->lisymbol)) {
  18455. $this->lispacer = $this->lisymbol;
  18456. } else {
  18457. $this->lispacer = '#';
  18458. }
  18459. ++$this->listcount[$this->listnum];
  18460. if (isset($tag['attribute']['value'])) {
  18461. $this->listcount[$this->listnum] = intval($tag['attribute']['value']);
  18462. }
  18463. } else {
  18464. // unordered item
  18465. if (isset($parent['attribute']['type']) AND !TCPDF_STATIC::empty_string($parent['attribute']['type'])) {
  18466. $this->lispacer = $parent['attribute']['type'];
  18467. } elseif (isset($parent['listtype']) AND !TCPDF_STATIC::empty_string($parent['listtype'])) {
  18468. $this->lispacer = $parent['listtype'];
  18469. } elseif (isset($this->lisymbol) AND !TCPDF_STATIC::empty_string($this->lisymbol)) {
  18470. $this->lispacer = $this->lisymbol;
  18471. } else {
  18472. $this->lispacer = '!';
  18473. }
  18474. }
  18475. break;
  18476. }
  18477. case 'blockquote': {
  18478. if ($this->rtl) {
  18479. $this->rMargin += $this->listindent;
  18480. } else {
  18481. $this->lMargin += $this->listindent;
  18482. }
  18483. ++$this->listindentlevel;
  18484. $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
  18485. break;
  18486. }
  18487. case 'br': {
  18488. $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
  18489. break;
  18490. }
  18491. case 'div': {
  18492. $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
  18493. break;
  18494. }
  18495. case 'p': {
  18496. $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
  18497. break;
  18498. }
  18499. case 'pre': {
  18500. $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
  18501. $this->premode = true;
  18502. break;
  18503. }
  18504. case 'sup': {
  18505. $this->SetXY($this->GetX(), $this->GetY() - ((0.7 * $this->FontSizePt) / $this->k));
  18506. break;
  18507. }
  18508. case 'sub': {
  18509. $this->SetXY($this->GetX(), $this->GetY() + ((0.3 * $this->FontSizePt) / $this->k));
  18510. break;
  18511. }
  18512. case 'h1':
  18513. case 'h2':
  18514. case 'h3':
  18515. case 'h4':
  18516. case 'h5':
  18517. case 'h6': {
  18518. $this->addHTMLVertSpace($hbz, $hb, $cell, $firsttag);
  18519. break;
  18520. }
  18521. // Form fields (since 4.8.000 - 2009-09-07)
  18522. case 'form': {
  18523. if (isset($tag['attribute']['action'])) {
  18524. $this->form_action = $tag['attribute']['action'];
  18525. } else {
  18526. $this->Error('Please explicitly set action attribute path!');
  18527. }
  18528. if (isset($tag['attribute']['enctype'])) {
  18529. $this->form_enctype = $tag['attribute']['enctype'];
  18530. } else {
  18531. $this->form_enctype = 'application/x-www-form-urlencoded';
  18532. }
  18533. if (isset($tag['attribute']['method'])) {
  18534. $this->form_mode = $tag['attribute']['method'];
  18535. } else {
  18536. $this->form_mode = 'post';
  18537. }
  18538. break;
  18539. }
  18540. case 'input': {
  18541. if (isset($tag['attribute']['name']) AND !TCPDF_STATIC::empty_string($tag['attribute']['name'])) {
  18542. $name = $tag['attribute']['name'];
  18543. } else {
  18544. break;
  18545. }
  18546. $prop = array();
  18547. $opt = array();
  18548. if (isset($tag['attribute']['readonly']) AND !TCPDF_STATIC::empty_string($tag['attribute']['readonly'])) {
  18549. $prop['readonly'] = true;
  18550. }
  18551. if (isset($tag['attribute']['value']) AND !TCPDF_STATIC::empty_string($tag['attribute']['value'])) {
  18552. $value = $tag['attribute']['value'];
  18553. }
  18554. if (isset($tag['attribute']['maxlength']) AND !TCPDF_STATIC::empty_string($tag['attribute']['maxlength'])) {
  18555. $opt['maxlen'] = intval($tag['attribute']['maxlength']);
  18556. }
  18557. $h = $this->getCellHeight($this->FontSize);
  18558. if (isset($tag['attribute']['size']) AND !TCPDF_STATIC::empty_string($tag['attribute']['size'])) {
  18559. $w = intval($tag['attribute']['size']) * $this->GetStringWidth(chr(32)) * 2;
  18560. } else {
  18561. $w = $h;
  18562. }
  18563. if (isset($tag['attribute']['checked']) AND (($tag['attribute']['checked'] == 'checked') OR ($tag['attribute']['checked'] == 'true'))) {
  18564. $checked = true;
  18565. } else {
  18566. $checked = false;
  18567. }
  18568. if (isset($tag['align'])) {
  18569. switch ($tag['align']) {
  18570. case 'C': {
  18571. $opt['q'] = 1;
  18572. break;
  18573. }
  18574. case 'R': {
  18575. $opt['q'] = 2;
  18576. break;
  18577. }
  18578. case 'L':
  18579. default: {
  18580. break;
  18581. }
  18582. }
  18583. }
  18584. switch ($tag['attribute']['type']) {
  18585. case 'text': {
  18586. if (isset($value)) {
  18587. $opt['v'] = $value;
  18588. }
  18589. $this->TextField($name, $w, $h, $prop, $opt, '', '', false);
  18590. break;
  18591. }
  18592. case 'password': {
  18593. if (isset($value)) {
  18594. $opt['v'] = $value;
  18595. }
  18596. $prop['password'] = 'true';
  18597. $this->TextField($name, $w, $h, $prop, $opt, '', '', false);
  18598. break;
  18599. }
  18600. case 'checkbox': {
  18601. if (!isset($value)) {
  18602. break;
  18603. }
  18604. $this->CheckBox($name, $w, $checked, $prop, $opt, $value, '', '', false);
  18605. break;
  18606. }
  18607. case 'radio': {
  18608. if (!isset($value)) {
  18609. break;
  18610. }
  18611. $this->RadioButton($name, $w, $prop, $opt, $value, $checked, '', '', false);
  18612. break;
  18613. }
  18614. case 'submit': {
  18615. if (!isset($value)) {
  18616. $value = 'submit';
  18617. }
  18618. $w = $this->GetStringWidth($value) * 1.5;
  18619. $h *= 1.6;
  18620. $prop = array('lineWidth'=>1, 'borderStyle'=>'beveled', 'fillColor'=>array(196, 196, 196), 'strokeColor'=>array(255, 255, 255));
  18621. $action = array();
  18622. $action['S'] = 'SubmitForm';
  18623. $action['F'] = $this->form_action;
  18624. if ($this->form_enctype != 'FDF') {
  18625. $action['Flags'] = array('ExportFormat');
  18626. }
  18627. if ($this->form_mode == 'get') {
  18628. $action['Flags'] = array('GetMethod');
  18629. }
  18630. $this->Button($name, $w, $h, $value, $action, $prop, $opt, '', '', false);
  18631. break;
  18632. }
  18633. case 'reset': {
  18634. if (!isset($value)) {
  18635. $value = 'reset';
  18636. }
  18637. $w = $this->GetStringWidth($value) * 1.5;
  18638. $h *= 1.6;
  18639. $prop = array('lineWidth'=>1, 'borderStyle'=>'beveled', 'fillColor'=>array(196, 196, 196), 'strokeColor'=>array(255, 255, 255));
  18640. $this->Button($name, $w, $h, $value, array('S'=>'ResetForm'), $prop, $opt, '', '', false);
  18641. break;
  18642. }
  18643. case 'file': {
  18644. $prop['fileSelect'] = 'true';
  18645. $this->TextField($name, $w, $h, $prop, $opt, '', '', false);
  18646. if (!isset($value)) {
  18647. $value = '*';
  18648. }
  18649. $w = $this->GetStringWidth($value) * 2;
  18650. $h *= 1.2;
  18651. $prop = array('lineWidth'=>1, 'borderStyle'=>'beveled', 'fillColor'=>array(196, 196, 196), 'strokeColor'=>array(255, 255, 255));
  18652. $jsaction = 'var f=this.getField(\''.$name.'\'); f.browseForFileToSubmit();';
  18653. $this->Button('FB_'.$name, $w, $h, $value, $jsaction, $prop, $opt, '', '', false);
  18654. break;
  18655. }
  18656. case 'hidden': {
  18657. if (isset($value)) {
  18658. $opt['v'] = $value;
  18659. }
  18660. $opt['f'] = array('invisible', 'hidden');
  18661. $this->TextField($name, 0, 0, $prop, $opt, '', '', false);
  18662. break;
  18663. }
  18664. case 'image': {
  18665. // THIS TYPE MUST BE FIXED
  18666. if (isset($tag['attribute']['src']) AND !TCPDF_STATIC::empty_string($tag['attribute']['src'])) {
  18667. $img = $tag['attribute']['src'];
  18668. } else {
  18669. break;
  18670. }
  18671. $value = 'img';
  18672. //$opt['mk'] = array('i'=>$img, 'tp'=>1, 'if'=>array('sw'=>'A', 's'=>'A', 'fb'=>false));
  18673. if (isset($tag['attribute']['onclick']) AND !empty($tag['attribute']['onclick'])) {
  18674. $jsaction = $tag['attribute']['onclick'];
  18675. } else {
  18676. $jsaction = '';
  18677. }
  18678. $this->Button($name, $w, $h, $value, $jsaction, $prop, $opt, '', '', false);
  18679. break;
  18680. }
  18681. case 'button': {
  18682. if (!isset($value)) {
  18683. $value = ' ';
  18684. }
  18685. $w = $this->GetStringWidth($value) * 1.5;
  18686. $h *= 1.6;
  18687. $prop = array('lineWidth'=>1, 'borderStyle'=>'beveled', 'fillColor'=>array(196, 196, 196), 'strokeColor'=>array(255, 255, 255));
  18688. if (isset($tag['attribute']['onclick']) AND !empty($tag['attribute']['onclick'])) {
  18689. $jsaction = $tag['attribute']['onclick'];
  18690. } else {
  18691. $jsaction = '';
  18692. }
  18693. $this->Button($name, $w, $h, $value, $jsaction, $prop, $opt, '', '', false);
  18694. break;
  18695. }
  18696. }
  18697. break;
  18698. }
  18699. case 'textarea': {
  18700. $prop = array();
  18701. $opt = array();
  18702. if (isset($tag['attribute']['readonly']) AND !TCPDF_STATIC::empty_string($tag['attribute']['readonly'])) {
  18703. $prop['readonly'] = true;
  18704. }
  18705. if (isset($tag['attribute']['name']) AND !TCPDF_STATIC::empty_string($tag['attribute']['name'])) {
  18706. $name = $tag['attribute']['name'];
  18707. } else {
  18708. break;
  18709. }
  18710. if (isset($tag['attribute']['value']) AND !TCPDF_STATIC::empty_string($tag['attribute']['value'])) {
  18711. $opt['v'] = $tag['attribute']['value'];
  18712. }
  18713. if (isset($tag['attribute']['cols']) AND !TCPDF_STATIC::empty_string($tag['attribute']['cols'])) {
  18714. $w = intval($tag['attribute']['cols']) * $this->GetStringWidth(chr(32)) * 2;
  18715. } else {
  18716. $w = 40;
  18717. }
  18718. if (isset($tag['attribute']['rows']) AND !TCPDF_STATIC::empty_string($tag['attribute']['rows'])) {
  18719. $h = intval($tag['attribute']['rows']) * $this->getCellHeight($this->FontSize);
  18720. } else {
  18721. $h = 10;
  18722. }
  18723. $prop['multiline'] = 'true';
  18724. $this->TextField($name, $w, $h, $prop, $opt, '', '', false);
  18725. break;
  18726. }
  18727. case 'select': {
  18728. $h = $this->getCellHeight($this->FontSize);
  18729. if (isset($tag['attribute']['size']) AND !TCPDF_STATIC::empty_string($tag['attribute']['size'])) {
  18730. $h *= ($tag['attribute']['size'] + 1);
  18731. }
  18732. $prop = array();
  18733. $opt = array();
  18734. if (isset($tag['attribute']['name']) AND !TCPDF_STATIC::empty_string($tag['attribute']['name'])) {
  18735. $name = $tag['attribute']['name'];
  18736. } else {
  18737. break;
  18738. }
  18739. $w = 0;
  18740. if (isset($tag['attribute']['opt']) AND !TCPDF_STATIC::empty_string($tag['attribute']['opt'])) {
  18741. $options = explode('#!NwL!#', $tag['attribute']['opt']);
  18742. $values = array();
  18743. foreach ($options as $val) {
  18744. if (strpos($val, '#!TaB!#') !== false) {
  18745. $opts = explode('#!TaB!#', $val);
  18746. $values[] = $opts;
  18747. $w = max($w, $this->GetStringWidth($opts[1]));
  18748. } else {
  18749. $values[] = $val;
  18750. $w = max($w, $this->GetStringWidth($val));
  18751. }
  18752. }
  18753. } else {
  18754. break;
  18755. }
  18756. $w *= 2;
  18757. if (isset($tag['attribute']['multiple']) AND ($tag['attribute']['multiple']='multiple')) {
  18758. $prop['multipleSelection'] = 'true';
  18759. $this->ListBox($name, $w, $h, $values, $prop, $opt, '', '', false);
  18760. } else {
  18761. $this->ComboBox($name, $w, $h, $values, $prop, $opt, '', '', false);
  18762. }
  18763. break;
  18764. }
  18765. case 'tcpdf': {
  18766. if (defined('K_TCPDF_CALLS_IN_HTML') AND (K_TCPDF_CALLS_IN_HTML === true)) {
  18767. // Special tag used to call TCPDF methods
  18768. if (isset($tag['attribute']['method'])) {
  18769. $tcpdf_method = $tag['attribute']['method'];
  18770. if (method_exists($this, $tcpdf_method)) {
  18771. if (isset($tag['attribute']['params']) AND (!empty($tag['attribute']['params']))) {
  18772. $params = $this->unserializeTCPDFtagParameters($tag['attribute']['params']);
  18773. call_user_func_array(array($this, $tcpdf_method), $params);
  18774. } else {
  18775. $this->$tcpdf_method();
  18776. }
  18777. $this->newline = true;
  18778. }
  18779. }
  18780. }
  18781. break;
  18782. }
  18783. default: {
  18784. break;
  18785. }
  18786. }
  18787. // define tags that support borders and background colors
  18788. $bordertags = array('blockquote','br','dd','dl','div','dt','h1','h2','h3','h4','h5','h6','hr','li','ol','p','pre','ul','tcpdf','table');
  18789. if (in_array($tag['value'], $bordertags)) {
  18790. // set border
  18791. $dom[$key]['borderposition'] = $this->getBorderStartPosition();
  18792. }
  18793. if ($dom[$key]['self'] AND isset($dom[$key]['attribute']['pagebreakafter'])) {
  18794. $pba = $dom[$key]['attribute']['pagebreakafter'];
  18795. // check for pagebreak
  18796. if (($pba == 'true') OR ($pba == 'left') OR ($pba == 'right')) {
  18797. // add a page (or trig AcceptPageBreak() for multicolumn mode)
  18798. $this->checkPageBreak($this->PageBreakTrigger + 1);
  18799. }
  18800. if ((($pba == 'left') AND (((!$this->rtl) AND (($this->page % 2) == 0)) OR (($this->rtl) AND (($this->page % 2) != 0))))
  18801. OR (($pba == 'right') AND (((!$this->rtl) AND (($this->page % 2) != 0)) OR (($this->rtl) AND (($this->page % 2) == 0))))) {
  18802. // add a page (or trig AcceptPageBreak() for multicolumn mode)
  18803. $this->checkPageBreak($this->PageBreakTrigger + 1);
  18804. }
  18805. }
  18806. return $dom;
  18807. }
  18808. /**
  18809. * Process closing tags.
  18810. * @param $dom (array) html dom array
  18811. * @param $key (int) current element id
  18812. * @param $cell (boolean) if true add the default left (or right if RTL) padding to each new line (default false).
  18813. * @param $maxbottomliney (int) maximum y value of current line
  18814. * @return $dom array
  18815. * @protected
  18816. */
  18817. protected function closeHTMLTagHandler($dom, $key, $cell, $maxbottomliney=0) {
  18818. $tag = $dom[$key];
  18819. $parent = $dom[($dom[$key]['parent'])];
  18820. $lasttag = ((!isset($dom[($key + 1)])) OR ((!isset($dom[($key + 2)])) AND ($dom[($key + 1)]['value'] == 'marker')));
  18821. $in_table_head = false;
  18822. // maximum x position (used to draw borders)
  18823. if ($this->rtl) {
  18824. $xmax = $this->w;
  18825. } else {
  18826. $xmax = 0;
  18827. }
  18828. if ($tag['block']) {
  18829. $hbz = 0; // distance from y to line bottom
  18830. $hb = 0; // vertical space between block tags
  18831. // calculate vertical space for block tags
  18832. if (isset($this->tagvspaces[$tag['value']][1]['h']) && !empty($this->tagvspaces[$tag['value']][1]['h']) && ($this->tagvspaces[$tag['value']][1]['h'] >= 0)) {
  18833. $pre_h = $this->tagvspaces[$tag['value']][1]['h'];
  18834. } elseif (isset($parent['fontsize'])) {
  18835. $pre_h = $this->getCellHeight($parent['fontsize'] / $this->k);
  18836. } else {
  18837. $pre_h = $this->getCellHeight($this->FontSize);
  18838. }
  18839. if (isset($this->tagvspaces[$tag['value']][1]['n'])) {
  18840. $cn = $this->tagvspaces[$tag['value']][1]['n'];
  18841. } elseif (preg_match('/[h][0-9]/', $tag['value']) > 0) {
  18842. $cn = 0.6;
  18843. } else {
  18844. $cn = 1;
  18845. }
  18846. if ((!isset($this->tagvspaces[$tag['value']])) AND ($tag['value'] == 'div')) {
  18847. $hb = 0;
  18848. } else {
  18849. $hb = ($cn * $pre_h);
  18850. }
  18851. if ($maxbottomliney > $this->PageBreakTrigger) {
  18852. $hbz = $this->getCellHeight($this->FontSize);
  18853. } elseif ($this->y < $maxbottomliney) {
  18854. $hbz = ($maxbottomliney - $this->y);
  18855. }
  18856. }
  18857. // Closing tag
  18858. switch($tag['value']) {
  18859. case 'tr': {
  18860. $table_el = $dom[($dom[$key]['parent'])]['parent'];
  18861. if (!isset($parent['endy'])) {
  18862. $dom[($dom[$key]['parent'])]['endy'] = $this->y;
  18863. $parent['endy'] = $this->y;
  18864. }
  18865. if (!isset($parent['endpage'])) {
  18866. $dom[($dom[$key]['parent'])]['endpage'] = $this->page;
  18867. $parent['endpage'] = $this->page;
  18868. }
  18869. if (!isset($parent['endcolumn'])) {
  18870. $dom[($dom[$key]['parent'])]['endcolumn'] = $this->current_column;
  18871. $parent['endcolumn'] = $this->current_column;
  18872. }
  18873. // update row-spanned cells
  18874. if (isset($dom[$table_el]['rowspans'])) {
  18875. foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
  18876. $dom[$table_el]['rowspans'][$k]['rowspan'] -= 1;
  18877. if ($dom[$table_el]['rowspans'][$k]['rowspan'] == 0) {
  18878. if (($dom[$table_el]['rowspans'][$k]['endpage'] == $parent['endpage']) AND ($dom[$table_el]['rowspans'][$k]['endcolumn'] == $parent['endcolumn'])) {
  18879. $dom[($dom[$key]['parent'])]['endy'] = max($dom[$table_el]['rowspans'][$k]['endy'], $parent['endy']);
  18880. } elseif (($dom[$table_el]['rowspans'][$k]['endpage'] > $parent['endpage']) OR ($dom[$table_el]['rowspans'][$k]['endcolumn'] > $parent['endcolumn'])) {
  18881. $dom[($dom[$key]['parent'])]['endy'] = $dom[$table_el]['rowspans'][$k]['endy'];
  18882. $dom[($dom[$key]['parent'])]['endpage'] = $dom[$table_el]['rowspans'][$k]['endpage'];
  18883. $dom[($dom[$key]['parent'])]['endcolumn'] = $dom[$table_el]['rowspans'][$k]['endcolumn'];
  18884. }
  18885. }
  18886. }
  18887. // report new endy and endpage to the rowspanned cells
  18888. foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
  18889. if ($dom[$table_el]['rowspans'][$k]['rowspan'] == 0) {
  18890. $dom[$table_el]['rowspans'][$k]['endpage'] = max($dom[$table_el]['rowspans'][$k]['endpage'], $dom[($dom[$key]['parent'])]['endpage']);
  18891. $dom[($dom[$key]['parent'])]['endpage'] = $dom[$table_el]['rowspans'][$k]['endpage'];
  18892. $dom[$table_el]['rowspans'][$k]['endcolumn'] = max($dom[$table_el]['rowspans'][$k]['endcolumn'], $dom[($dom[$key]['parent'])]['endcolumn']);
  18893. $dom[($dom[$key]['parent'])]['endcolumn'] = $dom[$table_el]['rowspans'][$k]['endcolumn'];
  18894. $dom[$table_el]['rowspans'][$k]['endy'] = max($dom[$table_el]['rowspans'][$k]['endy'], $dom[($dom[$key]['parent'])]['endy']);
  18895. $dom[($dom[$key]['parent'])]['endy'] = $dom[$table_el]['rowspans'][$k]['endy'];
  18896. }
  18897. }
  18898. // update remaining rowspanned cells
  18899. foreach ($dom[$table_el]['rowspans'] as $k => $trwsp) {
  18900. if ($dom[$table_el]['rowspans'][$k]['rowspan'] == 0) {
  18901. $dom[$table_el]['rowspans'][$k]['endpage'] = $dom[($dom[$key]['parent'])]['endpage'];
  18902. $dom[$table_el]['rowspans'][$k]['endcolumn'] = $dom[($dom[$key]['parent'])]['endcolumn'];
  18903. $dom[$table_el]['rowspans'][$k]['endy'] = $dom[($dom[$key]['parent'])]['endy'];
  18904. }
  18905. }
  18906. }
  18907. $prev_page = $this->page;
  18908. $this->setPage($dom[($dom[$key]['parent'])]['endpage']);
  18909. if ($this->num_columns > 1) {
  18910. if (($prev_page < $this->page)
  18911. AND ((($this->current_column == 0) AND ($dom[($dom[$key]['parent'])]['endcolumn'] == ($this->num_columns - 1)))
  18912. OR ($this->current_column == $dom[($dom[$key]['parent'])]['endcolumn']))) {
  18913. // page jump
  18914. $this->selectColumn(0);
  18915. $dom[($dom[$key]['parent'])]['endcolumn'] = 0;
  18916. $dom[($dom[$key]['parent'])]['endy'] = $this->y;
  18917. } else {
  18918. $this->selectColumn($dom[($dom[$key]['parent'])]['endcolumn']);
  18919. $this->y = $dom[($dom[$key]['parent'])]['endy'];
  18920. }
  18921. } else {
  18922. $this->y = $dom[($dom[$key]['parent'])]['endy'];
  18923. }
  18924. if (isset($dom[$table_el]['attribute']['cellspacing'])) {
  18925. $this->y += $this->getHTMLUnitToUnits($dom[$table_el]['attribute']['cellspacing'], 1, 'px');
  18926. } elseif (isset($dom[$table_el]['border-spacing'])) {
  18927. $this->y += $dom[$table_el]['border-spacing']['V'];
  18928. }
  18929. $this->Ln(0, $cell);
  18930. if ($this->current_column == $parent['startcolumn']) {
  18931. $this->x = $parent['startx'];
  18932. }
  18933. // account for booklet mode
  18934. if ($this->page > $parent['startpage']) {
  18935. if (($this->rtl) AND ($this->pagedim[$this->page]['orm'] != $this->pagedim[$parent['startpage']]['orm'])) {
  18936. $this->x -= ($this->pagedim[$this->page]['orm'] - $this->pagedim[$parent['startpage']]['orm']);
  18937. } elseif ((!$this->rtl) AND ($this->pagedim[$this->page]['olm'] != $this->pagedim[$parent['startpage']]['olm'])) {
  18938. $this->x += ($this->pagedim[$this->page]['olm'] - $this->pagedim[$parent['startpage']]['olm']);
  18939. }
  18940. }
  18941. break;
  18942. }
  18943. case 'tablehead':
  18944. // closing tag used for the thead part
  18945. $in_table_head = true;
  18946. $this->inthead = false;
  18947. case 'table': {
  18948. $table_el = $parent;
  18949. // set default border
  18950. if (isset($table_el['attribute']['border']) AND ($table_el['attribute']['border'] > 0)) {
  18951. // set default border
  18952. $border = array('LTRB' => array('width' => $this->getCSSBorderWidth($table_el['attribute']['border']), 'cap'=>'square', 'join'=>'miter', 'dash'=> 0, 'color'=>array(0,0,0)));
  18953. } else {
  18954. $border = 0;
  18955. }
  18956. $default_border = $border;
  18957. // fix bottom line alignment of last line before page break
  18958. foreach ($dom[($dom[$key]['parent'])]['trids'] as $j => $trkey) {
  18959. // update row-spanned cells
  18960. if (isset($dom[($dom[$key]['parent'])]['rowspans'])) {
  18961. foreach ($dom[($dom[$key]['parent'])]['rowspans'] as $k => $trwsp) {
  18962. if (isset($prevtrkey) AND ($trwsp['trid'] == $prevtrkey) AND ($trwsp['mrowspan'] > 0)) {
  18963. $dom[($dom[$key]['parent'])]['rowspans'][$k]['trid'] = $trkey;
  18964. }
  18965. if ($dom[($dom[$key]['parent'])]['rowspans'][$k]['trid'] == $trkey) {
  18966. $dom[($dom[$key]['parent'])]['rowspans'][$k]['mrowspan'] -= 1;
  18967. }
  18968. }
  18969. }
  18970. if (isset($prevtrkey) AND ($dom[$trkey]['startpage'] > $dom[$prevtrkey]['endpage'])) {
  18971. $pgendy = $this->pagedim[$dom[$prevtrkey]['endpage']]['hk'] - $this->pagedim[$dom[$prevtrkey]['endpage']]['bm'];
  18972. $dom[$prevtrkey]['endy'] = $pgendy;
  18973. // update row-spanned cells
  18974. if (isset($dom[($dom[$key]['parent'])]['rowspans'])) {
  18975. foreach ($dom[($dom[$key]['parent'])]['rowspans'] as $k => $trwsp) {
  18976. if (($trwsp['trid'] == $prevtrkey) AND ($trwsp['mrowspan'] >= 0) AND ($trwsp['endpage'] == $dom[$prevtrkey]['endpage'])) {
  18977. $dom[($dom[$key]['parent'])]['rowspans'][$k]['endy'] = $pgendy;
  18978. $dom[($dom[$key]['parent'])]['rowspans'][$k]['mrowspan'] = -1;
  18979. }
  18980. }
  18981. }
  18982. }
  18983. $prevtrkey = $trkey;
  18984. $table_el = $dom[($dom[$key]['parent'])];
  18985. }
  18986. // for each row
  18987. if (count($table_el['trids']) > 0) {
  18988. unset($xmax);
  18989. }
  18990. foreach ($table_el['trids'] as $j => $trkey) {
  18991. $parent = $dom[$trkey];
  18992. if (!isset($xmax)) {
  18993. $xmax = $parent['cellpos'][(count($parent['cellpos']) - 1)]['endx'];
  18994. }
  18995. // for each cell on the row
  18996. foreach ($parent['cellpos'] as $k => $cellpos) {
  18997. if (isset($cellpos['rowspanid']) AND ($cellpos['rowspanid'] >= 0)) {
  18998. $cellpos['startx'] = $table_el['rowspans'][($cellpos['rowspanid'])]['startx'];
  18999. $cellpos['endx'] = $table_el['rowspans'][($cellpos['rowspanid'])]['endx'];
  19000. $endy = $table_el['rowspans'][($cellpos['rowspanid'])]['endy'];
  19001. $startpage = $table_el['rowspans'][($cellpos['rowspanid'])]['startpage'];
  19002. $endpage = $table_el['rowspans'][($cellpos['rowspanid'])]['endpage'];
  19003. $startcolumn = $table_el['rowspans'][($cellpos['rowspanid'])]['startcolumn'];
  19004. $endcolumn = $table_el['rowspans'][($cellpos['rowspanid'])]['endcolumn'];
  19005. } else {
  19006. $endy = $parent['endy'];
  19007. $startpage = $parent['startpage'];
  19008. $endpage = $parent['endpage'];
  19009. $startcolumn = $parent['startcolumn'];
  19010. $endcolumn = $parent['endcolumn'];
  19011. }
  19012. if ($this->num_columns == 0) {
  19013. $this->num_columns = 1;
  19014. }
  19015. if (isset($cellpos['border'])) {
  19016. $border = $cellpos['border'];
  19017. }
  19018. if (isset($cellpos['bgcolor']) AND ($cellpos['bgcolor']) !== false) {
  19019. $this->SetFillColorArray($cellpos['bgcolor']);
  19020. $fill = true;
  19021. } else {
  19022. $fill = false;
  19023. }
  19024. $x = $cellpos['startx'];
  19025. $y = $parent['starty'];
  19026. $starty = $y;
  19027. $w = abs($cellpos['endx'] - $cellpos['startx']);
  19028. // get border modes
  19029. $border_start = TCPDF_STATIC::getBorderMode($border, $position='start', $this->opencell);
  19030. $border_end = TCPDF_STATIC::getBorderMode($border, $position='end', $this->opencell);
  19031. $border_middle = TCPDF_STATIC::getBorderMode($border, $position='middle', $this->opencell);
  19032. // design borders around HTML cells.
  19033. for ($page = $startpage; $page <= $endpage; ++$page) { // for each page
  19034. $ccode = '';
  19035. $this->setPage($page);
  19036. if ($this->num_columns < 2) {
  19037. // single-column mode
  19038. $this->x = $x;
  19039. $this->y = $this->tMargin;
  19040. }
  19041. // account for margin changes
  19042. if ($page > $startpage) {
  19043. if (($this->rtl) AND ($this->pagedim[$page]['orm'] != $this->pagedim[$startpage]['orm'])) {
  19044. $this->x -= ($this->pagedim[$page]['orm'] - $this->pagedim[$startpage]['orm']);
  19045. } elseif ((!$this->rtl) AND ($this->pagedim[$page]['olm'] != $this->pagedim[$startpage]['olm'])) {
  19046. $this->x += ($this->pagedim[$page]['olm'] - $this->pagedim[$startpage]['olm']);
  19047. }
  19048. }
  19049. if ($startpage == $endpage) { // single page
  19050. $deltacol = 0;
  19051. $deltath = 0;
  19052. for ($column = $startcolumn; $column <= $endcolumn; ++$column) { // for each column
  19053. $this->selectColumn($column);
  19054. if ($startcolumn == $endcolumn) { // single column
  19055. $cborder = $border;
  19056. $h = $endy - $parent['starty'];
  19057. $this->y = $y;
  19058. $this->x = $x;
  19059. } elseif ($column == $startcolumn) { // first column
  19060. $cborder = $border_start;
  19061. $this->y = $starty;
  19062. $this->x = $x;
  19063. $h = $this->h - $this->y - $this->bMargin;
  19064. if ($this->rtl) {
  19065. $deltacol = $this->x + $this->rMargin - $this->w;
  19066. } else {
  19067. $deltacol = $this->x - $this->lMargin;
  19068. }
  19069. } elseif ($column == $endcolumn) { // end column
  19070. $cborder = $border_end;
  19071. if (isset($this->columns[$column]['th']['\''.$page.'\''])) {
  19072. $this->y = $this->columns[$column]['th']['\''.$page.'\''];
  19073. }
  19074. $this->x += $deltacol;
  19075. $h = $endy - $this->y;
  19076. } else { // middle column
  19077. $cborder = $border_middle;
  19078. if (isset($this->columns[$column]['th']['\''.$page.'\''])) {
  19079. $this->y = $this->columns[$column]['th']['\''.$page.'\''];
  19080. }
  19081. $this->x += $deltacol;
  19082. $h = $this->h - $this->y - $this->bMargin;
  19083. }
  19084. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  19085. } // end for each column
  19086. } elseif ($page == $startpage) { // first page
  19087. $deltacol = 0;
  19088. $deltath = 0;
  19089. for ($column = $startcolumn; $column < $this->num_columns; ++$column) { // for each column
  19090. $this->selectColumn($column);
  19091. if ($column == $startcolumn) { // first column
  19092. $cborder = $border_start;
  19093. $this->y = $starty;
  19094. $this->x = $x;
  19095. $h = $this->h - $this->y - $this->bMargin;
  19096. if ($this->rtl) {
  19097. $deltacol = $this->x + $this->rMargin - $this->w;
  19098. } else {
  19099. $deltacol = $this->x - $this->lMargin;
  19100. }
  19101. } else { // middle column
  19102. $cborder = $border_middle;
  19103. if (isset($this->columns[$column]['th']['\''.$page.'\''])) {
  19104. $this->y = $this->columns[$column]['th']['\''.$page.'\''];
  19105. }
  19106. $this->x += $deltacol;
  19107. $h = $this->h - $this->y - $this->bMargin;
  19108. }
  19109. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  19110. } // end for each column
  19111. } elseif ($page == $endpage) { // last page
  19112. $deltacol = 0;
  19113. $deltath = 0;
  19114. for ($column = 0; $column <= $endcolumn; ++$column) { // for each column
  19115. $this->selectColumn($column);
  19116. if ($column == $endcolumn) { // end column
  19117. $cborder = $border_end;
  19118. if (isset($this->columns[$column]['th']['\''.$page.'\''])) {
  19119. $this->y = $this->columns[$column]['th']['\''.$page.'\''];
  19120. }
  19121. $this->x += $deltacol;
  19122. $h = $endy - $this->y;
  19123. } else { // middle column
  19124. $cborder = $border_middle;
  19125. if (isset($this->columns[$column]['th']['\''.$page.'\''])) {
  19126. $this->y = $this->columns[$column]['th']['\''.$page.'\''];
  19127. }
  19128. $this->x += $deltacol;
  19129. $h = $this->h - $this->y - $this->bMargin;
  19130. }
  19131. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  19132. } // end for each column
  19133. } else { // middle page
  19134. $deltacol = 0;
  19135. $deltath = 0;
  19136. for ($column = 0; $column < $this->num_columns; ++$column) { // for each column
  19137. $this->selectColumn($column);
  19138. $cborder = $border_middle;
  19139. if (isset($this->columns[$column]['th']['\''.$page.'\''])) {
  19140. $this->y = $this->columns[$column]['th']['\''.$page.'\''];
  19141. }
  19142. $this->x += $deltacol;
  19143. $h = $this->h - $this->y - $this->bMargin;
  19144. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  19145. } // end for each column
  19146. }
  19147. if (!empty($cborder) OR !empty($fill)) {
  19148. $offsetlen = strlen($ccode);
  19149. // draw border and fill
  19150. if ($this->inxobj) {
  19151. // we are inside an XObject template
  19152. if (end($this->xobjects[$this->xobjid]['transfmrk']) !== false) {
  19153. $pagemarkkey = key($this->xobjects[$this->xobjid]['transfmrk']);
  19154. $pagemark = $this->xobjects[$this->xobjid]['transfmrk'][$pagemarkkey];
  19155. $this->xobjects[$this->xobjid]['transfmrk'][$pagemarkkey] += $offsetlen;
  19156. } else {
  19157. $pagemark = $this->xobjects[$this->xobjid]['intmrk'];
  19158. $this->xobjects[$this->xobjid]['intmrk'] += $offsetlen;
  19159. }
  19160. $pagebuff = $this->xobjects[$this->xobjid]['outdata'];
  19161. $pstart = substr($pagebuff, 0, $pagemark);
  19162. $pend = substr($pagebuff, $pagemark);
  19163. $this->xobjects[$this->xobjid]['outdata'] = $pstart.$ccode.$pend;
  19164. } else {
  19165. // draw border and fill
  19166. if (end($this->transfmrk[$this->page]) !== false) {
  19167. $pagemarkkey = key($this->transfmrk[$this->page]);
  19168. $pagemark = $this->transfmrk[$this->page][$pagemarkkey];
  19169. } elseif ($this->InFooter) {
  19170. $pagemark = $this->footerpos[$this->page];
  19171. } else {
  19172. $pagemark = $this->intmrk[$this->page];
  19173. }
  19174. $pagebuff = $this->getPageBuffer($this->page);
  19175. $pstart = substr($pagebuff, 0, $pagemark);
  19176. $pend = substr($pagebuff, $pagemark);
  19177. $this->setPageBuffer($this->page, $pstart.$ccode.$pend);
  19178. }
  19179. }
  19180. } // end for each page
  19181. // restore default border
  19182. $border = $default_border;
  19183. } // end for each cell on the row
  19184. if (isset($table_el['attribute']['cellspacing'])) {
  19185. $this->y += $this->getHTMLUnitToUnits($table_el['attribute']['cellspacing'], 1, 'px');
  19186. } elseif (isset($table_el['border-spacing'])) {
  19187. $this->y += $table_el['border-spacing']['V'];
  19188. }
  19189. $this->Ln(0, $cell);
  19190. $this->x = $parent['startx'];
  19191. if ($endpage > $startpage) {
  19192. if (($this->rtl) AND ($this->pagedim[$endpage]['orm'] != $this->pagedim[$startpage]['orm'])) {
  19193. $this->x += ($this->pagedim[$endpage]['orm'] - $this->pagedim[$startpage]['orm']);
  19194. } elseif ((!$this->rtl) AND ($this->pagedim[$endpage]['olm'] != $this->pagedim[$startpage]['olm'])) {
  19195. $this->x += ($this->pagedim[$endpage]['olm'] - $this->pagedim[$startpage]['olm']);
  19196. }
  19197. }
  19198. }
  19199. if (!$in_table_head) { // we are not inside a thead section
  19200. $this->cell_padding = $table_el['old_cell_padding'];
  19201. // reset row height
  19202. $this->resetLastH();
  19203. if (($this->page == ($this->numpages - 1)) AND ($this->pageopen[$this->numpages])) {
  19204. $plendiff = ($this->pagelen[$this->numpages] - $this->emptypagemrk[$this->numpages]);
  19205. if (($plendiff > 0) AND ($plendiff < 60)) {
  19206. $pagediff = substr($this->getPageBuffer($this->numpages), $this->emptypagemrk[$this->numpages], $plendiff);
  19207. if (substr($pagediff, 0, 5) == 'BT /F') {
  19208. // the difference is only a font setting
  19209. $plendiff = 0;
  19210. }
  19211. }
  19212. if ($plendiff == 0) {
  19213. // remove last blank page
  19214. $this->deletePage($this->numpages);
  19215. }
  19216. }
  19217. if (isset($this->theadMargins['top'])) {
  19218. // restore top margin
  19219. $this->tMargin = $this->theadMargins['top'];
  19220. }
  19221. if (!isset($table_el['attribute']['nested']) OR ($table_el['attribute']['nested'] != 'true')) {
  19222. // reset main table header
  19223. $this->thead = '';
  19224. $this->theadMargins = array();
  19225. $this->pagedim[$this->page]['tm'] = $this->tMargin;
  19226. }
  19227. }
  19228. $parent = $table_el;
  19229. break;
  19230. }
  19231. case 'a': {
  19232. $this->HREF = array();
  19233. break;
  19234. }
  19235. case 'sup': {
  19236. $this->SetXY($this->GetX(), $this->GetY() + ((0.7 * $parent['fontsize']) / $this->k));
  19237. break;
  19238. }
  19239. case 'sub': {
  19240. $this->SetXY($this->GetX(), $this->GetY() - ((0.3 * $parent['fontsize']) / $this->k));
  19241. break;
  19242. }
  19243. case 'div': {
  19244. $this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
  19245. break;
  19246. }
  19247. case 'blockquote': {
  19248. if ($this->rtl) {
  19249. $this->rMargin -= $this->listindent;
  19250. } else {
  19251. $this->lMargin -= $this->listindent;
  19252. }
  19253. --$this->listindentlevel;
  19254. $this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
  19255. break;
  19256. }
  19257. case 'p': {
  19258. $this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
  19259. break;
  19260. }
  19261. case 'pre': {
  19262. $this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
  19263. $this->premode = false;
  19264. break;
  19265. }
  19266. case 'dl': {
  19267. --$this->listnum;
  19268. if ($this->listnum <= 0) {
  19269. $this->listnum = 0;
  19270. $this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
  19271. } else {
  19272. $this->addHTMLVertSpace(0, 0, $cell, false, $lasttag);
  19273. }
  19274. $this->resetLastH();
  19275. break;
  19276. }
  19277. case 'dt': {
  19278. $this->lispacer = '';
  19279. $this->addHTMLVertSpace(0, 0, $cell, false, $lasttag);
  19280. break;
  19281. }
  19282. case 'dd': {
  19283. $this->lispacer = '';
  19284. if ($this->rtl) {
  19285. $this->rMargin -= $this->listindent;
  19286. } else {
  19287. $this->lMargin -= $this->listindent;
  19288. }
  19289. --$this->listindentlevel;
  19290. $this->addHTMLVertSpace(0, 0, $cell, false, $lasttag);
  19291. break;
  19292. }
  19293. case 'ul':
  19294. case 'ol': {
  19295. --$this->listnum;
  19296. $this->lispacer = '';
  19297. if ($this->rtl) {
  19298. $this->rMargin -= $this->listindent;
  19299. } else {
  19300. $this->lMargin -= $this->listindent;
  19301. }
  19302. --$this->listindentlevel;
  19303. if ($this->listnum <= 0) {
  19304. $this->listnum = 0;
  19305. $this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
  19306. } else {
  19307. $this->addHTMLVertSpace(0, 0, $cell, false, $lasttag);
  19308. }
  19309. $this->resetLastH();
  19310. break;
  19311. }
  19312. case 'li': {
  19313. $this->lispacer = '';
  19314. $this->addHTMLVertSpace(0, 0, $cell, false, $lasttag);
  19315. break;
  19316. }
  19317. case 'h1':
  19318. case 'h2':
  19319. case 'h3':
  19320. case 'h4':
  19321. case 'h5':
  19322. case 'h6': {
  19323. $this->addHTMLVertSpace($hbz, $hb, $cell, false, $lasttag);
  19324. break;
  19325. }
  19326. // Form fields (since 4.8.000 - 2009-09-07)
  19327. case 'form': {
  19328. $this->form_action = '';
  19329. $this->form_enctype = 'application/x-www-form-urlencoded';
  19330. break;
  19331. }
  19332. default : {
  19333. break;
  19334. }
  19335. }
  19336. // draw border and background (if any)
  19337. $this->drawHTMLTagBorder($parent, $xmax);
  19338. if (isset($dom[($dom[$key]['parent'])]['attribute']['pagebreakafter'])) {
  19339. $pba = $dom[($dom[$key]['parent'])]['attribute']['pagebreakafter'];
  19340. // check for pagebreak
  19341. if (($pba == 'true') OR ($pba == 'left') OR ($pba == 'right')) {
  19342. // add a page (or trig AcceptPageBreak() for multicolumn mode)
  19343. $this->checkPageBreak($this->PageBreakTrigger + 1);
  19344. }
  19345. if ((($pba == 'left') AND (((!$this->rtl) AND (($this->page % 2) == 0)) OR (($this->rtl) AND (($this->page % 2) != 0))))
  19346. OR (($pba == 'right') AND (((!$this->rtl) AND (($this->page % 2) != 0)) OR (($this->rtl) AND (($this->page % 2) == 0))))) {
  19347. // add a page (or trig AcceptPageBreak() for multicolumn mode)
  19348. $this->checkPageBreak($this->PageBreakTrigger + 1);
  19349. }
  19350. }
  19351. $this->tmprtl = false;
  19352. return $dom;
  19353. }
  19354. /**
  19355. * Add vertical spaces if needed.
  19356. * @param $hbz (string) Distance between current y and line bottom.
  19357. * @param $hb (string) The height of the break.
  19358. * @param $cell (boolean) if true add the default left (or right if RTL) padding to each new line (default false).
  19359. * @param $firsttag (boolean) set to true when the tag is the first.
  19360. * @param $lasttag (boolean) set to true when the tag is the last.
  19361. * @protected
  19362. */
  19363. protected function addHTMLVertSpace($hbz=0, $hb=0, $cell=false, $firsttag=false, $lasttag=false) {
  19364. if ($firsttag) {
  19365. $this->Ln(0, $cell);
  19366. $this->htmlvspace = 0;
  19367. return;
  19368. }
  19369. if ($lasttag) {
  19370. $this->Ln($hbz, $cell);
  19371. $this->htmlvspace = 0;
  19372. return;
  19373. }
  19374. if ($hb < $this->htmlvspace) {
  19375. $hd = 0;
  19376. } else {
  19377. $hd = $hb - $this->htmlvspace;
  19378. $this->htmlvspace = $hb;
  19379. }
  19380. $this->Ln(($hbz + $hd), $cell);
  19381. }
  19382. /**
  19383. * Return the starting coordinates to draw an html border
  19384. * @return array containing top-left border coordinates
  19385. * @protected
  19386. * @since 5.7.000 (2010-08-03)
  19387. */
  19388. protected function getBorderStartPosition() {
  19389. if ($this->rtl) {
  19390. $xmax = $this->lMargin;
  19391. } else {
  19392. $xmax = $this->w - $this->rMargin;
  19393. }
  19394. return array('page' => $this->page, 'column' => $this->current_column, 'x' => $this->x, 'y' => $this->y, 'xmax' => $xmax);
  19395. }
  19396. /**
  19397. * Draw an HTML block border and fill
  19398. * @param $tag (array) array of tag properties.
  19399. * @param $xmax (int) end X coordinate for border.
  19400. * @protected
  19401. * @since 5.7.000 (2010-08-03)
  19402. */
  19403. protected function drawHTMLTagBorder($tag, $xmax) {
  19404. if (!isset($tag['borderposition'])) {
  19405. // nothing to draw
  19406. return;
  19407. }
  19408. $prev_x = $this->x;
  19409. $prev_y = $this->y;
  19410. $prev_lasth = $this->lasth;
  19411. $border = 0;
  19412. $fill = false;
  19413. $this->lasth = 0;
  19414. if (isset($tag['border']) AND !empty($tag['border'])) {
  19415. // get border style
  19416. $border = $tag['border'];
  19417. if (!TCPDF_STATIC::empty_string($this->thead) AND (!$this->inthead)) {
  19418. // border for table header
  19419. $border = TCPDF_STATIC::getBorderMode($border, $position='middle', $this->opencell);
  19420. }
  19421. }
  19422. if (isset($tag['bgcolor']) AND ($tag['bgcolor'] !== false)) {
  19423. // get background color
  19424. $old_bgcolor = $this->bgcolor;
  19425. $this->SetFillColorArray($tag['bgcolor']);
  19426. $fill = true;
  19427. }
  19428. if (!$border AND !$fill) {
  19429. // nothing to draw
  19430. return;
  19431. }
  19432. if (isset($tag['attribute']['cellspacing'])) {
  19433. $clsp = $this->getHTMLUnitToUnits($tag['attribute']['cellspacing'], 1, 'px');
  19434. $cellspacing = array('H' => $clsp, 'V' => $clsp);
  19435. } elseif (isset($tag['border-spacing'])) {
  19436. $cellspacing = $tag['border-spacing'];
  19437. } else {
  19438. $cellspacing = array('H' => 0, 'V' => 0);
  19439. }
  19440. if (($tag['value'] != 'table') AND (is_array($border)) AND (!empty($border))) {
  19441. // draw the border externally respect the sqare edge.
  19442. $border['mode'] = 'ext';
  19443. }
  19444. if ($this->rtl) {
  19445. if ($xmax >= $tag['borderposition']['x']) {
  19446. $xmax = $tag['borderposition']['xmax'];
  19447. }
  19448. $w = ($tag['borderposition']['x'] - $xmax);
  19449. } else {
  19450. if ($xmax <= $tag['borderposition']['x']) {
  19451. $xmax = $tag['borderposition']['xmax'];
  19452. }
  19453. $w = ($xmax - $tag['borderposition']['x']);
  19454. }
  19455. if ($w <= 0) {
  19456. return;
  19457. }
  19458. $w += $cellspacing['H'];
  19459. $startpage = $tag['borderposition']['page'];
  19460. $startcolumn = $tag['borderposition']['column'];
  19461. $x = $tag['borderposition']['x'];
  19462. $y = $tag['borderposition']['y'];
  19463. $endpage = $this->page;
  19464. $starty = $tag['borderposition']['y'] - $cellspacing['V'];
  19465. $currentY = $this->y;
  19466. $this->x = $x;
  19467. // get latest column
  19468. $endcolumn = $this->current_column;
  19469. if ($this->num_columns == 0) {
  19470. $this->num_columns = 1;
  19471. }
  19472. // get border modes
  19473. $border_start = TCPDF_STATIC::getBorderMode($border, $position='start', $this->opencell);
  19474. $border_end = TCPDF_STATIC::getBorderMode($border, $position='end', $this->opencell);
  19475. $border_middle = TCPDF_STATIC::getBorderMode($border, $position='middle', $this->opencell);
  19476. // temporary disable page regions
  19477. $temp_page_regions = $this->page_regions;
  19478. $this->page_regions = array();
  19479. // design borders around HTML cells.
  19480. for ($page = $startpage; $page <= $endpage; ++$page) { // for each page
  19481. $ccode = '';
  19482. $this->setPage($page);
  19483. if ($this->num_columns < 2) {
  19484. // single-column mode
  19485. $this->x = $x;
  19486. $this->y = $this->tMargin;
  19487. }
  19488. // account for margin changes
  19489. if ($page > $startpage) {
  19490. if (($this->rtl) AND ($this->pagedim[$page]['orm'] != $this->pagedim[$startpage]['orm'])) {
  19491. $this->x -= ($this->pagedim[$page]['orm'] - $this->pagedim[$startpage]['orm']);
  19492. } elseif ((!$this->rtl) AND ($this->pagedim[$page]['olm'] != $this->pagedim[$startpage]['olm'])) {
  19493. $this->x += ($this->pagedim[$page]['olm'] - $this->pagedim[$startpage]['olm']);
  19494. }
  19495. }
  19496. if ($startpage == $endpage) {
  19497. // single page
  19498. for ($column = $startcolumn; $column <= $endcolumn; ++$column) { // for each column
  19499. $this->selectColumn($column);
  19500. if ($startcolumn == $endcolumn) { // single column
  19501. $cborder = $border;
  19502. $h = ($currentY - $y) + $cellspacing['V'];
  19503. $this->y = $starty;
  19504. } elseif ($column == $startcolumn) { // first column
  19505. $cborder = $border_start;
  19506. $this->y = $starty;
  19507. $h = $this->h - $this->y - $this->bMargin;
  19508. } elseif ($column == $endcolumn) { // end column
  19509. $cborder = $border_end;
  19510. $h = $currentY - $this->y;
  19511. } else { // middle column
  19512. $cborder = $border_middle;
  19513. $h = $this->h - $this->y - $this->bMargin;
  19514. }
  19515. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  19516. } // end for each column
  19517. } elseif ($page == $startpage) { // first page
  19518. for ($column = $startcolumn; $column < $this->num_columns; ++$column) { // for each column
  19519. $this->selectColumn($column);
  19520. if ($column == $startcolumn) { // first column
  19521. $cborder = $border_start;
  19522. $this->y = $starty;
  19523. $h = $this->h - $this->y - $this->bMargin;
  19524. } else { // middle column
  19525. $cborder = $border_middle;
  19526. $h = $this->h - $this->y - $this->bMargin;
  19527. }
  19528. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  19529. } // end for each column
  19530. } elseif ($page == $endpage) { // last page
  19531. for ($column = 0; $column <= $endcolumn; ++$column) { // for each column
  19532. $this->selectColumn($column);
  19533. if ($column == $endcolumn) {
  19534. // end column
  19535. $cborder = $border_end;
  19536. $h = $currentY - $this->y;
  19537. } else {
  19538. // middle column
  19539. $cborder = $border_middle;
  19540. $h = $this->h - $this->y - $this->bMargin;
  19541. }
  19542. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  19543. } // end for each column
  19544. } else { // middle page
  19545. for ($column = 0; $column < $this->num_columns; ++$column) { // for each column
  19546. $this->selectColumn($column);
  19547. $cborder = $border_middle;
  19548. $h = $this->h - $this->y - $this->bMargin;
  19549. $ccode .= $this->getCellCode($w, $h, '', $cborder, 1, '', $fill, '', 0, true)."\n";
  19550. } // end for each column
  19551. }
  19552. if ($cborder OR $fill) {
  19553. $offsetlen = strlen($ccode);
  19554. // draw border and fill
  19555. if ($this->inxobj) {
  19556. // we are inside an XObject template
  19557. if (end($this->xobjects[$this->xobjid]['transfmrk']) !== false) {
  19558. $pagemarkkey = key($this->xobjects[$this->xobjid]['transfmrk']);
  19559. $pagemark = $this->xobjects[$this->xobjid]['transfmrk'][$pagemarkkey];
  19560. $this->xobjects[$this->xobjid]['transfmrk'][$pagemarkkey] += $offsetlen;
  19561. } else {
  19562. $pagemark = $this->xobjects[$this->xobjid]['intmrk'];
  19563. $this->xobjects[$this->xobjid]['intmrk'] += $offsetlen;
  19564. }
  19565. $pagebuff = $this->xobjects[$this->xobjid]['outdata'];
  19566. $pstart = substr($pagebuff, 0, $pagemark);
  19567. $pend = substr($pagebuff, $pagemark);
  19568. $this->xobjects[$this->xobjid]['outdata'] = $pstart.$ccode.$pend;
  19569. } else {
  19570. if (end($this->transfmrk[$this->page]) !== false) {
  19571. $pagemarkkey = key($this->transfmrk[$this->page]);
  19572. $pagemark = $this->transfmrk[$this->page][$pagemarkkey];
  19573. } elseif ($this->InFooter) {
  19574. $pagemark = $this->footerpos[$this->page];
  19575. } else {
  19576. $pagemark = $this->intmrk[$this->page];
  19577. }
  19578. $pagebuff = $this->getPageBuffer($this->page);
  19579. $pstart = substr($pagebuff, 0, $pagemark);
  19580. $pend = substr($pagebuff, $pagemark);
  19581. $this->setPageBuffer($this->page, $pstart.$ccode.$pend);
  19582. $this->bordermrk[$this->page] += $offsetlen;
  19583. $this->cntmrk[$this->page] += $offsetlen;
  19584. }
  19585. }
  19586. } // end for each page
  19587. // restore page regions
  19588. $this->page_regions = $temp_page_regions;
  19589. if (isset($old_bgcolor)) {
  19590. // restore background color
  19591. $this->SetFillColorArray($old_bgcolor);
  19592. }
  19593. // restore pointer position
  19594. $this->x = $prev_x;
  19595. $this->y = $prev_y;
  19596. $this->lasth = $prev_lasth;
  19597. }
  19598. /**
  19599. * Set the default bullet to be used as LI bullet symbol
  19600. * @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')
  19601. * @public
  19602. * @since 4.0.028 (2008-09-26)
  19603. */
  19604. public function setLIsymbol($symbol='!') {
  19605. // check for custom image symbol
  19606. if (substr($symbol, 0, 4) == 'img|') {
  19607. $this->lisymbol = $symbol;
  19608. return;
  19609. }
  19610. $symbol = strtolower($symbol);
  19611. $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');
  19612. if (in_array($symbol, $valid_symbols)) {
  19613. $this->lisymbol = $symbol;
  19614. } else {
  19615. $this->lisymbol = '';
  19616. }
  19617. }
  19618. /**
  19619. * Set the booklet mode for double-sided pages.
  19620. * @param $booklet (boolean) true set the booklet mode on, false otherwise.
  19621. * @param $inner (float) Inner page margin.
  19622. * @param $outer (float) Outer page margin.
  19623. * @public
  19624. * @since 4.2.000 (2008-10-29)
  19625. */
  19626. public function SetBooklet($booklet=true, $inner=-1, $outer=-1) {
  19627. $this->booklet = $booklet;
  19628. if ($inner >= 0) {
  19629. $this->lMargin = $inner;
  19630. }
  19631. if ($outer >= 0) {
  19632. $this->rMargin = $outer;
  19633. }
  19634. }
  19635. /**
  19636. * Swap the left and right margins.
  19637. * @param $reverse (boolean) if true swap left and right margins.
  19638. * @protected
  19639. * @since 4.2.000 (2008-10-29)
  19640. */
  19641. protected function swapMargins($reverse=true) {
  19642. if ($reverse) {
  19643. // swap left and right margins
  19644. $mtemp = $this->original_lMargin;
  19645. $this->original_lMargin = $this->original_rMargin;
  19646. $this->original_rMargin = $mtemp;
  19647. $deltam = $this->original_lMargin - $this->original_rMargin;
  19648. $this->lMargin += $deltam;
  19649. $this->rMargin -= $deltam;
  19650. }
  19651. }
  19652. /**
  19653. * Set the vertical spaces for HTML tags.
  19654. * The array must have the following structure (example):
  19655. * $tagvs = array('h1' => array(0 => array('h' => '', 'n' => 2), 1 => array('h' => 1.3, 'n' => 1)));
  19656. * The first array level contains the tag names,
  19657. * the second level contains 0 for opening tags or 1 for closing tags,
  19658. * the third level contains the vertical space unit (h) and the number spaces to add (n).
  19659. * If the h parameter is not specified, default values are used.
  19660. * @param $tagvs (array) array of tags and relative vertical spaces.
  19661. * @public
  19662. * @since 4.2.001 (2008-10-30)
  19663. */
  19664. public function setHtmlVSpace($tagvs) {
  19665. $this->tagvspaces = $tagvs;
  19666. }
  19667. /**
  19668. * Set custom width for list indentation.
  19669. * @param $width (float) width of the indentation. Use negative value to disable it.
  19670. * @public
  19671. * @since 4.2.007 (2008-11-12)
  19672. */
  19673. public function setListIndentWidth($width) {
  19674. return $this->customlistindent = floatval($width);
  19675. }
  19676. /**
  19677. * Set the top/bottom cell sides to be open or closed when the cell cross the page.
  19678. * @param $isopen (boolean) if true keeps the top/bottom border open for the cell sides that cross the page.
  19679. * @public
  19680. * @since 4.2.010 (2008-11-14)
  19681. */
  19682. public function setOpenCell($isopen) {
  19683. $this->opencell = $isopen;
  19684. }
  19685. /**
  19686. * Set the color and font style for HTML links.
  19687. * @param $color (array) RGB array of colors
  19688. * @param $fontstyle (string) additional font styles to add
  19689. * @public
  19690. * @since 4.4.003 (2008-12-09)
  19691. */
  19692. public function setHtmlLinksStyle($color=array(0,0,255), $fontstyle='U') {
  19693. $this->htmlLinkColorArray = $color;
  19694. $this->htmlLinkFontStyle = $fontstyle;
  19695. }
  19696. /**
  19697. * Convert HTML string containing value and unit of measure to user's units or points.
  19698. * @param $htmlval (string) String containing values and unit.
  19699. * @param $refsize (string) Reference value in points.
  19700. * @param $defaultunit (string) Default unit (can be one of the following: %, em, ex, px, in, mm, pc, pt).
  19701. * @param $points (boolean) If true returns points, otherwise returns value in user's units.
  19702. * @return float value in user's unit or point if $points=true
  19703. * @public
  19704. * @since 4.4.004 (2008-12-10)
  19705. */
  19706. public function getHTMLUnitToUnits($htmlval, $refsize=1, $defaultunit='px', $points=false) {
  19707. $supportedunits = array('%', 'em', 'ex', 'px', 'in', 'cm', 'mm', 'pc', 'pt');
  19708. $retval = 0;
  19709. $value = 0;
  19710. $unit = 'px';
  19711. if ($points) {
  19712. $k = 1;
  19713. } else {
  19714. $k = $this->k;
  19715. }
  19716. if (in_array($defaultunit, $supportedunits)) {
  19717. $unit = $defaultunit;
  19718. }
  19719. if (is_numeric($htmlval)) {
  19720. $value = floatval($htmlval);
  19721. } elseif (preg_match('/([0-9\.\-\+]+)/', $htmlval, $mnum)) {
  19722. $value = floatval($mnum[1]);
  19723. if (preg_match('/([a-z%]+)/', $htmlval, $munit)) {
  19724. if (in_array($munit[1], $supportedunits)) {
  19725. $unit = $munit[1];
  19726. }
  19727. }
  19728. }
  19729. switch ($unit) {
  19730. // percentage
  19731. case '%': {
  19732. $retval = (($value * $refsize) / 100);
  19733. break;
  19734. }
  19735. // relative-size
  19736. case 'em': {
  19737. $retval = ($value * $refsize);
  19738. break;
  19739. }
  19740. // height of lower case 'x' (about half the font-size)
  19741. case 'ex': {
  19742. $retval = ($value * ($refsize / 2));
  19743. break;
  19744. }
  19745. // absolute-size
  19746. case 'in': {
  19747. $retval = (($value * $this->dpi) / $k);
  19748. break;
  19749. }
  19750. // centimeters
  19751. case 'cm': {
  19752. $retval = (($value / 2.54 * $this->dpi) / $k);
  19753. break;
  19754. }
  19755. // millimeters
  19756. case 'mm': {
  19757. $retval = (($value / 25.4 * $this->dpi) / $k);
  19758. break;
  19759. }
  19760. // one pica is 12 points
  19761. case 'pc': {
  19762. $retval = (($value * 12) / $k);
  19763. break;
  19764. }
  19765. // points
  19766. case 'pt': {
  19767. $retval = ($value / $k);
  19768. break;
  19769. }
  19770. // pixels
  19771. case 'px': {
  19772. $retval = $this->pixelsToUnits($value);
  19773. if ($points) {
  19774. $retval *= $this->k;
  19775. }
  19776. break;
  19777. }
  19778. }
  19779. return $retval;
  19780. }
  19781. /**
  19782. * Output an HTML list bullet or ordered item symbol
  19783. * @param $listdepth (int) list nesting level
  19784. * @param $listtype (string) type of list
  19785. * @param $size (float) current font size
  19786. * @protected
  19787. * @since 4.4.004 (2008-12-10)
  19788. */
  19789. protected function putHtmlListBullet($listdepth, $listtype='', $size=10) {
  19790. if ($this->state != 2) {
  19791. return;
  19792. }
  19793. $size /= $this->k;
  19794. $fill = '';
  19795. $bgcolor = $this->bgcolor;
  19796. $color = $this->fgcolor;
  19797. $strokecolor = $this->strokecolor;
  19798. $width = 0;
  19799. $textitem = '';
  19800. $tmpx = $this->x;
  19801. $lspace = $this->GetStringWidth(' ');
  19802. if ($listtype == '^') {
  19803. // special symbol used for avoid justification of rect bullet
  19804. $this->lispacer = '';
  19805. return;
  19806. } elseif ($listtype == '!') {
  19807. // set default list type for unordered list
  19808. $deftypes = array('disc', 'circle', 'square');
  19809. $listtype = $deftypes[($listdepth - 1) % 3];
  19810. } elseif ($listtype == '#') {
  19811. // set default list type for ordered list
  19812. $listtype = 'decimal';
  19813. } elseif (substr($listtype, 0, 4) == 'img|') {
  19814. // custom image type ('img|type|width|height|image.ext')
  19815. $img = explode('|', $listtype);
  19816. $listtype = 'img';
  19817. }
  19818. switch ($listtype) {
  19819. // unordered types
  19820. case 'none': {
  19821. break;
  19822. }
  19823. case 'disc': {
  19824. $r = $size / 6;
  19825. $lspace += (2 * $r);
  19826. if ($this->rtl) {
  19827. $this->x += $lspace;
  19828. } else {
  19829. $this->x -= $lspace;
  19830. }
  19831. $this->Circle(($this->x + $r), ($this->y + ($this->lasth / 2)), $r, 0, 360, 'F', array(), $color, 8);
  19832. break;
  19833. }
  19834. case 'circle': {
  19835. $r = $size / 6;
  19836. $lspace += (2 * $r);
  19837. if ($this->rtl) {
  19838. $this->x += $lspace;
  19839. } else {
  19840. $this->x -= $lspace;
  19841. }
  19842. $prev_line_style = $this->linestyleWidth.' '.$this->linestyleCap.' '.$this->linestyleJoin.' '.$this->linestyleDash.' '.$this->DrawColor;
  19843. $new_line_style = array('width' => ($r / 3), 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'phase' => 0, 'color'=>$color);
  19844. $this->Circle(($this->x + $r), ($this->y + ($this->lasth / 2)), ($r * (1 - (1/6))), 0, 360, 'D', $new_line_style, array(), 8);
  19845. $this->_out($prev_line_style); // restore line settings
  19846. break;
  19847. }
  19848. case 'square': {
  19849. $l = $size / 3;
  19850. $lspace += $l;
  19851. if ($this->rtl) {;
  19852. $this->x += $lspace;
  19853. } else {
  19854. $this->x -= $lspace;
  19855. }
  19856. $this->Rect($this->x, ($this->y + (($this->lasth - $l) / 2)), $l, $l, 'F', array(), $color);
  19857. break;
  19858. }
  19859. case 'img': {
  19860. // 1=>type, 2=>width, 3=>height, 4=>image.ext
  19861. $lspace += $img[2];
  19862. if ($this->rtl) {;
  19863. $this->x += $lspace;
  19864. } else {
  19865. $this->x -= $lspace;
  19866. }
  19867. $imgtype = strtolower($img[1]);
  19868. $prev_y = $this->y;
  19869. switch ($imgtype) {
  19870. case 'svg': {
  19871. $this->ImageSVG($img[4], $this->x, ($this->y + (($this->lasth - $img[3]) / 2)), $img[2], $img[3], '', 'T', '', 0, false);
  19872. break;
  19873. }
  19874. case 'ai':
  19875. case 'eps': {
  19876. $this->ImageEps($img[4], $this->x, ($this->y + (($this->lasth - $img[3]) / 2)), $img[2], $img[3], '', true, 'T', '', 0, false);
  19877. break;
  19878. }
  19879. default: {
  19880. $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);
  19881. break;
  19882. }
  19883. }
  19884. $this->y = $prev_y;
  19885. break;
  19886. }
  19887. // ordered types
  19888. // $this->listcount[$this->listnum];
  19889. // $textitem
  19890. case '1':
  19891. case 'decimal': {
  19892. $textitem = $this->listcount[$this->listnum];
  19893. break;
  19894. }
  19895. case 'decimal-leading-zero': {
  19896. $textitem = sprintf('%02d', $this->listcount[$this->listnum]);
  19897. break;
  19898. }
  19899. case 'i':
  19900. case 'lower-roman': {
  19901. $textitem = strtolower(TCPDF_STATIC::intToRoman($this->listcount[$this->listnum]));
  19902. break;
  19903. }
  19904. case 'I':
  19905. case 'upper-roman': {
  19906. $textitem = TCPDF_STATIC::intToRoman($this->listcount[$this->listnum]);
  19907. break;
  19908. }
  19909. case 'a':
  19910. case 'lower-alpha':
  19911. case 'lower-latin': {
  19912. $textitem = chr(97 + $this->listcount[$this->listnum] - 1);
  19913. break;
  19914. }
  19915. case 'A':
  19916. case 'upper-alpha':
  19917. case 'upper-latin': {
  19918. $textitem = chr(65 + $this->listcount[$this->listnum] - 1);
  19919. break;
  19920. }
  19921. case 'lower-greek': {
  19922. $textitem = TCPDF_FONTS::unichr((945 + $this->listcount[$this->listnum] - 1), $this->isunicode);
  19923. break;
  19924. }
  19925. /*
  19926. // Types to be implemented (special handling)
  19927. case 'hebrew': {
  19928. break;
  19929. }
  19930. case 'armenian': {
  19931. break;
  19932. }
  19933. case 'georgian': {
  19934. break;
  19935. }
  19936. case 'cjk-ideographic': {
  19937. break;
  19938. }
  19939. case 'hiragana': {
  19940. break;
  19941. }
  19942. case 'katakana': {
  19943. break;
  19944. }
  19945. case 'hiragana-iroha': {
  19946. break;
  19947. }
  19948. case 'katakana-iroha': {
  19949. break;
  19950. }
  19951. */
  19952. default: {
  19953. $textitem = $this->listcount[$this->listnum];
  19954. }
  19955. }
  19956. if (!TCPDF_STATIC::empty_string($textitem)) {
  19957. // Check whether we need a new page or new column
  19958. $prev_y = $this->y;
  19959. $h = $this->getCellHeight($this->FontSize);
  19960. if ($this->checkPageBreak($h) OR ($this->y < $prev_y)) {
  19961. $tmpx = $this->x;
  19962. }
  19963. // print ordered item
  19964. if ($this->rtl) {
  19965. $textitem = '.'.$textitem;
  19966. } else {
  19967. $textitem = $textitem.'.';
  19968. }
  19969. $lspace += $this->GetStringWidth($textitem);
  19970. if ($this->rtl) {
  19971. $this->x += $lspace;
  19972. } else {
  19973. $this->x -= $lspace;
  19974. }
  19975. $this->Write($this->lasth, $textitem, '', false, '', false, 0, false);
  19976. }
  19977. $this->x = $tmpx;
  19978. $this->lispacer = '^';
  19979. // restore colors
  19980. $this->SetFillColorArray($bgcolor);
  19981. $this->SetDrawColorArray($strokecolor);
  19982. $this->SettextColorArray($color);
  19983. }
  19984. /**
  19985. * Returns current graphic variables as array.
  19986. * @return array of graphic variables
  19987. * @protected
  19988. * @since 4.2.010 (2008-11-14)
  19989. */
  19990. protected function getGraphicVars() {
  19991. $grapvars = array(
  19992. 'FontFamily' => $this->FontFamily,
  19993. 'FontStyle' => $this->FontStyle,
  19994. 'FontSizePt' => $this->FontSizePt,
  19995. 'rMargin' => $this->rMargin,
  19996. 'lMargin' => $this->lMargin,
  19997. 'cell_padding' => $this->cell_padding,
  19998. 'cell_margin' => $this->cell_margin,
  19999. 'LineWidth' => $this->LineWidth,
  20000. 'linestyleWidth' => $this->linestyleWidth,
  20001. 'linestyleCap' => $this->linestyleCap,
  20002. 'linestyleJoin' => $this->linestyleJoin,
  20003. 'linestyleDash' => $this->linestyleDash,
  20004. 'textrendermode' => $this->textrendermode,
  20005. 'textstrokewidth' => $this->textstrokewidth,
  20006. 'DrawColor' => $this->DrawColor,
  20007. 'FillColor' => $this->FillColor,
  20008. 'TextColor' => $this->TextColor,
  20009. 'ColorFlag' => $this->ColorFlag,
  20010. 'bgcolor' => $this->bgcolor,
  20011. 'fgcolor' => $this->fgcolor,
  20012. 'htmlvspace' => $this->htmlvspace,
  20013. 'listindent' => $this->listindent,
  20014. 'listindentlevel' => $this->listindentlevel,
  20015. 'listnum' => $this->listnum,
  20016. 'listordered' => $this->listordered,
  20017. 'listcount' => $this->listcount,
  20018. 'lispacer' => $this->lispacer,
  20019. 'cell_height_ratio' => $this->cell_height_ratio,
  20020. 'font_stretching' => $this->font_stretching,
  20021. 'font_spacing' => $this->font_spacing,
  20022. 'alpha' => $this->alpha,
  20023. // extended
  20024. 'lasth' => $this->lasth,
  20025. 'tMargin' => $this->tMargin,
  20026. 'bMargin' => $this->bMargin,
  20027. 'AutoPageBreak' => $this->AutoPageBreak,
  20028. 'PageBreakTrigger' => $this->PageBreakTrigger,
  20029. 'x' => $this->x,
  20030. 'y' => $this->y,
  20031. 'w' => $this->w,
  20032. 'h' => $this->h,
  20033. 'wPt' => $this->wPt,
  20034. 'hPt' => $this->hPt,
  20035. 'fwPt' => $this->fwPt,
  20036. 'fhPt' => $this->fhPt,
  20037. 'page' => $this->page,
  20038. 'current_column' => $this->current_column,
  20039. 'num_columns' => $this->num_columns
  20040. );
  20041. return $grapvars;
  20042. }
  20043. /**
  20044. * Set graphic variables.
  20045. * @param $gvars (array) array of graphic variablesto restore
  20046. * @param $extended (boolean) if true restore extended graphic variables
  20047. * @protected
  20048. * @since 4.2.010 (2008-11-14)
  20049. */
  20050. protected function setGraphicVars($gvars, $extended=false) {
  20051. if ($this->state != 2) {
  20052. return;
  20053. }
  20054. $this->FontFamily = $gvars['FontFamily'];
  20055. $this->FontStyle = $gvars['FontStyle'];
  20056. $this->FontSizePt = $gvars['FontSizePt'];
  20057. $this->rMargin = $gvars['rMargin'];
  20058. $this->lMargin = $gvars['lMargin'];
  20059. $this->cell_padding = $gvars['cell_padding'];
  20060. $this->cell_margin = $gvars['cell_margin'];
  20061. $this->LineWidth = $gvars['LineWidth'];
  20062. $this->linestyleWidth = $gvars['linestyleWidth'];
  20063. $this->linestyleCap = $gvars['linestyleCap'];
  20064. $this->linestyleJoin = $gvars['linestyleJoin'];
  20065. $this->linestyleDash = $gvars['linestyleDash'];
  20066. $this->textrendermode = $gvars['textrendermode'];
  20067. $this->textstrokewidth = $gvars['textstrokewidth'];
  20068. $this->DrawColor = $gvars['DrawColor'];
  20069. $this->FillColor = $gvars['FillColor'];
  20070. $this->TextColor = $gvars['TextColor'];
  20071. $this->ColorFlag = $gvars['ColorFlag'];
  20072. $this->bgcolor = $gvars['bgcolor'];
  20073. $this->fgcolor = $gvars['fgcolor'];
  20074. $this->htmlvspace = $gvars['htmlvspace'];
  20075. $this->listindent = $gvars['listindent'];
  20076. $this->listindentlevel = $gvars['listindentlevel'];
  20077. $this->listnum = $gvars['listnum'];
  20078. $this->listordered = $gvars['listordered'];
  20079. $this->listcount = $gvars['listcount'];
  20080. $this->lispacer = $gvars['lispacer'];
  20081. $this->cell_height_ratio = $gvars['cell_height_ratio'];
  20082. $this->font_stretching = $gvars['font_stretching'];
  20083. $this->font_spacing = $gvars['font_spacing'];
  20084. $this->alpha = $gvars['alpha'];
  20085. if ($extended) {
  20086. // restore extended values
  20087. $this->lasth = $gvars['lasth'];
  20088. $this->tMargin = $gvars['tMargin'];
  20089. $this->bMargin = $gvars['bMargin'];
  20090. $this->AutoPageBreak = $gvars['AutoPageBreak'];
  20091. $this->PageBreakTrigger = $gvars['PageBreakTrigger'];
  20092. $this->x = $gvars['x'];
  20093. $this->y = $gvars['y'];
  20094. $this->w = $gvars['w'];
  20095. $this->h = $gvars['h'];
  20096. $this->wPt = $gvars['wPt'];
  20097. $this->hPt = $gvars['hPt'];
  20098. $this->fwPt = $gvars['fwPt'];
  20099. $this->fhPt = $gvars['fhPt'];
  20100. $this->page = $gvars['page'];
  20101. $this->current_column = $gvars['current_column'];
  20102. $this->num_columns = $gvars['num_columns'];
  20103. }
  20104. $this->_out(''.$this->linestyleWidth.' '.$this->linestyleCap.' '.$this->linestyleJoin.' '.$this->linestyleDash.' '.$this->DrawColor.' '.$this->FillColor.'');
  20105. if (!TCPDF_STATIC::empty_string($this->FontFamily)) {
  20106. $this->SetFont($this->FontFamily, $this->FontStyle, $this->FontSizePt);
  20107. }
  20108. }
  20109. /**
  20110. * Outputs the "save graphics state" operator 'q'
  20111. * @protected
  20112. */
  20113. protected function _outSaveGraphicsState() {
  20114. $this->_out('q');
  20115. }
  20116. /**
  20117. * Outputs the "restore graphics state" operator 'Q'
  20118. * @protected
  20119. */
  20120. protected function _outRestoreGraphicsState() {
  20121. $this->_out('Q');
  20122. }
  20123. /**
  20124. * Set buffer content (always append data).
  20125. * @param $data (string) data
  20126. * @protected
  20127. * @since 4.5.000 (2009-01-02)
  20128. */
  20129. protected function setBuffer($data) {
  20130. $this->bufferlen += strlen($data);
  20131. $this->buffer .= $data;
  20132. }
  20133. /**
  20134. * Replace the buffer content
  20135. * @param $data (string) data
  20136. * @protected
  20137. * @since 5.5.000 (2010-06-22)
  20138. */
  20139. protected function replaceBuffer($data) {
  20140. $this->bufferlen = strlen($data);
  20141. $this->buffer = $data;
  20142. }
  20143. /**
  20144. * Get buffer content.
  20145. * @return string buffer content
  20146. * @protected
  20147. * @since 4.5.000 (2009-01-02)
  20148. */
  20149. protected function getBuffer() {
  20150. return $this->buffer;
  20151. }
  20152. /**
  20153. * Set page buffer content.
  20154. * @param $page (int) page number
  20155. * @param $data (string) page data
  20156. * @param $append (boolean) if true append data, false replace.
  20157. * @protected
  20158. * @since 4.5.000 (2008-12-31)
  20159. */
  20160. protected function setPageBuffer($page, $data, $append=false) {
  20161. if ($append) {
  20162. $this->pages[$page] .= $data;
  20163. } else {
  20164. $this->pages[$page] = $data;
  20165. }
  20166. if ($append AND isset($this->pagelen[$page])) {
  20167. $this->pagelen[$page] += strlen($data);
  20168. } else {
  20169. $this->pagelen[$page] = strlen($data);
  20170. }
  20171. }
  20172. /**
  20173. * Get page buffer content.
  20174. * @param $page (int) page number
  20175. * @return string page buffer content or false in case of error
  20176. * @protected
  20177. * @since 4.5.000 (2008-12-31)
  20178. */
  20179. protected function getPageBuffer($page) {
  20180. if (isset($this->pages[$page])) {
  20181. return $this->pages[$page];
  20182. }
  20183. return false;
  20184. }
  20185. /**
  20186. * Set image buffer content.
  20187. * @param $image (string) image key
  20188. * @param $data (array) image data
  20189. * @return int image index number
  20190. * @protected
  20191. * @since 4.5.000 (2008-12-31)
  20192. */
  20193. protected function setImageBuffer($image, $data) {
  20194. if (($data['i'] = array_search($image, $this->imagekeys)) === FALSE) {
  20195. $this->imagekeys[$this->numimages] = $image;
  20196. $data['i'] = $this->numimages;
  20197. ++$this->numimages;
  20198. }
  20199. $this->images[$image] = $data;
  20200. return $data['i'];
  20201. }
  20202. /**
  20203. * Set image buffer content for a specified sub-key.
  20204. * @param $image (string) image key
  20205. * @param $key (string) image sub-key
  20206. * @param $data (array) image data
  20207. * @protected
  20208. * @since 4.5.000 (2008-12-31)
  20209. */
  20210. protected function setImageSubBuffer($image, $key, $data) {
  20211. if (!isset($this->images[$image])) {
  20212. $this->setImageBuffer($image, array());
  20213. }
  20214. $this->images[$image][$key] = $data;
  20215. }
  20216. /**
  20217. * Get image buffer content.
  20218. * @param $image (string) image key
  20219. * @return string image buffer content or false in case of error
  20220. * @protected
  20221. * @since 4.5.000 (2008-12-31)
  20222. */
  20223. protected function getImageBuffer($image) {
  20224. if (isset($this->images[$image])) {
  20225. return $this->images[$image];
  20226. }
  20227. return false;
  20228. }
  20229. /**
  20230. * Set font buffer content.
  20231. * @param $font (string) font key
  20232. * @param $data (array) font data
  20233. * @protected
  20234. * @since 4.5.000 (2009-01-02)
  20235. */
  20236. protected function setFontBuffer($font, $data) {
  20237. $this->fonts[$font] = $data;
  20238. if (!in_array($font, $this->fontkeys)) {
  20239. $this->fontkeys[] = $font;
  20240. // store object ID for current font
  20241. ++$this->n;
  20242. $this->font_obj_ids[$font] = $this->n;
  20243. $this->setFontSubBuffer($font, 'n', $this->n);
  20244. }
  20245. }
  20246. /**
  20247. * Set font buffer content.
  20248. * @param $font (string) font key
  20249. * @param $key (string) font sub-key
  20250. * @param $data (array) font data
  20251. * @protected
  20252. * @since 4.5.000 (2009-01-02)
  20253. */
  20254. protected function setFontSubBuffer($font, $key, $data) {
  20255. if (!isset($this->fonts[$font])) {
  20256. $this->setFontBuffer($font, array());
  20257. }
  20258. $this->fonts[$font][$key] = $data;
  20259. }
  20260. /**
  20261. * Get font buffer content.
  20262. * @param $font (string) font key
  20263. * @return string font buffer content or false in case of error
  20264. * @protected
  20265. * @since 4.5.000 (2009-01-02)
  20266. */
  20267. protected function getFontBuffer($font) {
  20268. if (isset($this->fonts[$font])) {
  20269. return $this->fonts[$font];
  20270. }
  20271. return false;
  20272. }
  20273. /**
  20274. * Move a page to a previous position.
  20275. * @param $frompage (int) number of the source page
  20276. * @param $topage (int) number of the destination page (must be less than $frompage)
  20277. * @return true in case of success, false in case of error.
  20278. * @public
  20279. * @since 4.5.000 (2009-01-02)
  20280. */
  20281. public function movePage($frompage, $topage) {
  20282. if (($frompage > $this->numpages) OR ($frompage <= $topage)) {
  20283. return false;
  20284. }
  20285. if ($frompage == $this->page) {
  20286. // close the page before moving it
  20287. $this->endPage();
  20288. }
  20289. // move all page-related states
  20290. $tmppage = $this->getPageBuffer($frompage);
  20291. $tmppagedim = $this->pagedim[$frompage];
  20292. $tmppagelen = $this->pagelen[$frompage];
  20293. $tmpintmrk = $this->intmrk[$frompage];
  20294. $tmpbordermrk = $this->bordermrk[$frompage];
  20295. $tmpcntmrk = $this->cntmrk[$frompage];
  20296. $tmppageobjects = $this->pageobjects[$frompage];
  20297. if (isset($this->footerpos[$frompage])) {
  20298. $tmpfooterpos = $this->footerpos[$frompage];
  20299. }
  20300. if (isset($this->footerlen[$frompage])) {
  20301. $tmpfooterlen = $this->footerlen[$frompage];
  20302. }
  20303. if (isset($this->transfmrk[$frompage])) {
  20304. $tmptransfmrk = $this->transfmrk[$frompage];
  20305. }
  20306. if (isset($this->PageAnnots[$frompage])) {
  20307. $tmpannots = $this->PageAnnots[$frompage];
  20308. }
  20309. if (isset($this->newpagegroup) AND !empty($this->newpagegroup)) {
  20310. for ($i = $frompage; $i > $topage; --$i) {
  20311. if (isset($this->newpagegroup[$i]) AND (($i + $this->pagegroups[$this->newpagegroup[$i]]) > $frompage)) {
  20312. --$this->pagegroups[$this->newpagegroup[$i]];
  20313. break;
  20314. }
  20315. }
  20316. for ($i = $topage; $i > 0; --$i) {
  20317. if (isset($this->newpagegroup[$i]) AND (($i + $this->pagegroups[$this->newpagegroup[$i]]) > $topage)) {
  20318. ++$this->pagegroups[$this->newpagegroup[$i]];
  20319. break;
  20320. }
  20321. }
  20322. }
  20323. for ($i = $frompage; $i > $topage; --$i) {
  20324. $j = $i - 1;
  20325. // shift pages down
  20326. $this->setPageBuffer($i, $this->getPageBuffer($j));
  20327. $this->pagedim[$i] = $this->pagedim[$j];
  20328. $this->pagelen[$i] = $this->pagelen[$j];
  20329. $this->intmrk[$i] = $this->intmrk[$j];
  20330. $this->bordermrk[$i] = $this->bordermrk[$j];
  20331. $this->cntmrk[$i] = $this->cntmrk[$j];
  20332. $this->pageobjects[$i] = $this->pageobjects[$j];
  20333. if (isset($this->footerpos[$j])) {
  20334. $this->footerpos[$i] = $this->footerpos[$j];
  20335. } elseif (isset($this->footerpos[$i])) {
  20336. unset($this->footerpos[$i]);
  20337. }
  20338. if (isset($this->footerlen[$j])) {
  20339. $this->footerlen[$i] = $this->footerlen[$j];
  20340. } elseif (isset($this->footerlen[$i])) {
  20341. unset($this->footerlen[$i]);
  20342. }
  20343. if (isset($this->transfmrk[$j])) {
  20344. $this->transfmrk[$i] = $this->transfmrk[$j];
  20345. } elseif (isset($this->transfmrk[$i])) {
  20346. unset($this->transfmrk[$i]);
  20347. }
  20348. if (isset($this->PageAnnots[$j])) {
  20349. $this->PageAnnots[$i] = $this->PageAnnots[$j];
  20350. } elseif (isset($this->PageAnnots[$i])) {
  20351. unset($this->PageAnnots[$i]);
  20352. }
  20353. if (isset($this->newpagegroup[$j])) {
  20354. $this->newpagegroup[$i] = $this->newpagegroup[$j];
  20355. unset($this->newpagegroup[$j]);
  20356. }
  20357. if ($this->currpagegroup == $j) {
  20358. $this->currpagegroup = $i;
  20359. }
  20360. }
  20361. $this->setPageBuffer($topage, $tmppage);
  20362. $this->pagedim[$topage] = $tmppagedim;
  20363. $this->pagelen[$topage] = $tmppagelen;
  20364. $this->intmrk[$topage] = $tmpintmrk;
  20365. $this->bordermrk[$topage] = $tmpbordermrk;
  20366. $this->cntmrk[$topage] = $tmpcntmrk;
  20367. $this->pageobjects[$topage] = $tmppageobjects;
  20368. if (isset($tmpfooterpos)) {
  20369. $this->footerpos[$topage] = $tmpfooterpos;
  20370. } elseif (isset($this->footerpos[$topage])) {
  20371. unset($this->footerpos[$topage]);
  20372. }
  20373. if (isset($tmpfooterlen)) {
  20374. $this->footerlen[$topage] = $tmpfooterlen;
  20375. } elseif (isset($this->footerlen[$topage])) {
  20376. unset($this->footerlen[$topage]);
  20377. }
  20378. if (isset($tmptransfmrk)) {
  20379. $this->transfmrk[$topage] = $tmptransfmrk;
  20380. } elseif (isset($this->transfmrk[$topage])) {
  20381. unset($this->transfmrk[$topage]);
  20382. }
  20383. if (isset($tmpannots)) {
  20384. $this->PageAnnots[$topage] = $tmpannots;
  20385. } elseif (isset($this->PageAnnots[$topage])) {
  20386. unset($this->PageAnnots[$topage]);
  20387. }
  20388. // adjust outlines
  20389. $tmpoutlines = $this->outlines;
  20390. foreach ($tmpoutlines as $key => $outline) {
  20391. if (!$outline['f']) {
  20392. if (($outline['p'] >= $topage) AND ($outline['p'] < $frompage)) {
  20393. $this->outlines[$key]['p'] = ($outline['p'] + 1);
  20394. } elseif ($outline['p'] == $frompage) {
  20395. $this->outlines[$key]['p'] = $topage;
  20396. }
  20397. }
  20398. }
  20399. // adjust dests
  20400. $tmpdests = $this->dests;
  20401. foreach ($tmpdests as $key => $dest) {
  20402. if (!$dest['f']) {
  20403. if (($dest['p'] >= $topage) AND ($dest['p'] < $frompage)) {
  20404. $this->dests[$key]['p'] = ($dest['p'] + 1);
  20405. } elseif ($dest['p'] == $frompage) {
  20406. $this->dests[$key]['p'] = $topage;
  20407. }
  20408. }
  20409. }
  20410. // adjust links
  20411. $tmplinks = $this->links;
  20412. foreach ($tmplinks as $key => $link) {
  20413. if (!$link['f']) {
  20414. if (($link['p'] >= $topage) AND ($link['p'] < $frompage)) {
  20415. $this->links[$key]['p'] = ($link['p'] + 1);
  20416. } elseif ($link['p'] == $frompage) {
  20417. $this->links[$key]['p'] = $topage;
  20418. }
  20419. }
  20420. }
  20421. // adjust javascript
  20422. $jfrompage = $frompage;
  20423. $jtopage = $topage;
  20424. if (preg_match_all('/this\.addField\(\'([^\']*)\',\'([^\']*)\',([0-9]+)/', $this->javascript, $pamatch) > 0) {
  20425. foreach($pamatch[0] as $pk => $pmatch) {
  20426. $pagenum = intval($pamatch[3][$pk]) + 1;
  20427. if (($pagenum >= $jtopage) AND ($pagenum < $jfrompage)) {
  20428. $newpage = ($pagenum + 1);
  20429. } elseif ($pagenum == $jfrompage) {
  20430. $newpage = $jtopage;
  20431. } else {
  20432. $newpage = $pagenum;
  20433. }
  20434. --$newpage;
  20435. $newjs = "this.addField(\'".$pamatch[1][$pk]."\',\'".$pamatch[2][$pk]."\',".$newpage;
  20436. $this->javascript = str_replace($pmatch, $newjs, $this->javascript);
  20437. }
  20438. unset($pamatch);
  20439. }
  20440. // return to last page
  20441. $this->lastPage(true);
  20442. return true;
  20443. }
  20444. /**
  20445. * Remove the specified page.
  20446. * @param $page (int) page to remove
  20447. * @return true in case of success, false in case of error.
  20448. * @public
  20449. * @since 4.6.004 (2009-04-23)
  20450. */
  20451. public function deletePage($page) {
  20452. if (($page < 1) OR ($page > $this->numpages)) {
  20453. return false;
  20454. }
  20455. // delete current page
  20456. unset($this->pages[$page]);
  20457. unset($this->pagedim[$page]);
  20458. unset($this->pagelen[$page]);
  20459. unset($this->intmrk[$page]);
  20460. unset($this->bordermrk[$page]);
  20461. unset($this->cntmrk[$page]);
  20462. foreach ($this->pageobjects[$page] as $oid) {
  20463. if (isset($this->offsets[$oid])){
  20464. unset($this->offsets[$oid]);
  20465. }
  20466. }
  20467. unset($this->pageobjects[$page]);
  20468. if (isset($this->footerpos[$page])) {
  20469. unset($this->footerpos[$page]);
  20470. }
  20471. if (isset($this->footerlen[$page])) {
  20472. unset($this->footerlen[$page]);
  20473. }
  20474. if (isset($this->transfmrk[$page])) {
  20475. unset($this->transfmrk[$page]);
  20476. }
  20477. if (isset($this->PageAnnots[$page])) {
  20478. unset($this->PageAnnots[$page]);
  20479. }
  20480. if (isset($this->newpagegroup) AND !empty($this->newpagegroup)) {
  20481. for ($i = $page; $i > 0; --$i) {
  20482. if (isset($this->newpagegroup[$i]) AND (($i + $this->pagegroups[$this->newpagegroup[$i]]) > $page)) {
  20483. --$this->pagegroups[$this->newpagegroup[$i]];
  20484. break;
  20485. }
  20486. }
  20487. }
  20488. if (isset($this->pageopen[$page])) {
  20489. unset($this->pageopen[$page]);
  20490. }
  20491. if ($page < $this->numpages) {
  20492. // update remaining pages
  20493. for ($i = $page; $i < $this->numpages; ++$i) {
  20494. $j = $i + 1;
  20495. // shift pages
  20496. $this->setPageBuffer($i, $this->getPageBuffer($j));
  20497. $this->pagedim[$i] = $this->pagedim[$j];
  20498. $this->pagelen[$i] = $this->pagelen[$j];
  20499. $this->intmrk[$i] = $this->intmrk[$j];
  20500. $this->bordermrk[$i] = $this->bordermrk[$j];
  20501. $this->cntmrk[$i] = $this->cntmrk[$j];
  20502. $this->pageobjects[$i] = $this->pageobjects[$j];
  20503. if (isset($this->footerpos[$j])) {
  20504. $this->footerpos[$i] = $this->footerpos[$j];
  20505. } elseif (isset($this->footerpos[$i])) {
  20506. unset($this->footerpos[$i]);
  20507. }
  20508. if (isset($this->footerlen[$j])) {
  20509. $this->footerlen[$i] = $this->footerlen[$j];
  20510. } elseif (isset($this->footerlen[$i])) {
  20511. unset($this->footerlen[$i]);
  20512. }
  20513. if (isset($this->transfmrk[$j])) {
  20514. $this->transfmrk[$i] = $this->transfmrk[$j];
  20515. } elseif (isset($this->transfmrk[$i])) {
  20516. unset($this->transfmrk[$i]);
  20517. }
  20518. if (isset($this->PageAnnots[$j])) {
  20519. $this->PageAnnots[$i] = $this->PageAnnots[$j];
  20520. } elseif (isset($this->PageAnnots[$i])) {
  20521. unset($this->PageAnnots[$i]);
  20522. }
  20523. if (isset($this->newpagegroup[$j])) {
  20524. $this->newpagegroup[$i] = $this->newpagegroup[$j];
  20525. unset($this->newpagegroup[$j]);
  20526. }
  20527. if ($this->currpagegroup == $j) {
  20528. $this->currpagegroup = $i;
  20529. }
  20530. if (isset($this->pageopen[$j])) {
  20531. $this->pageopen[$i] = $this->pageopen[$j];
  20532. } elseif (isset($this->pageopen[$i])) {
  20533. unset($this->pageopen[$i]);
  20534. }
  20535. }
  20536. // remove last page
  20537. unset($this->pages[$this->numpages]);
  20538. unset($this->pagedim[$this->numpages]);
  20539. unset($this->pagelen[$this->numpages]);
  20540. unset($this->intmrk[$this->numpages]);
  20541. unset($this->bordermrk[$this->numpages]);
  20542. unset($this->cntmrk[$this->numpages]);
  20543. foreach ($this->pageobjects[$this->numpages] as $oid) {
  20544. if (isset($this->offsets[$oid])){
  20545. unset($this->offsets[$oid]);
  20546. }
  20547. }
  20548. unset($this->pageobjects[$this->numpages]);
  20549. if (isset($this->footerpos[$this->numpages])) {
  20550. unset($this->footerpos[$this->numpages]);
  20551. }
  20552. if (isset($this->footerlen[$this->numpages])) {
  20553. unset($this->footerlen[$this->numpages]);
  20554. }
  20555. if (isset($this->transfmrk[$this->numpages])) {
  20556. unset($this->transfmrk[$this->numpages]);
  20557. }
  20558. if (isset($this->PageAnnots[$this->numpages])) {
  20559. unset($this->PageAnnots[$this->numpages]);
  20560. }
  20561. if (isset($this->newpagegroup[$this->numpages])) {
  20562. unset($this->newpagegroup[$this->numpages]);
  20563. }
  20564. if ($this->currpagegroup == $this->numpages) {
  20565. $this->currpagegroup = ($this->numpages - 1);
  20566. }
  20567. if (isset($this->pagegroups[$this->numpages])) {
  20568. unset($this->pagegroups[$this->numpages]);
  20569. }
  20570. if (isset($this->pageopen[$this->numpages])) {
  20571. unset($this->pageopen[$this->numpages]);
  20572. }
  20573. }
  20574. --$this->numpages;
  20575. $this->page = $this->numpages;
  20576. // adjust outlines
  20577. $tmpoutlines = $this->outlines;
  20578. foreach ($tmpoutlines as $key => $outline) {
  20579. if (!$outline['f']) {
  20580. if ($outline['p'] > $page) {
  20581. $this->outlines[$key]['p'] = $outline['p'] - 1;
  20582. } elseif ($outline['p'] == $page) {
  20583. unset($this->outlines[$key]);
  20584. }
  20585. }
  20586. }
  20587. // adjust dests
  20588. $tmpdests = $this->dests;
  20589. foreach ($tmpdests as $key => $dest) {
  20590. if (!$dest['f']) {
  20591. if ($dest['p'] > $page) {
  20592. $this->dests[$key]['p'] = $dest['p'] - 1;
  20593. } elseif ($dest['p'] == $page) {
  20594. unset($this->dests[$key]);
  20595. }
  20596. }
  20597. }
  20598. // adjust links
  20599. $tmplinks = $this->links;
  20600. foreach ($tmplinks as $key => $link) {
  20601. if (!$link['f']) {
  20602. if ($link['p'] > $page) {
  20603. $this->links[$key]['p'] = $link['p'] - 1;
  20604. } elseif ($link['p'] == $page) {
  20605. unset($this->links[$key]);
  20606. }
  20607. }
  20608. }
  20609. // adjust javascript
  20610. $jpage = $page;
  20611. if (preg_match_all('/this\.addField\(\'([^\']*)\',\'([^\']*)\',([0-9]+)/', $this->javascript, $pamatch) > 0) {
  20612. foreach($pamatch[0] as $pk => $pmatch) {
  20613. $pagenum = intval($pamatch[3][$pk]) + 1;
  20614. if ($pagenum >= $jpage) {
  20615. $newpage = ($pagenum - 1);
  20616. } elseif ($pagenum == $jpage) {
  20617. $newpage = 1;
  20618. } else {
  20619. $newpage = $pagenum;
  20620. }
  20621. --$newpage;
  20622. $newjs = "this.addField(\'".$pamatch[1][$pk]."\',\'".$pamatch[2][$pk]."\',".$newpage;
  20623. $this->javascript = str_replace($pmatch, $newjs, $this->javascript);
  20624. }
  20625. unset($pamatch);
  20626. }
  20627. // return to last page
  20628. if ($this->numpages > 0) {
  20629. $this->lastPage(true);
  20630. }
  20631. return true;
  20632. }
  20633. /**
  20634. * Clone the specified page to a new page.
  20635. * @param $page (int) number of page to copy (0 = current page)
  20636. * @return true in case of success, false in case of error.
  20637. * @public
  20638. * @since 4.9.015 (2010-04-20)
  20639. */
  20640. public function copyPage($page=0) {
  20641. if ($page == 0) {
  20642. // default value
  20643. $page = $this->page;
  20644. }
  20645. if (($page < 1) OR ($page > $this->numpages)) {
  20646. return false;
  20647. }
  20648. // close the last page
  20649. $this->endPage();
  20650. // copy all page-related states
  20651. ++$this->numpages;
  20652. $this->page = $this->numpages;
  20653. $this->setPageBuffer($this->page, $this->getPageBuffer($page));
  20654. $this->pagedim[$this->page] = $this->pagedim[$page];
  20655. $this->pagelen[$this->page] = $this->pagelen[$page];
  20656. $this->intmrk[$this->page] = $this->intmrk[$page];
  20657. $this->bordermrk[$this->page] = $this->bordermrk[$page];
  20658. $this->cntmrk[$this->page] = $this->cntmrk[$page];
  20659. $this->pageobjects[$this->page] = $this->pageobjects[$page];
  20660. $this->pageopen[$this->page] = false;
  20661. if (isset($this->footerpos[$page])) {
  20662. $this->footerpos[$this->page] = $this->footerpos[$page];
  20663. }
  20664. if (isset($this->footerlen[$page])) {
  20665. $this->footerlen[$this->page] = $this->footerlen[$page];
  20666. }
  20667. if (isset($this->transfmrk[$page])) {
  20668. $this->transfmrk[$this->page] = $this->transfmrk[$page];
  20669. }
  20670. if (isset($this->PageAnnots[$page])) {
  20671. $this->PageAnnots[$this->page] = $this->PageAnnots[$page];
  20672. }
  20673. if (isset($this->newpagegroup[$page])) {
  20674. // start a new group
  20675. $this->newpagegroup[$this->page] = sizeof($this->newpagegroup) + 1;
  20676. $this->currpagegroup = $this->newpagegroup[$this->page];
  20677. $this->pagegroups[$this->currpagegroup] = 1;
  20678. } elseif (isset($this->currpagegroup) AND ($this->currpagegroup > 0)) {
  20679. ++$this->pagegroups[$this->currpagegroup];
  20680. }
  20681. // copy outlines
  20682. $tmpoutlines = $this->outlines;
  20683. foreach ($tmpoutlines as $key => $outline) {
  20684. if ($outline['p'] == $page) {
  20685. $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']);
  20686. }
  20687. }
  20688. // copy links
  20689. $tmplinks = $this->links;
  20690. foreach ($tmplinks as $key => $link) {
  20691. if ($link['p'] == $page) {
  20692. $this->links[] = array('p' => $this->page, 'y' => $link['y'], 'f' => $link['f']);
  20693. }
  20694. }
  20695. // return to last page
  20696. $this->lastPage(true);
  20697. return true;
  20698. }
  20699. /**
  20700. * Output a Table of Content Index (TOC).
  20701. * This method must be called after all Bookmarks were set.
  20702. * Before calling this method you have to open the page using the addTOCPage() method.
  20703. * After calling this method you have to call endTOCPage() to close the TOC page.
  20704. * You can override this method to achieve different styles.
  20705. * @param $page (int) page number where this TOC should be inserted (leave empty for current page).
  20706. * @param $numbersfont (string) set the font for page numbers (please use monospaced font for better alignment).
  20707. * @param $filler (string) string used to fill the space between text and page number.
  20708. * @param $toc_name (string) name to use for TOC bookmark.
  20709. * @param $style (string) Font style for title: B = Bold, I = Italic, BI = Bold + Italic.
  20710. * @param $color (array) RGB color array for bookmark title (values from 0 to 255).
  20711. * @public
  20712. * @author Nicola Asuni
  20713. * @since 4.5.000 (2009-01-02)
  20714. * @see addTOCPage(), endTOCPage(), addHTMLTOC()
  20715. */
  20716. public function addTOC($page='', $numbersfont='', $filler='.', $toc_name='TOC', $style='', $color=array(0,0,0)) {
  20717. $fontsize = $this->FontSizePt;
  20718. $fontfamily = $this->FontFamily;
  20719. $fontstyle = $this->FontStyle;
  20720. $w = $this->w - $this->lMargin - $this->rMargin;
  20721. $spacer = $this->GetStringWidth(chr(32)) * 4;
  20722. $lmargin = $this->lMargin;
  20723. $rmargin = $this->rMargin;
  20724. $x_start = $this->GetX();
  20725. $page_first = $this->page;
  20726. $current_page = $this->page;
  20727. $page_fill_start = false;
  20728. $page_fill_end = false;
  20729. $current_column = $this->current_column;
  20730. if (TCPDF_STATIC::empty_string($numbersfont)) {
  20731. $numbersfont = $this->default_monospaced_font;
  20732. }
  20733. if (TCPDF_STATIC::empty_string($filler)) {
  20734. $filler = ' ';
  20735. }
  20736. if (TCPDF_STATIC::empty_string($page)) {
  20737. $gap = ' ';
  20738. } else {
  20739. $gap = '';
  20740. if ($page < 1) {
  20741. $page = 1;
  20742. }
  20743. }
  20744. $this->SetFont($numbersfont, $fontstyle, $fontsize);
  20745. $numwidth = $this->GetStringWidth('00000');
  20746. $maxpage = 0; //used for pages on attached documents
  20747. foreach ($this->outlines as $key => $outline) {
  20748. // check for extra pages (used for attachments)
  20749. if (($this->page > $page_first) AND ($outline['p'] >= $this->numpages)) {
  20750. $outline['p'] += ($this->page - $page_first);
  20751. }
  20752. if ($this->rtl) {
  20753. $aligntext = 'R';
  20754. $alignnum = 'L';
  20755. } else {
  20756. $aligntext = 'L';
  20757. $alignnum = 'R';
  20758. }
  20759. if ($outline['l'] == 0) {
  20760. $this->SetFont($fontfamily, $outline['s'].'B', $fontsize);
  20761. } else {
  20762. $this->SetFont($fontfamily, $outline['s'], $fontsize - $outline['l']);
  20763. }
  20764. $this->SetTextColorArray($outline['c']);
  20765. // check for page break
  20766. $this->checkPageBreak(2 * $this->getCellHeight($this->FontSize));
  20767. // set margins and X position
  20768. if (($this->page == $current_page) AND ($this->current_column == $current_column)) {
  20769. $this->lMargin = $lmargin;
  20770. $this->rMargin = $rmargin;
  20771. } else {
  20772. if ($this->current_column != $current_column) {
  20773. if ($this->rtl) {
  20774. $x_start = $this->w - $this->columns[$this->current_column]['x'];
  20775. } else {
  20776. $x_start = $this->columns[$this->current_column]['x'];
  20777. }
  20778. }
  20779. $lmargin = $this->lMargin;
  20780. $rmargin = $this->rMargin;
  20781. $current_page = $this->page;
  20782. $current_column = $this->current_column;
  20783. }
  20784. $this->SetX($x_start);
  20785. $indent = ($spacer * $outline['l']);
  20786. if ($this->rtl) {
  20787. $this->x -= $indent;
  20788. $this->rMargin = $this->w - $this->x;
  20789. } else {
  20790. $this->x += $indent;
  20791. $this->lMargin = $this->x;
  20792. }
  20793. $link = $this->AddLink();
  20794. $this->SetLink($link, $outline['y'], $outline['p']);
  20795. // write the text
  20796. if ($this->rtl) {
  20797. $txt = ' '.$outline['t'];
  20798. } else {
  20799. $txt = $outline['t'].' ';
  20800. }
  20801. $this->Write(0, $txt, $link, false, $aligntext, false, 0, false, false, 0, $numwidth, '');
  20802. if ($this->rtl) {
  20803. $tw = $this->x - $this->lMargin;
  20804. } else {
  20805. $tw = $this->w - $this->rMargin - $this->x;
  20806. }
  20807. $this->SetFont($numbersfont, $fontstyle, $fontsize);
  20808. if (TCPDF_STATIC::empty_string($page)) {
  20809. $pagenum = $outline['p'];
  20810. } else {
  20811. // placemark to be replaced with the correct number
  20812. $pagenum = '{#'.($outline['p']).'}';
  20813. if ($this->isUnicodeFont()) {
  20814. $pagenum = '{'.$pagenum.'}';
  20815. }
  20816. $maxpage = max($maxpage, $outline['p']);
  20817. }
  20818. $fw = ($tw - $this->GetStringWidth($pagenum.$filler));
  20819. $wfiller = $this->GetStringWidth($filler);
  20820. if ($wfiller > 0) {
  20821. $numfills = floor($fw / $wfiller);
  20822. } else {
  20823. $numfills = 0;
  20824. }
  20825. if ($numfills > 0) {
  20826. $rowfill = str_repeat($filler, $numfills);
  20827. } else {
  20828. $rowfill = '';
  20829. }
  20830. if ($this->rtl) {
  20831. $pagenum = $pagenum.$gap.$rowfill;
  20832. } else {
  20833. $pagenum = $rowfill.$gap.$pagenum;
  20834. }
  20835. // write the number
  20836. $this->Cell($tw, 0, $pagenum, 0, 1, $alignnum, 0, $link, 0);
  20837. }
  20838. $page_last = $this->getPage();
  20839. $numpages = ($page_last - $page_first + 1);
  20840. // account for booklet mode
  20841. if ($this->booklet) {
  20842. // check if a blank page is required before TOC
  20843. $page_fill_start = ((($page_first % 2) == 0) XOR (($page % 2) == 0));
  20844. $page_fill_end = (!((($numpages % 2) == 0) XOR ($page_fill_start)));
  20845. if ($page_fill_start) {
  20846. // add a page at the end (to be moved before TOC)
  20847. $this->addPage();
  20848. ++$page_last;
  20849. ++$numpages;
  20850. }
  20851. if ($page_fill_end) {
  20852. // add a page at the end
  20853. $this->addPage();
  20854. ++$page_last;
  20855. ++$numpages;
  20856. }
  20857. }
  20858. $maxpage = max($maxpage, $page_last);
  20859. if (!TCPDF_STATIC::empty_string($page)) {
  20860. for ($p = $page_first; $p <= $page_last; ++$p) {
  20861. // get page data
  20862. $temppage = $this->getPageBuffer($p);
  20863. for ($n = 1; $n <= $maxpage; ++$n) {
  20864. // update page numbers
  20865. $a = '{#'.$n.'}';
  20866. // get page number aliases
  20867. $pnalias = $this->getInternalPageNumberAliases($a);
  20868. // calculate replacement number
  20869. if (($n >= $page) AND ($n <= $this->numpages)) {
  20870. $np = $n + $numpages;
  20871. } else {
  20872. $np = $n;
  20873. }
  20874. $na = TCPDF_STATIC::formatTOCPageNumber(($this->starting_page_number + $np - 1));
  20875. $nu = TCPDF_FONTS::UTF8ToUTF16BE($na, false, $this->isunicode, $this->CurrentFont);
  20876. // replace aliases with numbers
  20877. foreach ($pnalias['u'] as $u) {
  20878. $sfill = str_repeat($filler, max(0, (strlen($u) - strlen($nu.' '))));
  20879. if ($this->rtl) {
  20880. $nr = $nu.TCPDF_FONTS::UTF8ToUTF16BE(' '.$sfill, false, $this->isunicode, $this->CurrentFont);
  20881. } else {
  20882. $nr = TCPDF_FONTS::UTF8ToUTF16BE($sfill.' ', false, $this->isunicode, $this->CurrentFont).$nu;
  20883. }
  20884. $temppage = str_replace($u, $nr, $temppage);
  20885. }
  20886. foreach ($pnalias['a'] as $a) {
  20887. $sfill = str_repeat($filler, max(0, (strlen($a) - strlen($na.' '))));
  20888. if ($this->rtl) {
  20889. $nr = $na.' '.$sfill;
  20890. } else {
  20891. $nr = $sfill.' '.$na;
  20892. }
  20893. $temppage = str_replace($a, $nr, $temppage);
  20894. }
  20895. }
  20896. // save changes
  20897. $this->setPageBuffer($p, $temppage);
  20898. }
  20899. // move pages
  20900. $this->Bookmark($toc_name, 0, 0, $page_first, $style, $color);
  20901. if ($page_fill_start) {
  20902. $this->movePage($page_last, $page_first);
  20903. }
  20904. for ($i = 0; $i < $numpages; ++$i) {
  20905. $this->movePage($page_last, $page);
  20906. }
  20907. }
  20908. }
  20909. /**
  20910. * Output a Table Of Content Index (TOC) using HTML templates.
  20911. * This method must be called after all Bookmarks were set.
  20912. * Before calling this method you have to open the page using the addTOCPage() method.
  20913. * After calling this method you have to call endTOCPage() to close the TOC page.
  20914. * @param $page (int) page number where this TOC should be inserted (leave empty for current page).
  20915. * @param $toc_name (string) name to use for TOC bookmark.
  20916. * @param $templates (array) array of html templates. Use: "#TOC_DESCRIPTION#" for bookmark title, "#TOC_PAGE_NUMBER#" for page number.
  20917. * @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)
  20918. * @param $style (string) Font style for title: B = Bold, I = Italic, BI = Bold + Italic.
  20919. * @param $color (array) RGB color array for title (values from 0 to 255).
  20920. * @public
  20921. * @author Nicola Asuni
  20922. * @since 5.0.001 (2010-05-06)
  20923. * @see addTOCPage(), endTOCPage(), addTOC()
  20924. */
  20925. public function addHTMLTOC($page='', $toc_name='TOC', $templates=array(), $correct_align=true, $style='', $color=array(0,0,0)) {
  20926. $filler = ' ';
  20927. $prev_htmlLinkColorArray = $this->htmlLinkColorArray;
  20928. $prev_htmlLinkFontStyle = $this->htmlLinkFontStyle;
  20929. // set new style for link
  20930. $this->htmlLinkColorArray = array();
  20931. $this->htmlLinkFontStyle = '';
  20932. $page_first = $this->getPage();
  20933. $page_fill_start = false;
  20934. $page_fill_end = false;
  20935. // get the font type used for numbers in each template
  20936. $current_font = $this->FontFamily;
  20937. foreach ($templates as $level => $html) {
  20938. $dom = $this->getHtmlDomArray($html);
  20939. foreach ($dom as $key => $value) {
  20940. if ($value['value'] == '#TOC_PAGE_NUMBER#') {
  20941. $this->SetFont($dom[($key - 1)]['fontname']);
  20942. $templates['F'.$level] = $this->isUnicodeFont();
  20943. }
  20944. }
  20945. }
  20946. $this->SetFont($current_font);
  20947. $maxpage = 0; //used for pages on attached documents
  20948. foreach ($this->outlines as $key => $outline) {
  20949. // get HTML template
  20950. $row = $templates[$outline['l']];
  20951. if (TCPDF_STATIC::empty_string($page)) {
  20952. $pagenum = $outline['p'];
  20953. } else {
  20954. // placemark to be replaced with the correct number
  20955. $pagenum = '{#'.($outline['p']).'}';
  20956. if (isset($templates['F'.$outline['l']]) && $templates['F'.$outline['l']]) {
  20957. $pagenum = '{'.$pagenum.'}';
  20958. }
  20959. $maxpage = max($maxpage, $outline['p']);
  20960. }
  20961. // replace templates with current values
  20962. $row = str_replace('#TOC_DESCRIPTION#', $outline['t'], $row);
  20963. $row = str_replace('#TOC_PAGE_NUMBER#', $pagenum, $row);
  20964. // add link to page
  20965. $row = '<a href="#'.$outline['p'].','.$outline['y'].'">'.$row.'</a>';
  20966. // write bookmark entry
  20967. $this->writeHTML($row, false, false, true, false, '');
  20968. }
  20969. // restore link styles
  20970. $this->htmlLinkColorArray = $prev_htmlLinkColorArray;
  20971. $this->htmlLinkFontStyle = $prev_htmlLinkFontStyle;
  20972. // move TOC page and replace numbers
  20973. $page_last = $this->getPage();
  20974. $numpages = ($page_last - $page_first + 1);
  20975. // account for booklet mode
  20976. if ($this->booklet) {
  20977. // check if a blank page is required before TOC
  20978. $page_fill_start = ((($page_first % 2) == 0) XOR (($page % 2) == 0));
  20979. $page_fill_end = (!((($numpages % 2) == 0) XOR ($page_fill_start)));
  20980. if ($page_fill_start) {
  20981. // add a page at the end (to be moved before TOC)
  20982. $this->addPage();
  20983. ++$page_last;
  20984. ++$numpages;
  20985. }
  20986. if ($page_fill_end) {
  20987. // add a page at the end
  20988. $this->addPage();
  20989. ++$page_last;
  20990. ++$numpages;
  20991. }
  20992. }
  20993. $maxpage = max($maxpage, $page_last);
  20994. if (!TCPDF_STATIC::empty_string($page)) {
  20995. for ($p = $page_first; $p <= $page_last; ++$p) {
  20996. // get page data
  20997. $temppage = $this->getPageBuffer($p);
  20998. for ($n = 1; $n <= $maxpage; ++$n) {
  20999. // update page numbers
  21000. $a = '{#'.$n.'}';
  21001. // get page number aliases
  21002. $pnalias = $this->getInternalPageNumberAliases($a);
  21003. // calculate replacement number
  21004. if ($n >= $page) {
  21005. $np = $n + $numpages;
  21006. } else {
  21007. $np = $n;
  21008. }
  21009. $na = TCPDF_STATIC::formatTOCPageNumber(($this->starting_page_number + $np - 1));
  21010. $nu = TCPDF_FONTS::UTF8ToUTF16BE($na, false, $this->isunicode, $this->CurrentFont);
  21011. // replace aliases with numbers
  21012. foreach ($pnalias['u'] as $u) {
  21013. if ($correct_align) {
  21014. $sfill = str_repeat($filler, (strlen($u) - strlen($nu.' ')));
  21015. if ($this->rtl) {
  21016. $nr = $nu.TCPDF_FONTS::UTF8ToUTF16BE(' '.$sfill, false, $this->isunicode, $this->CurrentFont);
  21017. } else {
  21018. $nr = TCPDF_FONTS::UTF8ToUTF16BE($sfill.' ', false, $this->isunicode, $this->CurrentFont).$nu;
  21019. }
  21020. } else {
  21021. $nr = $nu;
  21022. }
  21023. $temppage = str_replace($u, $nr, $temppage);
  21024. }
  21025. foreach ($pnalias['a'] as $a) {
  21026. if ($correct_align) {
  21027. $sfill = str_repeat($filler, (strlen($a) - strlen($na.' ')));
  21028. if ($this->rtl) {
  21029. $nr = $na.' '.$sfill;
  21030. } else {
  21031. $nr = $sfill.' '.$na;
  21032. }
  21033. } else {
  21034. $nr = $na;
  21035. }
  21036. $temppage = str_replace($a, $nr, $temppage);
  21037. }
  21038. }
  21039. // save changes
  21040. $this->setPageBuffer($p, $temppage);
  21041. }
  21042. // move pages
  21043. $this->Bookmark($toc_name, 0, 0, $page_first, $style, $color);
  21044. if ($page_fill_start) {
  21045. $this->movePage($page_last, $page_first);
  21046. }
  21047. for ($i = 0; $i < $numpages; ++$i) {
  21048. $this->movePage($page_last, $page);
  21049. }
  21050. }
  21051. }
  21052. /**
  21053. * Stores a copy of the current TCPDF object used for undo operation.
  21054. * @public
  21055. * @since 4.5.029 (2009-03-19)
  21056. */
  21057. public function startTransaction() {
  21058. if (isset($this->objcopy)) {
  21059. // remove previous copy
  21060. $this->commitTransaction();
  21061. }
  21062. // record current page number and Y position
  21063. $this->start_transaction_page = $this->page;
  21064. $this->start_transaction_y = $this->y;
  21065. // clone current object
  21066. $this->objcopy = TCPDF_STATIC::objclone($this);
  21067. }
  21068. /**
  21069. * Delete the copy of the current TCPDF object used for undo operation.
  21070. * @public
  21071. * @since 4.5.029 (2009-03-19)
  21072. */
  21073. public function commitTransaction() {
  21074. if (isset($this->objcopy)) {
  21075. $this->objcopy->_destroy(true, true);
  21076. unset($this->objcopy);
  21077. }
  21078. }
  21079. /**
  21080. * This method allows to undo the latest transaction by returning the latest saved TCPDF object with startTransaction().
  21081. * @param $self (boolean) if true restores current class object to previous state without the need of reassignment via the returned value.
  21082. * @return TCPDF object.
  21083. * @public
  21084. * @since 4.5.029 (2009-03-19)
  21085. */
  21086. public function rollbackTransaction($self=false) {
  21087. if (isset($this->objcopy)) {
  21088. $this->_destroy(true, true);
  21089. if ($self) {
  21090. $objvars = get_object_vars($this->objcopy);
  21091. foreach ($objvars as $key => $value) {
  21092. $this->$key = $value;
  21093. }
  21094. }
  21095. return $this->objcopy;
  21096. }
  21097. return $this;
  21098. }
  21099. // --- MULTI COLUMNS METHODS -----------------------
  21100. /**
  21101. * Set multiple columns of the same size
  21102. * @param $numcols (int) number of columns (set to zero to disable columns mode)
  21103. * @param $width (int) column width
  21104. * @param $y (int) column starting Y position (leave empty for current Y position)
  21105. * @public
  21106. * @since 4.9.001 (2010-03-28)
  21107. */
  21108. public function setEqualColumns($numcols=0, $width=0, $y='') {
  21109. $this->columns = array();
  21110. if ($numcols < 2) {
  21111. $numcols = 0;
  21112. $this->columns = array();
  21113. } else {
  21114. // maximum column width
  21115. $maxwidth = ($this->w - $this->original_lMargin - $this->original_rMargin) / $numcols;
  21116. if (($width == 0) OR ($width > $maxwidth)) {
  21117. $width = $maxwidth;
  21118. }
  21119. if (TCPDF_STATIC::empty_string($y)) {
  21120. $y = $this->y;
  21121. }
  21122. // space between columns
  21123. $space = (($this->w - $this->original_lMargin - $this->original_rMargin - ($numcols * $width)) / ($numcols - 1));
  21124. // fill the columns array (with, space, starting Y position)
  21125. for ($i = 0; $i < $numcols; ++$i) {
  21126. $this->columns[$i] = array('w' => $width, 's' => $space, 'y' => $y);
  21127. }
  21128. }
  21129. $this->num_columns = $numcols;
  21130. $this->current_column = 0;
  21131. $this->column_start_page = $this->page;
  21132. $this->selectColumn(0);
  21133. }
  21134. /**
  21135. * Remove columns and reset page margins.
  21136. * @public
  21137. * @since 5.9.072 (2011-04-26)
  21138. */
  21139. public function resetColumns() {
  21140. $this->lMargin = $this->original_lMargin;
  21141. $this->rMargin = $this->original_rMargin;
  21142. $this->setEqualColumns();
  21143. }
  21144. /**
  21145. * Set columns array.
  21146. * Each column is represented by an array of arrays with the following keys: (w = width, s = space between columns, y = column top position).
  21147. * @param $columns (array)
  21148. * @public
  21149. * @since 4.9.001 (2010-03-28)
  21150. */
  21151. public function setColumnsArray($columns) {
  21152. $this->columns = $columns;
  21153. $this->num_columns = count($columns);
  21154. $this->current_column = 0;
  21155. $this->column_start_page = $this->page;
  21156. $this->selectColumn(0);
  21157. }
  21158. /**
  21159. * Set position at a given column
  21160. * @param $col (int) column number (from 0 to getNumberOfColumns()-1); empty string = current column.
  21161. * @public
  21162. * @since 4.9.001 (2010-03-28)
  21163. */
  21164. public function selectColumn($col='') {
  21165. if (is_string($col)) {
  21166. $col = $this->current_column;
  21167. } elseif ($col >= $this->num_columns) {
  21168. $col = 0;
  21169. }
  21170. $xshift = array('x' => 0, 's' => array('H' => 0, 'V' => 0), 'p' => array('L' => 0, 'T' => 0, 'R' => 0, 'B' => 0));
  21171. $enable_thead = false;
  21172. if ($this->num_columns > 1) {
  21173. if ($col != $this->current_column) {
  21174. // move Y pointer at the top of the column
  21175. if ($this->column_start_page == $this->page) {
  21176. $this->y = $this->columns[$col]['y'];
  21177. } else {
  21178. $this->y = $this->tMargin;
  21179. }
  21180. // Avoid to write table headers more than once
  21181. if (($this->page > $this->maxselcol['page']) OR (($this->page == $this->maxselcol['page']) AND ($col > $this->maxselcol['column']))) {
  21182. $enable_thead = true;
  21183. $this->maxselcol['page'] = $this->page;
  21184. $this->maxselcol['column'] = $col;
  21185. }
  21186. }
  21187. $xshift = $this->colxshift;
  21188. // set X position of the current column by case
  21189. $listindent = ($this->listindentlevel * $this->listindent);
  21190. // calculate column X position
  21191. $colpos = 0;
  21192. for ($i = 0; $i < $col; ++$i) {
  21193. $colpos += ($this->columns[$i]['w'] + $this->columns[$i]['s']);
  21194. }
  21195. if ($this->rtl) {
  21196. $x = $this->w - $this->original_rMargin - $colpos;
  21197. $this->rMargin = ($this->w - $x + $listindent);
  21198. $this->lMargin = ($x - $this->columns[$col]['w']);
  21199. $this->x = $x - $listindent;
  21200. } else {
  21201. $x = $this->original_lMargin + $colpos;
  21202. $this->lMargin = ($x + $listindent);
  21203. $this->rMargin = ($this->w - $x - $this->columns[$col]['w']);
  21204. $this->x = $x + $listindent;
  21205. }
  21206. $this->columns[$col]['x'] = $x;
  21207. }
  21208. $this->current_column = $col;
  21209. // fix for HTML mode
  21210. $this->newline = true;
  21211. // print HTML table header (if any)
  21212. if ((!TCPDF_STATIC::empty_string($this->thead)) AND (!$this->inthead)) {
  21213. if ($enable_thead) {
  21214. // print table header
  21215. $this->writeHTML($this->thead, false, false, false, false, '');
  21216. $this->y += $xshift['s']['V'];
  21217. // store end of header position
  21218. if (!isset($this->columns[$col]['th'])) {
  21219. $this->columns[$col]['th'] = array();
  21220. }
  21221. $this->columns[$col]['th']['\''.$this->page.'\''] = $this->y;
  21222. $this->lasth = 0;
  21223. } elseif (isset($this->columns[$col]['th']['\''.$this->page.'\''])) {
  21224. $this->y = $this->columns[$col]['th']['\''.$this->page.'\''];
  21225. }
  21226. }
  21227. // account for an html table cell over multiple columns
  21228. if ($this->rtl) {
  21229. $this->rMargin += $xshift['x'];
  21230. $this->x -= ($xshift['x'] + $xshift['p']['R']);
  21231. } else {
  21232. $this->lMargin += $xshift['x'];
  21233. $this->x += $xshift['x'] + $xshift['p']['L'];
  21234. }
  21235. }
  21236. /**
  21237. * Return the current column number
  21238. * @return int current column number
  21239. * @public
  21240. * @since 5.5.011 (2010-07-08)
  21241. */
  21242. public function getColumn() {
  21243. return $this->current_column;
  21244. }
  21245. /**
  21246. * Return the current number of columns.
  21247. * @return int number of columns
  21248. * @public
  21249. * @since 5.8.018 (2010-08-25)
  21250. */
  21251. public function getNumberOfColumns() {
  21252. return $this->num_columns;
  21253. }
  21254. /**
  21255. * Set Text rendering mode.
  21256. * @param $stroke (int) outline size in user units (0 = disable).
  21257. * @param $fill (boolean) if true fills the text (default).
  21258. * @param $clip (boolean) if true activate clipping mode
  21259. * @public
  21260. * @since 4.9.008 (2009-04-02)
  21261. */
  21262. public function setTextRenderingMode($stroke=0, $fill=true, $clip=false) {
  21263. // Ref.: PDF 32000-1:2008 - 9.3.6 Text Rendering Mode
  21264. // convert text rendering parameters
  21265. if ($stroke < 0) {
  21266. $stroke = 0;
  21267. }
  21268. if ($fill === true) {
  21269. if ($stroke > 0) {
  21270. if ($clip === true) {
  21271. // Fill, then stroke text and add to path for clipping
  21272. $textrendermode = 6;
  21273. } else {
  21274. // Fill, then stroke text
  21275. $textrendermode = 2;
  21276. }
  21277. $textstrokewidth = $stroke;
  21278. } else {
  21279. if ($clip === true) {
  21280. // Fill text and add to path for clipping
  21281. $textrendermode = 4;
  21282. } else {
  21283. // Fill text
  21284. $textrendermode = 0;
  21285. }
  21286. }
  21287. } else {
  21288. if ($stroke > 0) {
  21289. if ($clip === true) {
  21290. // Stroke text and add to path for clipping
  21291. $textrendermode = 5;
  21292. } else {
  21293. // Stroke text
  21294. $textrendermode = 1;
  21295. }
  21296. $textstrokewidth = $stroke;
  21297. } else {
  21298. if ($clip === true) {
  21299. // Add text to path for clipping
  21300. $textrendermode = 7;
  21301. } else {
  21302. // Neither fill nor stroke text (invisible)
  21303. $textrendermode = 3;
  21304. }
  21305. }
  21306. }
  21307. $this->textrendermode = $textrendermode;
  21308. $this->textstrokewidth = $stroke;
  21309. }
  21310. /**
  21311. * Set parameters for drop shadow effect for text.
  21312. * @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.
  21313. * @since 5.9.174 (2012-07-25)
  21314. * @public
  21315. */
  21316. public function setTextShadow($params=array('enabled'=>false, 'depth_w'=>0, 'depth_h'=>0, 'color'=>false, 'opacity'=>1, 'blend_mode'=>'Normal')) {
  21317. if (isset($params['enabled'])) {
  21318. $this->txtshadow['enabled'] = $params['enabled']?true:false;
  21319. } else {
  21320. $this->txtshadow['enabled'] = false;
  21321. }
  21322. if (isset($params['depth_w'])) {
  21323. $this->txtshadow['depth_w'] = floatval($params['depth_w']);
  21324. } else {
  21325. $this->txtshadow['depth_w'] = 0;
  21326. }
  21327. if (isset($params['depth_h'])) {
  21328. $this->txtshadow['depth_h'] = floatval($params['depth_h']);
  21329. } else {
  21330. $this->txtshadow['depth_h'] = 0;
  21331. }
  21332. if (isset($params['color']) AND ($params['color'] !== false) AND is_array($params['color'])) {
  21333. $this->txtshadow['color'] = $params['color'];
  21334. } else {
  21335. $this->txtshadow['color'] = $this->strokecolor;
  21336. }
  21337. if (isset($params['opacity'])) {
  21338. $this->txtshadow['opacity'] = min(1, max(0, floatval($params['opacity'])));
  21339. } else {
  21340. $this->txtshadow['opacity'] = 1;
  21341. }
  21342. 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'))) {
  21343. $this->txtshadow['blend_mode'] = $params['blend_mode'];
  21344. } else {
  21345. $this->txtshadow['blend_mode'] = 'Normal';
  21346. }
  21347. if ((($this->txtshadow['depth_w'] == 0) AND ($this->txtshadow['depth_h'] == 0)) OR ($this->txtshadow['opacity'] == 0)) {
  21348. $this->txtshadow['enabled'] = false;
  21349. }
  21350. }
  21351. /**
  21352. * Return the text shadow parameters array.
  21353. * @return Array of parameters.
  21354. * @since 5.9.174 (2012-07-25)
  21355. * @public
  21356. */
  21357. public function getTextShadow() {
  21358. return $this->txtshadow;
  21359. }
  21360. /**
  21361. * Returns an array of chars containing soft hyphens.
  21362. * @param $word (array) array of chars
  21363. * @param $patterns (array) Array of hypenation patterns.
  21364. * @param $dictionary (array) Array of words to be returned without applying the hyphenation algorithm.
  21365. * @param $leftmin (int) Minimum number of character to leave on the left of the word without applying the hyphens.
  21366. * @param $rightmin (int) Minimum number of character to leave on the right of the word without applying the hyphens.
  21367. * @param $charmin (int) Minimum word length to apply the hyphenation algorithm.
  21368. * @param $charmax (int) Maximum length of broken piece of word.
  21369. * @return array text with soft hyphens
  21370. * @author Nicola Asuni
  21371. * @since 4.9.012 (2010-04-12)
  21372. * @protected
  21373. */
  21374. protected function hyphenateWord($word, $patterns, $dictionary=array(), $leftmin=1, $rightmin=2, $charmin=1, $charmax=8) {
  21375. $hyphenword = array(); // hyphens positions
  21376. $numchars = count($word);
  21377. if ($numchars <= $charmin) {
  21378. return $word;
  21379. }
  21380. $word_string = TCPDF_FONTS::UTF8ArrSubString($word, '', '', $this->isunicode);
  21381. // some words will be returned as-is
  21382. $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})(\]?)$/';
  21383. if (preg_match($pattern, $word_string) > 0) {
  21384. // email
  21385. return $word;
  21386. }
  21387. $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})(\]?)$/';
  21388. if (preg_match($pattern, $word_string) > 0) {
  21389. // URL
  21390. return $word;
  21391. }
  21392. if (isset($dictionary[$word_string])) {
  21393. return TCPDF_FONTS::UTF8StringToArray($dictionary[$word_string], $this->isunicode, $this->CurrentFont);
  21394. }
  21395. // surround word with '_' characters
  21396. $tmpword = array_merge(array(46), $word, array(46));
  21397. $tmpnumchars = $numchars + 2;
  21398. $maxpos = $tmpnumchars - 1;
  21399. for ($pos = 0; $pos < $maxpos; ++$pos) {
  21400. $imax = min(($tmpnumchars - $pos), $charmax);
  21401. for ($i = 1; $i <= $imax; ++$i) {
  21402. $subword = strtolower(TCPDF_FONTS::UTF8ArrSubString($tmpword, $pos, ($pos + $i), $this->isunicode));
  21403. if (isset($patterns[$subword])) {
  21404. $pattern = TCPDF_FONTS::UTF8StringToArray($patterns[$subword], $this->isunicode, $this->CurrentFont);
  21405. $pattern_length = count($pattern);
  21406. $digits = 1;
  21407. for ($j = 0; $j < $pattern_length; ++$j) {
  21408. // check if $pattern[$j] is a number = hyphenation level (only numbers from 1 to 5 are valid)
  21409. if (($pattern[$j] >= 48) AND ($pattern[$j] <= 57)) {
  21410. if ($j == 0) {
  21411. $zero = $pos - 1;
  21412. } else {
  21413. $zero = $pos + $j - $digits;
  21414. }
  21415. // get hyphenation level
  21416. $level = ($pattern[$j] - 48);
  21417. // if two levels from two different patterns match at the same point, the higher one is selected.
  21418. if (!isset($hyphenword[$zero]) OR ($hyphenword[$zero] < $level)) {
  21419. $hyphenword[$zero] = $level;
  21420. }
  21421. ++$digits;
  21422. }
  21423. }
  21424. }
  21425. }
  21426. }
  21427. $inserted = 0;
  21428. $maxpos = $numchars - $rightmin;
  21429. for ($i = $leftmin; $i <= $maxpos; ++$i) {
  21430. // only odd levels indicate allowed hyphenation points
  21431. if (isset($hyphenword[$i]) AND (($hyphenword[$i] % 2) != 0)) {
  21432. // 173 = soft hyphen character
  21433. array_splice($word, $i + $inserted, 0, 173);
  21434. ++$inserted;
  21435. }
  21436. }
  21437. return $word;
  21438. }
  21439. /**
  21440. * Returns text with soft hyphens.
  21441. * @param $text (string) text to process
  21442. * @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/
  21443. * @param $dictionary (array) Array of words to be returned without applying the hyphenation algorithm.
  21444. * @param $leftmin (int) Minimum number of character to leave on the left of the word without applying the hyphens.
  21445. * @param $rightmin (int) Minimum number of character to leave on the right of the word without applying the hyphens.
  21446. * @param $charmin (int) Minimum word length to apply the hyphenation algorithm.
  21447. * @param $charmax (int) Maximum length of broken piece of word.
  21448. * @return array text with soft hyphens
  21449. * @author Nicola Asuni
  21450. * @since 4.9.012 (2010-04-12)
  21451. * @public
  21452. */
  21453. public function hyphenateText($text, $patterns, $dictionary=array(), $leftmin=1, $rightmin=2, $charmin=1, $charmax=8) {
  21454. $text = $this->unhtmlentities($text);
  21455. $word = array(); // last word
  21456. $txtarr = array(); // text to be returned
  21457. $intag = false; // true if we are inside an HTML tag
  21458. $skip = false; // true to skip hyphenation
  21459. if (!is_array($patterns)) {
  21460. $patterns = TCPDF_STATIC::getHyphenPatternsFromTEX($patterns);
  21461. }
  21462. // get array of characters
  21463. $unichars = TCPDF_FONTS::UTF8StringToArray($text, $this->isunicode, $this->CurrentFont);
  21464. // for each char
  21465. foreach ($unichars as $char) {
  21466. if ((!$intag) AND (!$skip) AND TCPDF_FONT_DATA::$uni_type[$char] == 'L') {
  21467. // letter character
  21468. $word[] = $char;
  21469. } else {
  21470. // other type of character
  21471. if (!TCPDF_STATIC::empty_string($word)) {
  21472. // hypenate the word
  21473. $txtarr = array_merge($txtarr, $this->hyphenateWord($word, $patterns, $dictionary, $leftmin, $rightmin, $charmin, $charmax));
  21474. $word = array();
  21475. }
  21476. $txtarr[] = $char;
  21477. if (chr($char) == '<') {
  21478. // we are inside an HTML tag
  21479. $intag = true;
  21480. } elseif ($intag AND (chr($char) == '>')) {
  21481. // end of HTML tag
  21482. $intag = false;
  21483. // check for style tag
  21484. $expected = array(115, 116, 121, 108, 101); // = 'style'
  21485. $current = array_slice($txtarr, -6, 5); // last 5 chars
  21486. $compare = array_diff($expected, $current);
  21487. if (empty($compare)) {
  21488. // check if it is a closing tag
  21489. $expected = array(47); // = '/'
  21490. $current = array_slice($txtarr, -7, 1);
  21491. $compare = array_diff($expected, $current);
  21492. if (empty($compare)) {
  21493. // closing style tag
  21494. $skip = false;
  21495. } else {
  21496. // opening style tag
  21497. $skip = true;
  21498. }
  21499. }
  21500. }
  21501. }
  21502. }
  21503. if (!TCPDF_STATIC::empty_string($word)) {
  21504. // hypenate the word
  21505. $txtarr = array_merge($txtarr, $this->hyphenateWord($word, $patterns, $dictionary, $leftmin, $rightmin, $charmin, $charmax));
  21506. }
  21507. // convert char array to string and return
  21508. return TCPDF_FONTS::UTF8ArrSubString($txtarr, '', '', $this->isunicode);
  21509. }
  21510. /**
  21511. * Enable/disable rasterization of vector images using ImageMagick library.
  21512. * @param $mode (boolean) if true enable rasterization, false otherwise.
  21513. * @public
  21514. * @since 5.0.000 (2010-04-27)
  21515. */
  21516. public function setRasterizeVectorImages($mode) {
  21517. $this->rasterize_vector_images = $mode;
  21518. }
  21519. /**
  21520. * Enable or disable default option for font subsetting.
  21521. * @param $enable (boolean) if true enable font subsetting by default.
  21522. * @author Nicola Asuni
  21523. * @public
  21524. * @since 5.3.002 (2010-06-07)
  21525. */
  21526. public function setFontSubsetting($enable=true) {
  21527. if ($this->pdfa_mode) {
  21528. $this->font_subsetting = false;
  21529. } else {
  21530. $this->font_subsetting = $enable ? true : false;
  21531. }
  21532. }
  21533. /**
  21534. * Return the default option for font subsetting.
  21535. * @return boolean default font subsetting state.
  21536. * @author Nicola Asuni
  21537. * @public
  21538. * @since 5.3.002 (2010-06-07)
  21539. */
  21540. public function getFontSubsetting() {
  21541. return $this->font_subsetting;
  21542. }
  21543. /**
  21544. * Left trim the input string
  21545. * @param $str (string) string to trim
  21546. * @param $replace (string) string that replace spaces.
  21547. * @return left trimmed string
  21548. * @author Nicola Asuni
  21549. * @public
  21550. * @since 5.8.000 (2010-08-11)
  21551. */
  21552. public function stringLeftTrim($str, $replace='') {
  21553. return preg_replace('/^'.$this->re_space['p'].'+/'.$this->re_space['m'], $replace, $str);
  21554. }
  21555. /**
  21556. * Right trim the input string
  21557. * @param $str (string) string to trim
  21558. * @param $replace (string) string that replace spaces.
  21559. * @return right trimmed string
  21560. * @author Nicola Asuni
  21561. * @public
  21562. * @since 5.8.000 (2010-08-11)
  21563. */
  21564. public function stringRightTrim($str, $replace='') {
  21565. return preg_replace('/'.$this->re_space['p'].'+$/'.$this->re_space['m'], $replace, $str);
  21566. }
  21567. /**
  21568. * Trim the input string
  21569. * @param $str (string) string to trim
  21570. * @param $replace (string) string that replace spaces.
  21571. * @return trimmed string
  21572. * @author Nicola Asuni
  21573. * @public
  21574. * @since 5.8.000 (2010-08-11)
  21575. */
  21576. public function stringTrim($str, $replace='') {
  21577. $str = $this->stringLeftTrim($str, $replace);
  21578. $str = $this->stringRightTrim($str, $replace);
  21579. return $str;
  21580. }
  21581. /**
  21582. * Return true if the current font is unicode type.
  21583. * @return true for unicode font, false otherwise.
  21584. * @author Nicola Asuni
  21585. * @public
  21586. * @since 5.8.002 (2010-08-14)
  21587. */
  21588. public function isUnicodeFont() {
  21589. return (($this->CurrentFont['type'] == 'TrueTypeUnicode') OR ($this->CurrentFont['type'] == 'cidfont0'));
  21590. }
  21591. /**
  21592. * Return normalized font name
  21593. * @param $fontfamily (string) property string containing font family names
  21594. * @return string normalized font name
  21595. * @author Nicola Asuni
  21596. * @public
  21597. * @since 5.8.004 (2010-08-17)
  21598. */
  21599. public function getFontFamilyName($fontfamily) {
  21600. // remove spaces and symbols
  21601. $fontfamily = preg_replace('/[^a-z0-9_\,]/', '', strtolower($fontfamily));
  21602. // extract all font names
  21603. $fontslist = preg_split('/[,]/', $fontfamily);
  21604. // find first valid font name
  21605. foreach ($fontslist as $font) {
  21606. // replace font variations
  21607. $font = preg_replace('/regular$/', '', $font);
  21608. $font = preg_replace('/italic$/', 'I', $font);
  21609. $font = preg_replace('/oblique$/', 'I', $font);
  21610. $font = preg_replace('/bold([I]?)$/', 'B\\1', $font);
  21611. // replace common family names and core fonts
  21612. $pattern = array();
  21613. $replacement = array();
  21614. $pattern[] = '/^serif|^cursive|^fantasy|^timesnewroman/';
  21615. $replacement[] = 'times';
  21616. $pattern[] = '/^sansserif/';
  21617. $replacement[] = 'helvetica';
  21618. $pattern[] = '/^monospace/';
  21619. $replacement[] = 'courier';
  21620. $font = preg_replace($pattern, $replacement, $font);
  21621. if (in_array(strtolower($font), $this->fontlist) OR in_array($font, $this->fontkeys)) {
  21622. return $font;
  21623. }
  21624. }
  21625. // return current font as default
  21626. return $this->CurrentFont['fontkey'];
  21627. }
  21628. /**
  21629. * Start a new XObject Template.
  21630. * 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).
  21631. * 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.
  21632. * Note: X,Y coordinates will be reset to 0,0.
  21633. * @param $w (int) Template width in user units (empty string or zero = page width less margins).
  21634. * @param $h (int) Template height in user units (empty string or zero = page height less margins).
  21635. * @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).
  21636. * @return int the XObject Template ID in case of success or false in case of error.
  21637. * @author Nicola Asuni
  21638. * @public
  21639. * @since 5.8.017 (2010-08-24)
  21640. * @see endTemplate(), printTemplate()
  21641. */
  21642. public function startTemplate($w=0, $h=0, $group=false) {
  21643. if ($this->inxobj) {
  21644. // we are already inside an XObject template
  21645. return false;
  21646. }
  21647. $this->inxobj = true;
  21648. ++$this->n;
  21649. // XObject ID
  21650. $this->xobjid = 'XT'.$this->n;
  21651. // object ID
  21652. $this->xobjects[$this->xobjid] = array('n' => $this->n);
  21653. // store current graphic state
  21654. $this->xobjects[$this->xobjid]['gvars'] = $this->getGraphicVars();
  21655. // initialize data
  21656. $this->xobjects[$this->xobjid]['intmrk'] = 0;
  21657. $this->xobjects[$this->xobjid]['transfmrk'] = array();
  21658. $this->xobjects[$this->xobjid]['outdata'] = '';
  21659. $this->xobjects[$this->xobjid]['xobjects'] = array();
  21660. $this->xobjects[$this->xobjid]['images'] = array();
  21661. $this->xobjects[$this->xobjid]['fonts'] = array();
  21662. $this->xobjects[$this->xobjid]['annotations'] = array();
  21663. $this->xobjects[$this->xobjid]['extgstates'] = array();
  21664. $this->xobjects[$this->xobjid]['gradients'] = array();
  21665. $this->xobjects[$this->xobjid]['spot_colors'] = array();
  21666. // set new environment
  21667. $this->num_columns = 1;
  21668. $this->current_column = 0;
  21669. $this->SetAutoPageBreak(false);
  21670. if (($w === '') OR ($w <= 0)) {
  21671. $w = $this->w - $this->lMargin - $this->rMargin;
  21672. }
  21673. if (($h === '') OR ($h <= 0)) {
  21674. $h = $this->h - $this->tMargin - $this->bMargin;
  21675. }
  21676. $this->xobjects[$this->xobjid]['x'] = 0;
  21677. $this->xobjects[$this->xobjid]['y'] = 0;
  21678. $this->xobjects[$this->xobjid]['w'] = $w;
  21679. $this->xobjects[$this->xobjid]['h'] = $h;
  21680. $this->w = $w;
  21681. $this->h = $h;
  21682. $this->wPt = $this->w * $this->k;
  21683. $this->hPt = $this->h * $this->k;
  21684. $this->fwPt = $this->wPt;
  21685. $this->fhPt = $this->hPt;
  21686. $this->x = 0;
  21687. $this->y = 0;
  21688. $this->lMargin = 0;
  21689. $this->rMargin = 0;
  21690. $this->tMargin = 0;
  21691. $this->bMargin = 0;
  21692. // set group mode
  21693. $this->xobjects[$this->xobjid]['group'] = $group;
  21694. return $this->xobjid;
  21695. }
  21696. /**
  21697. * End the current XObject Template started with startTemplate() and restore the previous graphic state.
  21698. * 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).
  21699. * 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.
  21700. * @return int the XObject Template ID in case of success or false in case of error.
  21701. * @author Nicola Asuni
  21702. * @public
  21703. * @since 5.8.017 (2010-08-24)
  21704. * @see startTemplate(), printTemplate()
  21705. */
  21706. public function endTemplate() {
  21707. if (!$this->inxobj) {
  21708. // we are not inside a template
  21709. return false;
  21710. }
  21711. $this->inxobj = false;
  21712. // restore previous graphic state
  21713. $this->setGraphicVars($this->xobjects[$this->xobjid]['gvars'], true);
  21714. return $this->xobjid;
  21715. }
  21716. /**
  21717. * Print an XObject Template.
  21718. * You can print an XObject Template inside the currently opened Template.
  21719. * 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).
  21720. * 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.
  21721. * @param $id (string) The ID of XObject Template to print.
  21722. * @param $x (int) X position in user units (empty string = current x position)
  21723. * @param $y (int) Y position in user units (empty string = current y position)
  21724. * @param $w (int) Width in user units (zero = remaining page width)
  21725. * @param $h (int) Height in user units (zero = remaining page height)
  21726. * @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>
  21727. * @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>
  21728. * @param $fitonpage (boolean) If true the template is resized to not exceed page dimensions.
  21729. * @author Nicola Asuni
  21730. * @public
  21731. * @since 5.8.017 (2010-08-24)
  21732. * @see startTemplate(), endTemplate()
  21733. */
  21734. public function printTemplate($id, $x='', $y='', $w=0, $h=0, $align='', $palign='', $fitonpage=false) {
  21735. if ($this->state != 2) {
  21736. return;
  21737. }
  21738. if (!isset($this->xobjects[$id])) {
  21739. $this->Error('The XObject Template \''.$id.'\' doesn\'t exist!');
  21740. }
  21741. if ($this->inxobj) {
  21742. if ($id == $this->xobjid) {
  21743. // close current template
  21744. $this->endTemplate();
  21745. } else {
  21746. // use the template as resource for the template currently opened
  21747. $this->xobjects[$this->xobjid]['xobjects'][$id] = $this->xobjects[$id];
  21748. }
  21749. }
  21750. // set default values
  21751. if ($x === '') {
  21752. $x = $this->x;
  21753. }
  21754. if ($y === '') {
  21755. $y = $this->y;
  21756. }
  21757. // check page for no-write regions and adapt page margins if necessary
  21758. list($x, $y) = $this->checkPageRegions($h, $x, $y);
  21759. $ow = $this->xobjects[$id]['w'];
  21760. if ($ow <= 0) {
  21761. $ow = 1;
  21762. }
  21763. $oh = $this->xobjects[$id]['h'];
  21764. if ($oh <= 0) {
  21765. $oh = 1;
  21766. }
  21767. // calculate template width and height on document
  21768. if (($w <= 0) AND ($h <= 0)) {
  21769. $w = $ow;
  21770. $h = $oh;
  21771. } elseif ($w <= 0) {
  21772. $w = $h * $ow / $oh;
  21773. } elseif ($h <= 0) {
  21774. $h = $w * $oh / $ow;
  21775. }
  21776. // fit the template on available space
  21777. list($w, $h, $x, $y) = $this->fitBlock($w, $h, $x, $y, $fitonpage);
  21778. // set page alignment
  21779. $rb_y = $y + $h;
  21780. // set alignment
  21781. if ($this->rtl) {
  21782. if ($palign == 'L') {
  21783. $xt = $this->lMargin;
  21784. } elseif ($palign == 'C') {
  21785. $xt = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
  21786. } elseif ($palign == 'R') {
  21787. $xt = $this->w - $this->rMargin - $w;
  21788. } else {
  21789. $xt = $x - $w;
  21790. }
  21791. $rb_x = $xt;
  21792. } else {
  21793. if ($palign == 'L') {
  21794. $xt = $this->lMargin;
  21795. } elseif ($palign == 'C') {
  21796. $xt = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
  21797. } elseif ($palign == 'R') {
  21798. $xt = $this->w - $this->rMargin - $w;
  21799. } else {
  21800. $xt = $x;
  21801. }
  21802. $rb_x = $xt + $w;
  21803. }
  21804. // print XObject Template + Transformation matrix
  21805. $this->StartTransform();
  21806. // translate and scale
  21807. $sx = ($w / $ow);
  21808. $sy = ($h / $oh);
  21809. $tm = array();
  21810. $tm[0] = $sx;
  21811. $tm[1] = 0;
  21812. $tm[2] = 0;
  21813. $tm[3] = $sy;
  21814. $tm[4] = $xt * $this->k;
  21815. $tm[5] = ($this->h - $h - $y) * $this->k;
  21816. $this->Transform($tm);
  21817. // set object
  21818. $this->_out('/'.$id.' Do');
  21819. $this->StopTransform();
  21820. // add annotations
  21821. if (!empty($this->xobjects[$id]['annotations'])) {
  21822. foreach ($this->xobjects[$id]['annotations'] as $annot) {
  21823. // transform original coordinates
  21824. $coordlt = TCPDF_STATIC::getTransformationMatrixProduct($tm, array(1, 0, 0, 1, ($annot['x'] * $this->k), (-$annot['y'] * $this->k)));
  21825. $ax = ($coordlt[4] / $this->k);
  21826. $ay = ($this->h - $h - ($coordlt[5] / $this->k));
  21827. $coordrb = TCPDF_STATIC::getTransformationMatrixProduct($tm, array(1, 0, 0, 1, (($annot['x'] + $annot['w']) * $this->k), ((-$annot['y'] - $annot['h']) * $this->k)));
  21828. $aw = ($coordrb[4] / $this->k) - $ax;
  21829. $ah = ($this->h - $h - ($coordrb[5] / $this->k)) - $ay;
  21830. $this->Annotation($ax, $ay, $aw, $ah, $annot['text'], $annot['opt'], $annot['spaces']);
  21831. }
  21832. }
  21833. // set pointer to align the next text/objects
  21834. switch($align) {
  21835. case 'T': {
  21836. $this->y = $y;
  21837. $this->x = $rb_x;
  21838. break;
  21839. }
  21840. case 'M': {
  21841. $this->y = $y + round($h/2);
  21842. $this->x = $rb_x;
  21843. break;
  21844. }
  21845. case 'B': {
  21846. $this->y = $rb_y;
  21847. $this->x = $rb_x;
  21848. break;
  21849. }
  21850. case 'N': {
  21851. $this->SetY($rb_y);
  21852. break;
  21853. }
  21854. default:{
  21855. break;
  21856. }
  21857. }
  21858. }
  21859. /**
  21860. * Set the percentage of character stretching.
  21861. * @param $perc (int) percentage of stretching (100 = no stretching)
  21862. * @author Nicola Asuni
  21863. * @public
  21864. * @since 5.9.000 (2010-09-29)
  21865. */
  21866. public function setFontStretching($perc=100) {
  21867. $this->font_stretching = $perc;
  21868. }
  21869. /**
  21870. * Get the percentage of character stretching.
  21871. * @return float stretching value
  21872. * @author Nicola Asuni
  21873. * @public
  21874. * @since 5.9.000 (2010-09-29)
  21875. */
  21876. public function getFontStretching() {
  21877. return $this->font_stretching;
  21878. }
  21879. /**
  21880. * Set the amount to increase or decrease the space between characters in a text.
  21881. * @param $spacing (float) amount to increase or decrease the space between characters in a text (0 = default spacing)
  21882. * @author Nicola Asuni
  21883. * @public
  21884. * @since 5.9.000 (2010-09-29)
  21885. */
  21886. public function setFontSpacing($spacing=0) {
  21887. $this->font_spacing = $spacing;
  21888. }
  21889. /**
  21890. * Get the amount to increase or decrease the space between characters in a text.
  21891. * @return int font spacing (tracking) value
  21892. * @author Nicola Asuni
  21893. * @public
  21894. * @since 5.9.000 (2010-09-29)
  21895. */
  21896. public function getFontSpacing() {
  21897. return $this->font_spacing;
  21898. }
  21899. /**
  21900. * Return an array of no-write page regions
  21901. * @return array of no-write page regions
  21902. * @author Nicola Asuni
  21903. * @public
  21904. * @since 5.9.003 (2010-10-13)
  21905. * @see setPageRegions(), addPageRegion()
  21906. */
  21907. public function getPageRegions() {
  21908. return $this->page_regions;
  21909. }
  21910. /**
  21911. * Set no-write regions on page.
  21912. * 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.
  21913. * A region is always aligned on the left or right side of the page ad is defined using a vertical segment.
  21914. * You can set multiple regions for the same page.
  21915. * @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.
  21916. * @author Nicola Asuni
  21917. * @public
  21918. * @since 5.9.003 (2010-10-13)
  21919. * @see addPageRegion(), getPageRegions()
  21920. */
  21921. public function setPageRegions($regions=array()) {
  21922. // empty current regions array
  21923. $this->page_regions = array();
  21924. // add regions
  21925. foreach ($regions as $data) {
  21926. $this->addPageRegion($data);
  21927. }
  21928. }
  21929. /**
  21930. * Add a single no-write region on selected page.
  21931. * 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.
  21932. * A region is always aligned on the left or right side of the page ad is defined using a vertical segment.
  21933. * You can set multiple regions for the same page.
  21934. * @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).
  21935. * @author Nicola Asuni
  21936. * @public
  21937. * @since 5.9.003 (2010-10-13)
  21938. * @see setPageRegions(), getPageRegions()
  21939. */
  21940. public function addPageRegion($region) {
  21941. if (!isset($region['page']) OR empty($region['page'])) {
  21942. $region['page'] = $this->page;
  21943. }
  21944. if (isset($region['xt']) AND isset($region['xb']) AND ($region['xt'] > 0) AND ($region['xb'] > 0)
  21945. AND isset($region['yt']) AND isset($region['yb']) AND ($region['yt'] >= 0) AND ($region['yt'] < $region['yb'])
  21946. AND isset($region['side']) AND (($region['side'] == 'L') OR ($region['side'] == 'R'))) {
  21947. $this->page_regions[] = $region;
  21948. }
  21949. }
  21950. /**
  21951. * Remove a single no-write region.
  21952. * @param $key (int) region key
  21953. * @author Nicola Asuni
  21954. * @public
  21955. * @since 5.9.003 (2010-10-13)
  21956. * @see setPageRegions(), getPageRegions()
  21957. */
  21958. public function removePageRegion($key) {
  21959. if (isset($this->page_regions[$key])) {
  21960. unset($this->page_regions[$key]);
  21961. }
  21962. }
  21963. /**
  21964. * Check page for no-write regions and adapt current coordinates and page margins if necessary.
  21965. * 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.
  21966. * A region is always aligned on the left or right side of the page ad is defined using a vertical segment.
  21967. * @param $h (float) height of the text/image/object to print in user units
  21968. * @param $x (float) current X coordinate in user units
  21969. * @param $y (float) current Y coordinate in user units
  21970. * @return array($x, $y)
  21971. * @author Nicola Asuni
  21972. * @protected
  21973. * @since 5.9.003 (2010-10-13)
  21974. */
  21975. protected function checkPageRegions($h, $x, $y) {
  21976. // set default values
  21977. if ($x === '') {
  21978. $x = $this->x;
  21979. }
  21980. if ($y === '') {
  21981. $y = $this->y;
  21982. }
  21983. if (!$this->check_page_regions OR empty($this->page_regions)) {
  21984. // no page regions defined
  21985. return array($x, $y);
  21986. }
  21987. if (empty($h)) {
  21988. $h = $this->getCellHeight($this->FontSize);
  21989. }
  21990. // check for page break
  21991. if ($this->checkPageBreak($h, $y)) {
  21992. // the content will be printed on a new page
  21993. $x = $this->x;
  21994. $y = $this->y;
  21995. }
  21996. if ($this->num_columns > 1) {
  21997. if ($this->rtl) {
  21998. $this->lMargin = ($this->columns[$this->current_column]['x'] - $this->columns[$this->current_column]['w']);
  21999. } else {
  22000. $this->rMargin = ($this->w - $this->columns[$this->current_column]['x'] - $this->columns[$this->current_column]['w']);
  22001. }
  22002. } else {
  22003. if ($this->rtl) {
  22004. $this->lMargin = max($this->clMargin, $this->original_lMargin);
  22005. } else {
  22006. $this->rMargin = max($this->crMargin, $this->original_rMargin);
  22007. }
  22008. }
  22009. // adjust coordinates and page margins
  22010. foreach ($this->page_regions as $regid => $regdata) {
  22011. if ($regdata['page'] == $this->page) {
  22012. // check region boundaries
  22013. if (($y > ($regdata['yt'] - $h)) AND ($y <= $regdata['yb'])) {
  22014. // Y is inside the region
  22015. $minv = ($regdata['xb'] - $regdata['xt']) / ($regdata['yb'] - $regdata['yt']); // inverse of angular coefficient
  22016. $yt = max($y, $regdata['yt']);
  22017. $yb = min(($yt + $h), $regdata['yb']);
  22018. $xt = (($yt - $regdata['yt']) * $minv) + $regdata['xt'];
  22019. $xb = (($yb - $regdata['yt']) * $minv) + $regdata['xt'];
  22020. if ($regdata['side'] == 'L') { // left side
  22021. $new_margin = max($xt, $xb);
  22022. if ($this->lMargin < $new_margin) {
  22023. if ($this->rtl) {
  22024. // adjust left page margin
  22025. $this->lMargin = max(0, $new_margin);
  22026. }
  22027. if ($x < $new_margin) {
  22028. // adjust x position
  22029. $x = $new_margin;
  22030. if ($new_margin > ($this->w - $this->rMargin)) {
  22031. // adjust y position
  22032. $y = $regdata['yb'] - $h;
  22033. }
  22034. }
  22035. }
  22036. } elseif ($regdata['side'] == 'R') { // right side
  22037. $new_margin = min($xt, $xb);
  22038. if (($this->w - $this->rMargin) > $new_margin) {
  22039. if (!$this->rtl) {
  22040. // adjust right page margin
  22041. $this->rMargin = max(0, ($this->w - $new_margin));
  22042. }
  22043. if ($x > $new_margin) {
  22044. // adjust x position
  22045. $x = $new_margin;
  22046. if ($new_margin > $this->lMargin) {
  22047. // adjust y position
  22048. $y = $regdata['yb'] - $h;
  22049. }
  22050. }
  22051. }
  22052. }
  22053. }
  22054. }
  22055. }
  22056. return array($x, $y);
  22057. }
  22058. // --- SVG METHODS ---------------------------------------------------------
  22059. /**
  22060. * Embedd a Scalable Vector Graphics (SVG) image.
  22061. * NOTE: SVG standard is not yet fully implemented, use the setRasterizeVectorImages() method to enable/disable rasterization of vector images using ImageMagick library.
  22062. * @param $file (string) Name of the SVG file or a '@' character followed by the SVG data string.
  22063. * @param $x (float) Abscissa of the upper-left corner.
  22064. * @param $y (float) Ordinate of the upper-left corner.
  22065. * @param $w (float) Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
  22066. * @param $h (float) Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
  22067. * @param $link (mixed) URL or identifier returned by AddLink().
  22068. * @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.
  22069. * @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>
  22070. * @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)))
  22071. * @param $fitonpage (boolean) if true the image is resized to not exceed page dimensions.
  22072. * @author Nicola Asuni
  22073. * @since 5.0.000 (2010-05-02)
  22074. * @public
  22075. */
  22076. public function ImageSVG($file, $x='', $y='', $w=0, $h=0, $link='', $align='', $palign='', $border=0, $fitonpage=false) {
  22077. if ($this->state != 2) {
  22078. return;
  22079. }
  22080. // reset SVG vars
  22081. $this->svggradients = array();
  22082. $this->svggradientid = 0;
  22083. $this->svgdefsmode = false;
  22084. $this->svgdefs = array();
  22085. $this->svgclipmode = false;
  22086. $this->svgclippaths = array();
  22087. $this->svgcliptm = array();
  22088. $this->svgclipid = 0;
  22089. $this->svgtext = '';
  22090. $this->svgtextmode = array();
  22091. if ($this->rasterize_vector_images AND ($w > 0) AND ($h > 0)) {
  22092. // convert SVG to raster image using GD or ImageMagick libraries
  22093. return $this->Image($file, $x, $y, $w, $h, 'SVG', $link, $align, true, 300, $palign, false, false, $border, false, false, false);
  22094. }
  22095. if ($file[0] === '@') { // image from string
  22096. $this->svgdir = '';
  22097. $svgdata = substr($file, 1);
  22098. } else { // SVG file
  22099. $this->svgdir = dirname($file);
  22100. $svgdata = TCPDF_STATIC::fileGetContents($file);
  22101. }
  22102. if ($svgdata === FALSE) {
  22103. $this->Error('SVG file not found: '.$file);
  22104. }
  22105. if ($x === '') {
  22106. $x = $this->x;
  22107. }
  22108. if ($y === '') {
  22109. $y = $this->y;
  22110. }
  22111. // check page for no-write regions and adapt page margins if necessary
  22112. list($x, $y) = $this->checkPageRegions($h, $x, $y);
  22113. $k = $this->k;
  22114. $ox = 0;
  22115. $oy = 0;
  22116. $ow = $w;
  22117. $oh = $h;
  22118. $aspect_ratio_align = 'xMidYMid';
  22119. $aspect_ratio_ms = 'meet';
  22120. $regs = array();
  22121. // get original image width and height
  22122. preg_match('/<svg([^\>]*)>/si', $svgdata, $regs);
  22123. if (isset($regs[1]) AND !empty($regs[1])) {
  22124. $tmp = array();
  22125. if (preg_match('/[\s]+x[\s]*=[\s]*"([^"]*)"/si', $regs[1], $tmp)) {
  22126. $ox = $this->getHTMLUnitToUnits($tmp[1], 0, $this->svgunit, false);
  22127. }
  22128. $tmp = array();
  22129. if (preg_match('/[\s]+y[\s]*=[\s]*"([^"]*)"/si', $regs[1], $tmp)) {
  22130. $oy = $this->getHTMLUnitToUnits($tmp[1], 0, $this->svgunit, false);
  22131. }
  22132. $tmp = array();
  22133. if (preg_match('/[\s]+width[\s]*=[\s]*"([^"]*)"/si', $regs[1], $tmp)) {
  22134. $ow = $this->getHTMLUnitToUnits($tmp[1], 1, $this->svgunit, false);
  22135. }
  22136. $tmp = array();
  22137. if (preg_match('/[\s]+height[\s]*=[\s]*"([^"]*)"/si', $regs[1], $tmp)) {
  22138. $oh = $this->getHTMLUnitToUnits($tmp[1], 1, $this->svgunit, false);
  22139. }
  22140. $tmp = array();
  22141. $view_box = array();
  22142. if (preg_match('/[\s]+viewBox[\s]*=[\s]*"[\s]*([0-9\.\-]+)[\s]+([0-9\.\-]+)[\s]+([0-9\.]+)[\s]+([0-9\.]+)[\s]*"/si', $regs[1], $tmp)) {
  22143. if (count($tmp) == 5) {
  22144. array_shift($tmp);
  22145. foreach ($tmp as $key => $val) {
  22146. $view_box[$key] = $this->getHTMLUnitToUnits($val, 0, $this->svgunit, false);
  22147. }
  22148. $ox = $view_box[0];
  22149. $oy = $view_box[1];
  22150. }
  22151. // get aspect ratio
  22152. $tmp = array();
  22153. if (preg_match('/[\s]+preserveAspectRatio[\s]*=[\s]*"([^"]*)"/si', $regs[1], $tmp)) {
  22154. $aspect_ratio = preg_split('/[\s]+/si', $tmp[1]);
  22155. switch (count($aspect_ratio)) {
  22156. case 3: {
  22157. $aspect_ratio_align = $aspect_ratio[1];
  22158. $aspect_ratio_ms = $aspect_ratio[2];
  22159. break;
  22160. }
  22161. case 2: {
  22162. $aspect_ratio_align = $aspect_ratio[0];
  22163. $aspect_ratio_ms = $aspect_ratio[1];
  22164. break;
  22165. }
  22166. case 1: {
  22167. $aspect_ratio_align = $aspect_ratio[0];
  22168. $aspect_ratio_ms = 'meet';
  22169. break;
  22170. }
  22171. }
  22172. }
  22173. }
  22174. }
  22175. if ($ow <= 0) {
  22176. $ow = 1;
  22177. }
  22178. if ($oh <= 0) {
  22179. $oh = 1;
  22180. }
  22181. // calculate image width and height on document
  22182. if (($w <= 0) AND ($h <= 0)) {
  22183. // convert image size to document unit
  22184. $w = $ow;
  22185. $h = $oh;
  22186. } elseif ($w <= 0) {
  22187. $w = $h * $ow / $oh;
  22188. } elseif ($h <= 0) {
  22189. $h = $w * $oh / $ow;
  22190. }
  22191. // fit the image on available space
  22192. list($w, $h, $x, $y) = $this->fitBlock($w, $h, $x, $y, $fitonpage);
  22193. if ($this->rasterize_vector_images) {
  22194. // convert SVG to raster image using GD or ImageMagick libraries
  22195. return $this->Image($file, $x, $y, $w, $h, 'SVG', $link, $align, true, 300, $palign, false, false, $border, false, false, false);
  22196. }
  22197. // set alignment
  22198. $this->img_rb_y = $y + $h;
  22199. // set alignment
  22200. if ($this->rtl) {
  22201. if ($palign == 'L') {
  22202. $ximg = $this->lMargin;
  22203. } elseif ($palign == 'C') {
  22204. $ximg = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
  22205. } elseif ($palign == 'R') {
  22206. $ximg = $this->w - $this->rMargin - $w;
  22207. } else {
  22208. $ximg = $x - $w;
  22209. }
  22210. $this->img_rb_x = $ximg;
  22211. } else {
  22212. if ($palign == 'L') {
  22213. $ximg = $this->lMargin;
  22214. } elseif ($palign == 'C') {
  22215. $ximg = ($this->w + $this->lMargin - $this->rMargin - $w) / 2;
  22216. } elseif ($palign == 'R') {
  22217. $ximg = $this->w - $this->rMargin - $w;
  22218. } else {
  22219. $ximg = $x;
  22220. }
  22221. $this->img_rb_x = $ximg + $w;
  22222. }
  22223. // store current graphic vars
  22224. $gvars = $this->getGraphicVars();
  22225. // store SVG position and scale factors
  22226. $svgoffset_x = ($ximg - $ox) * $this->k;
  22227. $svgoffset_y = -($y - $oy) * $this->k;
  22228. if (isset($view_box[2]) AND ($view_box[2] > 0) AND ($view_box[3] > 0)) {
  22229. $ow = $view_box[2];
  22230. $oh = $view_box[3];
  22231. } else {
  22232. if ($ow <= 0) {
  22233. $ow = $w;
  22234. }
  22235. if ($oh <= 0) {
  22236. $oh = $h;
  22237. }
  22238. }
  22239. $svgscale_x = $w / $ow;
  22240. $svgscale_y = $h / $oh;
  22241. // scaling and alignment
  22242. if ($aspect_ratio_align != 'none') {
  22243. // store current scaling values
  22244. $svgscale_old_x = $svgscale_x;
  22245. $svgscale_old_y = $svgscale_y;
  22246. // force uniform scaling
  22247. if ($aspect_ratio_ms == 'slice') {
  22248. // the entire viewport is covered by the viewBox
  22249. if ($svgscale_x > $svgscale_y) {
  22250. $svgscale_y = $svgscale_x;
  22251. } elseif ($svgscale_x < $svgscale_y) {
  22252. $svgscale_x = $svgscale_y;
  22253. }
  22254. } else { // meet
  22255. // the entire viewBox is visible within the viewport
  22256. if ($svgscale_x < $svgscale_y) {
  22257. $svgscale_y = $svgscale_x;
  22258. } elseif ($svgscale_x > $svgscale_y) {
  22259. $svgscale_x = $svgscale_y;
  22260. }
  22261. }
  22262. // correct X alignment
  22263. switch (substr($aspect_ratio_align, 1, 3)) {
  22264. case 'Min': {
  22265. // do nothing
  22266. break;
  22267. }
  22268. case 'Max': {
  22269. $svgoffset_x += (($w * $this->k) - ($ow * $this->k * $svgscale_x));
  22270. break;
  22271. }
  22272. default:
  22273. case 'Mid': {
  22274. $svgoffset_x += ((($w * $this->k) - ($ow * $this->k * $svgscale_x)) / 2);
  22275. break;
  22276. }
  22277. }
  22278. // correct Y alignment
  22279. switch (substr($aspect_ratio_align, 5)) {
  22280. case 'Min': {
  22281. // do nothing
  22282. break;
  22283. }
  22284. case 'Max': {
  22285. $svgoffset_y -= (($h * $this->k) - ($oh * $this->k * $svgscale_y));
  22286. break;
  22287. }
  22288. default:
  22289. case 'Mid': {
  22290. $svgoffset_y -= ((($h * $this->k) - ($oh * $this->k * $svgscale_y)) / 2);
  22291. break;
  22292. }
  22293. }
  22294. }
  22295. // store current page break mode
  22296. $page_break_mode = $this->AutoPageBreak;
  22297. $page_break_margin = $this->getBreakMargin();
  22298. $cell_padding = $this->cell_padding;
  22299. $this->SetCellPadding(0);
  22300. $this->SetAutoPageBreak(false);
  22301. // save the current graphic state
  22302. $this->_out('q'.$this->epsmarker);
  22303. // set initial clipping mask
  22304. $this->Rect($ximg, $y, $w, $h, 'CNZ', array(), array());
  22305. // scale and translate
  22306. $e = $ox * $this->k * (1 - $svgscale_x);
  22307. $f = ($this->h - $oy) * $this->k * (1 - $svgscale_y);
  22308. $this->_out(sprintf('%F %F %F %F %F %F cm', $svgscale_x, 0, 0, $svgscale_y, ($e + $svgoffset_x), ($f + $svgoffset_y)));
  22309. // creates a new XML parser to be used by the other XML functions
  22310. $this->parser = xml_parser_create('UTF-8');
  22311. // the following function allows to use parser inside object
  22312. xml_set_object($this->parser, $this);
  22313. // disable case-folding for this XML parser
  22314. xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0);
  22315. // sets the element handler functions for the XML parser
  22316. xml_set_element_handler($this->parser, 'startSVGElementHandler', 'endSVGElementHandler');
  22317. // sets the character data handler function for the XML parser
  22318. xml_set_character_data_handler($this->parser, 'segSVGContentHandler');
  22319. // start parsing an XML document
  22320. if (!xml_parse($this->parser, $svgdata)) {
  22321. $error_message = sprintf('SVG Error: %s at line %d', xml_error_string(xml_get_error_code($this->parser)), xml_get_current_line_number($this->parser));
  22322. $this->Error($error_message);
  22323. }
  22324. // free this XML parser
  22325. xml_parser_free($this->parser);
  22326. // restore previous graphic state
  22327. $this->_out($this->epsmarker.'Q');
  22328. // restore graphic vars
  22329. $this->setGraphicVars($gvars);
  22330. $this->lasth = $gvars['lasth'];
  22331. if (!empty($border)) {
  22332. $bx = $this->x;
  22333. $by = $this->y;
  22334. $this->x = $ximg;
  22335. if ($this->rtl) {
  22336. $this->x += $w;
  22337. }
  22338. $this->y = $y;
  22339. $this->Cell($w, $h, '', $border, 0, '', 0, '', 0, true);
  22340. $this->x = $bx;
  22341. $this->y = $by;
  22342. }
  22343. if ($link) {
  22344. $this->Link($ximg, $y, $w, $h, $link, 0);
  22345. }
  22346. // set pointer to align the next text/objects
  22347. switch($align) {
  22348. case 'T':{
  22349. $this->y = $y;
  22350. $this->x = $this->img_rb_x;
  22351. break;
  22352. }
  22353. case 'M':{
  22354. $this->y = $y + round($h/2);
  22355. $this->x = $this->img_rb_x;
  22356. break;
  22357. }
  22358. case 'B':{
  22359. $this->y = $this->img_rb_y;
  22360. $this->x = $this->img_rb_x;
  22361. break;
  22362. }
  22363. case 'N':{
  22364. $this->SetY($this->img_rb_y);
  22365. break;
  22366. }
  22367. default:{
  22368. // restore pointer to starting position
  22369. $this->x = $gvars['x'];
  22370. $this->y = $gvars['y'];
  22371. $this->page = $gvars['page'];
  22372. $this->current_column = $gvars['current_column'];
  22373. $this->tMargin = $gvars['tMargin'];
  22374. $this->bMargin = $gvars['bMargin'];
  22375. $this->w = $gvars['w'];
  22376. $this->h = $gvars['h'];
  22377. $this->wPt = $gvars['wPt'];
  22378. $this->hPt = $gvars['hPt'];
  22379. $this->fwPt = $gvars['fwPt'];
  22380. $this->fhPt = $gvars['fhPt'];
  22381. break;
  22382. }
  22383. }
  22384. $this->endlinex = $this->img_rb_x;
  22385. // restore page break
  22386. $this->SetAutoPageBreak($page_break_mode, $page_break_margin);
  22387. $this->cell_padding = $cell_padding;
  22388. }
  22389. /**
  22390. * Convert SVG transformation matrix to PDF.
  22391. * @param $tm (array) original SVG transformation matrix
  22392. * @return array transformation matrix
  22393. * @protected
  22394. * @since 5.0.000 (2010-05-02)
  22395. */
  22396. protected function convertSVGtMatrix($tm) {
  22397. $a = $tm[0];
  22398. $b = -$tm[1];
  22399. $c = -$tm[2];
  22400. $d = $tm[3];
  22401. $e = $this->getHTMLUnitToUnits($tm[4], 1, $this->svgunit, false) * $this->k;
  22402. $f = -$this->getHTMLUnitToUnits($tm[5], 1, $this->svgunit, false) * $this->k;
  22403. $x = 0;
  22404. $y = $this->h * $this->k;
  22405. $e = ($x * (1 - $a)) - ($y * $c) + $e;
  22406. $f = ($y * (1 - $d)) - ($x * $b) + $f;
  22407. return array($a, $b, $c, $d, $e, $f);
  22408. }
  22409. /**
  22410. * Apply SVG graphic transformation matrix.
  22411. * @param $tm (array) original SVG transformation matrix
  22412. * @protected
  22413. * @since 5.0.000 (2010-05-02)
  22414. */
  22415. protected function SVGTransform($tm) {
  22416. $this->Transform($this->convertSVGtMatrix($tm));
  22417. }
  22418. /**
  22419. * Apply the requested SVG styles (*** TO BE COMPLETED ***)
  22420. * @param $svgstyle (array) array of SVG styles to apply
  22421. * @param $prevsvgstyle (array) array of previous SVG style
  22422. * @param $x (int) X origin of the bounding box
  22423. * @param $y (int) Y origin of the bounding box
  22424. * @param $w (int) width of the bounding box
  22425. * @param $h (int) height of the bounding box
  22426. * @param $clip_function (string) clip function
  22427. * @param $clip_params (array) array of parameters for clipping function
  22428. * @return object style
  22429. * @author Nicola Asuni
  22430. * @since 5.0.000 (2010-05-02)
  22431. * @protected
  22432. */
  22433. protected function setSVGStyles($svgstyle, $prevsvgstyle, $x=0, $y=0, $w=1, $h=1, $clip_function='', $clip_params=array()) {
  22434. if ($this->state != 2) {
  22435. return;
  22436. }
  22437. $objstyle = '';
  22438. $minlen = (0.01 / $this->k); // minimum acceptable length
  22439. if (!isset($svgstyle['opacity'])) {
  22440. return $objstyle;
  22441. }
  22442. // clip-path
  22443. $regs = array();
  22444. if (preg_match('/url\([\s]*\#([^\)]*)\)/si', $svgstyle['clip-path'], $regs)) {
  22445. $clip_path = $this->svgclippaths[$regs[1]];
  22446. foreach ($clip_path as $cp) {
  22447. $this->startSVGElementHandler('clip-path', $cp['name'], $cp['attribs'], $cp['tm']);
  22448. }
  22449. }
  22450. // opacity
  22451. if ($svgstyle['opacity'] != 1) {
  22452. $this->setAlpha($svgstyle['opacity'], 'Normal', $svgstyle['opacity'], false);
  22453. }
  22454. // color
  22455. $fill_color = TCPDF_COLORS::convertHTMLColorToDec($svgstyle['color'], $this->spot_colors);
  22456. $this->SetFillColorArray($fill_color);
  22457. // text color
  22458. $text_color = TCPDF_COLORS::convertHTMLColorToDec($svgstyle['text-color'], $this->spot_colors);
  22459. $this->SetTextColorArray($text_color);
  22460. // clip
  22461. if (preg_match('/rect\(([a-z0-9\-\.]*)[\s]*([a-z0-9\-\.]*)[\s]*([a-z0-9\-\.]*)[\s]*([a-z0-9\-\.]*)\)/si', $svgstyle['clip'], $regs)) {
  22462. $top = (isset($regs[1])?$this->getHTMLUnitToUnits($regs[1], 0, $this->svgunit, false):0);
  22463. $right = (isset($regs[2])?$this->getHTMLUnitToUnits($regs[2], 0, $this->svgunit, false):0);
  22464. $bottom = (isset($regs[3])?$this->getHTMLUnitToUnits($regs[3], 0, $this->svgunit, false):0);
  22465. $left = (isset($regs[4])?$this->getHTMLUnitToUnits($regs[4], 0, $this->svgunit, false):0);
  22466. $cx = $x + $left;
  22467. $cy = $y + $top;
  22468. $cw = $w - $left - $right;
  22469. $ch = $h - $top - $bottom;
  22470. if ($svgstyle['clip-rule'] == 'evenodd') {
  22471. $clip_rule = 'CNZ';
  22472. } else {
  22473. $clip_rule = 'CEO';
  22474. }
  22475. $this->Rect($cx, $cy, $cw, $ch, $clip_rule, array(), array());
  22476. }
  22477. // fill
  22478. $regs = array();
  22479. if (preg_match('/url\([\s]*\#([^\)]*)\)/si', $svgstyle['fill'], $regs)) {
  22480. // gradient
  22481. $gradient = $this->svggradients[$regs[1]];
  22482. if (isset($gradient['xref'])) {
  22483. // reference to another gradient definition
  22484. $newgradient = $this->svggradients[$gradient['xref']];
  22485. $newgradient['coords'] = $gradient['coords'];
  22486. $newgradient['mode'] = $gradient['mode'];
  22487. $newgradient['type'] = $gradient['type'];
  22488. $newgradient['gradientUnits'] = $gradient['gradientUnits'];
  22489. if (isset($gradient['gradientTransform'])) {
  22490. $newgradient['gradientTransform'] = $gradient['gradientTransform'];
  22491. }
  22492. $gradient = $newgradient;
  22493. }
  22494. //save current Graphic State
  22495. $this->_outSaveGraphicsState();
  22496. //set clipping area
  22497. if (!empty($clip_function) AND method_exists($this, $clip_function)) {
  22498. $bbox = call_user_func_array(array($this, $clip_function), $clip_params);
  22499. if ((!isset($gradient['type']) OR ($gradient['type'] != 3)) AND is_array($bbox) AND (count($bbox) == 4)) {
  22500. list($x, $y, $w, $h) = $bbox;
  22501. }
  22502. }
  22503. if ($gradient['mode'] == 'measure') {
  22504. if (!isset($gradient['coords'][4])) {
  22505. $gradient['coords'][4] = 0.5;
  22506. }
  22507. if (isset($gradient['gradientTransform']) AND !empty($gradient['gradientTransform'])) {
  22508. $gtm = $gradient['gradientTransform'];
  22509. // apply transformation matrix
  22510. $xa = ($gtm[0] * $gradient['coords'][0]) + ($gtm[2] * $gradient['coords'][1]) + $gtm[4];
  22511. $ya = ($gtm[1] * $gradient['coords'][0]) + ($gtm[3] * $gradient['coords'][1]) + $gtm[5];
  22512. $xb = ($gtm[0] * $gradient['coords'][2]) + ($gtm[2] * $gradient['coords'][3]) + $gtm[4];
  22513. $yb = ($gtm[1] * $gradient['coords'][2]) + ($gtm[3] * $gradient['coords'][3]) + $gtm[5];
  22514. $r = sqrt(pow(($gtm[0] * $gradient['coords'][4]), 2) + pow(($gtm[1] * $gradient['coords'][4]), 2));
  22515. $gradient['coords'][0] = $xa;
  22516. $gradient['coords'][1] = $ya;
  22517. $gradient['coords'][2] = $xb;
  22518. $gradient['coords'][3] = $yb;
  22519. $gradient['coords'][4] = $r;
  22520. }
  22521. // convert SVG coordinates to user units
  22522. $gradient['coords'][0] = $this->getHTMLUnitToUnits($gradient['coords'][0], 0, $this->svgunit, false);
  22523. $gradient['coords'][1] = $this->getHTMLUnitToUnits($gradient['coords'][1], 0, $this->svgunit, false);
  22524. $gradient['coords'][2] = $this->getHTMLUnitToUnits($gradient['coords'][2], 0, $this->svgunit, false);
  22525. $gradient['coords'][3] = $this->getHTMLUnitToUnits($gradient['coords'][3], 0, $this->svgunit, false);
  22526. $gradient['coords'][4] = $this->getHTMLUnitToUnits($gradient['coords'][4], 0, $this->svgunit, false);
  22527. if ($w <= $minlen) {
  22528. $w = $minlen;
  22529. }
  22530. if ($h <= $minlen) {
  22531. $h = $minlen;
  22532. }
  22533. // shift units
  22534. if ($gradient['gradientUnits'] == 'objectBoundingBox') {
  22535. // convert to SVG coordinate system
  22536. $gradient['coords'][0] += $x;
  22537. $gradient['coords'][1] += $y;
  22538. $gradient['coords'][2] += $x;
  22539. $gradient['coords'][3] += $y;
  22540. }
  22541. // calculate percentages
  22542. $gradient['coords'][0] = (($gradient['coords'][0] - $x) / $w);
  22543. $gradient['coords'][1] = (($gradient['coords'][1] - $y) / $h);
  22544. $gradient['coords'][2] = (($gradient['coords'][2] - $x) / $w);
  22545. $gradient['coords'][3] = (($gradient['coords'][3] - $y) / $h);
  22546. $gradient['coords'][4] /= $w;
  22547. } elseif ($gradient['mode'] == 'percentage') {
  22548. foreach($gradient['coords'] as $key => $val) {
  22549. $gradient['coords'][$key] = (intval($val) / 100);
  22550. if ($val < 0) {
  22551. $gradient['coords'][$key] = 0;
  22552. } elseif ($val > 1) {
  22553. $gradient['coords'][$key] = 1;
  22554. }
  22555. }
  22556. }
  22557. if (($gradient['type'] == 2) AND ($gradient['coords'][0] == $gradient['coords'][2]) AND ($gradient['coords'][1] == $gradient['coords'][3])) {
  22558. // single color (no shading)
  22559. $gradient['coords'][0] = 1;
  22560. $gradient['coords'][1] = 0;
  22561. $gradient['coords'][2] = 0.999;
  22562. $gradient['coords'][3] = 0;
  22563. }
  22564. // swap Y coordinates
  22565. $tmp = $gradient['coords'][1];
  22566. $gradient['coords'][1] = $gradient['coords'][3];
  22567. $gradient['coords'][3] = $tmp;
  22568. // set transformation map for gradient
  22569. $cy = ($this->h - $y);
  22570. if ($gradient['type'] == 3) {
  22571. // circular gradient
  22572. $cy -= ($gradient['coords'][1] * ($w + $h));
  22573. $h = $w = max($w, $h);
  22574. } else {
  22575. $cy -= $h;
  22576. }
  22577. $this->_out(sprintf('%F 0 0 %F %F %F cm', ($w * $this->k), ($h * $this->k), ($x * $this->k), ($cy * $this->k)));
  22578. if (count($gradient['stops']) > 1) {
  22579. $this->Gradient($gradient['type'], $gradient['coords'], $gradient['stops'], array(), false);
  22580. }
  22581. } elseif ($svgstyle['fill'] != 'none') {
  22582. $fill_color = TCPDF_COLORS::convertHTMLColorToDec($svgstyle['fill'], $this->spot_colors);
  22583. if ($svgstyle['fill-opacity'] != 1) {
  22584. $this->setAlpha($this->alpha['CA'], 'Normal', $svgstyle['fill-opacity'], false);
  22585. }
  22586. $this->SetFillColorArray($fill_color);
  22587. if ($svgstyle['fill-rule'] == 'evenodd') {
  22588. $objstyle .= 'F*';
  22589. } else {
  22590. $objstyle .= 'F';
  22591. }
  22592. }
  22593. // stroke
  22594. if ($svgstyle['stroke'] != 'none') {
  22595. if ($svgstyle['stroke-opacity'] != 1) {
  22596. $this->setAlpha($svgstyle['stroke-opacity'], 'Normal', $this->alpha['ca'], false);
  22597. } elseif (preg_match('/rgba\(\d+%?,\s*\d+%?,\s*\d+%?,\s*(\d+(?:\.\d+)?)\)/i', $svgstyle['stroke'], $rgba_matches)) {
  22598. $this->setAlpha($rgba_matches[1], 'Normal', $this->alpha['ca'], false);
  22599. }
  22600. $stroke_style = array(
  22601. 'color' => TCPDF_COLORS::convertHTMLColorToDec($svgstyle['stroke'], $this->spot_colors),
  22602. 'width' => $this->getHTMLUnitToUnits($svgstyle['stroke-width'], 0, $this->svgunit, false),
  22603. 'cap' => $svgstyle['stroke-linecap'],
  22604. 'join' => $svgstyle['stroke-linejoin']
  22605. );
  22606. if (isset($svgstyle['stroke-dasharray']) AND !empty($svgstyle['stroke-dasharray']) AND ($svgstyle['stroke-dasharray'] != 'none')) {
  22607. $stroke_style['dash'] = $svgstyle['stroke-dasharray'];
  22608. }
  22609. $this->SetLineStyle($stroke_style);
  22610. $objstyle .= 'D';
  22611. }
  22612. // font
  22613. $regs = array();
  22614. if (!empty($svgstyle['font'])) {
  22615. if (preg_match('/font-family[\s]*:[\s]*([^\;\"]*)/si', $svgstyle['font'], $regs)) {
  22616. $font_family = $this->getFontFamilyName($regs[1]);
  22617. } else {
  22618. $font_family = $svgstyle['font-family'];
  22619. }
  22620. if (preg_match('/font-size[\s]*:[\s]*([^\s\;\"]*)/si', $svgstyle['font'], $regs)) {
  22621. $font_size = trim($regs[1]);
  22622. } else {
  22623. $font_size = $svgstyle['font-size'];
  22624. }
  22625. if (preg_match('/font-style[\s]*:[\s]*([^\s\;\"]*)/si', $svgstyle['font'], $regs)) {
  22626. $font_style = trim($regs[1]);
  22627. } else {
  22628. $font_style = $svgstyle['font-style'];
  22629. }
  22630. if (preg_match('/font-weight[\s]*:[\s]*([^\s\;\"]*)/si', $svgstyle['font'], $regs)) {
  22631. $font_weight = trim($regs[1]);
  22632. } else {
  22633. $font_weight = $svgstyle['font-weight'];
  22634. }
  22635. if (preg_match('/font-stretch[\s]*:[\s]*([^\s\;\"]*)/si', $svgstyle['font'], $regs)) {
  22636. $font_stretch = trim($regs[1]);
  22637. } else {
  22638. $font_stretch = $svgstyle['font-stretch'];
  22639. }
  22640. if (preg_match('/letter-spacing[\s]*:[\s]*([^\s\;\"]*)/si', $svgstyle['font'], $regs)) {
  22641. $font_spacing = trim($regs[1]);
  22642. } else {
  22643. $font_spacing = $svgstyle['letter-spacing'];
  22644. }
  22645. } else {
  22646. $font_family = $this->getFontFamilyName($svgstyle['font-family']);
  22647. $font_size = $svgstyle['font-size'];
  22648. $font_style = $svgstyle['font-style'];
  22649. $font_weight = $svgstyle['font-weight'];
  22650. $font_stretch = $svgstyle['font-stretch'];
  22651. $font_spacing = $svgstyle['letter-spacing'];
  22652. }
  22653. $font_size = $this->getHTMLFontUnits($font_size, $this->svgstyles[0]['font-size'], $prevsvgstyle['font-size'], $this->svgunit);
  22654. $font_stretch = $this->getCSSFontStretching($font_stretch, $svgstyle['font-stretch']);
  22655. $font_spacing = $this->getCSSFontSpacing($font_spacing, $svgstyle['letter-spacing']);
  22656. switch ($font_style) {
  22657. case 'italic': {
  22658. $font_style = 'I';
  22659. break;
  22660. }
  22661. case 'oblique': {
  22662. $font_style = 'I';
  22663. break;
  22664. }
  22665. default:
  22666. case 'normal': {
  22667. $font_style = '';
  22668. break;
  22669. }
  22670. }
  22671. switch ($font_weight) {
  22672. case 'bold':
  22673. case 'bolder': {
  22674. $font_style .= 'B';
  22675. break;
  22676. }
  22677. case 'normal': {
  22678. if ((substr($font_family, -1) == 'I') AND (substr($font_family, -2, 1) == 'B')) {
  22679. $font_family = substr($font_family, 0, -2).'I';
  22680. } elseif (substr($font_family, -1) == 'B') {
  22681. $font_family = substr($font_family, 0, -1);
  22682. }
  22683. break;
  22684. }
  22685. }
  22686. switch ($svgstyle['text-decoration']) {
  22687. case 'underline': {
  22688. $font_style .= 'U';
  22689. break;
  22690. }
  22691. case 'overline': {
  22692. $font_style .= 'O';
  22693. break;
  22694. }
  22695. case 'line-through': {
  22696. $font_style .= 'D';
  22697. break;
  22698. }
  22699. default:
  22700. case 'none': {
  22701. break;
  22702. }
  22703. }
  22704. $this->SetFont($font_family, $font_style, $font_size);
  22705. $this->setFontStretching($font_stretch);
  22706. $this->setFontSpacing($font_spacing);
  22707. return $objstyle;
  22708. }
  22709. /**
  22710. * Draws an SVG path
  22711. * @param $d (string) attribute d of the path SVG element
  22712. * @param $style (string) Style of rendering. Possible values are:
  22713. * <ul>
  22714. * <li>D or empty string: Draw (default).</li>
  22715. * <li>F: Fill.</li>
  22716. * <li>F*: Fill using the even-odd rule to determine which regions lie inside the clipping path.</li>
  22717. * <li>DF or FD: Draw and fill.</li>
  22718. * <li>DF* or FD*: Draw and fill using the even-odd rule to determine which regions lie inside the clipping path.</li>
  22719. * <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
  22720. * <li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
  22721. * </ul>
  22722. * @return array of container box measures (x, y, w, h)
  22723. * @author Nicola Asuni
  22724. * @since 5.0.000 (2010-05-02)
  22725. * @protected
  22726. */
  22727. protected function SVGPath($d, $style='') {
  22728. if ($this->state != 2) {
  22729. return;
  22730. }
  22731. // set fill/stroke style
  22732. $op = TCPDF_STATIC::getPathPaintOperator($style, '');
  22733. if (empty($op)) {
  22734. return;
  22735. }
  22736. $paths = array();
  22737. $d = preg_replace('/([0-9ACHLMQSTVZ])([\-\+])/si', '\\1 \\2', $d);
  22738. preg_match_all('/([ACHLMQSTVZ])[\s]*([^ACHLMQSTVZ\"]*)/si', $d, $paths, PREG_SET_ORDER);
  22739. $x = 0;
  22740. $y = 0;
  22741. $x1 = 0;
  22742. $y1 = 0;
  22743. $x2 = 0;
  22744. $y2 = 0;
  22745. $xmin = 2147483647;
  22746. $xmax = 0;
  22747. $ymin = 2147483647;
  22748. $ymax = 0;
  22749. $xinitial = 0;
  22750. $yinitial = 0;
  22751. $relcoord = false;
  22752. $minlen = (0.01 / $this->k); // minimum acceptable length (3 point)
  22753. $firstcmd = true; // used to print first point
  22754. // draw curve pieces
  22755. foreach ($paths as $key => $val) {
  22756. // get curve type
  22757. $cmd = trim($val[1]);
  22758. if (strtolower($cmd) == $cmd) {
  22759. // use relative coordinated instead of absolute
  22760. $relcoord = true;
  22761. $xoffset = $x;
  22762. $yoffset = $y;
  22763. } else {
  22764. $relcoord = false;
  22765. $xoffset = 0;
  22766. $yoffset = 0;
  22767. }
  22768. $params = array();
  22769. if (isset($val[2])) {
  22770. // get curve parameters
  22771. $rawparams = preg_split('/([\,\s]+)/si', trim($val[2]));
  22772. $params = array();
  22773. foreach ($rawparams as $ck => $cp) {
  22774. $params[$ck] = $this->getHTMLUnitToUnits($cp, 0, $this->svgunit, false);
  22775. if (abs($params[$ck]) < $minlen) {
  22776. // approximate little values to zero
  22777. $params[$ck] = 0;
  22778. }
  22779. }
  22780. }
  22781. // store current origin point
  22782. $x0 = $x;
  22783. $y0 = $y;
  22784. switch (strtoupper($cmd)) {
  22785. case 'M': { // moveto
  22786. foreach ($params as $ck => $cp) {
  22787. if (($ck % 2) == 0) {
  22788. $x = $cp + $xoffset;
  22789. } else {
  22790. $y = $cp + $yoffset;
  22791. if ($firstcmd OR (abs($x0 - $x) >= $minlen) OR (abs($y0 - $y) >= $minlen)) {
  22792. if ($ck == 1) {
  22793. $this->_outPoint($x, $y);
  22794. $firstcmd = false;
  22795. $xinitial = $x;
  22796. $yinitial = $y;
  22797. } else {
  22798. $this->_outLine($x, $y);
  22799. }
  22800. $x0 = $x;
  22801. $y0 = $y;
  22802. }
  22803. $xmin = min($xmin, $x);
  22804. $ymin = min($ymin, $y);
  22805. $xmax = max($xmax, $x);
  22806. $ymax = max($ymax, $y);
  22807. if ($relcoord) {
  22808. $xoffset = $x;
  22809. $yoffset = $y;
  22810. }
  22811. }
  22812. }
  22813. break;
  22814. }
  22815. case 'L': { // lineto
  22816. foreach ($params as $ck => $cp) {
  22817. if (($ck % 2) == 0) {
  22818. $x = $cp + $xoffset;
  22819. } else {
  22820. $y = $cp + $yoffset;
  22821. if ((abs($x0 - $x) >= $minlen) OR (abs($y0 - $y) >= $minlen)) {
  22822. $this->_outLine($x, $y);
  22823. $x0 = $x;
  22824. $y0 = $y;
  22825. }
  22826. $xmin = min($xmin, $x);
  22827. $ymin = min($ymin, $y);
  22828. $xmax = max($xmax, $x);
  22829. $ymax = max($ymax, $y);
  22830. if ($relcoord) {
  22831. $xoffset = $x;
  22832. $yoffset = $y;
  22833. }
  22834. }
  22835. }
  22836. break;
  22837. }
  22838. case 'H': { // horizontal lineto
  22839. foreach ($params as $ck => $cp) {
  22840. $x = $cp + $xoffset;
  22841. if ((abs($x0 - $x) >= $minlen) OR (abs($y0 - $y) >= $minlen)) {
  22842. $this->_outLine($x, $y);
  22843. $x0 = $x;
  22844. $y0 = $y;
  22845. }
  22846. $xmin = min($xmin, $x);
  22847. $xmax = max($xmax, $x);
  22848. if ($relcoord) {
  22849. $xoffset = $x;
  22850. }
  22851. }
  22852. break;
  22853. }
  22854. case 'V': { // vertical lineto
  22855. foreach ($params as $ck => $cp) {
  22856. $y = $cp + $yoffset;
  22857. if ((abs($x0 - $x) >= $minlen) OR (abs($y0 - $y) >= $minlen)) {
  22858. $this->_outLine($x, $y);
  22859. $x0 = $x;
  22860. $y0 = $y;
  22861. }
  22862. $ymin = min($ymin, $y);
  22863. $ymax = max($ymax, $y);
  22864. if ($relcoord) {
  22865. $yoffset = $y;
  22866. }
  22867. }
  22868. break;
  22869. }
  22870. case 'C': { // curveto
  22871. foreach ($params as $ck => $cp) {
  22872. $params[$ck] = $cp;
  22873. if ((($ck + 1) % 6) == 0) {
  22874. $x1 = $params[($ck - 5)] + $xoffset;
  22875. $y1 = $params[($ck - 4)] + $yoffset;
  22876. $x2 = $params[($ck - 3)] + $xoffset;
  22877. $y2 = $params[($ck - 2)] + $yoffset;
  22878. $x = $params[($ck - 1)] + $xoffset;
  22879. $y = $params[($ck)] + $yoffset;
  22880. $this->_outCurve($x1, $y1, $x2, $y2, $x, $y);
  22881. $xmin = min($xmin, $x, $x1, $x2);
  22882. $ymin = min($ymin, $y, $y1, $y2);
  22883. $xmax = max($xmax, $x, $x1, $x2);
  22884. $ymax = max($ymax, $y, $y1, $y2);
  22885. if ($relcoord) {
  22886. $xoffset = $x;
  22887. $yoffset = $y;
  22888. }
  22889. }
  22890. }
  22891. break;
  22892. }
  22893. case 'S': { // shorthand/smooth curveto
  22894. foreach ($params as $ck => $cp) {
  22895. $params[$ck] = $cp;
  22896. if ((($ck + 1) % 4) == 0) {
  22897. if (($key > 0) AND ((strtoupper($paths[($key - 1)][1]) == 'C') OR (strtoupper($paths[($key - 1)][1]) == 'S'))) {
  22898. $x1 = (2 * $x) - $x2;
  22899. $y1 = (2 * $y) - $y2;
  22900. } else {
  22901. $x1 = $x;
  22902. $y1 = $y;
  22903. }
  22904. $x2 = $params[($ck - 3)] + $xoffset;
  22905. $y2 = $params[($ck - 2)] + $yoffset;
  22906. $x = $params[($ck - 1)] + $xoffset;
  22907. $y = $params[($ck)] + $yoffset;
  22908. $this->_outCurve($x1, $y1, $x2, $y2, $x, $y);
  22909. $xmin = min($xmin, $x, $x1, $x2);
  22910. $ymin = min($ymin, $y, $y1, $y2);
  22911. $xmax = max($xmax, $x, $x1, $x2);
  22912. $ymax = max($ymax, $y, $y1, $y2);
  22913. if ($relcoord) {
  22914. $xoffset = $x;
  22915. $yoffset = $y;
  22916. }
  22917. }
  22918. }
  22919. break;
  22920. }
  22921. case 'Q': { // quadratic Bezier curveto
  22922. foreach ($params as $ck => $cp) {
  22923. $params[$ck] = $cp;
  22924. if ((($ck + 1) % 4) == 0) {
  22925. // convert quadratic points to cubic points
  22926. $x1 = $params[($ck - 3)] + $xoffset;
  22927. $y1 = $params[($ck - 2)] + $yoffset;
  22928. $xa = ($x + (2 * $x1)) / 3;
  22929. $ya = ($y + (2 * $y1)) / 3;
  22930. $x = $params[($ck - 1)] + $xoffset;
  22931. $y = $params[($ck)] + $yoffset;
  22932. $xb = ($x + (2 * $x1)) / 3;
  22933. $yb = ($y + (2 * $y1)) / 3;
  22934. $this->_outCurve($xa, $ya, $xb, $yb, $x, $y);
  22935. $xmin = min($xmin, $x, $xa, $xb);
  22936. $ymin = min($ymin, $y, $ya, $yb);
  22937. $xmax = max($xmax, $x, $xa, $xb);
  22938. $ymax = max($ymax, $y, $ya, $yb);
  22939. if ($relcoord) {
  22940. $xoffset = $x;
  22941. $yoffset = $y;
  22942. }
  22943. }
  22944. }
  22945. break;
  22946. }
  22947. case 'T': { // shorthand/smooth quadratic Bezier curveto
  22948. foreach ($params as $ck => $cp) {
  22949. $params[$ck] = $cp;
  22950. if (($ck % 2) != 0) {
  22951. if (($key > 0) AND ((strtoupper($paths[($key - 1)][1]) == 'Q') OR (strtoupper($paths[($key - 1)][1]) == 'T'))) {
  22952. $x1 = (2 * $x) - $x1;
  22953. $y1 = (2 * $y) - $y1;
  22954. } else {
  22955. $x1 = $x;
  22956. $y1 = $y;
  22957. }
  22958. // convert quadratic points to cubic points
  22959. $xa = ($x + (2 * $x1)) / 3;
  22960. $ya = ($y + (2 * $y1)) / 3;
  22961. $x = $params[($ck - 1)] + $xoffset;
  22962. $y = $params[($ck)] + $yoffset;
  22963. $xb = ($x + (2 * $x1)) / 3;
  22964. $yb = ($y + (2 * $y1)) / 3;
  22965. $this->_outCurve($xa, $ya, $xb, $yb, $x, $y);
  22966. $xmin = min($xmin, $x, $xa, $xb);
  22967. $ymin = min($ymin, $y, $ya, $yb);
  22968. $xmax = max($xmax, $x, $xa, $xb);
  22969. $ymax = max($ymax, $y, $ya, $yb);
  22970. if ($relcoord) {
  22971. $xoffset = $x;
  22972. $yoffset = $y;
  22973. }
  22974. }
  22975. }
  22976. break;
  22977. }
  22978. case 'A': { // elliptical arc
  22979. foreach ($params as $ck => $cp) {
  22980. $params[$ck] = $cp;
  22981. if ((($ck + 1) % 7) == 0) {
  22982. $x0 = $x;
  22983. $y0 = $y;
  22984. $rx = max(abs($params[($ck - 6)]), .000000001);
  22985. $ry = max(abs($params[($ck - 5)]), .000000001);
  22986. $ang = -$rawparams[($ck - 4)];
  22987. $angle = deg2rad($ang);
  22988. $fa = $rawparams[($ck - 3)]; // large-arc-flag
  22989. $fs = $rawparams[($ck - 2)]; // sweep-flag
  22990. $x = $params[($ck - 1)] + $xoffset;
  22991. $y = $params[$ck] + $yoffset;
  22992. if ((abs($x0 - $x) < $minlen) AND (abs($y0 - $y) < $minlen)) {
  22993. // endpoints are almost identical
  22994. $xmin = min($xmin, $x);
  22995. $ymin = min($ymin, $y);
  22996. $xmax = max($xmax, $x);
  22997. $ymax = max($ymax, $y);
  22998. } else {
  22999. $cos_ang = cos($angle);
  23000. $sin_ang = sin($angle);
  23001. $a = (($x0 - $x) / 2);
  23002. $b = (($y0 - $y) / 2);
  23003. $xa = ($a * $cos_ang) - ($b * $sin_ang);
  23004. $ya = ($a * $sin_ang) + ($b * $cos_ang);
  23005. $rx2 = $rx * $rx;
  23006. $ry2 = $ry * $ry;
  23007. $xa2 = $xa * $xa;
  23008. $ya2 = $ya * $ya;
  23009. $delta = ($xa2 / $rx2) + ($ya2 / $ry2);
  23010. if ($delta > 1) {
  23011. $rx *= sqrt($delta);
  23012. $ry *= sqrt($delta);
  23013. $rx2 = $rx * $rx;
  23014. $ry2 = $ry * $ry;
  23015. }
  23016. $numerator = (($rx2 * $ry2) - ($rx2 * $ya2) - ($ry2 * $xa2));
  23017. if ($numerator < 0) {
  23018. $root = 0;
  23019. } else {
  23020. $root = sqrt($numerator / (($rx2 * $ya2) + ($ry2 * $xa2)));
  23021. }
  23022. if ($fa == $fs){
  23023. $root *= -1;
  23024. }
  23025. $cax = $root * (($rx * $ya) / $ry);
  23026. $cay = -$root * (($ry * $xa) / $rx);
  23027. // coordinates of ellipse center
  23028. $cx = ($cax * $cos_ang) - ($cay * $sin_ang) + (($x0 + $x) / 2);
  23029. $cy = ($cax * $sin_ang) + ($cay * $cos_ang) + (($y0 + $y) / 2);
  23030. // get angles
  23031. $angs = TCPDF_STATIC::getVectorsAngle(1, 0, (($xa - $cax) / $rx), (($cay - $ya) / $ry));
  23032. $dang = TCPDF_STATIC::getVectorsAngle((($xa - $cax) / $rx), (($ya - $cay) / $ry), ((-$xa - $cax) / $rx), ((-$ya - $cay) / $ry));
  23033. if (($fs == 0) AND ($dang > 0)) {
  23034. $dang -= (2 * M_PI);
  23035. } elseif (($fs == 1) AND ($dang < 0)) {
  23036. $dang += (2 * M_PI);
  23037. }
  23038. $angf = $angs - $dang;
  23039. if ((($fs == 0) AND ($angs > $angf)) OR (($fs == 1) AND ($angs < $angf))) {
  23040. // reverse angles
  23041. $tmp = $angs;
  23042. $angs = $angf;
  23043. $angf = $tmp;
  23044. }
  23045. $angs = round(rad2deg($angs), 6);
  23046. $angf = round(rad2deg($angf), 6);
  23047. // covent angles to positive values
  23048. if (($angs < 0) AND ($angf < 0)) {
  23049. $angs += 360;
  23050. $angf += 360;
  23051. }
  23052. $pie = false;
  23053. if (($key == 0) AND (isset($paths[($key + 1)][1])) AND (trim($paths[($key + 1)][1]) == 'z')) {
  23054. $pie = true;
  23055. }
  23056. list($axmin, $aymin, $axmax, $aymax) = $this->_outellipticalarc($cx, $cy, $rx, $ry, $ang, $angs, $angf, $pie, 2, false, ($fs == 0), true);
  23057. $xmin = min($xmin, $x, $axmin);
  23058. $ymin = min($ymin, $y, $aymin);
  23059. $xmax = max($xmax, $x, $axmax);
  23060. $ymax = max($ymax, $y, $aymax);
  23061. }
  23062. if ($relcoord) {
  23063. $xoffset = $x;
  23064. $yoffset = $y;
  23065. }
  23066. }
  23067. }
  23068. break;
  23069. }
  23070. case 'Z': {
  23071. $this->_out('h');
  23072. $x = $x0 = $xinitial;
  23073. $y = $y0 = $yinitial;
  23074. break;
  23075. }
  23076. }
  23077. $firstcmd = false;
  23078. } // end foreach
  23079. if (!empty($op)) {
  23080. $this->_out($op);
  23081. }
  23082. return array($xmin, $ymin, ($xmax - $xmin), ($ymax - $ymin));
  23083. }
  23084. /**
  23085. * Return the tag name without the namespace
  23086. * @param $name (string) Tag name
  23087. * @protected
  23088. */
  23089. protected function removeTagNamespace($name) {
  23090. if(strpos($name, ':') !== false) {
  23091. $parts = explode(':', $name);
  23092. return $parts[(sizeof($parts) - 1)];
  23093. }
  23094. return $name;
  23095. }
  23096. /**
  23097. * Sets the opening SVG element handler function for the XML parser. (*** TO BE COMPLETED ***)
  23098. * @param $parser (resource) The first parameter, parser, is a reference to the XML parser calling the handler.
  23099. * @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.
  23100. * @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.
  23101. * @param $ctm (array) tranformation matrix for clipping mode (starting transformation matrix).
  23102. * @author Nicola Asuni
  23103. * @since 5.0.000 (2010-05-02)
  23104. * @protected
  23105. */
  23106. protected function startSVGElementHandler($parser, $name, $attribs, $ctm=array()) {
  23107. $name = $this->removeTagNamespace($name);
  23108. // check if we are in clip mode
  23109. if ($this->svgclipmode) {
  23110. $this->svgclippaths[$this->svgclipid][] = array('name' => $name, 'attribs' => $attribs, 'tm' => $this->svgcliptm[$this->svgclipid]);
  23111. return;
  23112. }
  23113. if ($this->svgdefsmode AND !in_array($name, array('clipPath', 'linearGradient', 'radialGradient', 'stop'))) {
  23114. if (isset($attribs['id'])) {
  23115. $attribs['child_elements'] = array();
  23116. $this->svgdefs[$attribs['id']] = array('name' => $name, 'attribs' => $attribs);
  23117. return;
  23118. }
  23119. if (end($this->svgdefs) !== FALSE) {
  23120. $last_svgdefs_id = key($this->svgdefs);
  23121. if (isset($this->svgdefs[$last_svgdefs_id]['attribs']['child_elements'])) {
  23122. $attribs['id'] = 'DF_'.(count($this->svgdefs[$last_svgdefs_id]['attribs']['child_elements']) + 1);
  23123. $this->svgdefs[$last_svgdefs_id]['attribs']['child_elements'][$attribs['id']] = array('name' => $name, 'attribs' => $attribs);
  23124. return;
  23125. }
  23126. }
  23127. return;
  23128. }
  23129. $clipping = false;
  23130. if ($parser == 'clip-path') {
  23131. // set clipping mode
  23132. $clipping = true;
  23133. }
  23134. // get styling properties
  23135. $prev_svgstyle = $this->svgstyles[max(0,(count($this->svgstyles) - 1))]; // previous style
  23136. $svgstyle = $this->svgstyles[0]; // set default style
  23137. if ($clipping AND !isset($attribs['fill']) AND (!isset($attribs['style']) OR (!preg_match('/[;\"\s]{1}fill[\s]*:[\s]*([^;\"]*)/si', $attribs['style'], $attrval)))) {
  23138. // default fill attribute for clipping
  23139. $attribs['fill'] = 'none';
  23140. }
  23141. if (isset($attribs['style']) AND !TCPDF_STATIC::empty_string($attribs['style']) AND ($attribs['style'][0] != ';')) {
  23142. // fix style for regular expression
  23143. $attribs['style'] = ';'.$attribs['style'];
  23144. }
  23145. foreach ($prev_svgstyle as $key => $val) {
  23146. if (in_array($key, TCPDF_IMAGES::$svginheritprop)) {
  23147. // inherit previous value
  23148. $svgstyle[$key] = $val;
  23149. }
  23150. if (isset($attribs[$key]) AND !TCPDF_STATIC::empty_string($attribs[$key])) {
  23151. // specific attribute settings
  23152. if ($attribs[$key] == 'inherit') {
  23153. $svgstyle[$key] = $val;
  23154. } else {
  23155. $svgstyle[$key] = $attribs[$key];
  23156. }
  23157. } elseif (isset($attribs['style']) AND !TCPDF_STATIC::empty_string($attribs['style'])) {
  23158. // CSS style syntax
  23159. $attrval = array();
  23160. if (preg_match('/[;\"\s]{1}'.$key.'[\s]*:[\s]*([^;\"]*)/si', $attribs['style'], $attrval) AND isset($attrval[1])) {
  23161. if ($attrval[1] == 'inherit') {
  23162. $svgstyle[$key] = $val;
  23163. } else {
  23164. $svgstyle[$key] = $attrval[1];
  23165. }
  23166. }
  23167. }
  23168. }
  23169. // transformation matrix
  23170. if (!empty($ctm)) {
  23171. $tm = $ctm;
  23172. } else {
  23173. $tm = array(1,0,0,1,0,0);
  23174. }
  23175. if (isset($attribs['transform']) AND !empty($attribs['transform'])) {
  23176. $tm = TCPDF_STATIC::getTransformationMatrixProduct($tm, TCPDF_STATIC::getSVGTransformMatrix($attribs['transform']));
  23177. }
  23178. $svgstyle['transfmatrix'] = $tm;
  23179. $invisible = false;
  23180. if (($svgstyle['visibility'] == 'hidden') OR ($svgstyle['visibility'] == 'collapse') OR ($svgstyle['display'] == 'none')) {
  23181. // the current graphics element is invisible (nothing is painted)
  23182. $invisible = true;
  23183. }
  23184. // process tag
  23185. switch($name) {
  23186. case 'defs': {
  23187. $this->svgdefsmode = true;
  23188. break;
  23189. }
  23190. // clipPath
  23191. case 'clipPath': {
  23192. if ($invisible) {
  23193. break;
  23194. }
  23195. $this->svgclipmode = true;
  23196. if (!isset($attribs['id'])) {
  23197. $attribs['id'] = 'CP_'.(count($this->svgcliptm) + 1);
  23198. }
  23199. $this->svgclipid = $attribs['id'];
  23200. $this->svgclippaths[$this->svgclipid] = array();
  23201. $this->svgcliptm[$this->svgclipid] = $tm;
  23202. break;
  23203. }
  23204. case 'svg': {
  23205. // start of SVG object
  23206. if(++$this->svg_tag_depth <= 1) {
  23207. break;
  23208. }
  23209. // inner SVG
  23210. array_push($this->svgstyles, $svgstyle);
  23211. $this->StartTransform();
  23212. $svgX = (isset($attribs['x'])?$attribs['x']:0);
  23213. $svgY = (isset($attribs['y'])?$attribs['y']:0);
  23214. $svgW = (isset($attribs['width'])?$attribs['width']:0);
  23215. $svgH = (isset($attribs['height'])?$attribs['height']:0);
  23216. // set x, y position using transform matrix
  23217. $tm = TCPDF_STATIC::getTransformationMatrixProduct($tm, array( 1, 0, 0, 1, $svgX, $svgY));
  23218. $this->SVGTransform($tm);
  23219. // set clipping for width and height
  23220. $x = 0;
  23221. $y = 0;
  23222. $w = (isset($attribs['width'])?$this->getHTMLUnitToUnits($attribs['width'], 0, $this->svgunit, false):$this->w);
  23223. $h = (isset($attribs['height'])?$this->getHTMLUnitToUnits($attribs['height'], 0, $this->svgunit, false):$this->h);
  23224. // draw clipping rect
  23225. $this->Rect($x, $y, $w, $h, 'CNZ', array(), array());
  23226. // parse viewbox, calculate extra transformation matrix
  23227. if (isset($attribs['viewBox'])) {
  23228. $tmp = array();
  23229. preg_match_all("/[0-9]+/", $attribs['viewBox'], $tmp);
  23230. $tmp = $tmp[0];
  23231. if (sizeof($tmp) == 4) {
  23232. $vx = $tmp[0];
  23233. $vy = $tmp[1];
  23234. $vw = $tmp[2];
  23235. $vh = $tmp[3];
  23236. // get aspect ratio
  23237. $tmp = array();
  23238. $aspectX = 'xMid';
  23239. $aspectY = 'YMid';
  23240. $fit = 'meet';
  23241. if (isset($attribs['preserveAspectRatio'])) {
  23242. if($attribs['preserveAspectRatio'] == 'none') {
  23243. $fit = 'none';
  23244. } else {
  23245. preg_match_all('/[a-zA-Z]+/', $attribs['preserveAspectRatio'], $tmp);
  23246. $tmp = $tmp[0];
  23247. if ((sizeof($tmp) == 2) AND (strlen($tmp[0]) == 8) AND (in_array($tmp[1], array('meet', 'slice', 'none')))) {
  23248. $aspectX = substr($tmp[0], 0, 4);
  23249. $aspectY = substr($tmp[0], 4, 4);
  23250. $fit = $tmp[1];
  23251. }
  23252. }
  23253. }
  23254. $wr = ($svgW / $vw);
  23255. $hr = ($svgH / $vh);
  23256. $ax = $ay = 0;
  23257. if ((($fit == 'meet') AND ($hr < $wr)) OR (($fit == 'slice') AND ($hr > $wr))) {
  23258. if ($aspectX == 'xMax') {
  23259. $ax = (($vw * ($wr / $hr)) - $vw);
  23260. }
  23261. if ($aspectX == 'xMid') {
  23262. $ax = ((($vw * ($wr / $hr)) - $vw) / 2);
  23263. }
  23264. $wr = $hr;
  23265. } elseif ((($fit == 'meet') AND ($hr > $wr)) OR (($fit == 'slice') AND ($hr < $wr))) {
  23266. if ($aspectY == 'YMax') {
  23267. $ay = (($vh * ($hr / $wr)) - $vh);
  23268. }
  23269. if ($aspectY == 'YMid') {
  23270. $ay = ((($vh * ($hr / $wr)) - $vh) / 2);
  23271. }
  23272. $hr = $wr;
  23273. }
  23274. $newtm = array($wr, 0, 0, $hr, (($wr * ($ax - $vx)) - $svgX), (($hr * ($ay - $vy)) - $svgY));
  23275. $tm = TCPDF_STATIC::getTransformationMatrixProduct($tm, $newtm);
  23276. $this->SVGTransform($tm);
  23277. }
  23278. }
  23279. $this->setSVGStyles($svgstyle, $prev_svgstyle);
  23280. break;
  23281. }
  23282. case 'g': {
  23283. // group together related graphics elements
  23284. array_push($this->svgstyles, $svgstyle);
  23285. $this->StartTransform();
  23286. $x = (isset($attribs['x'])?$attribs['x']:0);
  23287. $y = (isset($attribs['y'])?$attribs['y']:0);
  23288. $w = 1;//(isset($attribs['width'])?$attribs['width']:1);
  23289. $h = 1;//(isset($attribs['height'])?$attribs['height']:1);
  23290. $tm = TCPDF_STATIC::getTransformationMatrixProduct($tm, array($w, 0, 0, $h, $x, $y));
  23291. $this->SVGTransform($tm);
  23292. $this->setSVGStyles($svgstyle, $prev_svgstyle);
  23293. break;
  23294. }
  23295. case 'linearGradient': {
  23296. if ($this->pdfa_mode) {
  23297. break;
  23298. }
  23299. if (!isset($attribs['id'])) {
  23300. $attribs['id'] = 'GR_'.(count($this->svggradients) + 1);
  23301. }
  23302. $this->svggradientid = $attribs['id'];
  23303. $this->svggradients[$this->svggradientid] = array();
  23304. $this->svggradients[$this->svggradientid]['type'] = 2;
  23305. $this->svggradients[$this->svggradientid]['stops'] = array();
  23306. if (isset($attribs['gradientUnits'])) {
  23307. $this->svggradients[$this->svggradientid]['gradientUnits'] = $attribs['gradientUnits'];
  23308. } else {
  23309. $this->svggradients[$this->svggradientid]['gradientUnits'] = 'objectBoundingBox';
  23310. }
  23311. //$attribs['spreadMethod']
  23312. if (((!isset($attribs['x1'])) AND (!isset($attribs['y1'])) AND (!isset($attribs['x2'])) AND (!isset($attribs['y2'])))
  23313. OR ((isset($attribs['x1']) AND (substr($attribs['x1'], -1) == '%'))
  23314. OR (isset($attribs['y1']) AND (substr($attribs['y1'], -1) == '%'))
  23315. OR (isset($attribs['x2']) AND (substr($attribs['x2'], -1) == '%'))
  23316. OR (isset($attribs['y2']) AND (substr($attribs['y2'], -1) == '%')))) {
  23317. $this->svggradients[$this->svggradientid]['mode'] = 'percentage';
  23318. } else {
  23319. $this->svggradients[$this->svggradientid]['mode'] = 'measure';
  23320. }
  23321. $x1 = (isset($attribs['x1'])?$attribs['x1']:'0');
  23322. $y1 = (isset($attribs['y1'])?$attribs['y1']:'0');
  23323. $x2 = (isset($attribs['x2'])?$attribs['x2']:'100');
  23324. $y2 = (isset($attribs['y2'])?$attribs['y2']:'0');
  23325. if (isset($attribs['gradientTransform'])) {
  23326. $this->svggradients[$this->svggradientid]['gradientTransform'] = TCPDF_STATIC::getSVGTransformMatrix($attribs['gradientTransform']);
  23327. }
  23328. $this->svggradients[$this->svggradientid]['coords'] = array($x1, $y1, $x2, $y2);
  23329. if (isset($attribs['xlink:href']) AND !empty($attribs['xlink:href'])) {
  23330. // gradient is defined on another place
  23331. $this->svggradients[$this->svggradientid]['xref'] = substr($attribs['xlink:href'], 1);
  23332. }
  23333. break;
  23334. }
  23335. case 'radialGradient': {
  23336. if ($this->pdfa_mode) {
  23337. break;
  23338. }
  23339. if (!isset($attribs['id'])) {
  23340. $attribs['id'] = 'GR_'.(count($this->svggradients) + 1);
  23341. }
  23342. $this->svggradientid = $attribs['id'];
  23343. $this->svggradients[$this->svggradientid] = array();
  23344. $this->svggradients[$this->svggradientid]['type'] = 3;
  23345. $this->svggradients[$this->svggradientid]['stops'] = array();
  23346. if (isset($attribs['gradientUnits'])) {
  23347. $this->svggradients[$this->svggradientid]['gradientUnits'] = $attribs['gradientUnits'];
  23348. } else {
  23349. $this->svggradients[$this->svggradientid]['gradientUnits'] = 'objectBoundingBox';
  23350. }
  23351. //$attribs['spreadMethod']
  23352. if (((!isset($attribs['cx'])) AND (!isset($attribs['cy'])))
  23353. OR ((isset($attribs['cx']) AND (substr($attribs['cx'], -1) == '%'))
  23354. OR (isset($attribs['cy']) AND (substr($attribs['cy'], -1) == '%')))) {
  23355. $this->svggradients[$this->svggradientid]['mode'] = 'percentage';
  23356. } elseif (isset($attribs['r']) AND is_numeric($attribs['r']) AND ($attribs['r']) <= 1) {
  23357. $this->svggradients[$this->svggradientid]['mode'] = 'ratio';
  23358. } else {
  23359. $this->svggradients[$this->svggradientid]['mode'] = 'measure';
  23360. }
  23361. $cx = (isset($attribs['cx']) ? $attribs['cx'] : 0.5);
  23362. $cy = (isset($attribs['cy']) ? $attribs['cy'] : 0.5);
  23363. $fx = (isset($attribs['fx']) ? $attribs['fx'] : $cx);
  23364. $fy = (isset($attribs['fy']) ? $attribs['fy'] : $cy);
  23365. $r = (isset($attribs['r']) ? $attribs['r'] : 0.5);
  23366. if (isset($attribs['gradientTransform'])) {
  23367. $this->svggradients[$this->svggradientid]['gradientTransform'] = TCPDF_STATIC::getSVGTransformMatrix($attribs['gradientTransform']);
  23368. }
  23369. $this->svggradients[$this->svggradientid]['coords'] = array($cx, $cy, $fx, $fy, $r);
  23370. if (isset($attribs['xlink:href']) AND !empty($attribs['xlink:href'])) {
  23371. // gradient is defined on another place
  23372. $this->svggradients[$this->svggradientid]['xref'] = substr($attribs['xlink:href'], 1);
  23373. }
  23374. break;
  23375. }
  23376. case 'stop': {
  23377. // gradient stops
  23378. if (substr($attribs['offset'], -1) == '%') {
  23379. $offset = floatval(substr($attribs['offset'], 0, -1)) / 100;
  23380. } else {
  23381. $offset = floatval($attribs['offset']);
  23382. if ($offset > 1) {
  23383. $offset /= 100;
  23384. }
  23385. }
  23386. $stop_color = isset($svgstyle['stop-color'])?TCPDF_COLORS::convertHTMLColorToDec($svgstyle['stop-color'], $this->spot_colors):'black';
  23387. $opacity = isset($svgstyle['stop-opacity'])?$svgstyle['stop-opacity']:1;
  23388. $this->svggradients[$this->svggradientid]['stops'][] = array('offset' => $offset, 'color' => $stop_color, 'opacity' => $opacity);
  23389. break;
  23390. }
  23391. // paths
  23392. case 'path': {
  23393. if ($invisible) {
  23394. break;
  23395. }
  23396. if (isset($attribs['d'])) {
  23397. $d = trim($attribs['d']);
  23398. if (!empty($d)) {
  23399. $x = (isset($attribs['x'])?$attribs['x']:0);
  23400. $y = (isset($attribs['y'])?$attribs['y']:0);
  23401. $w = (isset($attribs['width'])?$attribs['width']:1);
  23402. $h = (isset($attribs['height'])?$attribs['height']:1);
  23403. $tm = TCPDF_STATIC::getTransformationMatrixProduct($tm, array($w, 0, 0, $h, $x, $y));
  23404. if ($clipping) {
  23405. $this->SVGTransform($tm);
  23406. $this->SVGPath($d, 'CNZ');
  23407. } else {
  23408. $this->StartTransform();
  23409. $this->SVGTransform($tm);
  23410. $obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h, 'SVGPath', array($d, 'CNZ'));
  23411. if (!empty($obstyle)) {
  23412. $this->SVGPath($d, $obstyle);
  23413. }
  23414. $this->StopTransform();
  23415. }
  23416. }
  23417. }
  23418. break;
  23419. }
  23420. // shapes
  23421. case 'rect': {
  23422. if ($invisible) {
  23423. break;
  23424. }
  23425. $x = (isset($attribs['x'])?$this->getHTMLUnitToUnits($attribs['x'], 0, $this->svgunit, false):0);
  23426. $y = (isset($attribs['y'])?$this->getHTMLUnitToUnits($attribs['y'], 0, $this->svgunit, false):0);
  23427. $w = (isset($attribs['width'])?$this->getHTMLUnitToUnits($attribs['width'], 0, $this->svgunit, false):0);
  23428. $h = (isset($attribs['height'])?$this->getHTMLUnitToUnits($attribs['height'], 0, $this->svgunit, false):0);
  23429. $rx = (isset($attribs['rx'])?$this->getHTMLUnitToUnits($attribs['rx'], 0, $this->svgunit, false):0);
  23430. $ry = (isset($attribs['ry'])?$this->getHTMLUnitToUnits($attribs['ry'], 0, $this->svgunit, false):$rx);
  23431. if ($clipping) {
  23432. $this->SVGTransform($tm);
  23433. $this->RoundedRectXY($x, $y, $w, $h, $rx, $ry, '1111', 'CNZ', array(), array());
  23434. } else {
  23435. $this->StartTransform();
  23436. $this->SVGTransform($tm);
  23437. $obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h, 'RoundedRectXY', array($x, $y, $w, $h, $rx, $ry, '1111', 'CNZ'));
  23438. if (!empty($obstyle)) {
  23439. $this->RoundedRectXY($x, $y, $w, $h, $rx, $ry, '1111', $obstyle, array(), array());
  23440. }
  23441. $this->StopTransform();
  23442. }
  23443. break;
  23444. }
  23445. case 'circle': {
  23446. if ($invisible) {
  23447. break;
  23448. }
  23449. $r = (isset($attribs['r']) ? $this->getHTMLUnitToUnits($attribs['r'], 0, $this->svgunit, false) : 0);
  23450. $cx = (isset($attribs['cx']) ? $this->getHTMLUnitToUnits($attribs['cx'], 0, $this->svgunit, false) : (isset($attribs['x']) ? $this->getHTMLUnitToUnits($attribs['x'], 0, $this->svgunit, false) : 0));
  23451. $cy = (isset($attribs['cy']) ? $this->getHTMLUnitToUnits($attribs['cy'], 0, $this->svgunit, false) : (isset($attribs['y']) ? $this->getHTMLUnitToUnits($attribs['y'], 0, $this->svgunit, false) : 0));
  23452. $x = ($cx - $r);
  23453. $y = ($cy - $r);
  23454. $w = (2 * $r);
  23455. $h = $w;
  23456. if ($clipping) {
  23457. $this->SVGTransform($tm);
  23458. $this->Circle($cx, $cy, $r, 0, 360, 'CNZ', array(), array(), 8);
  23459. } else {
  23460. $this->StartTransform();
  23461. $this->SVGTransform($tm);
  23462. $obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h, 'Circle', array($cx, $cy, $r, 0, 360, 'CNZ'));
  23463. if (!empty($obstyle)) {
  23464. $this->Circle($cx, $cy, $r, 0, 360, $obstyle, array(), array(), 8);
  23465. }
  23466. $this->StopTransform();
  23467. }
  23468. break;
  23469. }
  23470. case 'ellipse': {
  23471. if ($invisible) {
  23472. break;
  23473. }
  23474. $rx = (isset($attribs['rx']) ? $this->getHTMLUnitToUnits($attribs['rx'], 0, $this->svgunit, false) : 0);
  23475. $ry = (isset($attribs['ry']) ? $this->getHTMLUnitToUnits($attribs['ry'], 0, $this->svgunit, false) : 0);
  23476. $cx = (isset($attribs['cx']) ? $this->getHTMLUnitToUnits($attribs['cx'], 0, $this->svgunit, false) : (isset($attribs['x']) ? $this->getHTMLUnitToUnits($attribs['x'], 0, $this->svgunit, false) : 0));
  23477. $cy = (isset($attribs['cy']) ? $this->getHTMLUnitToUnits($attribs['cy'], 0, $this->svgunit, false) : (isset($attribs['y']) ? $this->getHTMLUnitToUnits($attribs['y'], 0, $this->svgunit, false) : 0));
  23478. $x = ($cx - $rx);
  23479. $y = ($cy - $ry);
  23480. $w = (2 * $rx);
  23481. $h = (2 * $ry);
  23482. if ($clipping) {
  23483. $this->SVGTransform($tm);
  23484. $this->Ellipse($cx, $cy, $rx, $ry, 0, 0, 360, 'CNZ', array(), array(), 8);
  23485. } else {
  23486. $this->StartTransform();
  23487. $this->SVGTransform($tm);
  23488. $obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h, 'Ellipse', array($cx, $cy, $rx, $ry, 0, 0, 360, 'CNZ'));
  23489. if (!empty($obstyle)) {
  23490. $this->Ellipse($cx, $cy, $rx, $ry, 0, 0, 360, $obstyle, array(), array(), 8);
  23491. }
  23492. $this->StopTransform();
  23493. }
  23494. break;
  23495. }
  23496. case 'line': {
  23497. if ($invisible) {
  23498. break;
  23499. }
  23500. $x1 = (isset($attribs['x1'])?$this->getHTMLUnitToUnits($attribs['x1'], 0, $this->svgunit, false):0);
  23501. $y1 = (isset($attribs['y1'])?$this->getHTMLUnitToUnits($attribs['y1'], 0, $this->svgunit, false):0);
  23502. $x2 = (isset($attribs['x2'])?$this->getHTMLUnitToUnits($attribs['x2'], 0, $this->svgunit, false):0);
  23503. $y2 = (isset($attribs['y2'])?$this->getHTMLUnitToUnits($attribs['y2'], 0, $this->svgunit, false):0);
  23504. $x = $x1;
  23505. $y = $y1;
  23506. $w = abs($x2 - $x1);
  23507. $h = abs($y2 - $y1);
  23508. if (!$clipping) {
  23509. $this->StartTransform();
  23510. $this->SVGTransform($tm);
  23511. $obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h, 'Line', array($x1, $y1, $x2, $y2));
  23512. $this->Line($x1, $y1, $x2, $y2);
  23513. $this->StopTransform();
  23514. }
  23515. break;
  23516. }
  23517. case 'polyline':
  23518. case 'polygon': {
  23519. if ($invisible) {
  23520. break;
  23521. }
  23522. $points = (isset($attribs['points'])?$attribs['points']:'0 0');
  23523. $points = trim($points);
  23524. // note that point may use a complex syntax not covered here
  23525. $points = preg_split('/[\,\s]+/si', $points);
  23526. if (count($points) < 4) {
  23527. break;
  23528. }
  23529. $p = array();
  23530. $xmin = 2147483647;
  23531. $xmax = 0;
  23532. $ymin = 2147483647;
  23533. $ymax = 0;
  23534. foreach ($points as $key => $val) {
  23535. $p[$key] = $this->getHTMLUnitToUnits($val, 0, $this->svgunit, false);
  23536. if (($key % 2) == 0) {
  23537. // X coordinate
  23538. $xmin = min($xmin, $p[$key]);
  23539. $xmax = max($xmax, $p[$key]);
  23540. } else {
  23541. // Y coordinate
  23542. $ymin = min($ymin, $p[$key]);
  23543. $ymax = max($ymax, $p[$key]);
  23544. }
  23545. }
  23546. $x = $xmin;
  23547. $y = $ymin;
  23548. $w = ($xmax - $xmin);
  23549. $h = ($ymax - $ymin);
  23550. if ($name == 'polyline') {
  23551. $this->StartTransform();
  23552. $this->SVGTransform($tm);
  23553. $obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h, 'PolyLine', array($p, 'CNZ'));
  23554. if (!empty($obstyle)) {
  23555. $this->PolyLine($p, $obstyle, array(), array());
  23556. }
  23557. $this->StopTransform();
  23558. } else { // polygon
  23559. if ($clipping) {
  23560. $this->SVGTransform($tm);
  23561. $this->Polygon($p, 'CNZ', array(), array(), true);
  23562. } else {
  23563. $this->StartTransform();
  23564. $this->SVGTransform($tm);
  23565. $obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h, 'Polygon', array($p, 'CNZ'));
  23566. if (!empty($obstyle)) {
  23567. $this->Polygon($p, $obstyle, array(), array(), true);
  23568. }
  23569. $this->StopTransform();
  23570. }
  23571. }
  23572. break;
  23573. }
  23574. // image
  23575. case 'image': {
  23576. if ($invisible) {
  23577. break;
  23578. }
  23579. if (!isset($attribs['xlink:href']) OR empty($attribs['xlink:href'])) {
  23580. break;
  23581. }
  23582. $x = (isset($attribs['x'])?$this->getHTMLUnitToUnits($attribs['x'], 0, $this->svgunit, false):0);
  23583. $y = (isset($attribs['y'])?$this->getHTMLUnitToUnits($attribs['y'], 0, $this->svgunit, false):0);
  23584. $w = (isset($attribs['width'])?$this->getHTMLUnitToUnits($attribs['width'], 0, $this->svgunit, false):0);
  23585. $h = (isset($attribs['height'])?$this->getHTMLUnitToUnits($attribs['height'], 0, $this->svgunit, false):0);
  23586. $img = $attribs['xlink:href'];
  23587. if (!$clipping) {
  23588. $this->StartTransform();
  23589. $this->SVGTransform($tm);
  23590. $obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, $w, $h);
  23591. if (preg_match('/^data:image\/[^;]+;base64,/', $img, $m) > 0) {
  23592. // embedded image encoded as base64
  23593. $img = '@'.base64_decode(substr($img, strlen($m[0])));
  23594. } else {
  23595. // fix image path
  23596. if (!TCPDF_STATIC::empty_string($this->svgdir) AND (($img[0] == '.') OR (basename($img) == $img))) {
  23597. // replace relative path with full server path
  23598. $img = $this->svgdir.'/'.$img;
  23599. }
  23600. if (($img[0] == '/') AND !empty($_SERVER['DOCUMENT_ROOT']) AND ($_SERVER['DOCUMENT_ROOT'] != '/')) {
  23601. $findroot = strpos($img, $_SERVER['DOCUMENT_ROOT']);
  23602. if (($findroot === false) OR ($findroot > 1)) {
  23603. if (substr($_SERVER['DOCUMENT_ROOT'], -1) == '/') {
  23604. $img = substr($_SERVER['DOCUMENT_ROOT'], 0, -1).$img;
  23605. } else {
  23606. $img = $_SERVER['DOCUMENT_ROOT'].$img;
  23607. }
  23608. }
  23609. }
  23610. $img = urldecode($img);
  23611. $testscrtype = @parse_url($img);
  23612. if (empty($testscrtype['query'])) {
  23613. // convert URL to server path
  23614. $img = str_replace(K_PATH_URL, K_PATH_MAIN, $img);
  23615. } elseif (preg_match('|^https?://|', $img) !== 1) {
  23616. // convert server path to URL
  23617. $img = str_replace(K_PATH_MAIN, K_PATH_URL, $img);
  23618. }
  23619. }
  23620. // get image type
  23621. $imgtype = TCPDF_IMAGES::getImageFileType($img);
  23622. if (($imgtype == 'eps') OR ($imgtype == 'ai')) {
  23623. $this->ImageEps($img, $x, $y, $w, $h);
  23624. } elseif ($imgtype == 'svg') {
  23625. // store SVG vars
  23626. $svggradients = $this->svggradients;
  23627. $svggradientid = $this->svggradientid;
  23628. $svgdefsmode = $this->svgdefsmode;
  23629. $svgdefs = $this->svgdefs;
  23630. $svgclipmode = $this->svgclipmode;
  23631. $svgclippaths = $this->svgclippaths;
  23632. $svgcliptm = $this->svgcliptm;
  23633. $svgclipid = $this->svgclipid;
  23634. $svgtext = $this->svgtext;
  23635. $svgtextmode = $this->svgtextmode;
  23636. $this->ImageSVG($img, $x, $y, $w, $h);
  23637. // restore SVG vars
  23638. $this->svggradients = $svggradients;
  23639. $this->svggradientid = $svggradientid;
  23640. $this->svgdefsmode = $svgdefsmode;
  23641. $this->svgdefs = $svgdefs;
  23642. $this->svgclipmode = $svgclipmode;
  23643. $this->svgclippaths = $svgclippaths;
  23644. $this->svgcliptm = $svgcliptm;
  23645. $this->svgclipid = $svgclipid;
  23646. $this->svgtext = $svgtext;
  23647. $this->svgtextmode = $svgtextmode;
  23648. } else {
  23649. $this->Image($img, $x, $y, $w, $h);
  23650. }
  23651. $this->StopTransform();
  23652. }
  23653. break;
  23654. }
  23655. // text
  23656. case 'text':
  23657. case 'tspan': {
  23658. if (isset($this->svgtextmode['text-anchor']) AND !empty($this->svgtext)) {
  23659. // @TODO: unsupported feature
  23660. }
  23661. // only basic support - advanced features must be implemented
  23662. $this->svgtextmode['invisible'] = $invisible;
  23663. if ($invisible) {
  23664. break;
  23665. }
  23666. array_push($this->svgstyles, $svgstyle);
  23667. if (isset($attribs['x'])) {
  23668. $x = $this->getHTMLUnitToUnits($attribs['x'], 0, $this->svgunit, false);
  23669. } elseif ($name == 'tspan') {
  23670. $x = $this->x;
  23671. } else {
  23672. $x = 0;
  23673. }
  23674. if (isset($attribs['dx'])) {
  23675. $x += $this->getHTMLUnitToUnits($attribs['dx'], 0, $this->svgunit, false);
  23676. }
  23677. if (isset($attribs['y'])) {
  23678. $y = $this->getHTMLUnitToUnits($attribs['y'], 0, $this->svgunit, false);
  23679. } elseif ($name == 'tspan') {
  23680. $y = $this->y;
  23681. } else {
  23682. $y = 0;
  23683. }
  23684. if (isset($attribs['dy'])) {
  23685. $y += $this->getHTMLUnitToUnits($attribs['dy'], 0, $this->svgunit, false);
  23686. }
  23687. $svgstyle['text-color'] = $svgstyle['fill'];
  23688. $this->svgtext = '';
  23689. if (isset($svgstyle['text-anchor'])) {
  23690. $this->svgtextmode['text-anchor'] = $svgstyle['text-anchor'];
  23691. } else {
  23692. $this->svgtextmode['text-anchor'] = 'start';
  23693. }
  23694. if (isset($svgstyle['direction'])) {
  23695. if ($svgstyle['direction'] == 'rtl') {
  23696. $this->svgtextmode['rtl'] = true;
  23697. } else {
  23698. $this->svgtextmode['rtl'] = false;
  23699. }
  23700. } else {
  23701. $this->svgtextmode['rtl'] = false;
  23702. }
  23703. if (isset($svgstyle['stroke']) AND ($svgstyle['stroke'] != 'none') AND isset($svgstyle['stroke-width']) AND ($svgstyle['stroke-width'] > 0)) {
  23704. $this->svgtextmode['stroke'] = $this->getHTMLUnitToUnits($svgstyle['stroke-width'], 0, $this->svgunit, false);
  23705. } else {
  23706. $this->svgtextmode['stroke'] = false;
  23707. }
  23708. $this->StartTransform();
  23709. $this->SVGTransform($tm);
  23710. $obstyle = $this->setSVGStyles($svgstyle, $prev_svgstyle, $x, $y, 1, 1);
  23711. $this->x = $x;
  23712. $this->y = $y;
  23713. break;
  23714. }
  23715. // use
  23716. case 'use': {
  23717. if (isset($attribs['xlink:href']) AND !empty($attribs['xlink:href'])) {
  23718. $svgdefid = substr($attribs['xlink:href'], 1);
  23719. if (isset($this->svgdefs[$svgdefid])) {
  23720. $use = $this->svgdefs[$svgdefid];
  23721. if (isset($attribs['xlink:href'])) {
  23722. unset($attribs['xlink:href']);
  23723. }
  23724. if (isset($attribs['id'])) {
  23725. unset($attribs['id']);
  23726. }
  23727. if (isset($use['attribs']['x']) AND isset($attribs['x'])) {
  23728. $attribs['x'] += $use['attribs']['x'];
  23729. }
  23730. if (isset($use['attribs']['y']) AND isset($attribs['y'])) {
  23731. $attribs['y'] += $use['attribs']['y'];
  23732. }
  23733. if (empty($attribs['style'])) {
  23734. $attribs['style'] = '';
  23735. }
  23736. if (!empty($use['attribs']['style'])) {
  23737. // merge styles
  23738. $attribs['style'] = str_replace(';;',';',';'.$use['attribs']['style'].$attribs['style']);
  23739. }
  23740. $attribs = array_merge($use['attribs'], $attribs);
  23741. $this->startSVGElementHandler($parser, $use['name'], $attribs);
  23742. return;
  23743. }
  23744. }
  23745. break;
  23746. }
  23747. default: {
  23748. break;
  23749. }
  23750. } // end of switch
  23751. // process child elements
  23752. if (!empty($attribs['child_elements'])) {
  23753. $child_elements = $attribs['child_elements'];
  23754. unset($attribs['child_elements']);
  23755. foreach($child_elements as $child_element) {
  23756. if (empty($child_element['attribs']['closing_tag'])) {
  23757. $this->startSVGElementHandler('child-tag', $child_element['name'], $child_element['attribs']);
  23758. } else {
  23759. if (isset($child_element['attribs']['content'])) {
  23760. $this->svgtext = $child_element['attribs']['content'];
  23761. }
  23762. $this->endSVGElementHandler('child-tag', $child_element['name']);
  23763. }
  23764. }
  23765. }
  23766. }
  23767. /**
  23768. * Sets the closing SVG element handler function for the XML parser.
  23769. * @param $parser (resource) The first parameter, parser, is a reference to the XML parser calling the handler.
  23770. * @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.
  23771. * @author Nicola Asuni
  23772. * @since 5.0.000 (2010-05-02)
  23773. * @protected
  23774. */
  23775. protected function endSVGElementHandler($parser, $name) {
  23776. $name = $this->removeTagNamespace($name);
  23777. if ($this->svgdefsmode AND !in_array($name, array('defs', 'clipPath', 'linearGradient', 'radialGradient', 'stop'))) {;
  23778. if (end($this->svgdefs) !== FALSE) {
  23779. $last_svgdefs_id = key($this->svgdefs);
  23780. if (isset($this->svgdefs[$last_svgdefs_id]['attribs']['child_elements'])) {
  23781. foreach($this->svgdefs[$last_svgdefs_id]['attribs']['child_elements'] as $child_element) {
  23782. if (isset($child_element['attribs']['id']) AND ($child_element['name'] == $name)) {
  23783. $this->svgdefs[$last_svgdefs_id]['attribs']['child_elements'][$child_element['attribs']['id'].'_CLOSE'] = array('name' => $name, 'attribs' => array('closing_tag' => TRUE, 'content' => $this->svgtext));
  23784. return;
  23785. }
  23786. }
  23787. if ($this->svgdefs[$last_svgdefs_id]['name'] == $name) {
  23788. $this->svgdefs[$last_svgdefs_id]['attribs']['child_elements'][$last_svgdefs_id.'_CLOSE'] = array('name' => $name, 'attribs' => array('closing_tag' => TRUE, 'content' => $this->svgtext));
  23789. return;
  23790. }
  23791. }
  23792. }
  23793. return;
  23794. }
  23795. switch($name) {
  23796. case 'defs': {
  23797. $this->svgdefsmode = false;
  23798. break;
  23799. }
  23800. // clipPath
  23801. case 'clipPath': {
  23802. $this->svgclipmode = false;
  23803. break;
  23804. }
  23805. case 'svg': {
  23806. if (--$this->svg_tag_depth <= 0) {
  23807. break;
  23808. }
  23809. }
  23810. case 'g': {
  23811. // ungroup: remove last style from array
  23812. array_pop($this->svgstyles);
  23813. $this->StopTransform();
  23814. break;
  23815. }
  23816. case 'text':
  23817. case 'tspan': {
  23818. if ($this->svgtextmode['invisible']) {
  23819. // This implementation must be fixed to following the rule:
  23820. // 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.
  23821. break;
  23822. }
  23823. // print text
  23824. $text = $this->svgtext;
  23825. //$text = $this->stringTrim($text);
  23826. $textlen = $this->GetStringWidth($text);
  23827. if ($this->svgtextmode['text-anchor'] != 'start') {
  23828. // check if string is RTL text
  23829. if ($this->svgtextmode['text-anchor'] == 'end') {
  23830. if ($this->svgtextmode['rtl']) {
  23831. $this->x += $textlen;
  23832. } else {
  23833. $this->x -= $textlen;
  23834. }
  23835. } elseif ($this->svgtextmode['text-anchor'] == 'middle') {
  23836. if ($this->svgtextmode['rtl']) {
  23837. $this->x += ($textlen / 2);
  23838. } else {
  23839. $this->x -= ($textlen / 2);
  23840. }
  23841. }
  23842. }
  23843. $textrendermode = $this->textrendermode;
  23844. $textstrokewidth = $this->textstrokewidth;
  23845. $this->setTextRenderingMode($this->svgtextmode['stroke'], true, false);
  23846. if ($name == 'text') {
  23847. // store current coordinates
  23848. $tmpx = $this->x;
  23849. $tmpy = $this->y;
  23850. }
  23851. // print the text
  23852. $this->Cell($textlen, 0, $text, 0, 0, '', false, '', 0, false, 'L', 'T');
  23853. if ($name == 'text') {
  23854. // restore coordinates
  23855. $this->x = $tmpx;
  23856. $this->y = $tmpy;
  23857. }
  23858. // restore previous rendering mode
  23859. $this->textrendermode = $textrendermode;
  23860. $this->textstrokewidth = $textstrokewidth;
  23861. $this->svgtext = '';
  23862. $this->StopTransform();
  23863. if (!$this->svgdefsmode) {
  23864. array_pop($this->svgstyles);
  23865. }
  23866. break;
  23867. }
  23868. default: {
  23869. break;
  23870. }
  23871. }
  23872. }
  23873. /**
  23874. * Sets the character data handler function for the XML parser.
  23875. * @param $parser (resource) The first parameter, parser, is a reference to the XML parser calling the handler.
  23876. * @param $data (string) The second parameter, data, contains the character data as a string.
  23877. * @author Nicola Asuni
  23878. * @since 5.0.000 (2010-05-02)
  23879. * @protected
  23880. */
  23881. protected function segSVGContentHandler($parser, $data) {
  23882. $this->svgtext .= $data;
  23883. }
  23884. // --- END SVG METHODS -----------------------------------------------------
  23885. } // END OF TCPDF CLASS
  23886. //============================================================+
  23887. // END OF FILE
  23888. //============================================================+